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

Last change on this file since 4641 was 4641, checked in by nmedfort, 4 years ago

Next nodes for While statements must be declared similar to how Defined Vars are for Ifs. (Temporarily breaks multiplexing correctness.)

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