source: icGREP/icgrep-devel/icgrep/pablo/pablo_compiler.cpp @ 4816

Last change on this file since 4816 was 4816, checked in by cameron, 4 years ago

Clean ups

File size: 23.1 KB
Line 
1/*
2 *  Copyright (c) 2014-15 International Characters.
3 *  This software is licensed to the public under the Open Software License 3.0.
4 *  icgrep is a trademark of International Characters.
5 */
6
7#include <pablo/pablo_compiler.h>
8#include <pablo/codegenstate.h>
9#include <pablo/carry_data.h>
10#include <pablo/carry_manager.h>
11#include <pablo/printer_pablos.h>
12#include <pablo/function.h>
13#include <cc/cc_namemap.hpp>
14#include <re/re_name.h>
15#include <stdexcept>
16#include <include/simd-lib/bitblock.hpp>
17#include <sstream>
18#include <IDISA/idisa_builder.h>
19#include <llvm/IR/Verifier.h>
20#include <llvm/Pass.h>
21#include <llvm/PassManager.h>
22#include <llvm/ADT/SmallVector.h>
23#include <llvm/Analysis/Passes.h>
24#include <llvm/IR/BasicBlock.h>
25#include <llvm/IR/CallingConv.h>
26#include <llvm/IR/DataLayout.h>
27#include <llvm/IR/DerivedTypes.h>
28#include <llvm/IR/Function.h>
29#include <llvm/IR/GlobalVariable.h>
30#include <llvm/IR/InlineAsm.h>
31#include <llvm/IR/Instructions.h>
32#include <llvm/IR/LLVMContext.h>
33#include <llvm/IR/Module.h>
34#include <llvm/Support/FormattedStream.h>
35#include <llvm/Support/MathExtras.h>
36#include <llvm/Support/Casting.h>
37#include <llvm/Support/Compiler.h>
38#include <llvm/Support/Debug.h>
39#include <llvm/Support/TargetSelect.h>
40#include <llvm/Support/Host.h>
41#include <llvm/Transforms/Scalar.h>
42#include <llvm/IRReader/IRReader.h>
43#include <llvm/Bitcode/ReaderWriter.h>
44#include <llvm/Support/MemoryBuffer.h>
45#include <llvm/IR/IRBuilder.h>
46#include <llvm/Support/CommandLine.h>
47#include <llvm/ADT/Twine.h>
48#include <iostream>
49
50static cl::OptionCategory eIRDumpOptions("LLVM IR Dump Options", "These options control dumping of LLVM IR.");
51static cl::opt<bool> DumpGeneratedIR("dump-generated-IR", cl::init(false), cl::desc("Print LLVM IR generated by Pablo Compiler."), cl::cat(eIRDumpOptions));
52
53static cl::OptionCategory fTracingOptions("Run-time Tracing Options", "These options control execution traces.");
54static cl::opt<bool> DumpTrace("dump-trace", cl::init(false), cl::desc("Generate dynamic traces of executed assignments."), cl::cat(fTracingOptions));
55
56namespace pablo {
57
58PabloCompiler::PabloCompiler()
59: mMod(nullptr)
60, mBuilder(nullptr)
61, mCarryManager(nullptr)
62, mBitBlockType(VectorType::get(IntegerType::get(getGlobalContext(), 64), BLOCK_SIZE / 64))
63, iBuilder(mBitBlockType)
64, mInputType(nullptr)
65, mWhileDepth(0)
66, mIfDepth(0)
67, mZeroInitializer(ConstantAggregateZero::get(mBitBlockType))
68, mOneInitializer(ConstantVector::getAllOnesValue(mBitBlockType))
69, mFunction(nullptr)
70, mInputAddressPtr(nullptr)
71, mOutputAddressPtr(nullptr)
72, mMaxWhileDepth(0)
73, mPrintRegisterFunction(nullptr) {
74
75}
76
77PabloCompiler::~PabloCompiler() {
78}
79   
80
81void PabloCompiler::genPrintRegister(std::string regName, Value * bitblockValue) {
82    Constant * regNameData = ConstantDataArray::getString(mMod->getContext(), regName);
83    GlobalVariable *regStrVar = new GlobalVariable(*mMod,
84                                                   ArrayType::get(IntegerType::get(mMod->getContext(), 8), regName.length()+1),
85                                                   /*isConstant=*/ true,
86                                                   /*Linkage=*/ GlobalValue::PrivateLinkage,
87                                                   /*Initializer=*/ regNameData);
88    Value * regStrPtr = mBuilder->CreateGEP(regStrVar, std::vector<Value *>({mBuilder->getInt64(0), mBuilder->getInt32(0)}));
89    mBuilder->CreateCall(mPrintRegisterFunction, std::vector<Value *>({regStrPtr, bitblockValue}));
90}
91
92llvm::Function * PabloCompiler::compile(PabloFunction * function) {
93    Module * module = new Module("", getGlobalContext());
94   
95    auto func = compile(function, module);
96   
97    //Display the IR that has been generated by this module.
98    if (LLVM_UNLIKELY(DumpGeneratedIR)) {
99        module->dump();
100    }
101    //Create a verifier.  The verifier will print an error message if our module is malformed in any way.
102    verifyModule(*module, &dbgs());
103
104    return func;
105}
106
107llvm::Function * PabloCompiler::compile(PabloFunction * function, Module * module) {
108
109 
110    PabloBlock & mainScope = function->getEntryBlock();
111
112    mainScope.enumerateScopes(0);
113   
114    Examine(*function);
115
116    mMod = module;
117
118    mBuilder = new IRBuilder<>(mMod->getContext());
119
120    iBuilder.initialize(mMod, mBuilder);
121
122    mCarryManager = new CarryManager(mBuilder, mBitBlockType, mZeroInitializer, &iBuilder);
123   
124    if (DumpTrace) DeclareDebugFunctions();
125       
126    GenerateFunction(*function);
127   
128    mBuilder->SetInsertPoint(BasicBlock::Create(mMod->getContext(), "entry", mFunction,0));
129
130    //The basis bits structure
131    for (unsigned i = 0; i != function->getNumOfParameters(); ++i) {
132        Value* indices[] = {mBuilder->getInt64(0), mBuilder->getInt32(i)};
133        Value * gep = mBuilder->CreateGEP(mInputAddressPtr, indices);
134        LoadInst * basisBit = mBuilder->CreateAlignedLoad(gep, BLOCK_SIZE/8, false, function->getParameter(i)->getName()->to_string());
135        mMarkerMap[function->getParameter(i)] = basisBit;
136        if (DumpTrace) {
137            genPrintRegister(function->getParameter(i)->getName()->to_string(), basisBit);
138        }
139    }
140     
141    //Generate the IR instructions for the function.
142   
143    mCarryManager->initialize(mMod, &mainScope);
144   
145    compileBlock(mainScope);
146   
147    mCarryManager->ensureCarriesStoredLocal();
148    mCarryManager->leaveScope();
149   
150   
151    mCarryManager->generateBlockNoIncrement();
152
153    if (DumpTrace) {
154        genPrintRegister("mBlockNo", mBuilder->CreateAlignedLoad(mBuilder->CreateBitCast(mCarryManager->getBlockNoPtr(), PointerType::get(mBitBlockType, 0)), BLOCK_SIZE/8, false));
155    }
156   
157    // Write the output values out
158    for (unsigned i = 0; i != function->getNumOfResults(); ++i) {
159        assert (function->getResult(i));
160        SetOutputValue(mMarkerMap[function->getResult(i)], i);
161    }
162
163    //Terminate the block
164    ReturnInst::Create(mMod->getContext(), mBuilder->GetInsertBlock());
165   
166    // Clean up
167    delete mCarryManager; mCarryManager = nullptr;
168    delete mBuilder; mBuilder = nullptr;
169    mMod = nullptr; // don't delete this. It's either owned by the ExecutionEngine or the calling function.
170
171    //Return the required size of the carry data area to the process_block function.
172    return mFunction;
173}
174
175inline void PabloCompiler::GenerateFunction(PabloFunction & function) {
176    mInputType = PointerType::get(StructType::get(mMod->getContext(), std::vector<Type *>(function.getNumOfParameters(), mBitBlockType)), 0);
177    Type * outputType = PointerType::get(StructType::get(mMod->getContext(), std::vector<Type *>(function.getNumOfResults(), mBitBlockType)), 0);
178    FunctionType * functionType = FunctionType::get(Type::getVoidTy(mMod->getContext()), std::vector<Type *>({mInputType, outputType}), false);
179
180
181    //Starts on process_block
182    SmallVector<AttributeSet, 3> Attrs;
183    Attrs.push_back(AttributeSet::get(mMod->getContext(), ~0U, std::vector<Attribute::AttrKind>({ Attribute::NoUnwind, Attribute::UWTable })));
184    Attrs.push_back(AttributeSet::get(mMod->getContext(), 1U, std::vector<Attribute::AttrKind>({ Attribute::ReadOnly, Attribute::NoCapture })));
185    Attrs.push_back(AttributeSet::get(mMod->getContext(), 2U, std::vector<Attribute::AttrKind>({ Attribute::ReadNone, Attribute::NoCapture })));
186    AttributeSet AttrSet = AttributeSet::get(mMod->getContext(), Attrs);
187
188    // Create the function that will be generated.
189    mFunction = Function::Create(functionType, GlobalValue::ExternalLinkage, function.getName()->value(), mMod);
190    mFunction->setCallingConv(CallingConv::C);
191    mFunction->setAttributes(AttrSet);
192
193    Function::arg_iterator args = mFunction->arg_begin();
194    mInputAddressPtr = args++;
195    mInputAddressPtr->setName("input");
196    mOutputAddressPtr = args++;
197    mOutputAddressPtr->setName("output");
198}
199
200inline void PabloCompiler::Examine(PabloFunction & function) {
201    mWhileDepth = 0;
202    mIfDepth = 0;
203    mMaxWhileDepth = 0;
204    Examine(function.getEntryBlock());
205    if (LLVM_UNLIKELY(mWhileDepth != 0 || mIfDepth != 0)) {
206        throw std::runtime_error("Malformed Pablo AST: Unbalanced If or While nesting depth!");
207    }
208}
209
210
211void PabloCompiler::Examine(PabloBlock & block) {
212    for (Statement * stmt : block) {
213        if (If * ifStatement = dyn_cast<If>(stmt)) {
214            Examine(ifStatement->getBody());
215        }
216        else if (While * whileStatement = dyn_cast<While>(stmt)) {
217            mMaxWhileDepth = std::max(mMaxWhileDepth, ++mWhileDepth);
218            Examine(whileStatement->getBody());
219            --mWhileDepth;
220        }
221    }
222}
223
224inline void PabloCompiler::DeclareDebugFunctions() {
225        //This function can be used for testing to print the contents of a register from JIT'd code to the terminal window.
226        mPrintRegisterFunction = mMod->getOrInsertFunction("wrapped_print_register", Type::getVoidTy(mMod->getContext()), Type::getInt8PtrTy(mMod->getContext()), mBitBlockType, NULL);
227}
228
229void PabloCompiler::compileBlock(PabloBlock & block) {
230    mPabloBlock = & block;
231    for (const Statement * statement : block) {
232        compileStatement(statement);
233    }
234    mPabloBlock = block.getParent();
235}
236
237    Value * PabloCompiler::genBitTest2(Value * e1, Value * e2) {
238        Type * t1 = e1->getType();
239        Type * t2 = e2->getType();
240        if (t1 == mBitBlockType) {
241            if (t2 == mBitBlockType) {
242                return iBuilder.bitblock_any(mBuilder->CreateOr(e1, e2));
243            }
244            else {
245                Value * m1 = mBuilder->CreateZExt(iBuilder.hsimd_signmask(16, e1), t2);
246                return mBuilder->CreateICmpNE(mBuilder->CreateOr(m1, e2), ConstantInt::get(t2, 0));
247            }
248        }
249        else if (t2 == mBitBlockType) {
250            Value * m2 = mBuilder->CreateZExt(iBuilder.hsimd_signmask(16, e2), t1);
251            return mBuilder->CreateICmpNE(mBuilder->CreateOr(e1, m2), ConstantInt::get(t1, 0));
252        }
253        else {
254            return mBuilder->CreateICmpNE(mBuilder->CreateOr(e1, e2), ConstantInt::get(t1, 0));
255        }
256    }
257   
258    void PabloCompiler::compileIf(const If * ifStatement) {       
259    //
260    //  The If-ElseZero stmt:
261    //  if <predicate:expr> then <body:stmt>* elsezero <defined:var>* endif
262    //  If the value of the predicate is nonzero, then determine the values of variables
263    //  <var>* by executing the given statements.  Otherwise, the value of the
264    //  variables are all zero.  Requirements: (a) no variable that is defined within
265    //  the body of the if may be accessed outside unless it is explicitly
266    //  listed in the variable list, (b) every variable in the defined list receives
267    //  a value within the body, and (c) the logical consequence of executing
268    //  the statements in the event that the predicate is zero is that the
269    //  values of all defined variables indeed work out to be 0.
270    //
271    //  Simple Implementation with Phi nodes:  a phi node in the if exit block
272    //  is inserted for each variable in the defined variable list.  It receives
273    //  a zero value from the ifentry block and the defined value from the if
274    //  body.
275    //
276
277    BasicBlock * ifEntryBlock = mBuilder->GetInsertBlock();
278    BasicBlock * ifBodyBlock = BasicBlock::Create(mMod->getContext(), "if.body", mFunction, 0);
279    BasicBlock * ifEndBlock = BasicBlock::Create(mMod->getContext(), "if.end", mFunction, 0);
280   
281    PabloBlock & ifBody = ifStatement -> getBody();
282   
283    Value * if_test_value = compileExpression(ifStatement->getCondition());
284   
285    mCarryManager->enterScope(&ifBody);
286    if (mCarryManager->blockHasCarries()) {
287        // load the summary variable
288        Value* last_if_pending_data = mCarryManager->getCarrySummaryExpr();
289        mBuilder->CreateCondBr(genBitTest2(if_test_value, last_if_pending_data), ifBodyBlock, ifEndBlock);
290
291    }
292    else {
293        mBuilder->CreateCondBr(iBuilder.bitblock_any(if_test_value), ifBodyBlock, ifEndBlock);
294    }
295    // Entry processing is complete, now handle the body of the if.
296    mBuilder->SetInsertPoint(ifBodyBlock);
297   
298    mCarryManager->initializeCarryDataAtIfEntry();
299    compileBlock(ifBody);
300    if (mCarryManager->blockHasCarries()) {
301        mCarryManager->generateCarryOutSummaryCodeIfNeeded();
302    }
303    BasicBlock * ifBodyFinalBlock = mBuilder->GetInsertBlock();
304    mCarryManager->ensureCarriesStoredLocal();
305    mBuilder->CreateBr(ifEndBlock);
306    //End Block
307    mBuilder->SetInsertPoint(ifEndBlock);
308    for (const PabloAST * node : ifStatement->getDefined()) {
309        const Assign * assign = cast<Assign>(node);
310        PHINode * phi = mBuilder->CreatePHI(mBitBlockType, 2, assign->getName()->value());
311        auto f = mMarkerMap.find(assign);
312        assert (f != mMarkerMap.end());
313        phi->addIncoming(mZeroInitializer, ifEntryBlock);
314        phi->addIncoming(f->second, ifBodyFinalBlock);
315        mMarkerMap[assign] = phi;
316    }
317    // Create the phi Node for the summary variable, if needed.
318    mCarryManager->buildCarryDataPhisAfterIfBody(ifEntryBlock, ifBodyFinalBlock);
319    mCarryManager->leaveScope();
320}
321
322void PabloCompiler::compileWhile(const While * whileStatement) {
323
324    PabloBlock & whileBody = whileStatement -> getBody();
325   
326    BasicBlock * whileEntryBlock = mBuilder->GetInsertBlock();
327    BasicBlock * whileBodyBlock = BasicBlock::Create(mMod->getContext(), "while.body", mFunction, 0);
328    BasicBlock * whileEndBlock = BasicBlock::Create(mMod->getContext(), "while.end", mFunction, 0);
329
330    mCarryManager->enterScope(&whileBody);
331    mCarryManager->ensureCarriesLoadedRecursive();
332
333    const auto & nextNodes = whileStatement->getVariants();
334    std::vector<PHINode *> nextPhis;
335    nextPhis.reserve(nextNodes.size());
336
337    // On entry to the while structure, proceed to execute the first iteration
338    // of the loop body unconditionally.   The while condition is tested at the end of
339    // the loop.
340
341    mBuilder->CreateBr(whileBodyBlock);
342    mBuilder->SetInsertPoint(whileBodyBlock);
343
344    //
345    // There are 3 sets of Phi nodes for the while loop.
346    // (1) Carry-ins: (a) incoming carry data first iterations, (b) zero thereafter
347    // (2) Carry-out accumulators: (a) zero first iteration, (b) |= carry-out of each iteration
348    // (3) Next nodes: (a) values set up before loop, (b) modified values calculated in loop.
349
350    mCarryManager->initializeCarryDataPhisAtWhileEntry(whileEntryBlock);
351
352    // for any Next nodes in the loop body, initialize to (a) pre-loop value.
353    for (const Next * n : nextNodes) {
354        PHINode * phi = mBuilder->CreatePHI(mBitBlockType, 2, n->getName()->value());
355        auto f = mMarkerMap.find(n->getInitial());
356        assert (f != mMarkerMap.end());
357        phi->addIncoming(f->second, whileEntryBlock);
358        mMarkerMap[n->getInitial()] = phi;
359        nextPhis.push_back(phi);
360    }
361
362    //
363    // Now compile the loop body proper.  Carry-out accumulated values
364    // and iterated values of Next nodes will be computed.
365    ++mWhileDepth;
366    compileBlock(whileBody);
367
368    BasicBlock * whileBodyFinalBlock = mBuilder->GetInsertBlock();
369
370    if (mCarryManager->blockHasCarries()) {
371        mCarryManager->generateCarryOutSummaryCodeIfNeeded();
372    }
373    mCarryManager->extendCarryDataPhisAtWhileBodyFinalBlock(whileBodyFinalBlock);
374
375    // Terminate the while loop body with a conditional branch back.
376    mBuilder->CreateCondBr(iBuilder.bitblock_any(compileExpression(whileStatement->getCondition())), whileBodyBlock, whileEndBlock);
377
378    // and for any Next nodes in the loop body
379    for (unsigned i = 0; i < nextNodes.size(); i++) {
380        const Next * n = nextNodes[i];
381        auto f = mMarkerMap.find(n->getExpr());
382        if (LLVM_UNLIKELY(f == mMarkerMap.end())) {
383            throw std::runtime_error("Next node expression was not compiled!");
384        }
385        nextPhis[i]->addIncoming(f->second, whileBodyFinalBlock);
386    }
387
388    mBuilder->SetInsertPoint(whileEndBlock);
389    --mWhileDepth;
390
391    mCarryManager->ensureCarriesStoredRecursive();
392    mCarryManager->leaveScope();
393}
394
395
396void PabloCompiler::compileStatement(const Statement * stmt) {
397    Value * expr = nullptr;
398    if (const Assign * assign = dyn_cast<const Assign>(stmt)) {
399        expr = compileExpression(assign->getExpression());
400    }
401    else if (const Next * next = dyn_cast<const Next>(stmt)) {
402        expr = compileExpression(next->getExpr());
403    }
404    else if (const If * ifStatement = dyn_cast<const If>(stmt)) {
405        compileIf(ifStatement);
406        return;
407    }
408    else if (const While * whileStatement = dyn_cast<const While>(stmt)) {
409        compileWhile(whileStatement);
410        return;
411    }
412    else if (const Call* call = dyn_cast<Call>(stmt)) {
413        //Call the callee once and store the result in the marker map.
414        if (mMarkerMap.count(call) != 0) {
415            return;
416        }
417
418        const Prototype * proto = call->getPrototype();
419        const String * callee = proto->getName();
420
421        Type * inputType = StructType::get(mMod->getContext(), std::vector<Type *>{proto->getNumOfParameters(), mBitBlockType});
422        Type * outputType = StructType::get(mMod->getContext(), std::vector<Type *>{proto->getNumOfResults(), mBitBlockType});
423        FunctionType * functionType = FunctionType::get(Type::getVoidTy(mMod->getContext()), std::vector<Type *>{PointerType::get(inputType, 0), PointerType::get(outputType, 0)}, false);
424
425        //Starts on process_block
426        SmallVector<AttributeSet, 3> Attrs;
427        Attrs.push_back(AttributeSet::get(mMod->getContext(), 1U, std::vector<Attribute::AttrKind>({ Attribute::ReadOnly, Attribute::NoCapture })));
428        Attrs.push_back(AttributeSet::get(mMod->getContext(), 2U, std::vector<Attribute::AttrKind>({ Attribute::ReadNone, Attribute::NoCapture })));
429        AttributeSet AttrSet = AttributeSet::get(mMod->getContext(), Attrs);
430
431        Function * externalFunction = cast<Function>(mMod->getOrInsertFunction(callee->value(), functionType, AttrSet));
432        if (LLVM_UNLIKELY(externalFunction == nullptr)) {
433            throw std::runtime_error("Could not create static method call for external function \"" + callee->to_string() + "\"");
434        }
435        externalFunction->setCallingConv(llvm::CallingConv::C);
436
437
438        AllocaInst * outputStruct = mBuilder->CreateAlloca(outputType);
439        mBuilder->CreateCall2(externalFunction, mInputAddressPtr, outputStruct);
440        Value * outputPtr = mBuilder->CreateGEP(outputStruct, std::vector<Value *>({ mBuilder->getInt32(0), mBuilder->getInt32(0) }));
441        expr = mBuilder->CreateAlignedLoad(outputPtr, BLOCK_SIZE / 8, false);
442    }
443    else if (const And * pablo_and = dyn_cast<And>(stmt)) {
444        expr = mBuilder->CreateAnd(compileExpression(pablo_and->getExpr1()), compileExpression(pablo_and->getExpr2()), "and");
445    }
446    else if (const Or * pablo_or = dyn_cast<Or>(stmt)) {
447        expr = mBuilder->CreateOr(compileExpression(pablo_or->getExpr1()), compileExpression(pablo_or->getExpr2()), "or");
448    }
449    else if (const Xor * pablo_xor = dyn_cast<Xor>(stmt)) {
450        expr = mBuilder->CreateXor(compileExpression(pablo_xor->getExpr1()), compileExpression(pablo_xor->getExpr2()), "xor");
451    }
452    else if (const Sel * sel = dyn_cast<Sel>(stmt)) {
453        Value* ifMask = compileExpression(sel->getCondition());
454        Value* ifTrue = mBuilder->CreateAnd(ifMask, compileExpression(sel->getTrueExpr()));
455        Value* ifFalse = mBuilder->CreateAnd(mBuilder->CreateNot(ifMask), compileExpression(sel->getFalseExpr()));
456        expr = mBuilder->CreateOr(ifTrue, ifFalse);
457    }
458    else if (const Not * pablo_not = dyn_cast<Not>(stmt)) {
459        expr = mBuilder->CreateNot(compileExpression(pablo_not->getExpr()));
460    }
461    else if (const Advance * adv = dyn_cast<Advance>(stmt)) {
462        Value* strm_value = compileExpression(adv->getExpr());
463        int shift = adv->getAdvanceAmount();
464        unsigned advance_index = adv->getLocalAdvanceIndex();
465        expr = mCarryManager->advanceCarryInCarryOut(advance_index, shift, strm_value);
466    }
467    else if (const Mod64Advance * adv = dyn_cast<Mod64Advance>(stmt)) {
468        Value* strm_value = compileExpression(adv->getExpr());
469        int shift = adv->getAdvanceAmount();
470        expr = iBuilder.simd_slli(64, strm_value, shift);
471    }
472    else if (const MatchStar * mstar = dyn_cast<MatchStar>(stmt)) {
473        Value * marker = compileExpression(mstar->getMarker());
474        Value * cc = compileExpression(mstar->getCharClass());
475        Value * marker_and_cc = mBuilder->CreateAnd(marker, cc);
476        unsigned carry_index = mstar->getLocalCarryIndex();
477        Value * sum = mCarryManager->addCarryInCarryOut(carry_index, marker_and_cc, cc);
478        expr = mBuilder->CreateOr(mBuilder->CreateXor(sum, cc), marker, "matchstar");
479    }
480    else if (const Mod64MatchStar * mstar = dyn_cast<Mod64MatchStar>(stmt)) {
481        Value * marker = compileExpression(mstar->getMarker());
482        Value * cc = compileExpression(mstar->getCharClass());
483        Value * marker_and_cc = mBuilder->CreateAnd(marker, cc);
484        Value * sum = iBuilder.simd_add(64, marker_and_cc, cc);
485        expr = mBuilder->CreateOr(mBuilder->CreateXor(sum, cc), marker, "matchstar64");
486    }
487    else if (const ScanThru * sthru = dyn_cast<ScanThru>(stmt)) {
488        Value * marker_expr = compileExpression(sthru->getScanFrom());
489        Value * cc_expr = compileExpression(sthru->getScanThru());
490        unsigned carry_index = sthru->getLocalCarryIndex();
491        Value * sum = mCarryManager->addCarryInCarryOut(carry_index, marker_expr, cc_expr);
492        expr = mBuilder->CreateAnd(sum, mBuilder->CreateNot(cc_expr), "scanthru");
493    }
494    else if (const Mod64ScanThru * sthru = dyn_cast<Mod64ScanThru>(stmt)) {
495        Value * marker_expr = compileExpression(sthru->getScanFrom());
496        Value * cc_expr = compileExpression(sthru->getScanThru());
497        Value * sum = iBuilder.simd_add(64, marker_expr, cc_expr);
498        expr = mBuilder->CreateAnd(sum, mBuilder->CreateNot(cc_expr), "scanthru64");
499    }
500    else if (const Count * c = dyn_cast<Count>(stmt)) {
501        unsigned count_index = c->getGlobalCountIndex();
502        Value * to_count = compileExpression(c->getExpr());
503        expr = mCarryManager->popCount(to_count, count_index);
504    }
505    else {
506        llvm::raw_os_ostream cerr(std::cerr);
507        PabloPrinter::print(stmt, cerr);
508        throw std::runtime_error("Unrecognized Pablo Statement! can't compile.");
509    }
510    mMarkerMap[stmt] = expr;
511    if (DumpTrace) {
512        genPrintRegister(stmt->getName()->to_string(), expr);
513    }
514   
515}
516
517Value * PabloCompiler::compileExpression(const PabloAST * expr) {
518    if (isa<Ones>(expr)) {
519        return mOneInitializer;
520    }
521    else if (isa<Zeroes>(expr)) {
522        return mZeroInitializer;
523    }
524    auto f = mMarkerMap.find(expr);
525    if (LLVM_UNLIKELY(f == mMarkerMap.end())) {
526        std::string o;
527        llvm::raw_string_ostream str(o);
528        str << "\"";
529        PabloPrinter::print(expr, str);
530        str << "\" was used before definition!";
531        throw std::runtime_error(str.str());
532    }
533    return f->second;
534}
535
536void PabloCompiler::SetOutputValue(Value * marker, const unsigned index) {
537    if (LLVM_UNLIKELY(marker == nullptr)) {
538        throw std::runtime_error("Cannot set result " + std::to_string(index) + " to Null");
539    }
540    if (LLVM_UNLIKELY(marker->getType()->isPointerTy())) {
541        marker = mBuilder->CreateAlignedLoad(marker, BLOCK_SIZE/8, false);
542    }
543    Value* indices[] = {mBuilder->getInt64(0), mBuilder->getInt32(index)};
544    Value* gep = mBuilder->CreateGEP(mOutputAddressPtr, indices);
545    mBuilder->CreateAlignedStore(marker, gep, BLOCK_SIZE/8, false);
546}
547
548}
Note: See TracBrowser for help on using the repository browser.