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

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

Pablo Command Line options restructured

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