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

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

Carry manager progress

File size: 34.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 <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> TraceNext("trace-next-nodes", cl::init(false), cl::desc("Generate dynamic traces of executed Next nodes (while control variables)."), cl::cat(fTracingOptions));
58static cl::opt<bool> DumpTrace("dump-trace", cl::init(false), cl::desc("Generate dynamic traces of executed assignments."), cl::cat(fTracingOptions));
59
60extern "C" {
61  void wrapped_print_register(char * regName, BitBlock bit_block) {
62      print_register<BitBlock>(regName, bit_block);
63  }
64}
65
66namespace pablo {
67
68PabloCompiler::PabloCompiler()
69: mMod(nullptr)
70, mExecutionEngine(nullptr)
71, mBuilder(nullptr)
72, mCarryManager(nullptr)
73, mCarryOffset(0)
74, mBitBlockType(VectorType::get(IntegerType::get(getGlobalContext(), 64), BLOCK_SIZE / 64))
75, iBuilder(mBitBlockType)
76, mInputType(nullptr)
77, mCarryDataPtr(nullptr)
78, mWhileDepth(0)
79, mIfDepth(0)
80, mZeroInitializer(ConstantAggregateZero::get(mBitBlockType))
81, mOneInitializer(ConstantVector::getAllOnesValue(mBitBlockType))
82, mFunction(nullptr)
83, mInputAddressPtr(nullptr)
84, mOutputAddressPtr(nullptr)
85, mMaxWhileDepth(0)
86, mPrintRegisterFunction(nullptr) {
87
88}
89
90PabloCompiler::~PabloCompiler() {
91}
92   
93
94void PabloCompiler::genPrintRegister(std::string regName, Value * bitblockValue) {
95    Constant * regNameData = ConstantDataArray::getString(mMod->getContext(), regName);
96    GlobalVariable *regStrVar = new GlobalVariable(*mMod,
97                                                   ArrayType::get(IntegerType::get(mMod->getContext(), 8), regName.length()+1),
98                                                   /*isConstant=*/ true,
99                                                   /*Linkage=*/ GlobalValue::PrivateLinkage,
100                                                   /*Initializer=*/ regNameData);
101    Value * regStrPtr = mBuilder->CreateGEP(regStrVar, {mBuilder->getInt64(0), mBuilder->getInt32(0)});
102    mBuilder->CreateCall(mPrintRegisterFunction, {regStrPtr, bitblockValue});
103}
104
105CompiledPabloFunction PabloCompiler::compile(PabloFunction & function) {
106
107    Examine(function);
108
109    InitializeNativeTarget();
110    InitializeNativeTargetAsmPrinter();
111    InitializeNativeTargetAsmParser();
112
113    Module * module = new Module("", getGlobalContext());
114
115    mMod = module;
116
117    std::string errMessage;
118    #ifdef USE_LLVM_3_5
119    EngineBuilder builder(mMod);
120    #else
121    EngineBuilder builder(std::move(std::unique_ptr<Module>(mMod)));
122    #endif
123    builder.setErrorStr(&errMessage);
124    builder.setMCPU(sys::getHostCPUName());
125    #ifdef USE_LLVM_3_5
126    builder.setUseMCJIT(true);
127    #endif
128    builder.setOptLevel(mMaxWhileDepth ? CodeGenOpt::Level::Less : CodeGenOpt::Level::None);
129    mExecutionEngine = builder.create();
130    if (mExecutionEngine == nullptr) {
131        throw std::runtime_error("Could not create ExecutionEngine: " + errMessage);
132    }
133    DeclareDebugFunctions();
134
135    auto func = compile(function, mMod);
136
137    //Display the IR that has been generated by this module.
138    if (LLVM_UNLIKELY(DumpGeneratedIR)) {
139        module->dump();
140    }
141    //Create a verifier.  The verifier will print an error message if our module is malformed in any way.
142    verifyModule(*module, &dbgs());
143
144    mExecutionEngine->finalizeObject();
145    ExecutionEngine * engine = mExecutionEngine;
146    mExecutionEngine = nullptr; // <-- pass ownership of the execution engine to the caller
147
148    return CompiledPabloFunction(func.second, func.first, engine);
149}
150
151std::pair<llvm::Function *, size_t> PabloCompiler::compile(PabloFunction & function, Module * module) {
152
153 
154    function.getEntryBlock().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    GenerateFunction(function);
167
168    mBuilder->SetInsertPoint(BasicBlock::Create(mMod->getContext(), "entry", mFunction,0));
169
170    //The basis bits structure
171    for (unsigned i = 0; i != function.getNumOfParameters(); ++i) {
172        Value* indices[] = {mBuilder->getInt64(0), mBuilder->getInt32(i)};
173        Value * gep = mBuilder->CreateGEP(mInputAddressPtr, indices);
174        LoadInst * basisBit = mBuilder->CreateAlignedLoad(gep, BLOCK_SIZE/8, false, function.getParameter(i)->getName()->to_string());
175        mMarkerMap[function.getParameter(i)] = basisBit;
176        if (DumpTrace) {
177            genPrintRegister(function.getParameter(i)->getName()->to_string(), basisBit);
178        }
179    }
180     
181    PabloBlock & mainScope = function.getEntryBlock();
182
183    mCarryOffset = mCarryManager->initialize(&mainScope, mCarryDataPtr);
184   
185    //Generate the IR instructions for the function.
186   
187    compileBlock(mainScope);
188   
189    mCarryManager->generateBlockNoIncrement();
190
191    if (DumpTrace || TraceNext) {
192        genPrintRegister("mBlockNo", mBuilder->CreateAlignedLoad(mBuilder->CreateBitCast(mCarryManager->getBlockNoPtr(), PointerType::get(mBitBlockType, 0)), BLOCK_SIZE/8, false));
193    }
194   
195    // Write the output values out
196    for (unsigned i = 0; i != function.getNumOfResults(); ++i) {
197        assert (function.getResult(i));
198        SetOutputValue(mMarkerMap[function.getResult(i)], i);
199    }
200
201    //Terminate the block
202    ReturnInst::Create(mMod->getContext(), mBuilder->GetInsertBlock());
203
204    // Clean up
205    delete mCarryManager; mCarryManager = nullptr;
206    delete mBuilder; mBuilder = nullptr;
207    mMod = nullptr; // don't delete this. It's either owned by the ExecutionEngine or the calling function.
208
209    //Return the required size of the carry data area to the process_block function.
210    return std::make_pair(mFunction, mCarryOffset * sizeof(BitBlock));
211}
212
213inline void PabloCompiler::GenerateFunction(PabloFunction & function) {
214    mInputType = PointerType::get(StructType::get(mMod->getContext(), std::vector<Type *>(function.getNumOfParameters(), mBitBlockType)), 0);
215    Type * carryType = PointerType::get(mBitBlockType, 0);
216    Type * outputType = PointerType::get(StructType::get(mMod->getContext(), std::vector<Type *>(function.getNumOfResults(), mBitBlockType)), 0);
217    FunctionType * functionType = FunctionType::get(Type::getVoidTy(mMod->getContext()), {{mInputType, carryType, outputType}}, false);
218
219#ifdef USE_UADD_OVERFLOW
220#ifdef USE_TWO_UADD_OVERFLOW
221    // Type Definitions for llvm.uadd.with.overflow.carryin.i128 or .i256
222    std::vector<Type*>StructTy_0_fields;
223    StructTy_0_fields.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
224    StructTy_0_fields.push_back(IntegerType::get(mMod->getContext(), 1));
225    StructType *StructTy_0 = StructType::get(mMod->getContext(), StructTy_0_fields, /*isPacked=*/false);
226
227    std::vector<Type*>FuncTy_1_args;
228    FuncTy_1_args.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
229    FuncTy_1_args.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
230    FunctionType* FuncTy_1 = FunctionType::get(
231                                              /*Result=*/StructTy_0,
232                                              /*Params=*/FuncTy_1_args,
233                                              /*isVarArg=*/false);
234
235    mFunctionUaddOverflow = mMod->getFunction("llvm.uadd.with.overflow.i" +
236                                              std::to_string(BLOCK_SIZE));
237    if (!mFunctionUaddOverflow) {
238        mFunctionUaddOverflow= Function::Create(
239          /*Type=*/ FuncTy_1,
240          /*Linkage=*/ GlobalValue::ExternalLinkage,
241          /*Name=*/ "llvm.uadd.with.overflow.i" + std::to_string(BLOCK_SIZE), mMod); // (external, no body)
242        mFunctionUaddOverflow->setCallingConv(CallingConv::C);
243    }
244    AttributeSet mFunctionUaddOverflowPAL;
245    {
246        SmallVector<AttributeSet, 4> Attrs;
247        AttributeSet PAS;
248        {
249          AttrBuilder B;
250          B.addAttribute(Attribute::NoUnwind);
251          B.addAttribute(Attribute::ReadNone);
252          PAS = AttributeSet::get(mMod->getContext(), ~0U, B);
253        }
254
255        Attrs.push_back(PAS);
256        mFunctionUaddOverflowPAL = AttributeSet::get(mMod->getContext(), Attrs);
257    }
258    mFunctionUaddOverflow->setAttributes(mFunctionUaddOverflowPAL);
259#else
260    // Type Definitions for llvm.uadd.with.overflow.carryin.i128 or .i256
261    std::vector<Type*>StructTy_0_fields;
262    StructTy_0_fields.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
263    StructTy_0_fields.push_back(IntegerType::get(mMod->getContext(), 1));
264    StructType *StructTy_0 = StructType::get(mMod->getContext(), StructTy_0_fields, /*isPacked=*/false);
265
266    std::vector<Type*>FuncTy_1_args;
267    FuncTy_1_args.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
268    FuncTy_1_args.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
269    FuncTy_1_args.push_back(IntegerType::get(mMod->getContext(), 1));
270    FunctionType* FuncTy_1 = FunctionType::get(
271                                              /*Result=*/StructTy_0,
272                                              /*Params=*/FuncTy_1_args,
273                                              /*isVarArg=*/false);
274
275    mFunctionUaddOverflowCarryin = mMod->getFunction("llvm.uadd.with.overflow.carryin.i" +
276                                              std::to_string(BLOCK_SIZE));
277    if (!mFunctionUaddOverflowCarryin) {
278        mFunctionUaddOverflowCarryin = Function::Create(
279          /*Type=*/ FuncTy_1,
280          /*Linkage=*/ GlobalValue::ExternalLinkage,
281          /*Name=*/ "llvm.uadd.with.overflow.carryin.i" + std::to_string(BLOCK_SIZE), mMod); // (external, no body)
282        mFunctionUaddOverflowCarryin->setCallingConv(CallingConv::C);
283    }
284    AttributeSet mFunctionUaddOverflowCarryinPAL;
285    {
286        SmallVector<AttributeSet, 4> Attrs;
287        AttributeSet PAS;
288        {
289          AttrBuilder B;
290          B.addAttribute(Attribute::NoUnwind);
291          B.addAttribute(Attribute::ReadNone);
292          PAS = AttributeSet::get(mMod->getContext(), ~0U, B);
293        }
294
295        Attrs.push_back(PAS);
296        mFunctionUaddOverflowCarryinPAL = AttributeSet::get(mMod->getContext(), Attrs);
297    }
298    mFunctionUaddOverflowCarryin->setAttributes(mFunctionUaddOverflowCarryinPAL);
299#endif
300#endif
301
302    //Starts on process_block
303    SmallVector<AttributeSet, 4> Attrs;
304    Attrs.push_back(AttributeSet::get(mMod->getContext(), ~0U, { Attribute::NoUnwind, Attribute::UWTable }));
305    Attrs.push_back(AttributeSet::get(mMod->getContext(), 1U, { Attribute::ReadOnly, Attribute::NoCapture }));
306    Attrs.push_back(AttributeSet::get(mMod->getContext(), 2U, { Attribute::NoCapture }));
307    Attrs.push_back(AttributeSet::get(mMod->getContext(), 3U, { Attribute::ReadNone, Attribute::NoCapture }));
308    AttributeSet AttrSet = AttributeSet::get(mMod->getContext(), Attrs);
309
310    // Create the function that will be generated.
311    mFunction = Function::Create(functionType, GlobalValue::ExternalLinkage, function.getName()->value(), mMod);
312    mFunction->setCallingConv(CallingConv::C);
313    mFunction->setAttributes(AttrSet);
314
315    Function::arg_iterator args = mFunction->arg_begin();
316    mInputAddressPtr = args++;
317    mInputAddressPtr->setName("input");
318    mCarryDataPtr = args++;
319    mCarryDataPtr->setName("carry");
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 || TraceNext) {
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
364Value * 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
385void 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   
426    ++mIfDepth;
427    compileBlock(ifBody);
428    --mIfDepth;
429    if (mCarryManager->blockHasCarries()) {
430        mCarryManager->generateCarryOutSummaryCodeIfNeeded();
431    }
432    BasicBlock * ifBodyFinalBlock = mBuilder->GetInsertBlock();
433    mBuilder->CreateBr(ifEndBlock);
434    //End Block
435    mBuilder->SetInsertPoint(ifEndBlock);
436    for (const PabloAST * node : ifStatement->getDefined()) {
437        const Assign * assign = cast<Assign>(node);
438        PHINode * phi = mBuilder->CreatePHI(mBitBlockType, 2, assign->getName()->value());
439        auto f = mMarkerMap.find(assign);
440        assert (f != mMarkerMap.end());
441        phi->addIncoming(mZeroInitializer, ifEntryBlock);
442        phi->addIncoming(f->second, ifBodyFinalBlock);
443        mMarkerMap[assign] = phi;
444    }
445    // Create the phi Node for the summary variable, if needed.
446    mCarryManager->addSummaryPhiIfNeeded(ifEntryBlock, ifBodyFinalBlock);
447    mCarryManager->leaveScope();
448}
449
450void PabloCompiler::compileWhile(const While * whileStatement) {
451
452    PabloBlock & whileBody = whileStatement -> getBody();
453   
454    BasicBlock * whileEntryBlock = mBuilder->GetInsertBlock();
455    BasicBlock * whileBodyBlock = BasicBlock::Create(mMod->getContext(), "while.body", mFunction, 0);
456    BasicBlock * whileEndBlock = BasicBlock::Create(mMod->getContext(), "while.end", mFunction, 0);
457
458    mCarryManager->enterScope(&whileBody);
459    mCarryManager->ensureCarriesLoadedRecursive();
460
461    const auto & nextNodes = whileStatement->getVariants();
462    std::vector<PHINode *> nextPhis;
463    nextPhis.reserve(nextNodes.size());
464
465    // On entry to the while structure, proceed to execute the first iteration
466    // of the loop body unconditionally.   The while condition is tested at the end of
467    // the loop.
468
469    mBuilder->CreateBr(whileBodyBlock);
470    mBuilder->SetInsertPoint(whileBodyBlock);
471
472    //
473    // There are 3 sets of Phi nodes for the while loop.
474    // (1) Carry-ins: (a) incoming carry data first iterations, (b) zero thereafter
475    // (2) Carry-out accumulators: (a) zero first iteration, (b) |= carry-out of each iteration
476    // (3) Next nodes: (a) values set up before loop, (b) modified values calculated in loop.
477
478    mCarryManager->initializeCarryDataPhisAtWhileEntry(whileEntryBlock);
479
480    // for any Next nodes in the loop body, initialize to (a) pre-loop value.
481    for (const Next * n : nextNodes) {
482        PHINode * phi = mBuilder->CreatePHI(mBitBlockType, 2, n->getName()->value());
483        auto f = mMarkerMap.find(n->getInitial());
484        assert (f != mMarkerMap.end());
485        phi->addIncoming(f->second, whileEntryBlock);
486        mMarkerMap[n->getInitial()] = phi;
487        nextPhis.push_back(phi);
488    }
489
490    //
491    // Now compile the loop body proper.  Carry-out accumulated values
492    // and iterated values of Next nodes will be computed.
493    ++mWhileDepth;
494    compileBlock(whileBody);
495
496    BasicBlock * whileBodyFinalBlock = mBuilder->GetInsertBlock();
497
498    if (mCarryManager->blockHasCarries()) {
499        mCarryManager->generateCarryOutSummaryCodeIfNeeded();
500    }
501    mCarryManager->extendCarryDataPhisAtWhileBodyFinalBlock(whileBodyFinalBlock);
502
503    // Terminate the while loop body with a conditional branch back.
504    mBuilder->CreateCondBr(iBuilder.bitblock_any(compileExpression(whileStatement->getCondition())), whileBodyBlock, whileEndBlock);
505
506    // and for any Next nodes in the loop body
507    for (unsigned i = 0; i < nextNodes.size(); i++) {
508        const Next * n = nextNodes[i];
509        auto f = mMarkerMap.find(n->getExpr());
510        if (LLVM_UNLIKELY(f == mMarkerMap.end())) {
511            throw std::runtime_error("Next node expression was not compiled!");
512        }
513        nextPhis[i]->addIncoming(f->second, whileBodyFinalBlock);
514    }
515
516    mBuilder->SetInsertPoint(whileEndBlock);
517    --mWhileDepth;
518
519    mCarryManager->ensureCarriesStoredRecursive();
520    mCarryManager->leaveScope();
521}
522
523
524void PabloCompiler::compileStatement(const Statement * stmt) {
525    Value * expr = nullptr;
526    if (const Assign * assign = dyn_cast<const Assign>(stmt)) {
527        expr = compileExpression(assign->getExpression());
528    }
529    else if (const Next * next = dyn_cast<const Next>(stmt)) {
530        expr = compileExpression(next->getExpr());
531        if (TraceNext) {
532            genPrintRegister(next->getName()->to_string(), expr);
533        }
534    }
535    else if (const If * ifStatement = dyn_cast<const If>(stmt)) {
536        compileIf(ifStatement);
537        return;
538    }
539    else if (const While * whileStatement = dyn_cast<const While>(stmt)) {
540        compileWhile(whileStatement);
541        return;
542    }
543    else if (const Call* call = dyn_cast<Call>(stmt)) {
544        //Call the callee once and store the result in the marker map.
545        if (mMarkerMap.count(call) != 0) {
546            return;
547        }
548
549        const Prototype * proto = call->getPrototype();
550        const String * callee = proto->getName();
551
552        Type * inputType = StructType::get(mMod->getContext(), std::vector<Type *>{proto->getNumOfParameters(), mBitBlockType});
553        Type * carryType = mBitBlockType;
554        Type * outputType = StructType::get(mMod->getContext(), std::vector<Type *>{proto->getNumOfResults(), mBitBlockType});
555        FunctionType * functionType = FunctionType::get(Type::getVoidTy(mMod->getContext()), std::vector<Type *>{PointerType::get(inputType, 0), PointerType::get(carryType, 0), PointerType::get(outputType, 0)}, false);
556
557        //Starts on process_block
558        SmallVector<AttributeSet, 3> Attrs;
559        Attrs.push_back(AttributeSet::get(mMod->getContext(), 1U, { Attribute::ReadOnly, Attribute::NoCapture }));
560        Attrs.push_back(AttributeSet::get(mMod->getContext(), 2U, { Attribute::NoCapture }));
561        Attrs.push_back(AttributeSet::get(mMod->getContext(), 3U, { Attribute::ReadNone, Attribute::NoCapture }));
562        AttributeSet AttrSet = AttributeSet::get(mMod->getContext(), Attrs);
563
564        Function * externalFunction = cast<Function>(mMod->getOrInsertFunction(callee->value(), functionType, AttrSet));
565        if (LLVM_UNLIKELY(externalFunction == nullptr)) {
566            throw std::runtime_error("Could not create static method call for external function \"" + callee->to_string() + "\"");
567        }
568        externalFunction->setCallingConv(llvm::CallingConv::C);
569
570        if (mExecutionEngine) mExecutionEngine->addGlobalMapping(externalFunction, proto->getFunctionPtr());
571
572        // add mCarryOffset to mCarryDataPtr
573        Value * carryFramePtr = mBuilder->CreateGEP(mCarryDataPtr, mBuilder->getInt64(mCarryOffset));
574        AllocaInst * outputStruct = mBuilder->CreateAlloca(outputType);
575        mBuilder->CreateCall3(externalFunction, mInputAddressPtr, carryFramePtr, outputStruct);
576        Value * outputPtr = mBuilder->CreateGEP(outputStruct, { mBuilder->getInt32(0), mBuilder->getInt32(0) });
577        expr = mBuilder->CreateAlignedLoad(outputPtr, BLOCK_SIZE / 8, false);
578
579        mCarryOffset += (proto->getRequiredStateSpace() + (BLOCK_SIZE / 8) - 1) / (BLOCK_SIZE / 8);
580    }
581    else if (const And * pablo_and = dyn_cast<And>(stmt)) {
582        expr = mBuilder->CreateAnd(compileExpression(pablo_and->getExpr1()), compileExpression(pablo_and->getExpr2()), "and");
583    }
584    else if (const Or * pablo_or = dyn_cast<Or>(stmt)) {
585        expr = mBuilder->CreateOr(compileExpression(pablo_or->getExpr1()), compileExpression(pablo_or->getExpr2()), "or");
586    }
587    else if (const Xor * pablo_xor = dyn_cast<Xor>(stmt)) {
588        expr = mBuilder->CreateXor(compileExpression(pablo_xor->getExpr1()), compileExpression(pablo_xor->getExpr2()), "xor");
589    }
590    else if (const Sel * sel = dyn_cast<Sel>(stmt)) {
591        Value* ifMask = compileExpression(sel->getCondition());
592        Value* ifTrue = mBuilder->CreateAnd(ifMask, compileExpression(sel->getTrueExpr()));
593        Value* ifFalse = mBuilder->CreateAnd(genNot(ifMask), compileExpression(sel->getFalseExpr()));
594        expr = mBuilder->CreateOr(ifTrue, ifFalse);
595    }
596    else if (const Not * pablo_not = dyn_cast<Not>(stmt)) {
597        expr = genNot(compileExpression(pablo_not->getExpr()));
598    }
599    else if (const Advance * adv = dyn_cast<Advance>(stmt)) {
600        Value* strm_value = compileExpression(adv->getExpr());
601        int shift = adv->getAdvanceAmount();
602        unsigned advance_index = adv->getLocalAdvanceIndex();
603        expr = mCarryManager->advanceCarryInCarryOut(advance_index, shift, strm_value);
604    }
605    else if (const MatchStar * mstar = dyn_cast<MatchStar>(stmt)) {
606        Value * marker = compileExpression(mstar->getMarker());
607        Value * cc = compileExpression(mstar->getCharClass());
608        Value * marker_and_cc = mBuilder->CreateAnd(marker, cc);
609        unsigned carry_index = mstar->getLocalCarryIndex();
610        expr = mBuilder->CreateOr(mBuilder->CreateXor(genAddWithCarry(marker_and_cc, cc, carry_index), cc), marker, "matchstar");
611    }
612    else if (const ScanThru * sthru = dyn_cast<ScanThru>(stmt)) {
613        Value * marker_expr = compileExpression(sthru->getScanFrom());
614        Value * cc_expr = compileExpression(sthru->getScanThru());
615        unsigned carry_index = sthru->getLocalCarryIndex();
616        expr = mBuilder->CreateAnd(genAddWithCarry(marker_expr, cc_expr, carry_index), genNot(cc_expr), "scanthru");
617    }
618    else {
619        llvm::raw_os_ostream cerr(std::cerr);
620        PabloPrinter::print(stmt, cerr);
621        throw std::runtime_error("Unrecognized Pablo Statement! can't compile.");
622    }
623    mMarkerMap[stmt] = expr;
624    if (DumpTrace) {
625        genPrintRegister(stmt->getName()->to_string(), expr);
626    }
627   
628}
629
630Value * PabloCompiler::compileExpression(const PabloAST * expr) {
631    if (isa<Ones>(expr)) {
632        return mOneInitializer;
633    }
634    else if (isa<Zeroes>(expr)) {
635        return mZeroInitializer;
636    }
637    auto f = mMarkerMap.find(expr);
638    if (LLVM_UNLIKELY(f == mMarkerMap.end())) {
639        std::string o;
640        llvm::raw_string_ostream str(o);
641        str << "\"";
642        PabloPrinter::print(expr, str);
643        str << "\" was used before definition!";
644        throw std::runtime_error(str.str());
645    }
646    return f->second;
647}
648
649
650#ifdef USE_UADD_OVERFLOW
651#ifdef USE_TWO_UADD_OVERFLOW
652PabloCompiler::SumWithOverflowPack PabloCompiler::callUaddOverflow(Value* int128_e1, Value* int128_e2) {
653    std::vector<Value*> struct_res_params;
654    struct_res_params.push_back(int128_e1);
655    struct_res_params.push_back(int128_e2);
656    CallInst* struct_res = CallInst::Create(mFunctionUaddOverflow, struct_res_params, "uadd_overflow_res", mBasicBlock);
657    struct_res->setCallingConv(CallingConv::C);
658    struct_res->setTailCall(false);
659    AttributeSet struct_res_PAL;
660    struct_res->setAttributes(struct_res_PAL);
661
662    SumWithOverflowPack ret;
663
664    std::vector<unsigned> int128_sum_indices;
665    int128_sum_indices.push_back(0);
666    ret.sum = ExtractValueInst::Create(struct_res, int128_sum_indices, "sum", mBasicBlock);
667
668    std::vector<unsigned> int1_obit_indices;
669    int1_obit_indices.push_back(1);
670    ret.obit = ExtractValueInst::Create(struct_res, int1_obit_indices, "obit", mBasicBlock);
671
672    return ret;
673}
674#else
675PabloCompiler::SumWithOverflowPack PabloCompiler::callUaddOverflow(Value* int128_e1, Value* int128_e2, Value* int1_cin) {
676    std::vector<Value*> struct_res_params;
677    struct_res_params.push_back(int128_e1);
678    struct_res_params.push_back(int128_e2);
679    struct_res_params.push_back(int1_cin);
680    CallInst* struct_res = CallInst::Create(mFunctionUaddOverflowCarryin, struct_res_params, "uadd_overflow_res", mBasicBlock);
681    struct_res->setCallingConv(CallingConv::C);
682    struct_res->setTailCall(false);
683    AttributeSet struct_res_PAL;
684    struct_res->setAttributes(struct_res_PAL);
685
686    SumWithOverflowPack ret;
687
688    std::vector<unsigned> int128_sum_indices;
689    int128_sum_indices.push_back(0);
690    ret.sum = ExtractValueInst::Create(struct_res, int128_sum_indices, "sum", mBasicBlock);
691
692    std::vector<unsigned> int1_obit_indices;
693    int1_obit_indices.push_back(1);
694    ret.obit = ExtractValueInst::Create(struct_res, int1_obit_indices, "obit", mBasicBlock);
695
696    return ret;
697}
698#endif
699#endif
700
701
702Value* PabloCompiler::genAddWithCarry(Value* e1, Value* e2, unsigned localIndex) {
703    Value * carryq_value = mCarryManager->getCarryOpCarryIn(localIndex);
704#ifdef USE_TWO_UADD_OVERFLOW
705    //This is the ideal implementation, which uses two uadd.with.overflow
706    //The back end should be able to recognize this pattern and combine it into uadd.with.overflow.carryin
707    CastInst* int128_e1 = new BitCastInst(e1, mBuilder->getIntNTy(BLOCK_SIZE), "e1_128", mBasicBlock);
708    CastInst* int128_e2 = new BitCastInst(e2, mBuilder->getIntNTy(BLOCK_SIZE), "e2_128", mBasicBlock);
709    CastInst* int128_carryq_value = new BitCastInst(carryq_value, mBuilder->getIntNTy(BLOCK_SIZE), "carryq_128", mBasicBlock);
710
711    SumWithOverflowPack sumpack0, sumpack1;
712
713    sumpack0 = callUaddOverflow(int128_e1, int128_e2);
714    sumpack1 = callUaddOverflow(sumpack0.sum, int128_carryq_value);
715
716    Value* obit = mBuilder->CreateOr(sumpack0.obit, sumpack1.obit, "carry_bit");
717    Value* sum = mBuilder->CreateBitCast(sumpack1.sum, mBitBlockType, "ret_sum");
718
719    /*obit is the i1 carryout, zero extend and insert it into a v2i64 or v4i64 vector.*/
720    ConstantAggregateZero* const_packed_5 = ConstantAggregateZero::get(mBitBlockType);
721    ConstantInt* const_int32_6 = ConstantInt::get(mMod->getContext(), APInt(32, StringRef("0"), 10));
722    CastInst* int64_o0 = new ZExtInst(obit, IntegerType::get(mMod->getContext(), 64), "o0", mBasicBlock);
723    InsertElementInst* carry_out = InsertElementInst::Create(const_packed_5, int64_o0, const_int32_6, "carry_out", mBasicBlock);
724
725#elif defined USE_UADD_OVERFLOW
726    //use llvm.uadd.with.overflow.i128 or i256
727    CastInst* int128_e1 = new BitCastInst(e1, mBuilder->getIntNTy(BLOCK_SIZE), "e1_128", mBasicBlock);
728    CastInst* int128_e2 = new BitCastInst(e2, mBuilder->getIntNTy(BLOCK_SIZE), "e2_128", mBasicBlock);
729
730    //get i1 carryin from iBLOCK_SIZE
731    ConstantInt* const_int32_6 = ConstantInt::get(mMod->getContext(), APInt(32, StringRef("0"), 10));
732    ExtractElementInst * int64_carryq_value = ExtractElementInst::Create(carryq_value, const_int32_6, "carryq_64", mBasicBlock);
733    CastInst* int1_carryq_value = new TruncInst(int64_carryq_value, IntegerType::get(mMod->getContext(), 1), "carryq_1", mBasicBlock);
734
735    SumWithOverflowPack sumpack0;
736    sumpack0 = callUaddOverflow(int128_e1, int128_e2, int1_carryq_value);
737    Value* obit = sumpack0.obit;
738    Value* sum = mBuilder->CreateBitCast(sumpack0.sum, mBitBlockType, "sum");
739
740    /*obit is the i1 carryout, zero extend and insert it into a v2i64 or v4i64 vector.*/
741    ConstantAggregateZero* const_packed_5 = ConstantAggregateZero::get(mBitBlockType);
742    CastInst* int64_o0 = new ZExtInst(obit, IntegerType::get(mMod->getContext(), 64), "o0", mBasicBlock);
743    InsertElementInst* carry_out = InsertElementInst::Create(const_packed_5, int64_o0, const_int32_6, "carry_out", mBasicBlock);
744#elif (BLOCK_SIZE == 128)
745    //calculate carry through logical ops
746    Value* carrygen = mBuilder->CreateAnd(e1, e2, "carrygen");
747    Value* carryprop = mBuilder->CreateOr(e1, e2, "carryprop");
748    Value* digitsum = mBuilder->CreateAdd(e1, e2, "digitsum");
749    Value* partial = mBuilder->CreateAdd(digitsum, carryq_value, "partial");
750    Value* digitcarry = mBuilder->CreateOr(carrygen, mBuilder->CreateAnd(carryprop, genNot(partial)));
751    Value* mid_carry_in = genShiftLeft64(mBuilder->CreateLShr(digitcarry, 63), "mid_carry_in");
752
753    Value* sum = mBuilder->CreateAdd(partial, mid_carry_in, "sum");
754    Value* carry_out = genShiftHighbitToLow(BLOCK_SIZE, mBuilder->CreateOr(carrygen, mBuilder->CreateAnd(carryprop, genNot(sum))));
755#else
756    //BLOCK_SIZE == 256, there is no other implementation
757    static_assert(false, "Add with carry for 256-bit bitblock requires USE_UADD_OVERFLOW");
758#endif //USE_TWO_UADD_OVERFLOW
759
760    mCarryManager->setCarryOpCarryOut(localIndex, carry_out);
761    return sum;
762}
763
764Value * PabloCompiler::genShiftHighbitToLow(unsigned FieldWidth, Value * op) {
765    unsigned FieldCount = BLOCK_SIZE/FieldWidth;
766    VectorType * vType = VectorType::get(IntegerType::get(mMod->getContext(), FieldWidth), FieldCount);
767    Value * v = mBuilder->CreateBitCast(op, vType);
768    return mBuilder->CreateBitCast(mBuilder->CreateLShr(v, FieldWidth - 1), mBitBlockType);
769}
770
771Value* PabloCompiler::genShiftLeft64(Value* e, const Twine &namehint) {
772    Value* i128_val = mBuilder->CreateBitCast(e, mBuilder->getIntNTy(BLOCK_SIZE));
773    return mBuilder->CreateBitCast(mBuilder->CreateShl(i128_val, 64, namehint), mBitBlockType);
774}
775
776inline Value* PabloCompiler::genNot(Value* expr) {
777    return mBuilder->CreateXor(expr, mOneInitializer, "not");
778}
779   
780void PabloCompiler::SetOutputValue(Value * marker, const unsigned index) {
781    if (LLVM_UNLIKELY(marker == nullptr)) {
782        throw std::runtime_error("Cannot set result " + std::to_string(index) + " to Null");
783    }
784    if (LLVM_UNLIKELY(marker->getType()->isPointerTy())) {
785        marker = mBuilder->CreateAlignedLoad(marker, BLOCK_SIZE/8, false);
786    }
787    Value* indices[] = {mBuilder->getInt64(0), mBuilder->getInt32(index)};
788    Value* gep = mBuilder->CreateGEP(mOutputAddressPtr, indices);
789    mBuilder->CreateAlignedStore(marker, gep, BLOCK_SIZE/8, false);
790}
791
792CompiledPabloFunction::CompiledPabloFunction(size_t carryDataSize, Function * function, ExecutionEngine * executionEngine)
793: CarryDataSize(carryDataSize)
794, FunctionPointer(executionEngine->getPointerToFunction(function))
795, mFunction(function)
796, mExecutionEngine(executionEngine)
797{
798
799}
800
801// Clean up the memory for the compiled function once we're finished using it.
802CompiledPabloFunction::~CompiledPabloFunction() {
803    if (mExecutionEngine) {
804        assert (mFunction);
805        // mExecutionEngine->freeMachineCodeForFunction(mFunction); // This function only prints a "not supported" message. Reevaluate with LLVM 3.6.
806        delete mExecutionEngine;
807    }
808}
809
810}
Note: See TracBrowser for help on using the repository browser.