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

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

Start of work to make the pablo compiler reenterant. Fixed bug that prevented it from using Less optimization level.

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