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

Last change on this file since 4980 was 4980, checked in by cameron, 3 years ago

Remove mod64 junk

File size: 19.0 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 <re/re_name.h>
14#include <stdexcept>
15#include <sstream>
16#include <IDISA/idisa_builder.h>
17#include <IDISA/idisa_avx_builder.h>
18#include <llvm/Pass.h>
19#include <llvm/PassManager.h>
20#include <llvm/ADT/SmallVector.h>
21#include <llvm/Analysis/Passes.h>
22#include <llvm/IR/BasicBlock.h>
23#include <llvm/IR/CallingConv.h>
24#include <llvm/IR/DataLayout.h>
25#include <llvm/IR/DerivedTypes.h>
26#include <llvm/IR/Function.h>
27#include <llvm/IR/GlobalVariable.h>
28#include <llvm/IR/InlineAsm.h>
29#include <llvm/IR/Instructions.h>
30#include <llvm/IR/LLVMContext.h>
31#include <llvm/IR/Module.h>
32#include <llvm/Support/FormattedStream.h>
33#include <llvm/Support/MathExtras.h>
34#include <llvm/Support/Casting.h>
35#include <llvm/Support/Compiler.h>
36#include <llvm/Support/Debug.h>
37#include <llvm/Support/TargetSelect.h>
38#include <llvm/Support/Host.h>
39#include <llvm/Transforms/Scalar.h>
40#include <llvm/IRReader/IRReader.h>
41#include <llvm/Bitcode/ReaderWriter.h>
42#include <llvm/Support/MemoryBuffer.h>
43#include <llvm/IR/IRBuilder.h>
44#include <llvm/Support/CommandLine.h>
45#include <llvm/ADT/Twine.h>
46#include <iostream>
47#include <llvm/Support/raw_ostream.h>
48#include <llvm/Support/FileSystem.h>
49#ifndef NDEBUG
50#include <llvm/IR/Verifier.h>
51#endif
52
53//#include <llvm/PassManager.h>
54//#include <llvm/Transforms/IPO/PassManagerBuilder.h>
55
56#include <hrtime.h>
57
58static cl::OptionCategory eIRDumpOptions("LLVM IR Dump Options", "These options control dumping of LLVM IR.");
59static cl::opt<bool> DumpGeneratedIR("dump-generated-IR", cl::init(false), cl::desc("Print LLVM IR generated by Pablo Compiler."), cl::cat(eIRDumpOptions));
60static cl::opt<std::string> IROutputFilename("dump-generated-IR-output", cl::init(""), cl::desc("output IR filename"), cl::cat(eIRDumpOptions));
61
62
63static cl::OptionCategory fTracingOptions("Run-time Tracing Options", "These options control execution traces.");
64static cl::opt<bool> DumpTrace("dump-trace", cl::init(false), cl::desc("Generate dynamic traces of executed assignments."), cl::cat(fTracingOptions));
65
66namespace pablo {
67
68#define DSSLI_FIELDWIDTH 64
69
70PabloCompiler::PabloCompiler(Module * m, IDISA::IDISA_Builder * b)
71: mMod(m)
72, iBuilder(b)
73, mBitBlockType(b->getBitBlockType())
74, mCarryManager(nullptr)
75, mPabloFunction(nullptr)
76, mPabloBlock(nullptr)
77, mKernelBuilder(nullptr)
78, mWhileDepth(0)
79, mIfDepth(0)
80, mFunction(nullptr)
81, mMaxWhileDepth(0) {
82   
83}
84
85void PabloCompiler::setKernel(kernel::KernelBuilder * kBuilder){
86    mKernelBuilder = kBuilder;
87} 
88
89llvm::Function * PabloCompiler::compile(PabloFunction * function) {
90
91    #ifdef PRINT_TIMING_INFORMATION
92    const timestamp_t pablo_compilation_start = read_cycle_counter();
93    #endif
94 
95    Examine(*function);
96
97    mCarryManager = new CarryManager(iBuilder);
98
99    GenerateKernel(function);
100       
101    delete mCarryManager;
102    mCarryManager = nullptr;
103   
104    #ifdef PRINT_TIMING_INFORMATION
105    const timestamp_t pablo_compilation_end = read_cycle_counter();
106    std::cerr << "PABLO COMPILATION TIME: " << (pablo_compilation_end - pablo_compilation_start) << std::endl;
107    #endif
108
109    if (LLVM_UNLIKELY(DumpGeneratedIR)) {
110
111        if (IROutputFilename.empty()) {
112            mMod->dump();
113        } else {
114            std::error_code error;
115            llvm::raw_fd_ostream out(IROutputFilename, error, sys::fs::OpenFlags::F_None);
116            mMod->print(out, nullptr);
117        }
118    }
119    return mFunction;
120}
121
122inline void PabloCompiler::GenerateKernel(PabloFunction * const function) {
123 
124    mPabloFunction = function;
125
126    for (unsigned i = 0; i < function->getNumOfParameters(); ++i) {
127        mKernelBuilder->addInputStream(1, function->getParameter(i)->getName()->to_string());
128    }
129    for (unsigned i = 0; i < function->getNumOfResults(); ++i) {
130        mKernelBuilder->addOutputStream(1);
131    }
132
133    mCarryManager->initialize(function, mKernelBuilder);
134
135    mFunction = mKernelBuilder->prepareFunction();
136
137    mCarryManager->reset();
138
139    for (unsigned j = 0; j < function->getNumOfParameters(); ++j) {
140        mMarkerMap.insert(std::make_pair(function->getParameter(j), mKernelBuilder->getInputStream(j)));
141    }
142
143    compileBlock(function->getEntryBlock());
144
145    for (unsigned j = 0; j < function->getNumOfResults(); ++j) {
146        const auto f = mMarkerMap.find(function->getResult(j));
147        Value * result = nullptr;
148        if (LLVM_UNLIKELY(f == mMarkerMap.end())) {
149            result = iBuilder->allZeroes();
150        } else {
151            result = f->second;
152        }
153        iBuilder->CreateBlockAlignedStore(result, mKernelBuilder->getOutputStream(j));
154    }
155
156    mKernelBuilder->finalize();
157}
158
159inline void PabloCompiler::Examine(PabloFunction & function) {
160    mWhileDepth = 0;
161    mIfDepth = 0;
162    mMaxWhileDepth = 0;
163    Examine(function.getEntryBlock());
164}
165
166void PabloCompiler::Examine(PabloBlock * block) {
167    for (Statement * stmt : *block) {
168        if (LLVM_UNLIKELY(isa<If>(stmt))) {
169            Examine(cast<If>(stmt)->getBody());
170        } else if (LLVM_UNLIKELY(isa<While>(stmt))) {
171            mMaxWhileDepth = std::max(mMaxWhileDepth, ++mWhileDepth);
172            Examine(cast<While>(stmt)->getBody());
173            --mWhileDepth;
174        }
175    }
176}
177
178void PabloCompiler::compileBlock(const PabloBlock * const block) {
179    mPabloBlock = block;
180    for (const Statement * statement : *block) {
181        compileStatement(statement);
182    }
183    mPabloBlock = block->getParent();
184}
185
186void PabloCompiler::compileIf(const If * ifStatement) {       
187    //
188    //  The If-ElseZero stmt:
189    //  if <predicate:expr> then <body:stmt>* elsezero <defined:var>* endif
190    //  If the value of the predicate is nonzero, then determine the values of variables
191    //  <var>* by executing the given statements.  Otherwise, the value of the
192    //  variables are all zero.  Requirements: (a) no variable that is defined within
193    //  the body of the if may be accessed outside unless it is explicitly
194    //  listed in the variable list, (b) every variable in the defined list receives
195    //  a value within the body, and (c) the logical consequence of executing
196    //  the statements in the event that the predicate is zero is that the
197    //  values of all defined variables indeed work out to be 0.
198    //
199    //  Simple Implementation with Phi nodes:  a phi node in the if exit block
200    //  is inserted for each variable in the defined variable list.  It receives
201    //  a zero value from the ifentry block and the defined value from the if
202    //  body.
203    //
204
205    BasicBlock * const ifEntryBlock = iBuilder->GetInsertBlock();
206    BasicBlock * const ifBodyBlock = BasicBlock::Create(mMod->getContext(), "if.body", mFunction, 0);
207    BasicBlock * const ifEndBlock = BasicBlock::Create(mMod->getContext(), "if.end", mFunction, 0);
208   
209    PabloBlock * ifBody = ifStatement->getBody();
210   
211    Value * const condition = compileExpression(ifStatement->getCondition());
212   
213    mCarryManager->enterScope(ifBody);
214    iBuilder->CreateCondBr(mCarryManager->generateSummaryTest(condition), ifBodyBlock, ifEndBlock);
215   
216    // Entry processing is complete, now handle the body of the if.
217    iBuilder->SetInsertPoint(ifBodyBlock);
218   
219    compileBlock(ifBody);
220    BasicBlock * ifExitBlock = iBuilder->GetInsertBlock();
221
222    if (mCarryManager->hasCarries()) {
223        mCarryManager->storeCarryOutSummary();
224    }
225    mCarryManager->addOuterSummaryToNestedSummary();
226
227    iBuilder->CreateBr(ifEndBlock);
228    //End Block
229    iBuilder->SetInsertPoint(ifEndBlock);
230    for (const PabloAST * node : ifStatement->getDefined()) {
231        const Assign * assign = cast<Assign>(node);
232        PHINode * phi = iBuilder->CreatePHI(mBitBlockType, 2, assign->getName()->value());
233        auto f = mMarkerMap.find(assign);
234        assert (f != mMarkerMap.end());
235        phi->addIncoming(iBuilder->allZeroes(), ifEntryBlock);
236        phi->addIncoming(f->second, ifExitBlock);
237        mMarkerMap[assign] = phi;
238    }
239    // Create the phi Node for the summary variable, if needed.
240    mCarryManager->buildCarryDataPhisAfterIfBody(ifEntryBlock, ifExitBlock);
241    mCarryManager->leaveScope();
242}
243
244void PabloCompiler::compileWhile(const While * whileStatement) {
245
246    PabloBlock * const whileBody = whileStatement->getBody();
247   
248    BasicBlock * whileEntryBlock = iBuilder->GetInsertBlock();
249    BasicBlock * whileBodyBlock = BasicBlock::Create(mMod->getContext(), "while.body", mFunction, 0);
250    BasicBlock * whileEndBlock = BasicBlock::Create(mMod->getContext(), "while.end", mFunction, 0);
251
252    mCarryManager->enterScope(whileBody);
253    mCarryManager->ensureCarriesLoadedRecursive();
254
255    const auto & nextNodes = whileStatement->getVariants();
256    std::vector<PHINode *> nextPhis;
257    nextPhis.reserve(nextNodes.size());
258
259    // On entry to the while structure, proceed to execute the first iteration
260    // of the loop body unconditionally.   The while condition is tested at the end of
261    // the loop.
262
263    iBuilder->CreateBr(whileBodyBlock);
264    iBuilder->SetInsertPoint(whileBodyBlock);
265
266    //
267    // There are 3 sets of Phi nodes for the while loop.
268    // (1) Carry-ins: (a) incoming carry data first iterations, (b) zero thereafter
269    // (2) Carry-out accumulators: (a) zero first iteration, (b) |= carry-out of each iteration
270    // (3) Next nodes: (a) values set up before loop, (b) modified values calculated in loop.
271
272    mCarryManager->initializeWhileEntryCarryDataPhis(whileEntryBlock);
273
274    // for any Next nodes in the loop body, initialize to (a) pre-loop value.
275    for (const Next * n : nextNodes) {
276        PHINode * phi = iBuilder->CreatePHI(mBitBlockType, 2, n->getName()->value());
277        auto f = mMarkerMap.find(n->getInitial());
278        assert (f != mMarkerMap.end());
279        phi->addIncoming(f->second, whileEntryBlock);
280        mMarkerMap[n->getInitial()] = phi;
281        nextPhis.push_back(phi);
282    }
283
284    //
285    // Now compile the loop body proper.  Carry-out accumulated values
286    // and iterated values of Next nodes will be computed.
287    ++mWhileDepth;
288    compileBlock(whileBody);
289
290    BasicBlock * whileExitBlock = iBuilder->GetInsertBlock();
291
292    if (mCarryManager->hasCarries()) {
293        mCarryManager->storeCarryOutSummary();
294    }
295    mCarryManager->finalizeWhileBlockCarryDataPhis(whileExitBlock);
296
297    // Terminate the while loop body with a conditional branch back.
298    iBuilder->CreateCondBr(iBuilder->bitblock_any(compileExpression(whileStatement->getCondition())), whileBodyBlock, whileEndBlock);
299
300    // and for any Next nodes in the loop body
301    for (unsigned i = 0; i < nextNodes.size(); i++) {
302        const Next * n = nextNodes[i];
303        auto f = mMarkerMap.find(n->getExpr());
304        if (LLVM_UNLIKELY(f == mMarkerMap.end())) {
305            throw std::runtime_error("Next node expression was not compiled!");
306        }
307        nextPhis[i]->addIncoming(f->second, whileExitBlock);
308    }
309
310    iBuilder->SetInsertPoint(whileEndBlock);
311    --mWhileDepth;
312
313    mCarryManager->ensureCarriesStoredRecursive();
314    mCarryManager->leaveScope();
315}
316
317
318void PabloCompiler::compileStatement(const Statement * stmt) {
319    Value * expr = nullptr;
320    if (const Assign * assign = dyn_cast<const Assign>(stmt)) {
321        expr = compileExpression(assign->getExpression());
322    } else if (const Next * next = dyn_cast<const Next>(stmt)) {
323        expr = compileExpression(next->getExpr());
324    } else if (const If * ifStatement = dyn_cast<const If>(stmt)) {
325        compileIf(ifStatement);
326        return;
327    } else if (const While * whileStatement = dyn_cast<const While>(stmt)) {
328        compileWhile(whileStatement);
329        return;
330//    } else if (const Call* call = dyn_cast<Call>(stmt)) {
331//        // Call the callee once and store the result in the marker map.
332//        if (LLVM_UNLIKELY(mMarkerMap.count(call) == 0)) {
333//            return;
334//        }
335
336//        const Prototype * proto = call->getPrototype();
337//        const String * callee = proto->getName();
338
339//        Type * inputType = StructType::get(mMod->getContext(), std::vector<Type *>{proto->getNumOfParameters(), mBitBlockType});
340//        Type * outputType = StructType::get(mMod->getContext(), std::vector<Type *>{proto->getNumOfResults(), mBitBlockType});
341//        FunctionType * functionType = FunctionType::get(Type::getVoidTy(mMod->getContext()), std::vector<Type *>{PointerType::get(inputType, 0), PointerType::get(outputType, 0)}, false);
342
343//        //Starts on process_block
344//        SmallVector<AttributeSet, 3> Attrs;
345//        Attrs.push_back(AttributeSet::get(mMod->getContext(), 1U, std::vector<Attribute::AttrKind>({ Attribute::ReadOnly, Attribute::NoCapture })));
346//        Attrs.push_back(AttributeSet::get(mMod->getContext(), 2U, std::vector<Attribute::AttrKind>({ Attribute::ReadNone, Attribute::NoCapture })));
347//        AttributeSet AttrSet = AttributeSet::get(mMod->getContext(), Attrs);
348
349//        Function * externalFunction = cast<Function>(mMod->getOrInsertFunction(callee->value(), functionType, AttrSet));
350//        if (LLVM_UNLIKELY(externalFunction == nullptr)) {
351//            throw std::runtime_error("Could not create static method call for external function \"" + callee->to_string() + "\"");
352//        }
353//        externalFunction->setCallingConv(llvm::CallingConv::C);
354
355//        AllocaInst * outputStruct = iBuilder->CreateAlloca(outputType);
356//        iBuilder->CreateCall2(externalFunction, mInputAddressPtr, outputStruct);
357//        Value * outputPtr = iBuilder->CreateGEP(outputStruct, std::vector<Value *>({ iBuilder->getInt32(0), iBuilder->getInt32(0) }));
358
359//        expr = iBuilder->CreateBlockAlignedLoad(outputPtr);
360    } else if (const And * pablo_and = dyn_cast<And>(stmt)) {
361        expr = iBuilder->simd_and(compileExpression(pablo_and->getOperand(0)), compileExpression(pablo_and->getOperand(1)));
362    } else if (const Or * pablo_or = dyn_cast<Or>(stmt)) {
363        expr = iBuilder->simd_or(compileExpression(pablo_or->getOperand(0)), compileExpression(pablo_or->getOperand(1)));
364    } else if (const Xor * pablo_xor = dyn_cast<Xor>(stmt)) {
365        expr = iBuilder->simd_xor(compileExpression(pablo_xor->getOperand(0)), compileExpression(pablo_xor->getOperand(1)));
366    } else if (const Sel * sel = dyn_cast<Sel>(stmt)) {
367        Value* ifMask = compileExpression(sel->getCondition());
368        Value* ifTrue = iBuilder->simd_and(ifMask, compileExpression(sel->getTrueExpr()));
369        Value* ifFalse = iBuilder->simd_and(iBuilder->simd_not(ifMask), compileExpression(sel->getFalseExpr()));
370        expr = iBuilder->simd_or(ifTrue, ifFalse);
371    } else if (const Not * pablo_not = dyn_cast<Not>(stmt)) {
372        expr = iBuilder->simd_not(compileExpression(pablo_not->getExpr()));
373    } else if (const Advance * adv = dyn_cast<Advance>(stmt)) {
374        Value * const strm_value = compileExpression(adv->getExpr());
375        expr = mCarryManager->advanceCarryInCarryOut(adv->getLocalIndex(), adv->getAmount(), strm_value);
376    } else if (const MatchStar * mstar = dyn_cast<MatchStar>(stmt)) {
377        Value * const marker = compileExpression(mstar->getMarker());
378        Value * const cc = compileExpression(mstar->getCharClass());
379        Value * const marker_and_cc = iBuilder->simd_and(marker, cc);
380        Value * const sum = mCarryManager->addCarryInCarryOut(mstar->getLocalCarryIndex(), marker_and_cc, cc);
381        expr = iBuilder->simd_or(iBuilder->simd_xor(sum, cc), marker);
382    } else if (const ScanThru * sthru = dyn_cast<ScanThru>(stmt)) {
383        Value * const  marker_expr = compileExpression(sthru->getScanFrom());
384        Value * const  cc_expr = compileExpression(sthru->getScanThru());
385        Value * const  sum = mCarryManager->addCarryInCarryOut(sthru->getLocalCarryIndex(), marker_expr, cc_expr);
386        expr = iBuilder->simd_and(sum, iBuilder->simd_not(cc_expr));
387    } else if (const Count * c = dyn_cast<Count>(stmt)) {
388        Value * const to_count = compileExpression(c->getExpr());
389        expr = mCarryManager->popCount(to_count, c->getGlobalCountIndex());
390    } else if (const Lookahead * l = dyn_cast<Lookahead>(stmt)) {
391        PabloAST * const var = l->getExpr();
392        if (LLVM_UNLIKELY(!isa<Var>(var))) {
393            throw std::runtime_error("Lookahead input type must be a Var object");
394        }
395        unsigned index = 0;
396        for (; index < mPabloFunction->getNumOfParameters(); ++index) {
397            if (mPabloFunction->getParameter(index) == var) {
398                break;
399            }
400        }
401        if (LLVM_UNLIKELY(index >= mPabloFunction->getNumOfParameters())) {
402            throw std::runtime_error("Lookahead has an illegal Var operand");
403        }
404        const unsigned offset = l->getAmount() / iBuilder->getBitBlockWidth();
405        const unsigned shift = (l->getAmount() % iBuilder->getBitBlockWidth());
406        Value * const v0 = iBuilder->CreateBlockAlignedLoad(mKernelBuilder->getInputStream(index, offset));
407        Value * const v1 = iBuilder->CreateBlockAlignedLoad(mKernelBuilder->getInputStream(index, offset + 1));
408        if (LLVM_UNLIKELY((shift % 8) == 0)) { // Use a single whole-byte shift, if possible.
409            expr = iBuilder->mvmd_dslli(8, v1, v0, (shift / 8));
410        } else if (LLVM_LIKELY(shift < DSSLI_FIELDWIDTH)) {
411            Value * ahead = iBuilder->mvmd_dslli(DSSLI_FIELDWIDTH, v1, v0, 1);
412            ahead = iBuilder->simd_slli(DSSLI_FIELDWIDTH, ahead, DSSLI_FIELDWIDTH - shift);
413            Value * value = iBuilder->simd_srli(DSSLI_FIELDWIDTH, v0, shift);
414            expr = iBuilder->simd_or(value, ahead);
415        } else {
416            Type  * const streamType = iBuilder->getIntNTy(iBuilder->getBitBlockWidth());
417            Value * b0 = iBuilder->CreateBitCast(v0, streamType);
418            Value * b1 = iBuilder->CreateBitCast(v1, streamType);
419            Value * result = iBuilder->CreateOr(iBuilder->CreateShl(b1, iBuilder->getBitBlockWidth() - shift), iBuilder->CreateLShr(b0, shift));
420            expr = iBuilder->CreateBitCast(result, mBitBlockType);
421        }
422    } else {
423        std::string tmp;
424        llvm::raw_string_ostream msg(tmp);
425        msg << "Internal error: ";
426        PabloPrinter::print(stmt, msg);
427        msg << " is not a recognized statement in the Pablo compiler.";
428        throw std::runtime_error(msg.str());
429    }
430    mMarkerMap[stmt] = expr;
431    if (DumpTrace) {
432        iBuilder->CallPrintRegister(stmt->getName()->to_string(), expr);
433    }
434   
435}
436
437Value * PabloCompiler::compileExpression(const PabloAST * expr) {
438    if (LLVM_UNLIKELY(isa<Ones>(expr))) {
439        return iBuilder->allOnes();
440    } else if (LLVM_UNLIKELY(isa<Zeroes>(expr))) {
441        return iBuilder->allZeroes();
442    }
443    auto f = mMarkerMap.find(expr);
444    if (LLVM_UNLIKELY(f == mMarkerMap.end())) {
445        std::string o;
446        llvm::raw_string_ostream str(o);
447        str << "\"";
448        PabloPrinter::print(expr, str);
449        str << "\" was used before definition!";
450        throw std::runtime_error(str.str());
451    }
452    Value * result = f->second;
453    if (LLVM_UNLIKELY(isa<Var>(expr))) {
454        assert (isa<GetElementPtrInst>(result));
455        result = iBuilder->CreateBlockAlignedLoad(result);
456    }
457    return result;
458}
459
460}
Note: See TracBrowser for help on using the repository browser.