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

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

Set up for necessary AVX2 #defines

File size: 47.5 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/printer_pablos.h>
10#include <cc/cc_namemap.hpp>
11#include <re/re_name.h>
12#include <stdexcept>
13#include <include/simd-lib/bitblock.hpp>
14#include <sstream>
15#include <llvm/IR/Verifier.h>
16#include <llvm/Pass.h>
17#include <llvm/PassManager.h>
18#include <llvm/ADT/SmallVector.h>
19#include <llvm/Analysis/Passes.h>
20#include <llvm/IR/BasicBlock.h>
21#include <llvm/IR/CallingConv.h>
22#include <llvm/IR/Constants.h>
23#include <llvm/IR/DataLayout.h>
24#include <llvm/IR/DerivedTypes.h>
25#include <llvm/IR/Function.h>
26#include <llvm/IR/GlobalVariable.h>
27#include <llvm/IR/InlineAsm.h>
28#include <llvm/IR/Instructions.h>
29#include <llvm/IR/LLVMContext.h>
30#include <llvm/IR/Module.h>
31#include <llvm/Support/FormattedStream.h>
32#include <llvm/Support/MathExtras.h>
33#include <llvm/Support/Casting.h>
34#include <llvm/Support/Compiler.h>
35#include <llvm/Support/Debug.h>
36#include <llvm/Support/TargetSelect.h>
37#include <llvm/Support/Host.h>
38#include <llvm/Transforms/Scalar.h>
39#include <llvm/ExecutionEngine/ExecutionEngine.h>
40#include <llvm/ExecutionEngine/MCJIT.h>
41#include <llvm/IRReader/IRReader.h>
42#include <llvm/Bitcode/ReaderWriter.h>
43#include <llvm/Support/MemoryBuffer.h>
44#include <llvm/IR/IRBuilder.h>
45#include <llvm/Support/CommandLine.h>
46#include <llvm/ADT/Twine.h>
47#include <iostream>
48
49cl::OptionCategory eIRDumpOptions("LLVM IR Dump Options", "These options control dumping of LLVM IR.");
50static cl::opt<bool> DumpGeneratedIR("dump-generated-IR", cl::init(false), cl::desc("print LLVM IR generated by RE compilation"), cl::cat(eIRDumpOptions));
51
52extern "C" {
53  void wrapped_print_register(BitBlock bit_block) {
54      print_register<BitBlock>("", bit_block);
55  }
56}
57
58namespace pablo {
59
60PabloCompiler::PabloCompiler(const std::vector<Var*> & basisBits)
61: mBasisBits(basisBits)
62, mMod(new Module("icgrep", getGlobalContext()))
63, mBasicBlock(nullptr)
64, mExecutionEngine(nullptr)
65, mBitBlockType(VectorType::get(IntegerType::get(mMod->getContext(), 64), BLOCK_SIZE / 64))
66, mBasisBitsInputPtr(nullptr)
67, mCarryQueueIdx(0)
68, mCarryQueuePtr(nullptr)
69, mNestingDepth(0)
70, mCarryQueueSize(0)
71, mAdvanceQueueIdx(0)
72, mAdvanceQueuePtr(nullptr)
73, mAdvanceQueueSize(0)
74, mZeroInitializer(ConstantAggregateZero::get(mBitBlockType))
75, mOneInitializer(ConstantVector::getAllOnesValue(mBitBlockType))
76, mFunctionType(nullptr)
77, mFunction(nullptr)
78, mBasisBitsAddr(nullptr)
79, mOutputAddrPtr(nullptr)
80, mMaxNestingDepth(0)
81, mPrintRegisterFunction(nullptr)
82{
83    //Create the jit execution engine.up
84    InitializeNativeTarget();
85    InitializeNativeTargetAsmPrinter();
86    InitializeNativeTargetAsmParser();
87    DefineTypes();
88}
89
90PabloCompiler::~PabloCompiler()
91{
92
93}
94   
95void PabloCompiler::InstallExternalFunction(std::string C_fn_name, void * fn_ptr) {
96    mExternalMap.insert(std::make_pair(C_fn_name, fn_ptr));
97}
98
99
100CompiledPabloFunction PabloCompiler::compile(PabloBlock & pb)
101{
102    mNestingDepth = 0;
103    mMaxNestingDepth = 0;
104    mCarryQueueSize = 0;
105    mAdvanceQueueSize = 0;
106    Examine(pb.statements());
107    mCarryQueueVector.resize(mCarryQueueSize);
108    mAdvanceQueueVector.resize(mAdvanceQueueSize);
109    mCarryQueueSummaryIdx.resize(mCarryQueueSize);
110    mAdvanceQueueSummaryIdx.resize(mAdvanceQueueSize);
111    std::string errMessage;
112    EngineBuilder builder(mMod);
113    builder.setErrorStr(&errMessage);
114    builder.setMCPU(sys::getHostCPUName());
115    builder.setUseMCJIT(true);
116    builder.setOptLevel(mMaxNestingDepth ? CodeGenOpt::Level::Less : CodeGenOpt::Level::None);
117    mExecutionEngine = builder.create();
118    if (mExecutionEngine == nullptr) {
119        throw std::runtime_error("Could not create ExecutionEngine: " + errMessage);
120    }
121    DeclareFunctions();
122
123    DeclareCallFunctions();
124
125    Function::arg_iterator args = mFunction->arg_begin();
126    mBasisBitsAddr = args++;
127    mBasisBitsAddr->setName("basis_bits");
128    mCarryQueuePtr = args++;
129    mCarryQueuePtr->setName("carry_q");
130    mAdvanceQueuePtr = args++;
131    mAdvanceQueuePtr->setName("advance_q");
132    mOutputAddrPtr = args++;
133    mOutputAddrPtr->setName("output");
134
135    //Create the carry and advance queues.
136    mCarryQueueIdx = 0;
137    mAdvanceQueueIdx = 0;
138    mNestingDepth = 0;
139    mMaxNestingDepth = 0;
140    mBasicBlock = BasicBlock::Create(mMod->getContext(), "parabix_entry", mFunction,0);
141
142    //The basis bits structure
143    for (unsigned i = 0; i != mBasisBits.size(); ++i) {
144        IRBuilder<> b(mBasicBlock);
145        Value* indices[] = {b.getInt64(0), b.getInt32(i)};
146        Value * gep = b.CreateGEP(mBasisBitsAddr, indices);
147        LoadInst * basisBit = b.CreateAlignedLoad(gep, BLOCK_SIZE/8, false, mBasisBits[i]->getName()->to_string());
148        mMarkerMap.insert(std::make_pair(mBasisBits[i], basisBit));
149    }
150
151    //Generate the IR instructions for the function.
152    compileStatements(pb.statements());
153
154    if (LLVM_UNLIKELY(mCarryQueueIdx != mCarryQueueSize)) {
155        throw std::runtime_error("Actual carry queue size (" + std::to_string(mCarryQueueIdx) + ") does not match expected (" + std::to_string(mCarryQueueSize) + ")");
156    }
157    if (LLVM_UNLIKELY(mAdvanceQueueIdx != mAdvanceQueueSize)) {
158        throw std::runtime_error("Actual advance queue size (" + std::to_string(mAdvanceQueueIdx) + ") does not match expected (" + std::to_string(mAdvanceQueueSize) + ")");
159    }
160    if (LLVM_UNLIKELY(mNestingDepth != 0)) {
161        throw std::runtime_error("Non-zero nesting depth error (" + std::to_string(mNestingDepth) + ")");
162    }
163
164    //Terminate the block
165    ReturnInst::Create(mMod->getContext(), mBasicBlock);
166
167    //Display the IR that has been generated by this module.
168    if (LLVM_UNLIKELY(DumpGeneratedIR)) {
169        mMod->dump();
170    }
171    //Create a verifier.  The verifier will print an error message if our module is malformed in any way.
172    verifyModule(*mMod, &dbgs());
173
174    mExecutionEngine->finalizeObject();
175
176    //Return the required size of the carry queue and a pointer to the process_block function.
177    return CompiledPabloFunction(mCarryQueueSize, mAdvanceQueueSize, mFunction, mExecutionEngine);
178}
179
180void PabloCompiler::DefineTypes()
181{
182    StructType * structBasisBits = mMod->getTypeByName("struct.Basis_bits");
183    if (structBasisBits == nullptr) {
184        structBasisBits = StructType::create(mMod->getContext(), "struct.Basis_bits");
185    }
186    std::vector<Type*>StructTy_struct_Basis_bits_fields;
187    for (int i = 0; i != mBasisBits.size(); i++)
188    {
189        StructTy_struct_Basis_bits_fields.push_back(mBitBlockType);
190    }
191    if (structBasisBits->isOpaque()) {
192        structBasisBits->setBody(StructTy_struct_Basis_bits_fields, /*isPacked=*/false);
193    }
194    mBasisBitsInputPtr = PointerType::get(structBasisBits, 0);
195
196    std::vector<Type*>functionTypeArgs;
197    functionTypeArgs.push_back(mBasisBitsInputPtr);
198
199    //The carry q array.
200    //A pointer to the BitBlock vector.
201    functionTypeArgs.push_back(PointerType::get(mBitBlockType, 0));
202    // Advance q array
203    functionTypeArgs.push_back(PointerType::get(mBitBlockType, 0));
204
205    //The output structure.
206    StructType * outputStruct = mMod->getTypeByName("struct.Output");
207    if (!outputStruct) {
208        outputStruct = StructType::create(mMod->getContext(), "struct.Output");
209    }
210    if (outputStruct->isOpaque()) {
211        std::vector<Type*>fields;
212        fields.push_back(mBitBlockType);
213        fields.push_back(mBitBlockType);
214        outputStruct->setBody(fields, /*isPacked=*/false);
215    }
216    PointerType* outputStructPtr = PointerType::get(outputStruct, 0);
217
218    //The &output parameter.
219    functionTypeArgs.push_back(outputStructPtr);
220
221    mFunctionType = FunctionType::get(
222     /*Result=*/Type::getVoidTy(mMod->getContext()),
223     /*Params=*/functionTypeArgs,
224     /*isVarArg=*/false);
225}
226
227void PabloCompiler::DeclareFunctions()
228{
229    //This function can be used for testing to print the contents of a register from JIT'd code to the terminal window.
230    mPrintRegisterFunction = mMod->getOrInsertFunction("wrapped_print_register", Type::getVoidTy(getGlobalContext()), mBitBlockType, NULL);
231    mExecutionEngine->addGlobalMapping(cast<GlobalValue>(mPrintRegisterFunction), (void *)&wrapped_print_register);
232    // to call->  b.CreateCall(mFunc_print_register, unicode_category);
233
234#ifdef USE_UADD_OVERFLOW
235#ifdef USE_TWO_UADD_OVERFLOW
236    // Type Definitions for llvm.uadd.with.overflow.carryin.i128 or .i256
237    std::vector<Type*>StructTy_0_fields;
238    StructTy_0_fields.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
239    StructTy_0_fields.push_back(IntegerType::get(mMod->getContext(), 1));
240    StructType *StructTy_0 = StructType::get(mMod->getContext(), StructTy_0_fields, /*isPacked=*/false);
241
242    std::vector<Type*>FuncTy_1_args;
243    FuncTy_1_args.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
244    FuncTy_1_args.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
245    FunctionType* FuncTy_1 = FunctionType::get(
246                                              /*Result=*/StructTy_0,
247                                              /*Params=*/FuncTy_1_args,
248                                              /*isVarArg=*/false);
249
250    mFunctionUaddOverflow = mMod->getFunction("llvm.uadd.with.overflow.i" +
251                                              std::to_string(BLOCK_SIZE));
252    if (!mFunctionUaddOverflow) {
253        mFunctionUaddOverflow= Function::Create(
254          /*Type=*/ FuncTy_1,
255          /*Linkage=*/ GlobalValue::ExternalLinkage,
256          /*Name=*/ "llvm.uadd.with.overflow.i" + std::to_string(BLOCK_SIZE), mMod); // (external, no body)
257        mFunctionUaddOverflow->setCallingConv(CallingConv::C);
258    }
259    AttributeSet mFunctionUaddOverflowPAL;
260    {
261        SmallVector<AttributeSet, 4> Attrs;
262        AttributeSet PAS;
263        {
264          AttrBuilder B;
265          B.addAttribute(Attribute::NoUnwind);
266          B.addAttribute(Attribute::ReadNone);
267          PAS = AttributeSet::get(mMod->getContext(), ~0U, B);
268        }
269
270        Attrs.push_back(PAS);
271        mFunctionUaddOverflowPAL = AttributeSet::get(mMod->getContext(), Attrs);
272    }
273    mFunctionUaddOverflow->setAttributes(mFunctionUaddOverflowPAL);
274#else
275    // Type Definitions for llvm.uadd.with.overflow.carryin.i128 or .i256
276    std::vector<Type*>StructTy_0_fields;
277    StructTy_0_fields.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
278    StructTy_0_fields.push_back(IntegerType::get(mMod->getContext(), 1));
279    StructType *StructTy_0 = StructType::get(mMod->getContext(), StructTy_0_fields, /*isPacked=*/false);
280
281    std::vector<Type*>FuncTy_1_args;
282    FuncTy_1_args.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
283    FuncTy_1_args.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
284    FuncTy_1_args.push_back(IntegerType::get(mMod->getContext(), 1));
285    FunctionType* FuncTy_1 = FunctionType::get(
286                                              /*Result=*/StructTy_0,
287                                              /*Params=*/FuncTy_1_args,
288                                              /*isVarArg=*/false);
289
290    mFunctionUaddOverflowCarryin = mMod->getFunction("llvm.uadd.with.overflow.carryin.i" +
291                                              std::to_string(BLOCK_SIZE));
292    if (!mFunctionUaddOverflowCarryin) {
293        mFunctionUaddOverflowCarryin = Function::Create(
294          /*Type=*/ FuncTy_1,
295          /*Linkage=*/ GlobalValue::ExternalLinkage,
296          /*Name=*/ "llvm.uadd.with.overflow.carryin.i" + std::to_string(BLOCK_SIZE), mMod); // (external, no body)
297        mFunctionUaddOverflowCarryin->setCallingConv(CallingConv::C);
298    }
299    AttributeSet mFunctionUaddOverflowCarryinPAL;
300    {
301        SmallVector<AttributeSet, 4> Attrs;
302        AttributeSet PAS;
303        {
304          AttrBuilder B;
305          B.addAttribute(Attribute::NoUnwind);
306          B.addAttribute(Attribute::ReadNone);
307          PAS = AttributeSet::get(mMod->getContext(), ~0U, B);
308        }
309
310        Attrs.push_back(PAS);
311        mFunctionUaddOverflowCarryinPAL = AttributeSet::get(mMod->getContext(), Attrs);
312    }
313    mFunctionUaddOverflowCarryin->setAttributes(mFunctionUaddOverflowCarryinPAL);
314#endif
315#endif
316
317    //Starts on process_block
318    SmallVector<AttributeSet, 5> Attrs;
319    AttributeSet PAS;
320    {
321        AttrBuilder B;
322        B.addAttribute(Attribute::ReadOnly);
323        B.addAttribute(Attribute::NoCapture);
324        PAS = AttributeSet::get(mMod->getContext(), 1U, B);
325    }
326    Attrs.push_back(PAS);
327    {
328        AttrBuilder B;
329        B.addAttribute(Attribute::NoCapture);
330        PAS = AttributeSet::get(mMod->getContext(), 2U, B);
331    }
332    Attrs.push_back(PAS);
333    {
334        AttrBuilder B;
335        B.addAttribute(Attribute::NoCapture);
336        PAS = AttributeSet::get(mMod->getContext(), 3U, B);
337    }
338    Attrs.push_back(PAS);
339    {
340        AttrBuilder B;
341        B.addAttribute(Attribute::NoCapture);
342        PAS = AttributeSet::get(mMod->getContext(), 4U, B);
343    }
344    Attrs.push_back(PAS);
345    {
346        AttrBuilder B;
347        B.addAttribute(Attribute::NoUnwind);
348        B.addAttribute(Attribute::UWTable);
349        PAS = AttributeSet::get(mMod->getContext(), ~0U, B);
350    }
351    AttributeSet AttrSet = AttributeSet::get(mMod->getContext(), Attrs);
352
353    //Create the function that will be generated.
354    mFunction = mMod->getFunction("process_block");
355    if (!mFunction) {
356        mFunction = Function::Create(
357            /*Type=*/mFunctionType,
358            /*Linkage=*/GlobalValue::ExternalLinkage,
359            /*Name=*/"process_block", mMod);
360        mFunction->setCallingConv(CallingConv::C);
361    }
362    mFunction->setAttributes(AttrSet);
363}
364
365//
366// CarryNumbering: sequential numbers associated with each
367// carry-generating operation encountered in a traversal of the
368// Pablo AST.    Carry-generating operations are MatchStar, ScanThru,
369// and so on.
370// AdvanceNumbering: sequential numbers associated with each Advance
371// operation encountered in tree traversal, with the following modifications.
372//   (a) an additional AdvanceQueue entry is created for each if-statement
373//       having more than one carry or advance opreation within it.  This
374//       additional entry is a summary entry which must be nonzero to
375//       indicate that there are carry or advance bits associated with
376//       any operation within the if-structure (at any nesting level).
377//   (b) advancing by a large amount may require multiple advance entries.
378//       the number of advance entries for an operation Adv(x, n) is
379//       (n - 1) / BLOCK_SIZE + 1
380//
381// Note that the initial carry/advance numbering is determined by the
382// Examine function.  The values determined at this stage must be consistent
383// with the later numbering calculated during actual statement compilation.
384//
385// Examine precomputes some CarryNumbering and AdvanceNumbering, as
386// well as mMaxNestingDepth of while loops.
387//
388void PabloCompiler::Examine(StatementList & stmts) {
389    for (Statement * stmt : stmts) {
390
391        if (Advance * adv = dyn_cast<Advance>(stmt)) {
392            mAdvanceQueueSize += (((adv->getAdvanceAmount() - 1) / BLOCK_SIZE) + 1);
393        }
394        else if (isa<MatchStar>(stmt) || isa<ScanThru>(stmt)) {
395            ++mCarryQueueSize;
396        }
397        if (Call * call = dyn_cast<Call>(stmt)) {
398            mCalleeMap.insert(std::make_pair(call->getCallee(), nullptr));
399        }
400        else if (If * ifStatement = dyn_cast<If>(stmt)) {
401            const auto preIfCarryCount = mCarryQueueSize;
402            const auto preIfAdvanceCount = mAdvanceQueueSize;
403            Examine(ifStatement->getBody());
404            int ifCarryCount = mCarryQueueSize - preIfCarryCount;
405            int ifAdvanceCount = mAdvanceQueueSize - preIfAdvanceCount;
406            if ((ifCarryCount + ifAdvanceCount) > 1) {
407              ++mAdvanceQueueSize;
408              ++ifAdvanceCount;
409            }
410            ifStatement->setInclusiveCarryCount(ifCarryCount);
411            ifStatement->setInclusiveAdvanceCount(ifAdvanceCount);
412        }
413        else if (While * whileStatement = dyn_cast<While>(stmt)) {
414            const auto preWhileCarryCount = mCarryQueueSize;
415            const auto preWhileAdvanceCount = mAdvanceQueueSize;
416            mMaxNestingDepth = std::max(mMaxNestingDepth, ++mNestingDepth);
417            Examine(whileStatement->getBody());
418            --mNestingDepth;
419            whileStatement->setInclusiveCarryCount(mCarryQueueSize - preWhileCarryCount);
420            whileStatement->setInclusiveAdvanceCount(mAdvanceQueueSize - preWhileAdvanceCount);
421        }
422    }
423}
424
425void PabloCompiler::DeclareCallFunctions() {
426    for (auto mapping : mCalleeMap) {
427        const String * callee = mapping.first;
428        //std::cerr << callee->str() << " to be declared\n";
429        auto ei = mExternalMap.find(callee->value());
430        if (ei != mExternalMap.end()) {
431            void * fn_ptr = ei->second;
432            //std::cerr << "Ptr found:" <<  std::hex << ((intptr_t) fn_ptr) << std::endl;
433            Value * externalValue = mMod->getOrInsertFunction(callee->value(), mBitBlockType, mBasisBitsInputPtr, NULL);
434            if (LLVM_UNLIKELY(externalValue == nullptr)) {
435                throw std::runtime_error("Could not create static method call for external function \"" + callee->to_string() + "\"");
436            }
437            mExecutionEngine->addGlobalMapping(cast<GlobalValue>(externalValue), fn_ptr);
438            mCalleeMap[callee] = externalValue;
439        }
440        else {
441            throw std::runtime_error("External function \"" + callee->to_string() + "\" not installed");
442        }
443    }
444}
445
446void PabloCompiler::compileStatements(const StatementList & stmts) {
447    for (const Statement * statement : stmts) {
448        compileStatement(statement);
449    }
450}
451
452void PabloCompiler::compileIf(const If * ifStatement) {
453        //
454        //  The If-ElseZero stmt:
455        //  if <predicate:expr> then <body:stmt>* elsezero <defined:var>* endif
456        //  If the value of the predicate is nonzero, then determine the values of variables
457        //  <var>* by executing the given statements.  Otherwise, the value of the
458        //  variables are all zero.  Requirements: (a) no variable that is defined within
459        //  the body of the if may be accessed outside unless it is explicitly
460        //  listed in the variable list, (b) every variable in the defined list receives
461        //  a value within the body, and (c) the logical consequence of executing
462        //  the statements in the event that the predicate is zero is that the
463        //  values of all defined variables indeed work out to be 0.
464        //
465        //  Simple Implementation with Phi nodes:  a phi node in the if exit block
466        //  is inserted for each variable in the defined variable list.  It receives
467        //  a zero value from the ifentry block and the defined value from the if
468        //  body.
469        //
470        BasicBlock * ifEntryBlock = mBasicBlock;  // The block we are in.
471        BasicBlock * ifBodyBlock = BasicBlock::Create(mMod->getContext(), "if.body", mFunction, 0);
472        BasicBlock * ifEndBlock = BasicBlock::Create(mMod->getContext(), "if.end", mFunction, 0);
473       
474        const auto baseCarryQueueIdx = mCarryQueueIdx;
475        const auto baseAdvanceQueueIdx = mAdvanceQueueIdx;
476       
477        int ifCarryCount = ifStatement->getInclusiveCarryCount();
478        int ifAdvanceCount = ifStatement->getInclusiveAdvanceCount();
479        //  Carry/Advance queue strategy.   
480        //  If there are any carries or advances at any nesting level within the
481        //  if statement, then the statement must be executed.   A "summary"
482        //  carryover variable is determined for this purpose, consisting of the
483        //  or of all of the carry and advance variables within the if.
484        //  This variable is determined as follows.
485        //  (a)  If the CarryCount and AdvanceCount are both 0, there is no summary variable.
486        //  (b)  If the CarryCount is 1 and the AdvanceCount is 0, then the summary
487        //       carryover variable is just the single carry queue entry.
488        //  (c)  If the CarryCount is 0 and the AdvanceCount is 1, then the summary
489        //       carryover variable is just the advance carry queue entry.
490        //  (d)  Otherwise, an additional advance queue entry is created for the
491        //       summary variable.
492        //  Note that the test for cases (c) and (d) may be combined: the summary carryover
493        //  variable is just last advance queue entry.
494        //
495       
496        IRBuilder<> b_entry(ifEntryBlock);
497        mBasicBlock = ifEntryBlock;
498        Value* if_test_value = compileExpression(ifStatement->getCondition());
499       
500        if ((ifCarryCount == 1) && (ifAdvanceCount == 0)) {
501            Value* last_if_pending_carries = genCarryInLoad(baseCarryQueueIdx);
502            if_test_value = b_entry.CreateOr(if_test_value, last_if_pending_carries);
503        }
504        else if ((ifCarryCount > 0) || (ifAdvanceCount > 0)) {
505            Value* last_if_pending_advances = genAdvanceInLoad(baseAdvanceQueueIdx + ifAdvanceCount - 1);
506            if_test_value = b_entry.CreateOr(if_test_value, last_if_pending_advances);
507        }
508        b_entry.CreateCondBr(genBitBlockAny(if_test_value), ifEndBlock, ifBodyBlock);
509
510        // Entry processing is complete, now handle the body of the if.
511        mBasicBlock = ifBodyBlock;
512        compileStatements(ifStatement->getBody());
513
514        // If we compiled an If or a While statement, we won't be in the same basic block as before.
515        // Create the branch from the current basic block to the end block.
516        IRBuilder<> bIfBody(mBasicBlock);
517        // After the recursive compile, now insert the code to compute the summary
518        // carry over variable.
519       
520        if ((ifCarryCount + ifAdvanceCount) > 1) {
521            // A summary variable is needed.
522
523            Value * carry_summary = mZeroInitializer;
524            for (int c = baseCarryQueueIdx; c < baseCarryQueueIdx + ifCarryCount; c++) {
525                int s = mCarryQueueSummaryIdx[c];
526                if (s == -1) {
527                    Value* carryq_value = mCarryQueueVector[c];
528                    if (carry_summary == mZeroInitializer) {
529                        carry_summary = carryq_value;
530                    }
531                    else {
532                        carry_summary = bIfBody.CreateOr(carry_summary, carryq_value);
533                    }
534                    mCarryQueueSummaryIdx[c] = mAdvanceQueueIdx;
535                }
536            }
537            // Note that the limit in the following uses -1, because
538            // last entry of the advance queue is for the summary variable.
539            for (int c = baseAdvanceQueueIdx; c < baseAdvanceQueueIdx + ifAdvanceCount - 1; c++) {
540                int s = mAdvanceQueueSummaryIdx[c];
541                if (s == -1 ) {
542                    Value* advance_q_value = mAdvanceQueueVector[c];
543                    if (carry_summary == mZeroInitializer) {
544                        carry_summary = advance_q_value;
545                    }
546                    else {
547                        carry_summary = bIfBody.CreateOr(carry_summary, advance_q_value);
548                    }
549                    mAdvanceQueueSummaryIdx[c] = mAdvanceQueueIdx;
550                }
551            }
552            genAdvanceOutStore(carry_summary, mAdvanceQueueIdx++);
553        }
554        bIfBody.CreateBr(ifEndBlock);
555        //End Block
556        IRBuilder<> bEnd(ifEndBlock);
557        for (const PabloAST * node : ifStatement->getDefined()) {
558            const Assign * assign = cast<Assign>(node);
559            PHINode * phi = bEnd.CreatePHI(mBitBlockType, 2, assign->getName()->value());
560            auto f = mMarkerMap.find(assign);
561            assert (f != mMarkerMap.end());
562            phi->addIncoming(mZeroInitializer, ifEntryBlock);
563            phi->addIncoming(f->second, mBasicBlock);
564            mMarkerMap[assign] = phi;
565        }
566        // Create the phi Node for the summary variable.
567        if (ifAdvanceCount >= 1) {
568            // final AdvanceQ entry is summary variable.
569            PHINode * summary_phi = bEnd.CreatePHI(mBitBlockType, 2, "summary");
570            summary_phi->addIncoming(mZeroInitializer, ifEntryBlock);
571            summary_phi->addIncoming(mAdvanceQueueVector[mAdvanceQueueIdx-1], mBasicBlock);
572            mAdvanceQueueVector[mAdvanceQueueIdx-1] = summary_phi;
573        }
574        else if (ifCarryCount == 1) {
575            PHINode * summary_phi = bEnd.CreatePHI(mBitBlockType, 2, "summary");
576            summary_phi->addIncoming(mZeroInitializer, ifEntryBlock);
577            summary_phi->addIncoming(mCarryQueueVector[baseCarryQueueIdx], mBasicBlock);
578            mCarryQueueVector[baseCarryQueueIdx] = summary_phi;
579        }
580       
581        // Set the basic block to the new end block
582        mBasicBlock = ifEndBlock;
583}
584
585void PabloCompiler::compileWhile(const While * whileStatement) {
586        const auto baseCarryQueueIdx = mCarryQueueIdx;
587        const auto baseAdvanceQueueIdx = mAdvanceQueueIdx;
588        if (mNestingDepth == 0) {
589            for (auto i = 0; i != whileStatement->getInclusiveCarryCount(); ++i) {
590                genCarryInLoad(baseCarryQueueIdx + i);
591            }
592            for (auto i = 0; i != whileStatement->getInclusiveAdvanceCount(); ++i) {
593                genAdvanceInLoad(baseAdvanceQueueIdx + i);
594            }
595        }
596
597        SmallVector<const Next*, 4> nextNodes;
598        for (const PabloAST * node : whileStatement->getBody()) {
599            if (isa<Next>(node)) {
600                nextNodes.push_back(cast<Next>(node));
601            }
602        }
603
604        // Compile the initial iteration statements; the calls to genCarryOutStore will update the
605        // mCarryQueueVector with the appropriate values. Although we're not actually entering a new basic
606        // block yet, increment the nesting depth so that any calls to genCarryInLoad or genCarryOutStore
607        // will refer to the previous value.
608
609        ++mNestingDepth;
610
611        compileStatements(whileStatement->getBody());
612
613        // Reset the carry queue index. Note: this ought to be changed in the future. Currently this assumes
614        // that compiling the while body twice will generate the equivalent IR. This is not necessarily true
615        // but works for now.
616        mCarryQueueIdx = baseCarryQueueIdx;
617        mAdvanceQueueIdx = baseAdvanceQueueIdx;
618
619        BasicBlock* whileCondBlock = BasicBlock::Create(mMod->getContext(), "while.cond", mFunction, 0);
620        BasicBlock* whileBodyBlock = BasicBlock::Create(mMod->getContext(), "while.body", mFunction, 0);
621        BasicBlock* whileEndBlock = BasicBlock::Create(mMod->getContext(), "while.end", mFunction, 0);
622
623        // Note: compileStatements may update the mBasicBlock pointer if the body contains nested loops. It
624        // may not be same one that we entered the function with.
625        IRBuilder<> bEntry(mBasicBlock);
626        bEntry.CreateBr(whileCondBlock);
627
628        // CONDITION BLOCK
629        IRBuilder<> bCond(whileCondBlock);
630        // generate phi nodes for any carry propogating instruction
631        int whileCarryCount = whileStatement->getInclusiveCarryCount();
632        int whileAdvanceCount = whileStatement->getInclusiveAdvanceCount();
633        std::vector<PHINode*> phiNodes(whileCarryCount + whileAdvanceCount + nextNodes.size());
634        unsigned index = 0;
635        for (index = 0; index != whileCarryCount; ++index) {
636            PHINode * phi = bCond.CreatePHI(mBitBlockType, 2);
637            phi->addIncoming(mCarryQueueVector[baseCarryQueueIdx + index], mBasicBlock);
638            mCarryQueueVector[baseCarryQueueIdx + index] = mZeroInitializer; // (use phi for multi-carry mode.)
639            phiNodes[index] = phi;
640        }
641        for (int i = 0; i != whileAdvanceCount; ++i) {
642            PHINode * phi = bCond.CreatePHI(mBitBlockType, 2);
643            phi->addIncoming(mAdvanceQueueVector[baseAdvanceQueueIdx + i], mBasicBlock);
644            mAdvanceQueueVector[baseAdvanceQueueIdx + i] = mZeroInitializer; // (use phi for multi-carry mode.)
645            phiNodes[index++] = phi;
646        }
647        // and for any Next nodes in the loop body
648        for (const Next * n : nextNodes) {
649            PHINode * phi = bCond.CreatePHI(mBitBlockType, 2, n->getName()->value());
650            auto f = mMarkerMap.find(n->getInitial());
651            assert (f != mMarkerMap.end());
652            phi->addIncoming(f->second, mBasicBlock);
653            mMarkerMap[n->getInitial()] = phi;
654            phiNodes[index++] = phi;
655        }
656
657        mBasicBlock = whileCondBlock;
658        bCond.CreateCondBr(genBitBlockAny(compileExpression(whileStatement->getCondition())), whileEndBlock, whileBodyBlock);
659
660        // BODY BLOCK
661        mBasicBlock = whileBodyBlock;
662        compileStatements(whileStatement->getBody());
663        // update phi nodes for any carry propogating instruction
664        IRBuilder<> bWhileBody(mBasicBlock);
665        for (index = 0; index != whileStatement->getInclusiveCarryCount(); ++index) {
666            Value * carryOut = bWhileBody.CreateOr(phiNodes[index], mCarryQueueVector[baseCarryQueueIdx + index]);
667            PHINode * phi = phiNodes[index];
668            phi->addIncoming(carryOut, mBasicBlock);
669            mCarryQueueVector[baseCarryQueueIdx + index] = phi;
670        }
671        for (int i = 0; i != whileAdvanceCount; ++i) {
672            Value * advOut = bWhileBody.CreateOr(phiNodes[index], mAdvanceQueueVector[baseAdvanceQueueIdx + i]);
673            PHINode * phi = phiNodes[index++];
674            phi->addIncoming(advOut, mBasicBlock);
675            mAdvanceQueueVector[baseAdvanceQueueIdx + i] = phi;
676        }
677        // and for any Next nodes in the loop body
678        for (const Next * n : nextNodes) {
679            auto f = mMarkerMap.find(n->getInitial());
680            assert (f != mMarkerMap.end());
681            PHINode * phi = phiNodes[index++];
682            phi->addIncoming(f->second, mBasicBlock);
683            mMarkerMap[n->getInitial()] = phi;
684        }
685
686        bWhileBody.CreateBr(whileCondBlock);
687
688        // EXIT BLOCK
689        mBasicBlock = whileEndBlock;
690        if (--mNestingDepth == 0) {
691            for (index = 0; index != whileCarryCount; ++index) {
692                genCarryOutStore(phiNodes[index], baseCarryQueueIdx + index);
693            }
694            for (index = 0; index != whileAdvanceCount; ++index) {
695                genAdvanceOutStore(phiNodes[whileCarryCount + index], baseAdvanceQueueIdx + index);
696            }
697        }
698 
699}
700
701void PabloCompiler::compileStatement(const Statement * stmt)
702{
703    IRBuilder<> b(mBasicBlock);
704    if (const Assign * assign = dyn_cast<const Assign>(stmt)) {
705        Value * expr = compileExpression(assign->getExpr());
706        mMarkerMap[assign] = expr;
707        if (LLVM_UNLIKELY(assign->isOutputAssignment())) {
708            SetOutputValue(expr, assign->getOutputIndex());
709        }
710    }
711    else if (const Next * next = dyn_cast<const Next>(stmt)) {
712        Value * expr = compileExpression(next->getExpr());
713        mMarkerMap[next->getInitial()] = expr;
714    }
715    else if (const If * ifStatement = dyn_cast<const If>(stmt))
716    {
717        compileIf(ifStatement);
718    }
719    else if (const While * whileStatement = dyn_cast<const While>(stmt))
720    {
721        compileWhile(whileStatement);
722    }
723    else if (const Call* call = dyn_cast<Call>(stmt)) {
724        //Call the callee once and store the result in the marker map.
725        auto mi = mMarkerMap.find(call);
726        if (mi == mMarkerMap.end()) {
727            auto ci = mCalleeMap.find(call->getCallee());
728            if (LLVM_UNLIKELY(ci == mCalleeMap.end())) {
729                throw std::runtime_error("Unexpected error locating static function for \"" + call->getCallee()->to_string() + "\"");
730            }
731            mi = mMarkerMap.insert(std::make_pair(call, b.CreateCall(ci->second, mBasisBitsAddr))).first;
732        }
733        // return mi->second;
734    }
735    else if (const And * pablo_and = dyn_cast<And>(stmt)) {
736        Value * expr = b.CreateAnd(compileExpression(pablo_and->getExpr1()), compileExpression(pablo_and->getExpr2()), "and");
737        mMarkerMap[pablo_and] = expr;
738        // return expr;
739    }
740    else if (const Or * pablo_or = dyn_cast<Or>(stmt)) {
741        Value * expr = b.CreateOr(compileExpression(pablo_or->getExpr1()), compileExpression(pablo_or->getExpr2()), "or");
742        mMarkerMap[pablo_or] = expr;
743        // return expr;
744    }
745    else if (const Xor * pablo_xor = dyn_cast<Xor>(stmt)) {
746        Value * expr = b.CreateXor(compileExpression(pablo_xor->getExpr1()), compileExpression(pablo_xor->getExpr2()), "xor");
747        mMarkerMap[pablo_xor] = expr;
748        // return expr;
749    }
750    else if (const Sel * sel = dyn_cast<Sel>(stmt)) {
751        Value* ifMask = compileExpression(sel->getCondition());
752        Value* ifTrue = b.CreateAnd(ifMask, compileExpression(sel->getTrueExpr()));
753        Value* ifFalse = b.CreateAnd(genNot(ifMask), compileExpression(sel->getFalseExpr()));
754        Value * expr = b.CreateOr(ifTrue, ifFalse);
755        mMarkerMap[sel] = expr;
756        // return expr;
757    }
758    else if (const Not * pablo_not = dyn_cast<Not>(stmt)) {
759        Value * expr = genNot(compileExpression(pablo_not->getExpr()));
760        mMarkerMap[pablo_not] = expr;
761        // return expr;
762    }
763    else if (const Advance * adv = dyn_cast<Advance>(stmt)) {
764        Value* strm_value = compileExpression(adv->getExpr());
765        int shift = adv->getAdvanceAmount();
766        Value * expr = genAdvanceWithCarry(strm_value, shift);
767        mMarkerMap[adv] = expr;
768        // return expr;
769    }
770    else if (const MatchStar * mstar = dyn_cast<MatchStar>(stmt))
771    {
772        Value * marker = compileExpression(mstar->getMarker());
773        Value * cc = compileExpression(mstar->getCharClass());
774        Value * marker_and_cc = b.CreateAnd(marker, cc);
775        Value * expr = b.CreateOr(b.CreateXor(genAddWithCarry(marker_and_cc, cc), cc), marker, "matchstar");
776        mMarkerMap[mstar] = expr;
777        // return expr;
778    }
779    else if (const ScanThru * sthru = dyn_cast<ScanThru>(stmt))
780    {
781        Value * marker_expr = compileExpression(sthru->getScanFrom());
782        Value * cc_expr = compileExpression(sthru->getScanThru());
783        Value * expr = b.CreateAnd(genAddWithCarry(marker_expr, cc_expr), genNot(cc_expr), "scanthru");
784        mMarkerMap[sthru] = expr;
785        // return expr;
786    }
787    else {
788        PabloPrinter::print(stmt, std::cerr);
789        throw std::runtime_error("Unrecognized Pablo Statement! can't compile.");
790    }
791}
792
793Value * PabloCompiler::compileExpression(const PabloAST * expr) {
794    if (isa<Ones>(expr)) {
795        return mOneInitializer;
796    }
797    else if (isa<Zeroes>(expr)) {
798        return mZeroInitializer;
799    }
800    else if (const Next * next = dyn_cast<Next>(expr)) {
801        expr = next->getInitial();
802    }
803    auto f = mMarkerMap.find(expr);
804    if (f == mMarkerMap.end()) {
805        std::stringstream str;
806        str << "\"";
807        PabloPrinter::print(expr, str);
808        str << "\" was used before definition!";
809        throw std::runtime_error(str.str());
810    }
811    return f->second;
812}
813
814
815#ifdef USE_UADD_OVERFLOW
816#ifdef USE_TWO_UADD_OVERFLOW
817PabloCompiler::SumWithOverflowPack PabloCompiler::callUaddOverflow(Value* int128_e1, Value* int128_e2) {
818    std::vector<Value*> struct_res_params;
819    struct_res_params.push_back(int128_e1);
820    struct_res_params.push_back(int128_e2);
821    CallInst* struct_res = CallInst::Create(mFunctionUaddOverflow, struct_res_params, "uadd_overflow_res", mBasicBlock);
822    struct_res->setCallingConv(CallingConv::C);
823    struct_res->setTailCall(false);
824    AttributeSet struct_res_PAL;
825    struct_res->setAttributes(struct_res_PAL);
826
827    SumWithOverflowPack ret;
828
829    std::vector<unsigned> int128_sum_indices;
830    int128_sum_indices.push_back(0);
831    ret.sum = ExtractValueInst::Create(struct_res, int128_sum_indices, "sum", mBasicBlock);
832
833    std::vector<unsigned> int1_obit_indices;
834    int1_obit_indices.push_back(1);
835    ret.obit = ExtractValueInst::Create(struct_res, int1_obit_indices, "obit", mBasicBlock);
836
837    return ret;
838}
839#else
840PabloCompiler::SumWithOverflowPack PabloCompiler::callUaddOverflow(Value* int128_e1, Value* int128_e2, Value* int1_cin) {
841    std::vector<Value*> struct_res_params;
842    struct_res_params.push_back(int128_e1);
843    struct_res_params.push_back(int128_e2);
844    struct_res_params.push_back(int1_cin);
845    CallInst* struct_res = CallInst::Create(mFunctionUaddOverflowCarryin, struct_res_params, "uadd_overflow_res", mBasicBlock);
846    struct_res->setCallingConv(CallingConv::C);
847    struct_res->setTailCall(false);
848    AttributeSet struct_res_PAL;
849    struct_res->setAttributes(struct_res_PAL);
850
851    SumWithOverflowPack ret;
852
853    std::vector<unsigned> int128_sum_indices;
854    int128_sum_indices.push_back(0);
855    ret.sum = ExtractValueInst::Create(struct_res, int128_sum_indices, "sum", mBasicBlock);
856
857    std::vector<unsigned> int1_obit_indices;
858    int1_obit_indices.push_back(1);
859    ret.obit = ExtractValueInst::Create(struct_res, int1_obit_indices, "obit", mBasicBlock);
860
861    return ret;
862}
863#endif
864#endif
865
866
867Value* PabloCompiler::genAddWithCarry(Value* e1, Value* e2) {
868    IRBuilder<> b(mBasicBlock);
869
870    //CarryQ - carry in.
871    const int carryIdx = mCarryQueueIdx++;
872    Value* carryq_value = genCarryInLoad(carryIdx);
873#ifdef USE_TWO_UADD_OVERFLOW
874    //This is the ideal implementation, which uses two uadd.with.overflow
875    //The back end should be able to recognize this pattern and combine it into uadd.with.overflow.carryin
876    CastInst* int128_e1 = new BitCastInst(e1, IntegerType::get(mMod->getContext(), BLOCK_SIZE), "e1_128", mBasicBlock);
877    CastInst* int128_e2 = new BitCastInst(e2, IntegerType::get(mMod->getContext(), BLOCK_SIZE), "e2_128", mBasicBlock);
878    CastInst* int128_carryq_value = new BitCastInst(carryq_value, IntegerType::get(mMod->getContext(), BLOCK_SIZE), "carryq_128", mBasicBlock);
879
880    SumWithOverflowPack sumpack0, sumpack1;
881
882    sumpack0 = callUaddOverflow(int128_e1, int128_e2);
883    sumpack1 = callUaddOverflow(sumpack0.sum, int128_carryq_value);
884
885    Value* obit = b.CreateOr(sumpack0.obit, sumpack1.obit, "carry_bit");
886    Value* sum = b.CreateBitCast(sumpack1.sum, mBitBlockType, "ret_sum");
887
888    /*obit is the i1 carryout, zero extend and insert it into a v2i64 or v4i64 vector.*/
889    ConstantAggregateZero* const_packed_5 = ConstantAggregateZero::get(mBitBlockType);
890    ConstantInt* const_int32_6 = ConstantInt::get(mMod->getContext(), APInt(32, StringRef("0"), 10));
891    CastInst* int64_o0 = new ZExtInst(obit, IntegerType::get(mMod->getContext(), 64), "o0", mBasicBlock);
892    InsertElementInst* carry_out = InsertElementInst::Create(const_packed_5, int64_o0, const_int32_6, "carry_out", mBasicBlock);
893
894#elif defined USE_UADD_OVERFLOW
895    //use llvm.uadd.with.overflow.i128 or i256
896    CastInst* int128_e1 = new BitCastInst(e1, IntegerType::get(mMod->getContext(), BLOCK_SIZE), "e1_128", mBasicBlock);
897    CastInst* int128_e2 = new BitCastInst(e2, IntegerType::get(mMod->getContext(), BLOCK_SIZE), "e2_128", mBasicBlock);
898
899    //get i1 carryin from iBLOCK_SIZE
900    ConstantInt* const_int32_6 = ConstantInt::get(mMod->getContext(), APInt(32, StringRef("0"), 10));
901    ExtractElementInst * int64_carryq_value = ExtractElementInst::Create(carryq_value, const_int32_6, "carryq_64", mBasicBlock);
902    CastInst* int1_carryq_value = new TruncInst(int64_carryq_value, IntegerType::get(mMod->getContext(), 1), "carryq_1", mBasicBlock);
903
904    SumWithOverflowPack sumpack0;
905    sumpack0 = callUaddOverflow(int128_e1, int128_e2, int1_carryq_value);
906    Value* obit = sumpack0.obit;
907    Value* sum = b.CreateBitCast(sumpack0.sum, mBitBlockType, "sum");
908
909    /*obit is the i1 carryout, zero extend and insert it into a v2i64 or v4i64 vector.*/
910    ConstantAggregateZero* const_packed_5 = ConstantAggregateZero::get(mBitBlockType);
911    CastInst* int64_o0 = new ZExtInst(obit, IntegerType::get(mMod->getContext(), 64), "o0", mBasicBlock);
912    InsertElementInst* carry_out = InsertElementInst::Create(const_packed_5, int64_o0, const_int32_6, "carry_out", mBasicBlock);
913#elif (BLOCK_SIZE == 128)
914    //calculate carry through logical ops
915    Value* carrygen = b.CreateAnd(e1, e2, "carrygen");
916    Value* carryprop = b.CreateOr(e1, e2, "carryprop");
917    Value* digitsum = b.CreateAdd(e1, e2, "digitsum");
918    Value* partial = b.CreateAdd(digitsum, carryq_value, "partial");
919    Value* digitcarry = b.CreateOr(carrygen, b.CreateAnd(carryprop, genNot(partial)));
920    Value* mid_carry_in = genShiftLeft64(b.CreateLShr(digitcarry, 63), "mid_carry_in");
921
922    Value* sum = b.CreateAdd(partial, mid_carry_in, "sum");
923    Value* carry_out = genShiftHighbitToLow(b.CreateOr(carrygen, b.CreateAnd(carryprop, genNot(sum))), "carry_out");
924#else
925    //BLOCK_SIZE == 256, there is no other implementation
926    static_assert(false, "Add with carry for 256-bit bitblock requires USE_UADD_OVERFLOW");
927#endif //USE_TWO_UADD_OVERFLOW
928
929    genCarryOutStore(carry_out, carryIdx);
930    return sum;
931}
932
933Value* PabloCompiler::genCarryInLoad(const unsigned index) {
934    assert (index < mCarryQueueVector.size());
935    if (mNestingDepth == 0) {
936        IRBuilder<> b(mBasicBlock);
937        mCarryQueueVector[index] = b.CreateAlignedLoad(b.CreateGEP(mCarryQueuePtr, b.getInt64(index)), BLOCK_SIZE/8, false);
938    }
939    return mCarryQueueVector[index];
940}
941
942void PabloCompiler::genCarryOutStore(Value* carryOut, const unsigned index ) {
943    assert (carryOut);
944    assert (index < mCarryQueueVector.size());
945    if (mNestingDepth == 0) {
946        IRBuilder<> b(mBasicBlock);
947        b.CreateAlignedStore(carryOut, b.CreateGEP(mCarryQueuePtr, b.getInt64(index)), BLOCK_SIZE/8, false);
948    }
949    mCarryQueueSummaryIdx[index] = -1;
950    mCarryQueueVector[index] = carryOut;
951}
952
953Value* PabloCompiler::genAdvanceInLoad(const unsigned index) {
954    assert (index < mAdvanceQueueVector.size());
955    if (mNestingDepth == 0) {
956        IRBuilder<> b(mBasicBlock);
957        mAdvanceQueueVector[index] = b.CreateAlignedLoad(b.CreateGEP(mAdvanceQueuePtr, b.getInt64(index)), BLOCK_SIZE/8, false);
958    }
959    return mAdvanceQueueVector[index];
960}
961
962void PabloCompiler::genAdvanceOutStore(Value* advanceOut, const unsigned index ) {
963    assert (advanceOut);
964    assert (index < mAdvanceQueueVector.size());
965    if (mNestingDepth == 0) {
966        IRBuilder<> b(mBasicBlock);
967        b.CreateAlignedStore(advanceOut, b.CreateGEP(mAdvanceQueuePtr, b.getInt64(index)), BLOCK_SIZE/8, false);
968    }
969    mAdvanceQueueSummaryIdx[index] = -1;
970    mAdvanceQueueVector[index] = advanceOut;
971}
972
973inline Value* PabloCompiler::genBitBlockAny(Value* test) {
974    IRBuilder<> b(mBasicBlock);
975    Value* cast_marker_value_1 = b.CreateBitCast(test, IntegerType::get(mMod->getContext(), BLOCK_SIZE));
976    return b.CreateICmpEQ(cast_marker_value_1, ConstantInt::get(IntegerType::get(mMod->getContext(), BLOCK_SIZE), 0));
977}
978
979Value* PabloCompiler::genShiftHighbitToLow(Value* e, const Twine &namehint) {
980    IRBuilder<> b(mBasicBlock);
981    Value* i128_val = b.CreateBitCast(e, IntegerType::get(mMod->getContext(), BLOCK_SIZE));
982    return b.CreateBitCast(b.CreateLShr(i128_val, BLOCK_SIZE - 1, namehint), mBitBlockType);
983}
984
985Value* PabloCompiler::genShiftLeft64(Value* e, const Twine &namehint) {
986    IRBuilder<> b(mBasicBlock);
987    Value* i128_val = b.CreateBitCast(e, IntegerType::get(mMod->getContext(), BLOCK_SIZE));
988    return b.CreateBitCast(b.CreateShl(i128_val, 64, namehint), mBitBlockType);
989}
990
991inline Value* PabloCompiler::genNot(Value* expr) {
992    IRBuilder<> b(mBasicBlock);
993    return b.CreateXor(expr, mOneInitializer, "not");
994}
995Value* PabloCompiler::genAdvanceWithCarry(Value* strm_value, int shift_amount) {
996    IRBuilder<> b(mBasicBlock);
997    int advEntries = (shift_amount - 1) / BLOCK_SIZE + 1;
998    int block_shift = shift_amount % BLOCK_SIZE;
999    const auto storeIdx = mAdvanceQueueIdx;
1000    const auto loadIdx = mAdvanceQueueIdx + advEntries - 1;
1001    mAdvanceQueueIdx += advEntries;
1002    Value* result_value;
1003   
1004    if (advEntries == 1) {
1005        if (block_shift == 0) { 
1006            result_value = genAdvanceInLoad(loadIdx);
1007            //b.CreateCall(mFunc_print_register, result_value);
1008        }
1009#if (BLOCK_SIZE == 128) && !defined(USE_LONG_INTEGER_SHIFT)
1010        if (block_shift == 1) {
1011            Value* advanceq_value = genShiftHighbitToLow(genAdvanceInLoad(loadIdx));
1012            Value* srli_1_value = b.CreateLShr(strm_value, 63);
1013            Value* packed_shuffle;
1014            Constant* const_packed_1_elems [] = {b.getInt32(0), b.getInt32(2)};
1015            Constant* const_packed_1 = ConstantVector::get(const_packed_1_elems);
1016            packed_shuffle = b.CreateShuffleVector(advanceq_value, srli_1_value, const_packed_1);
1017
1018            Constant* const_packed_2_elems[] = {b.getInt64(1), b.getInt64(1)};
1019            Constant* const_packed_2 = ConstantVector::get(const_packed_2_elems);
1020
1021            Value* shl_value = b.CreateShl(strm_value, const_packed_2);
1022            result_value = b.CreateOr(shl_value, packed_shuffle, "advance");
1023        }
1024        else { //if (block_shift < BLOCK_SIZE) {
1025            // This is the preferred logic, but is too slow for the general case.
1026            // We need to speed up our custom LLVM for this code.
1027            Value* advanceq_longint = b.CreateBitCast(genAdvanceInLoad(loadIdx), IntegerType::get(mMod->getContext(), BLOCK_SIZE));
1028            Value* strm_longint = b.CreateBitCast(strm_value, IntegerType::get(mMod->getContext(), BLOCK_SIZE));
1029            Value* adv_longint = b.CreateOr(b.CreateShl(strm_longint, block_shift), b.CreateLShr(advanceq_longint, BLOCK_SIZE - block_shift), "advance");
1030            result_value = b.CreateBitCast(adv_longint, mBitBlockType);
1031        }
1032#else
1033        Value* advanceq_longint = b.CreateBitCast(genAdvanceInLoad(loadIdx), IntegerType::get(mMod->getContext(), BLOCK_SIZE));
1034        Value* strm_longint = b.CreateBitCast(strm_value, IntegerType::get(mMod->getContext(), BLOCK_SIZE));
1035        Value* adv_longint = b.CreateOr(b.CreateShl(strm_longint, block_shift), b.CreateLShr(advanceq_longint, BLOCK_SIZE - block_shift), "advance");
1036        result_value = b.CreateBitCast(adv_longint, mBitBlockType);
1037
1038#endif
1039    }
1040    else {
1041        if (block_shift == 0) {
1042            result_value = genAdvanceInLoad(loadIdx);
1043        }
1044        else { 
1045            // The advance is based on the two oldest bit blocks in the advance queue.
1046            Value* advanceq_longint = b.CreateBitCast(genAdvanceInLoad(loadIdx), IntegerType::get(mMod->getContext(), BLOCK_SIZE));
1047            Value* strm_longint = b.CreateBitCast(genAdvanceInLoad(loadIdx-1), IntegerType::get(mMod->getContext(), BLOCK_SIZE));
1048            Value* adv_longint = b.CreateOr(b.CreateShl(strm_longint, block_shift), b.CreateLShr(advanceq_longint, BLOCK_SIZE - block_shift), "longadvance");
1049            result_value = b.CreateBitCast(adv_longint, mBitBlockType);
1050            //b.CreateCall(mFunc_print_register, genAdvanceInLoad(loadIdx));
1051            //b.CreateCall(mFunc_print_register, genAdvanceInLoad(loadIdx-1));
1052            //b.CreateCall(mFunc_print_register, result_value);
1053        }
1054        // copy entries from previous blocks forward
1055        for (int i = loadIdx; i > storeIdx; i--) {
1056            genAdvanceOutStore(genAdvanceInLoad(i-1), i);
1057        }
1058    }
1059    genAdvanceOutStore(strm_value, storeIdx);
1060    return result_value;
1061}
1062
1063void PabloCompiler::SetOutputValue(Value * marker, const unsigned index) {
1064    IRBuilder<> b(mBasicBlock);
1065    if (marker->getType()->isPointerTy()) {
1066        marker = b.CreateAlignedLoad(marker, BLOCK_SIZE/8, false);
1067    }
1068    Value* indices[] = {b.getInt64(0), b.getInt32(index)};
1069    Value* gep = b.CreateGEP(mOutputAddrPtr, indices);
1070    b.CreateAlignedStore(marker, gep, BLOCK_SIZE/8, false);
1071}
1072
1073CompiledPabloFunction::CompiledPabloFunction(unsigned carryQSize, unsigned advanceQSize, Function * function, ExecutionEngine * executionEngine)
1074: CarryQueueSize(carryQSize)
1075, AdvanceQueueSize(advanceQSize)
1076, FunctionPointer(executionEngine->getPointerToFunction(function))
1077, mFunction(function)
1078, mExecutionEngine(executionEngine)
1079{
1080
1081}
1082
1083// Clean up the memory for the compiled function once we're finished using it.
1084CompiledPabloFunction::~CompiledPabloFunction() {
1085    if (mExecutionEngine) {
1086        assert (mFunction);
1087        // mExecutionEngine->freeMachineCodeForFunction(mFunction); // This function only prints a "not supported" message. Reevaluate with LLVM 3.6.
1088        delete mExecutionEngine;
1089    }
1090}
1091
1092}
Note: See TracBrowser for help on using the repository browser.