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

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

pablo.Lookahead support updated for stream set access/kernel system

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