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

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

Carry Manager system integrated into Pablo compiler

File size: 36.7 KB
Line 
1/*
2 *  Copyright (c) 2014-15 International Characters.
3 *  This software is licensed to the public under the Open Software License 3.0.
4 *  icgrep is a trademark of International Characters.
5 */
6
7#include <pablo/pablo_compiler.h>
8#include <pablo/codegenstate.h>
9#include <pablo/carry_data.h>
10#include <pablo/carry_manager.h>
11#include <pablo/printer_pablos.h>
12#include <cc/cc_namemap.hpp>
13#include <re/re_name.h>
14#include <stdexcept>
15#include <include/simd-lib/bitblock.hpp>
16#include <sstream>
17#include <llvm/IR/Verifier.h>
18#include <llvm/Pass.h>
19#include <llvm/PassManager.h>
20#include <llvm/ADT/SmallVector.h>
21#include <llvm/Analysis/Passes.h>
22#include <llvm/IR/BasicBlock.h>
23#include <llvm/IR/CallingConv.h>
24#include <llvm/IR/Constants.h>
25#include <llvm/IR/DataLayout.h>
26#include <llvm/IR/DerivedTypes.h>
27#include <llvm/IR/Function.h>
28#include <llvm/IR/GlobalVariable.h>
29#include <llvm/IR/InlineAsm.h>
30#include <llvm/IR/Instructions.h>
31#include <llvm/IR/LLVMContext.h>
32#include <llvm/IR/Module.h>
33#include <llvm/Support/FormattedStream.h>
34#include <llvm/Support/MathExtras.h>
35#include <llvm/Support/Casting.h>
36#include <llvm/Support/Compiler.h>
37#include <llvm/Support/Debug.h>
38#include <llvm/Support/TargetSelect.h>
39#include <llvm/Support/Host.h>
40#include <llvm/Transforms/Scalar.h>
41#include <llvm/ExecutionEngine/ExecutionEngine.h>
42#include <llvm/ExecutionEngine/MCJIT.h>
43#include <llvm/IRReader/IRReader.h>
44#include <llvm/Bitcode/ReaderWriter.h>
45#include <llvm/Support/MemoryBuffer.h>
46#include <llvm/IR/IRBuilder.h>
47#include <llvm/Support/CommandLine.h>
48#include <llvm/ADT/Twine.h>
49#include <iostream>
50
51static cl::OptionCategory eIRDumpOptions("LLVM IR Dump Options", "These options control dumping of LLVM IR.");
52static cl::opt<bool> DumpGeneratedIR("dump-generated-IR", cl::init(false), cl::desc("print LLVM IR generated by RE compilation"), cl::cat(eIRDumpOptions));
53
54static cl::OptionCategory fTracingOptions("Run-time Tracing Options", "These options control execution traces.");
55static 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));
56static cl::opt<bool> DumpTrace("dump-trace", cl::init(false), cl::desc("Generate dynamic traces of executed assignments."), cl::cat(fTracingOptions));
57
58extern "C" {
59  void wrapped_print_register(char * regName, BitBlock bit_block) {
60      print_register<BitBlock>(regName, bit_block);
61  }
62}
63
64namespace pablo {
65
66PabloCompiler::PabloCompiler(const std::vector<Var*> & basisBits)
67: mBasisBits(basisBits)
68#ifdef USE_LLVM_3_5
69, mMod(new Module("icgrep", getGlobalContext()))
70#else
71, mModOwner(make_unique<Module>("icgrep", getGlobalContext()))
72, mMod(mModOwner.get())
73#endif
74, mBuilder(&LLVM_Builder)
75, mCarryManager(nullptr)
76, mExecutionEngine(nullptr)
77, mBitBlockType(VectorType::get(IntegerType::get(mMod->getContext(), 64), BLOCK_SIZE / 64))
78, mBasisBitsInputPtr(nullptr)
79, mCarryDataPtr(nullptr)
80, mWhileDepth(0)
81, mIfDepth(0)
82, mZeroInitializer(ConstantAggregateZero::get(mBitBlockType))
83, mOneInitializer(ConstantVector::getAllOnesValue(mBitBlockType))
84, mFunctionType(nullptr)
85, mFunction(nullptr)
86, mBasisBitsAddr(nullptr)
87, mOutputAddrPtr(nullptr)
88, mMaxWhileDepth(0)
89, mPrintRegisterFunction(nullptr)
90{
91    //Create the jit execution engine.up
92    InitializeNativeTarget();
93    InitializeNativeTargetAsmPrinter();
94    InitializeNativeTargetAsmParser();
95    DefineTypes();
96}
97
98PabloCompiler::~PabloCompiler()
99{
100
101}
102   
103void PabloCompiler::InstallExternalFunction(std::string C_fn_name, void * fn_ptr) {
104    mExternalMap.insert(std::make_pair(C_fn_name, fn_ptr));
105}
106
107void PabloCompiler::genPrintRegister(std::string regName, Value * bitblockValue) {
108    Constant * regNameData = ConstantDataArray::getString(mMod->getContext(), regName);
109    GlobalVariable *regStrVar = new GlobalVariable(*mMod, 
110                                                   ArrayType::get(IntegerType::get(mMod->getContext(), 8), regName.length()+1),
111                                                   /*isConstant=*/ true,
112                                                   /*Linkage=*/ GlobalValue::PrivateLinkage,
113                                                   /*Initializer=*/ regNameData);
114    Value * regStrPtr = mBuilder->CreateGEP(regStrVar, {mBuilder->getInt64(0), mBuilder->getInt32(0)});
115    mBuilder->CreateCall(mPrintRegisterFunction, {regStrPtr, bitblockValue});
116}
117
118CompiledPabloFunction PabloCompiler::compile(PabloBlock & pb)
119{
120    mWhileDepth = 0;
121    mIfDepth = 0;
122    mMaxWhileDepth = 0;
123    mCarryManager = new CarryManager(mBuilder, mBitBlockType, mZeroInitializer, mOneInitializer);
124   
125    std::string errMessage;
126#ifdef USE_LLVM_3_5
127    EngineBuilder builder(mMod);
128#else
129    EngineBuilder builder(std::move(mModOwner));
130#endif
131    builder.setErrorStr(&errMessage);
132    builder.setMCPU(sys::getHostCPUName());
133#ifdef USE_LLVM_3_5
134    builder.setUseMCJIT(true);
135#endif
136    builder.setOptLevel(mMaxWhileDepth ? CodeGenOpt::Level::Less : CodeGenOpt::Level::None);
137    mExecutionEngine = builder.create();
138    if (mExecutionEngine == nullptr) {
139        throw std::runtime_error("Could not create ExecutionEngine: " + errMessage);
140    }
141    DeclareFunctions();
142
143    Examine(pb);
144    DeclareCallFunctions();
145
146    Function::arg_iterator args = mFunction->arg_begin();
147    mBasisBitsAddr = args++;
148    mBasisBitsAddr->setName("basis_bits");
149    mCarryDataPtr = args++;
150    mCarryDataPtr->setName("carry_data");
151    mOutputAddrPtr = args++;
152    mOutputAddrPtr->setName("output");
153
154    mWhileDepth = 0;
155    mIfDepth = 0;
156    mMaxWhileDepth = 0;
157    BasicBlock * b = BasicBlock::Create(mMod->getContext(), "parabix_entry", mFunction,0);
158    mBuilder->SetInsertPoint(b);
159
160    //The basis bits structure
161    for (unsigned i = 0; i != mBasisBits.size(); ++i) {
162        Value* indices[] = {mBuilder->getInt64(0), mBuilder->getInt32(i)};
163        Value * gep = mBuilder->CreateGEP(mBasisBitsAddr, indices);
164        LoadInst * basisBit = mBuilder->CreateAlignedLoad(gep, BLOCK_SIZE/8, false, mBasisBits[i]->getName()->to_string());
165        mMarkerMap.insert(std::make_pair(mBasisBits[i], basisBit));
166    }
167       
168    unsigned totalCarryDataSize = mCarryManager->initialize(&pb, mCarryDataPtr);
169   
170    //Generate the IR instructions for the function.
171    compileBlock(pb);
172   
173    mCarryManager->generateBlockNoIncrement();
174
175    if (DumpTrace || TraceNext) {
176        genPrintRegister("mBlockNo", mBuilder->CreateAlignedLoad(mBuilder->CreateBitCast(mCarryManager->getBlockNoPtr(), PointerType::get(mBitBlockType, 0)), BLOCK_SIZE/8, false));
177    }
178   
179    if (LLVM_UNLIKELY(mWhileDepth != 0)) {
180        throw std::runtime_error("Non-zero nesting depth error (" + std::to_string(mWhileDepth) + ")");
181    }
182
183    //Terminate the block
184    ReturnInst::Create(mMod->getContext(), mBuilder->GetInsertBlock());
185
186    //Display the IR that has been generated by this module.
187    if (LLVM_UNLIKELY(DumpGeneratedIR)) {
188        mMod->dump();
189    }
190    //Create a verifier.  The verifier will print an error message if our module is malformed in any way.
191    verifyModule(*mMod, &dbgs());
192
193    mExecutionEngine->finalizeObject();
194
195    //Return the required size of the carry data area to the process_block function.
196    return CompiledPabloFunction(totalCarryDataSize * sizeof(BitBlock), mFunction, mExecutionEngine);
197}
198
199void PabloCompiler::DefineTypes()
200{
201    StructType * structBasisBits = mMod->getTypeByName("struct.Basis_bits");
202    if (structBasisBits == nullptr) {
203        structBasisBits = StructType::create(mMod->getContext(), "struct.Basis_bits");
204    }
205    std::vector<Type*>StructTy_struct_Basis_bits_fields;
206    for (int i = 0; i != mBasisBits.size(); i++)
207    {
208        StructTy_struct_Basis_bits_fields.push_back(mBitBlockType);
209    }
210    if (structBasisBits->isOpaque()) {
211        structBasisBits->setBody(StructTy_struct_Basis_bits_fields, /*isPacked=*/false);
212    }
213    mBasisBitsInputPtr = PointerType::get(structBasisBits, 0);
214
215    std::vector<Type*>functionTypeArgs;
216    functionTypeArgs.push_back(mBasisBitsInputPtr);
217
218    //The carry data array.
219    //A pointer to the BitBlock vector.
220    functionTypeArgs.push_back(PointerType::get(mBitBlockType, 0));
221
222    //The output structure.
223    StructType * outputStruct = mMod->getTypeByName("struct.Output");
224    if (!outputStruct) {
225        outputStruct = StructType::create(mMod->getContext(), "struct.Output");
226    }
227    if (outputStruct->isOpaque()) {
228        std::vector<Type*>fields;
229        fields.push_back(mBitBlockType);
230        fields.push_back(mBitBlockType);
231        outputStruct->setBody(fields, /*isPacked=*/false);
232    }
233    PointerType* outputStructPtr = PointerType::get(outputStruct, 0);
234
235    //The &output parameter.
236    functionTypeArgs.push_back(outputStructPtr);
237
238    mFunctionType = FunctionType::get(
239     /*Result=*/Type::getVoidTy(mMod->getContext()),
240     /*Params=*/functionTypeArgs,
241     /*isVarArg=*/false);
242}
243
244void PabloCompiler::DeclareFunctions()
245{
246    //This function can be used for testing to print the contents of a register from JIT'd code to the terminal window.
247    mPrintRegisterFunction = mMod->getOrInsertFunction("wrapped_print_register", Type::getVoidTy(getGlobalContext()), Type::getInt8PtrTy(getGlobalContext()), mBitBlockType, NULL);
248    mExecutionEngine->addGlobalMapping(cast<GlobalValue>(mPrintRegisterFunction), (void *)&wrapped_print_register);
249    // to call->  mBuilder->CreateCall(mFunc_print_register, unicode_category);
250
251#ifdef USE_UADD_OVERFLOW
252#ifdef USE_TWO_UADD_OVERFLOW
253    // Type Definitions for llvm.uadd.with.overflow.carryin.i128 or .i256
254    std::vector<Type*>StructTy_0_fields;
255    StructTy_0_fields.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
256    StructTy_0_fields.push_back(IntegerType::get(mMod->getContext(), 1));
257    StructType *StructTy_0 = StructType::get(mMod->getContext(), StructTy_0_fields, /*isPacked=*/false);
258
259    std::vector<Type*>FuncTy_1_args;
260    FuncTy_1_args.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
261    FuncTy_1_args.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
262    FunctionType* FuncTy_1 = FunctionType::get(
263                                              /*Result=*/StructTy_0,
264                                              /*Params=*/FuncTy_1_args,
265                                              /*isVarArg=*/false);
266
267    mFunctionUaddOverflow = mMod->getFunction("llvm.uadd.with.overflow.i" +
268                                              std::to_string(BLOCK_SIZE));
269    if (!mFunctionUaddOverflow) {
270        mFunctionUaddOverflow= Function::Create(
271          /*Type=*/ FuncTy_1,
272          /*Linkage=*/ GlobalValue::ExternalLinkage,
273          /*Name=*/ "llvm.uadd.with.overflow.i" + std::to_string(BLOCK_SIZE), mMod); // (external, no body)
274        mFunctionUaddOverflow->setCallingConv(CallingConv::C);
275    }
276    AttributeSet mFunctionUaddOverflowPAL;
277    {
278        SmallVector<AttributeSet, 4> Attrs;
279        AttributeSet PAS;
280        {
281          AttrBuilder B;
282          B.addAttribute(Attribute::NoUnwind);
283          B.addAttribute(Attribute::ReadNone);
284          PAS = AttributeSet::get(mMod->getContext(), ~0U, B);
285        }
286
287        Attrs.push_back(PAS);
288        mFunctionUaddOverflowPAL = AttributeSet::get(mMod->getContext(), Attrs);
289    }
290    mFunctionUaddOverflow->setAttributes(mFunctionUaddOverflowPAL);
291#else
292    // Type Definitions for llvm.uadd.with.overflow.carryin.i128 or .i256
293    std::vector<Type*>StructTy_0_fields;
294    StructTy_0_fields.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
295    StructTy_0_fields.push_back(IntegerType::get(mMod->getContext(), 1));
296    StructType *StructTy_0 = StructType::get(mMod->getContext(), StructTy_0_fields, /*isPacked=*/false);
297
298    std::vector<Type*>FuncTy_1_args;
299    FuncTy_1_args.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
300    FuncTy_1_args.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
301    FuncTy_1_args.push_back(IntegerType::get(mMod->getContext(), 1));
302    FunctionType* FuncTy_1 = FunctionType::get(
303                                              /*Result=*/StructTy_0,
304                                              /*Params=*/FuncTy_1_args,
305                                              /*isVarArg=*/false);
306
307    mFunctionUaddOverflowCarryin = mMod->getFunction("llvm.uadd.with.overflow.carryin.i" +
308                                              std::to_string(BLOCK_SIZE));
309    if (!mFunctionUaddOverflowCarryin) {
310        mFunctionUaddOverflowCarryin = Function::Create(
311          /*Type=*/ FuncTy_1,
312          /*Linkage=*/ GlobalValue::ExternalLinkage,
313          /*Name=*/ "llvm.uadd.with.overflow.carryin.i" + std::to_string(BLOCK_SIZE), mMod); // (external, no body)
314        mFunctionUaddOverflowCarryin->setCallingConv(CallingConv::C);
315    }
316    AttributeSet mFunctionUaddOverflowCarryinPAL;
317    {
318        SmallVector<AttributeSet, 4> Attrs;
319        AttributeSet PAS;
320        {
321          AttrBuilder B;
322          B.addAttribute(Attribute::NoUnwind);
323          B.addAttribute(Attribute::ReadNone);
324          PAS = AttributeSet::get(mMod->getContext(), ~0U, B);
325        }
326
327        Attrs.push_back(PAS);
328        mFunctionUaddOverflowCarryinPAL = AttributeSet::get(mMod->getContext(), Attrs);
329    }
330    mFunctionUaddOverflowCarryin->setAttributes(mFunctionUaddOverflowCarryinPAL);
331#endif
332#endif
333
334    //Starts on process_block
335    SmallVector<AttributeSet, 4> Attrs;
336    AttributeSet PAS;
337    {
338        AttrBuilder B;
339        B.addAttribute(Attribute::ReadOnly);
340        B.addAttribute(Attribute::NoCapture);
341        PAS = AttributeSet::get(mMod->getContext(), 1U, B);
342    }
343    Attrs.push_back(PAS);
344    {
345        AttrBuilder B;
346        B.addAttribute(Attribute::NoCapture);
347        PAS = AttributeSet::get(mMod->getContext(), 2U, B);
348    }
349    Attrs.push_back(PAS);
350    {
351        AttrBuilder B;
352        B.addAttribute(Attribute::NoCapture);
353        PAS = AttributeSet::get(mMod->getContext(), 3U, B);
354    }
355    Attrs.push_back(PAS);
356    {
357        AttrBuilder B;
358        B.addAttribute(Attribute::NoUnwind);
359        B.addAttribute(Attribute::UWTable);
360        PAS = AttributeSet::get(mMod->getContext(), ~0U, B);
361    }
362    AttributeSet AttrSet = AttributeSet::get(mMod->getContext(), Attrs);
363
364    //Create the function that will be generated.
365    mFunction = mMod->getFunction("process_block");
366    if (!mFunction) {
367        mFunction = Function::Create(
368            /*Type=*/mFunctionType,
369            /*Linkage=*/GlobalValue::ExternalLinkage,
370            /*Name=*/"process_block", mMod);
371        mFunction->setCallingConv(CallingConv::C);
372    }
373    mFunction->setAttributes(AttrSet);
374}
375   
376void PabloCompiler::Examine(PabloBlock & blk) {
377    for (Statement * stmt : blk) {
378        if (Call * call = dyn_cast<Call>(stmt)) {
379            mCalleeMap.insert(std::make_pair(call->getCallee(), nullptr));
380        }
381        else if (If * ifStatement = dyn_cast<If>(stmt)) {
382            ++mIfDepth;
383            Examine(ifStatement->getBody());
384            --mIfDepth;
385        }
386        else if (While * whileStatement = dyn_cast<While>(stmt)) {
387            mMaxWhileDepth = std::max(mMaxWhileDepth, ++mWhileDepth);
388            Examine(whileStatement->getBody());
389            --mWhileDepth;
390        }
391    }
392}
393
394void PabloCompiler::DeclareCallFunctions() {
395    for (auto mapping : mCalleeMap) {
396        const String * callee = mapping.first;
397        //std::cerr << callee->str() << " to be declared\n";
398        auto ei = mExternalMap.find(callee->value());
399        if (ei != mExternalMap.end()) {
400            void * fn_ptr = ei->second;
401            //std::cerr << "Ptr found:" <<  std::hex << ((intptr_t) fn_ptr) << std::endl;
402            Value * externalValue = mMod->getOrInsertFunction(callee->value(), mBitBlockType, mBasisBitsInputPtr, NULL);
403            if (LLVM_UNLIKELY(externalValue == nullptr)) {
404                throw std::runtime_error("Could not create static method call for external function \"" + callee->to_string() + "\"");
405            }
406            mExecutionEngine->addGlobalMapping(cast<GlobalValue>(externalValue), fn_ptr);
407            mCalleeMap[callee] = externalValue;
408        }
409        else {
410            throw std::runtime_error("External function \"" + callee->to_string() + "\" not installed");
411        }
412    }
413}
414
415void PabloCompiler::compileBlock(PabloBlock & block) {
416    mCarryManager->ensureCarriesLoadedLocal(block);
417    mPabloBlock = & block;
418    for (const Statement * statement : block) {
419        compileStatement(statement);
420    }
421    mPabloBlock = block.getParent();
422    mCarryManager->ensureCarriesStoredLocal(block);
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    PabloBlock & ifBody = ifStatement -> getBody();
449   
450    Value* if_test_value = compileExpression(ifStatement->getCondition());
451    if (mCarryManager->blockHasCarries(ifBody)) {
452        // load the summary variable
453        Value* last_if_pending_data = mCarryManager->getCarrySummaryExpr(ifBody);
454        if_test_value = mBuilder->CreateOr(if_test_value, last_if_pending_data);
455    }
456    mBuilder->CreateCondBr(genBitBlockAny(if_test_value), ifEndBlock, ifBodyBlock);
457    // Entry processing is complete, now handle the body of the if.
458    mBuilder->SetInsertPoint(ifBodyBlock);
459   
460    ++mIfDepth;
461    compileBlock(ifBody);
462    --mIfDepth;
463    if (mCarryManager->blockHasCarries(ifBody)) {
464        mCarryManager->generateCarryOutSummaryCode(ifBody);
465    }
466    BasicBlock * ifBodyFinalBlock = mBuilder->GetInsertBlock();
467    mBuilder->CreateBr(ifEndBlock);
468    //End Block
469    mBuilder->SetInsertPoint(ifEndBlock);
470    for (const PabloAST * node : ifStatement->getDefined()) {
471        const Assign * assign = cast<Assign>(node);
472        PHINode * phi = mBuilder->CreatePHI(mBitBlockType, 2, assign->getName()->value());
473        auto f = mMarkerMap.find(assign);
474        assert (f != mMarkerMap.end());
475        phi->addIncoming(mZeroInitializer, ifEntryBlock);
476        phi->addIncoming(f->second, ifBodyFinalBlock);
477        mMarkerMap[assign] = phi;
478    }
479    // Create the phi Node for the summary variable, if needed.
480    if (mCarryManager->summaryNeededInParentBlock(ifBody)) {
481        mCarryManager->addSummaryPhi(ifBody, ifEntryBlock, ifBodyFinalBlock);
482    }
483}
484
485void PabloCompiler::compileWhile(const While * whileStatement) {
486
487    PabloBlock & whileBody = whileStatement -> getBody();
488   
489    BasicBlock * whileEntryBlock = mBuilder->GetInsertBlock();
490    BasicBlock * whileBodyBlock = BasicBlock::Create(mMod->getContext(), "while.body", mFunction, 0);
491    BasicBlock * whileEndBlock = BasicBlock::Create(mMod->getContext(), "while.end", mFunction, 0);
492
493    mCarryManager->ensureCarriesLoadedRecursive(whileBody);
494
495    const auto & nextNodes = whileStatement->getVariants();
496    std::vector<PHINode *> nextPhis;
497    nextPhis.reserve(nextNodes.size());
498
499    // On entry to the while structure, proceed to execute the first iteration
500    // of the loop body unconditionally.   The while condition is tested at the end of
501    // the loop.
502
503    mBuilder->CreateBr(whileBodyBlock);
504    mBuilder->SetInsertPoint(whileBodyBlock);
505
506    //
507    // There are 3 sets of Phi nodes for the while loop.
508    // (1) Carry-ins: (a) incoming carry data first iterations, (b) zero thereafter
509    // (2) Carry-out accumulators: (a) zero first iteration, (b) |= carry-out of each iteration
510    // (3) Next nodes: (a) values set up before loop, (b) modified values calculated in loop.
511
512    mCarryManager->initializeCarryDataPhisAtWhileEntry(whileBody, whileEntryBlock);
513
514    // for any Next nodes in the loop body, initialize to (a) pre-loop value.
515    for (const Next * n : nextNodes) {
516        PHINode * phi = mBuilder->CreatePHI(mBitBlockType, 2, n->getName()->value());
517        auto f = mMarkerMap.find(n->getInitial());
518        assert (f != mMarkerMap.end());
519        phi->addIncoming(f->second, whileEntryBlock);
520        mMarkerMap[n->getInitial()] = phi;
521        nextPhis.push_back(phi);
522    }
523
524    //
525    // Now compile the loop body proper.  Carry-out accumulated values
526    // and iterated values of Next nodes will be computed.
527    ++mWhileDepth;
528    compileBlock(whileBody);
529
530    BasicBlock * whileBodyFinalBlock = mBuilder->GetInsertBlock();
531
532    mCarryManager->extendCarryDataPhisAtWhileBodyFinalBlock(whileBody, whileBodyFinalBlock);
533
534    // Terminate the while loop body with a conditional branch back.
535    mBuilder->CreateCondBr(genBitBlockAny(compileExpression(whileStatement->getCondition())), whileEndBlock, whileBodyBlock);
536
537    // and for any Next nodes in the loop body
538    for (unsigned i = 0; i < nextNodes.size(); i++) {
539        const Next * n = nextNodes[i];
540        auto f = mMarkerMap.find(n->getExpr());
541        if (LLVM_UNLIKELY(f == mMarkerMap.end())) {
542            throw std::runtime_error("Next node expression was not compiled!");
543        }
544        nextPhis[i]->addIncoming(f->second, whileBodyFinalBlock);
545    }
546
547    mBuilder->SetInsertPoint(whileEndBlock);
548    --mWhileDepth;
549
550    mCarryManager->ensureCarriesStoredRecursive(whileBody);
551}
552
553
554void PabloCompiler::compileStatement(const Statement * stmt) {
555    Value * expr = nullptr;
556    if (const Assign * assign = dyn_cast<const Assign>(stmt)) {
557        expr = compileExpression(assign->getExpr());
558        if (LLVM_UNLIKELY(assign->isOutputAssignment())) {
559            SetOutputValue(expr, assign->getOutputIndex());
560        }
561    }
562    else if (const Next * next = dyn_cast<const Next>(stmt)) {
563        expr = compileExpression(next->getExpr());
564        if (TraceNext) {
565            genPrintRegister(next->getName()->to_string(), expr);
566        }
567    }
568    else if (const If * ifStatement = dyn_cast<const If>(stmt)) {
569        compileIf(ifStatement);
570        return;
571    }
572    else if (const While * whileStatement = dyn_cast<const While>(stmt)) {
573        compileWhile(whileStatement);
574        return;
575    }
576    else if (const Call* call = dyn_cast<Call>(stmt)) {
577        //Call the callee once and store the result in the marker map.
578        if (mMarkerMap.count(call) != 0) {
579            return;
580        }
581        auto ci = mCalleeMap.find(call->getCallee());
582        if (LLVM_UNLIKELY(ci == mCalleeMap.end())) {
583            throw std::runtime_error("Unexpected error locating static function for \"" + call->getCallee()->to_string() + "\"");
584        }
585        expr = mBuilder->CreateCall(ci->second, mBasisBitsAddr);
586    }
587    else if (const And * pablo_and = dyn_cast<And>(stmt)) {
588        expr = mBuilder->CreateAnd(compileExpression(pablo_and->getExpr1()), compileExpression(pablo_and->getExpr2()), "and");
589    }
590    else if (const Or * pablo_or = dyn_cast<Or>(stmt)) {
591        expr = mBuilder->CreateOr(compileExpression(pablo_or->getExpr1()), compileExpression(pablo_or->getExpr2()), "or");
592    }
593    else if (const Xor * pablo_xor = dyn_cast<Xor>(stmt)) {
594        expr = mBuilder->CreateXor(compileExpression(pablo_xor->getExpr1()), compileExpression(pablo_xor->getExpr2()), "xor");
595    }
596    else if (const Sel * sel = dyn_cast<Sel>(stmt)) {
597        Value* ifMask = compileExpression(sel->getCondition());
598        Value* ifTrue = mBuilder->CreateAnd(ifMask, compileExpression(sel->getTrueExpr()));
599        Value* ifFalse = mBuilder->CreateAnd(genNot(ifMask), compileExpression(sel->getFalseExpr()));
600        expr = mBuilder->CreateOr(ifTrue, ifFalse);
601    }
602    else if (const Not * pablo_not = dyn_cast<Not>(stmt)) {
603        expr = genNot(compileExpression(pablo_not->getExpr()));
604    }
605    else if (const Advance * adv = dyn_cast<Advance>(stmt)) {
606        Value* strm_value = compileExpression(adv->getExpr());
607        int shift = adv->getAdvanceAmount();
608        unsigned advance_index = adv->getLocalAdvanceIndex();
609        if (shift == 1) {
610            expr = genUnitAdvanceWithCarry(strm_value, advance_index);
611        }
612        else if (shift < LongAdvanceBase) {
613            expr = genShortAdvanceWithCarry(strm_value, advance_index, shift);
614        }
615        else {
616            expr = genLongAdvanceWithCarry(strm_value, advance_index, shift);
617        }
618    }
619    else if (const MatchStar * mstar = dyn_cast<MatchStar>(stmt)) {
620        Value * marker = compileExpression(mstar->getMarker());
621        Value * cc = compileExpression(mstar->getCharClass());
622        Value * marker_and_cc = mBuilder->CreateAnd(marker, cc);
623        unsigned carry_index = mstar->getLocalCarryIndex();
624        expr = mBuilder->CreateOr(mBuilder->CreateXor(genAddWithCarry(marker_and_cc, cc, carry_index), cc), marker, "matchstar");
625    }
626    else if (const ScanThru * sthru = dyn_cast<ScanThru>(stmt)) {
627        Value * marker_expr = compileExpression(sthru->getScanFrom());
628        Value * cc_expr = compileExpression(sthru->getScanThru());
629        unsigned carry_index = sthru->getLocalCarryIndex();
630        expr = mBuilder->CreateAnd(genAddWithCarry(marker_expr, cc_expr, carry_index), genNot(cc_expr), "scanthru");
631    }
632    else {
633        llvm::raw_os_ostream cerr(std::cerr);
634        PabloPrinter::print(stmt, cerr);
635        throw std::runtime_error("Unrecognized Pablo Statement! can't compile.");
636    }
637    mMarkerMap[stmt] = expr;
638    if (DumpTrace) {
639        genPrintRegister(stmt->getName()->to_string(), expr);
640    }
641   
642}
643
644Value * PabloCompiler::compileExpression(const PabloAST * expr) {
645    if (isa<Ones>(expr)) {
646        return mOneInitializer;
647    }
648    else if (isa<Zeroes>(expr)) {
649        return mZeroInitializer;
650    }
651    auto f = mMarkerMap.find(expr);
652    if (LLVM_UNLIKELY(f == mMarkerMap.end())) {
653        std::string o;
654        llvm::raw_string_ostream str(o);
655        str << "\"";
656        PabloPrinter::print(expr, str);
657        str << "\" was used before definition!";
658        throw std::runtime_error(str.str());
659    }
660    return f->second;
661}
662
663
664#ifdef USE_UADD_OVERFLOW
665#ifdef USE_TWO_UADD_OVERFLOW
666PabloCompiler::SumWithOverflowPack PabloCompiler::callUaddOverflow(Value* int128_e1, Value* int128_e2) {
667    std::vector<Value*> struct_res_params;
668    struct_res_params.push_back(int128_e1);
669    struct_res_params.push_back(int128_e2);
670    CallInst* struct_res = CallInst::Create(mFunctionUaddOverflow, struct_res_params, "uadd_overflow_res", mBasicBlock);
671    struct_res->setCallingConv(CallingConv::C);
672    struct_res->setTailCall(false);
673    AttributeSet struct_res_PAL;
674    struct_res->setAttributes(struct_res_PAL);
675
676    SumWithOverflowPack ret;
677
678    std::vector<unsigned> int128_sum_indices;
679    int128_sum_indices.push_back(0);
680    ret.sum = ExtractValueInst::Create(struct_res, int128_sum_indices, "sum", mBasicBlock);
681
682    std::vector<unsigned> int1_obit_indices;
683    int1_obit_indices.push_back(1);
684    ret.obit = ExtractValueInst::Create(struct_res, int1_obit_indices, "obit", mBasicBlock);
685
686    return ret;
687}
688#else
689PabloCompiler::SumWithOverflowPack PabloCompiler::callUaddOverflow(Value* int128_e1, Value* int128_e2, Value* int1_cin) {
690    std::vector<Value*> struct_res_params;
691    struct_res_params.push_back(int128_e1);
692    struct_res_params.push_back(int128_e2);
693    struct_res_params.push_back(int1_cin);
694    CallInst* struct_res = CallInst::Create(mFunctionUaddOverflowCarryin, struct_res_params, "uadd_overflow_res", mBasicBlock);
695    struct_res->setCallingConv(CallingConv::C);
696    struct_res->setTailCall(false);
697    AttributeSet struct_res_PAL;
698    struct_res->setAttributes(struct_res_PAL);
699
700    SumWithOverflowPack ret;
701
702    std::vector<unsigned> int128_sum_indices;
703    int128_sum_indices.push_back(0);
704    ret.sum = ExtractValueInst::Create(struct_res, int128_sum_indices, "sum", mBasicBlock);
705
706    std::vector<unsigned> int1_obit_indices;
707    int1_obit_indices.push_back(1);
708    ret.obit = ExtractValueInst::Create(struct_res, int1_obit_indices, "obit", mBasicBlock);
709
710    return ret;
711}
712#endif
713#endif
714
715
716Value* PabloCompiler::genAddWithCarry(Value* e1, Value* e2, unsigned localIndex) {
717    Value * carryq_value = mCarryManager->getCarryOpCarryIn(mPabloBlock, localIndex);
718#ifdef USE_TWO_UADD_OVERFLOW
719    //This is the ideal implementation, which uses two uadd.with.overflow
720    //The back end should be able to recognize this pattern and combine it into uadd.with.overflow.carryin
721    CastInst* int128_e1 = new BitCastInst(e1, mBuilder->getIntNTy(BLOCK_SIZE), "e1_128", mBasicBlock);
722    CastInst* int128_e2 = new BitCastInst(e2, mBuilder->getIntNTy(BLOCK_SIZE), "e2_128", mBasicBlock);
723    CastInst* int128_carryq_value = new BitCastInst(carryq_value, mBuilder->getIntNTy(BLOCK_SIZE), "carryq_128", mBasicBlock);
724
725    SumWithOverflowPack sumpack0, sumpack1;
726
727    sumpack0 = callUaddOverflow(int128_e1, int128_e2);
728    sumpack1 = callUaddOverflow(sumpack0.sum, int128_carryq_value);
729
730    Value* obit = mBuilder->CreateOr(sumpack0.obit, sumpack1.obit, "carry_bit");
731    Value* sum = mBuilder->CreateBitCast(sumpack1.sum, mBitBlockType, "ret_sum");
732
733    /*obit is the i1 carryout, zero extend and insert it into a v2i64 or v4i64 vector.*/
734    ConstantAggregateZero* const_packed_5 = ConstantAggregateZero::get(mBitBlockType);
735    ConstantInt* const_int32_6 = ConstantInt::get(mMod->getContext(), APInt(32, StringRef("0"), 10));
736    CastInst* int64_o0 = new ZExtInst(obit, IntegerType::get(mMod->getContext(), 64), "o0", mBasicBlock);
737    InsertElementInst* carry_out = InsertElementInst::Create(const_packed_5, int64_o0, const_int32_6, "carry_out", mBasicBlock);
738
739#elif defined USE_UADD_OVERFLOW
740    //use llvm.uadd.with.overflow.i128 or i256
741    CastInst* int128_e1 = new BitCastInst(e1, mBuilder->getIntNTy(BLOCK_SIZE), "e1_128", mBasicBlock);
742    CastInst* int128_e2 = new BitCastInst(e2, mBuilder->getIntNTy(BLOCK_SIZE), "e2_128", mBasicBlock);
743
744    //get i1 carryin from iBLOCK_SIZE
745    ConstantInt* const_int32_6 = ConstantInt::get(mMod->getContext(), APInt(32, StringRef("0"), 10));
746    ExtractElementInst * int64_carryq_value = ExtractElementInst::Create(carryq_value, const_int32_6, "carryq_64", mBasicBlock);
747    CastInst* int1_carryq_value = new TruncInst(int64_carryq_value, IntegerType::get(mMod->getContext(), 1), "carryq_1", mBasicBlock);
748
749    SumWithOverflowPack sumpack0;
750    sumpack0 = callUaddOverflow(int128_e1, int128_e2, int1_carryq_value);
751    Value* obit = sumpack0.obit;
752    Value* sum = mBuilder->CreateBitCast(sumpack0.sum, mBitBlockType, "sum");
753
754    /*obit is the i1 carryout, zero extend and insert it into a v2i64 or v4i64 vector.*/
755    ConstantAggregateZero* const_packed_5 = ConstantAggregateZero::get(mBitBlockType);
756    CastInst* int64_o0 = new ZExtInst(obit, IntegerType::get(mMod->getContext(), 64), "o0", mBasicBlock);
757    InsertElementInst* carry_out = InsertElementInst::Create(const_packed_5, int64_o0, const_int32_6, "carry_out", mBasicBlock);
758#elif (BLOCK_SIZE == 128)
759    //calculate carry through logical ops
760    Value* carrygen = mBuilder->CreateAnd(e1, e2, "carrygen");
761    Value* carryprop = mBuilder->CreateOr(e1, e2, "carryprop");
762    Value* digitsum = mBuilder->CreateAdd(e1, e2, "digitsum");
763    Value* partial = mBuilder->CreateAdd(digitsum, carryq_value, "partial");
764    Value* digitcarry = mBuilder->CreateOr(carrygen, mBuilder->CreateAnd(carryprop, genNot(partial)));
765    Value* mid_carry_in = genShiftLeft64(mBuilder->CreateLShr(digitcarry, 63), "mid_carry_in");
766
767    Value* sum = mBuilder->CreateAdd(partial, mid_carry_in, "sum");
768    Value* carry_out = genShiftHighbitToLow(BLOCK_SIZE, mBuilder->CreateOr(carrygen, mBuilder->CreateAnd(carryprop, genNot(sum))));
769#else
770    //BLOCK_SIZE == 256, there is no other implementation
771    static_assert(false, "Add with carry for 256-bit bitblock requires USE_UADD_OVERFLOW");
772#endif //USE_TWO_UADD_OVERFLOW
773
774    mCarryManager->setCarryOpCarryOut(mPabloBlock, localIndex, carry_out);
775    return sum;
776}
777
778inline Value* PabloCompiler::genBitBlockAny(Value* test) {
779    Value* cast_marker_value_1 = mBuilder->CreateBitCast(test, mBuilder->getIntNTy(BLOCK_SIZE));
780    return mBuilder->CreateICmpEQ(cast_marker_value_1, ConstantInt::get(mBuilder->getIntNTy(BLOCK_SIZE), 0));
781}
782
783Value * PabloCompiler::genShiftHighbitToLow(unsigned FieldWidth, Value * op) {
784    unsigned FieldCount = BLOCK_SIZE/FieldWidth;
785    VectorType * vType = VectorType::get(IntegerType::get(mMod->getContext(), FieldWidth), FieldCount);
786    Value * v = mBuilder->CreateBitCast(op, vType);
787    return mBuilder->CreateBitCast(mBuilder->CreateLShr(v, FieldWidth - 1), mBitBlockType);
788}
789
790Value* PabloCompiler::genShiftLeft64(Value* e, const Twine &namehint) {
791    Value* i128_val = mBuilder->CreateBitCast(e, mBuilder->getIntNTy(BLOCK_SIZE));
792    return mBuilder->CreateBitCast(mBuilder->CreateShl(i128_val, 64, namehint), mBitBlockType);
793}
794
795inline Value* PabloCompiler::genNot(Value* expr) {
796    return mBuilder->CreateXor(expr, mOneInitializer, "not");
797}
798
799Value* PabloCompiler::genUnitAdvanceWithCarry(Value* strm_value, unsigned localIndex) {
800    Value * carry_in = mCarryManager->getUnitAdvanceCarryIn(mPabloBlock, localIndex);
801    Value* result_value;
802   
803#if (BLOCK_SIZE == 128) && !defined(USE_LONG_INTEGER_SHIFT)
804    Value* advanceq_value = genShiftHighbitToLow(BLOCK_SIZE, carry_in);
805    Value* srli_1_value = mBuilder->CreateLShr(strm_value, 63);
806    Value* packed_shuffle;
807    Constant* const_packed_1_elems [] = {mBuilder->getInt32(0), mBuilder->getInt32(2)};
808    Constant* const_packed_1 = ConstantVector::get(const_packed_1_elems);
809    packed_shuffle = mBuilder->CreateShuffleVector(advanceq_value, srli_1_value, const_packed_1);
810   
811    Constant* const_packed_2_elems[] = {mBuilder->getInt64(1), mBuilder->getInt64(1)};
812    Constant* const_packed_2 = ConstantVector::get(const_packed_2_elems);
813   
814    Value* shl_value = mBuilder->CreateShl(strm_value, const_packed_2);
815    result_value = mBuilder->CreateOr(shl_value, packed_shuffle, "advance");
816#else
817    Value* advanceq_longint = mBuilder->CreateBitCast(carry_in, mBuilder->getIntNTy(BLOCK_SIZE));
818    Value* strm_longint = mBuilder->CreateBitCast(strm_value, mBuilder->getIntNTy(BLOCK_SIZE));
819    Value* adv_longint = mBuilder->CreateOr(mBuilder->CreateShl(strm_longint, 1), mBuilder->CreateLShr(advanceq_longint, BLOCK_SIZE - 1), "advance");
820    result_value = mBuilder->CreateBitCast(adv_longint, mBitBlockType);
821   
822#endif
823    mCarryManager->setUnitAdvanceCarryOut(mPabloBlock, localIndex, strm_value);
824    return result_value;
825}
826                   
827Value* PabloCompiler::genShortAdvanceWithCarry(Value* strm_value, unsigned localIndex, int shift_amount) {
828    Value * carry_in = mCarryManager->getShortAdvanceCarryIn(mPabloBlock, localIndex, shift_amount);
829    Value* advanceq_longint = mBuilder->CreateBitCast(carry_in, mBuilder->getIntNTy(BLOCK_SIZE));
830    Value* strm_longint = mBuilder->CreateBitCast(strm_value, mBuilder->getIntNTy(BLOCK_SIZE));
831    Value* adv_longint = mBuilder->CreateOr(mBuilder->CreateShl(strm_longint, shift_amount), mBuilder->CreateLShr(advanceq_longint, BLOCK_SIZE - shift_amount), "advance");
832    Value* result_value = mBuilder->CreateBitCast(adv_longint, mBitBlockType);
833    mCarryManager->setShortAdvanceCarryOut(mPabloBlock, localIndex, shift_amount, strm_value);
834    return result_value;
835}
836                   
837Value* PabloCompiler::genLongAdvanceWithCarry(Value* strm_value, unsigned localIndex, int shift_amount) {
838    return mCarryManager->longAdvanceCarryInCarryOut(mPabloBlock, localIndex, shift_amount, strm_value);
839}
840   
841void PabloCompiler::SetOutputValue(Value * marker, const unsigned index) {
842    if (marker->getType()->isPointerTy()) {
843        marker = mBuilder->CreateAlignedLoad(marker, BLOCK_SIZE/8, false);
844    }
845    Value* indices[] = {mBuilder->getInt64(0), mBuilder->getInt32(index)};
846    Value* gep = mBuilder->CreateGEP(mOutputAddrPtr, indices);
847    mBuilder->CreateAlignedStore(marker, gep, BLOCK_SIZE/8, false);
848}
849
850CompiledPabloFunction::CompiledPabloFunction(size_t carryDataSize, Function * function, ExecutionEngine * executionEngine)
851: CarryDataSize(carryDataSize)
852, FunctionPointer(executionEngine->getPointerToFunction(function))
853, mFunction(function)
854, mExecutionEngine(executionEngine)
855{
856
857}
858
859// Clean up the memory for the compiled function once we're finished using it.
860CompiledPabloFunction::~CompiledPabloFunction() {
861    if (mExecutionEngine) {
862        assert (mFunction);
863        // mExecutionEngine->freeMachineCodeForFunction(mFunction); // This function only prints a "not supported" message. Reevaluate with LLVM 3.6.
864        delete mExecutionEngine;
865    }
866}
867
868}
Note: See TracBrowser for help on using the repository browser.