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

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

Embed carry data in compiled LLVM module; eliminate passing of carry data pointers/size

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