source: icGREP/icgrep-devel/icgrep/pablo/carry_manager.cpp @ 5246

Last change on this file since 5246 was 5246, checked in by nmedfort, 3 years ago

Code clean up to enforce proper calling order of KernelBuilder? methods

File size: 29.1 KB
Line 
1/*
2 *  Copyright (c) 2015 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 <stdexcept>
8#include <pablo/carry_data.h>
9#include <pablo/codegenstate.h>
10#include <pablo/carry_manager.h>
11#include <pablo/pabloAST.h>
12#include <llvm/Support/CommandLine.h>
13#include <llvm/IR/BasicBlock.h>
14#include <llvm/IR/CallingConv.h>
15#include <llvm/IR/Function.h>
16#include <pablo/printer_pablos.h>
17
18namespace pablo {
19
20inline static unsigned nearest_pow2(const uint32_t v) {
21    assert(v > 0 && v < (UINT32_MAX / 2));
22    return (v < 2) ? 1 : (1 << (32 - __builtin_clz(v - 1)));
23}
24
25inline static unsigned ceil_udiv(const unsigned x, const unsigned y) {
26    return (((x - 1) | (y - 1)) + 1) / y;
27}
28
29/** ------------------------------------------------------------------------------------------------------------- *
30 * @brief initializeCarryData
31 ** ------------------------------------------------------------------------------------------------------------- */
32void CarryManager::initializeCarryData(PabloKernel * const kernel) {
33
34    // Each scope constructs its own CarryData struct, which will be added to the final "carries" struct
35    // that is added to the Kernel. The scope index will indicate which struct to access.
36
37    // A CarryData struct either contains an array of CarryPackBlocks or an integer indicating the capacity of
38    // the variable length CarryData struct and pointer. A variable length CarryData struct is required whenever
39    // the streams accessed by a loop could vary between iterations. When resizing a CarryData struct for a
40    // particular loop, the current loop struct and all nested structs need to be resized. This accommodates
41    // the fact every pablo While loop must be executed at least once.
42
43    // A nested loop may also contain a variable length CarryData struct
44
45    // To determine whether we require a variable length CarryData struct, we test the escaped variables of
46    // each loop branch to see whether they are used as the index parameter of a nested Extract statement.
47    // Any scope that requires variable length CarryData, requires that all nested branches have a unique
48    // set of carries for that iteration.
49
50    mKernel = kernel;
51
52    mCurrentScope = kernel->getEntryBlock();
53
54    mCarryMetadata.resize(enumerate(mCurrentScope));
55
56    mKernel->addScalar(analyse(mCurrentScope), "carries");
57}
58
59/** ------------------------------------------------------------------------------------------------------------- *
60 * @brief initializeCodeGen
61 ** ------------------------------------------------------------------------------------------------------------- */
62void CarryManager::initializeCodeGen(Value * self, Function * function) {
63    // TODO: need to look into abstracting the Initialize creation function in KernelBuilder::generateKernel
64    // so that we can allocate the variable length buffers if needed.
65
66    mSelf = self;
67    mFunction = function;
68
69    assert(mCarryMetadata.size() > 0);
70    mCarryInfo = &mCarryMetadata[0];
71    assert (!mCarryInfo->hasSummary());
72
73    mCurrentFrame = iBuilder->CreateGEP(mSelf, {iBuilder->getInt32(0), mKernel->getScalarIndex("carries")}, "carries");
74    mCurrentFrameIndex = 0;
75
76    assert (mCarryFrame.empty());
77    assert (mCarrySummary.empty());
78}
79
80/** ------------------------------------------------------------------------------------------------------------- *
81 * @brief enterLoopScope
82 ** ------------------------------------------------------------------------------------------------------------- */
83void CarryManager::enterLoopScope(PabloBlock * const scope) {
84    assert (scope);
85    if (mLoopDepth++ == 0) {
86        Value * const blockNo = mKernel->getScalarField(mSelf, blockNoScalar);
87        mLoopSelector = iBuilder->CreateAnd(blockNo, ConstantInt::get(blockNo->getType(), 1));
88    }
89    enterScope(scope);
90}
91
92/** ------------------------------------------------------------------------------------------------------------- *
93 * @brief enterLoopBody
94 ** ------------------------------------------------------------------------------------------------------------- */
95void CarryManager::enterLoopBody(BasicBlock * const entryBlock) {
96
97    if (mCarryInfo->hasSummary()) {
98        PHINode * carrySummary = iBuilder->CreatePHI(mCarryPackType, 2, "summary");
99        assert (mCarrySummary.size() > 0);
100        carrySummary->addIncoming(mCarrySummary.back(), entryBlock);
101        // Replace the incoming carry summary with the phi node and add the phi node to the stack
102        // so that we can properly OR it into the outgoing summary value.
103        mCarrySummary.back() = carrySummary;
104        mCarrySummary.push_back(carrySummary);
105    }
106
107    if (LLVM_UNLIKELY(mCarryInfo->variableLength)) {
108        // Check whether we need to resize the carry state
109        PHINode * index = iBuilder->CreatePHI(iBuilder->getSizeTy(), 2);
110        mLoopIndicies.push_back(index);
111        index->addIncoming(iBuilder->getSize(0), entryBlock);
112        Value * capacityPtr = iBuilder->CreateGEP(mCurrentFrame, {iBuilder->getInt32(0), iBuilder->getInt32(0)});
113        Value * capacity = iBuilder->CreateLoad(capacityPtr, false, "capacity");
114        Value * arrayPtr = iBuilder->CreateGEP(mCurrentFrame, {iBuilder->getInt32(0), iBuilder->getInt32(1)});
115        Value * array = iBuilder->CreateLoad(arrayPtr, false, "array");
116
117        LLVMContext & C = iBuilder->getContext();
118
119        BasicBlock * resizeBlock = BasicBlock::Create(C, "", mFunction);
120        BasicBlock * cleanUpBlock = BasicBlock::Create(C, "", mFunction);
121        BasicBlock * zeroBlock = BasicBlock::Create(C, "", mFunction);
122        BasicBlock * codeBlock = BasicBlock::Create(C, "", mFunction);
123
124        Value * cond = iBuilder->CreateICmpULT(index, capacity);
125        iBuilder->CreateCondBr(cond, codeBlock, resizeBlock);
126        iBuilder->SetInsertPoint(resizeBlock);
127
128        Type * const carryStateType = array->getType()->getPointerElementType();
129        Value * newCapacity = iBuilder->CreateMul(iBuilder->CreateAdd(index, iBuilder->getSize(1)), iBuilder->getSize(2));
130        Value * newArray = iBuilder->CreateAlignedMalloc(carryStateType, newCapacity, iBuilder->getCacheAlignment());
131
132        assert (newCapacity->getType() == capacity->getType());
133        assert (newArray->getType() == array->getType());
134
135        Value * isNullCarryState = iBuilder->CreateICmpEQ(array, ConstantPointerNull::get(cast<PointerType>(array->getType())));
136
137        iBuilder->CreateCondBr(isNullCarryState, zeroBlock, cleanUpBlock);
138        iBuilder->SetInsertPoint(cleanUpBlock);
139
140        iBuilder->CreateMemCpy(newArray, array, capacity, iBuilder->getCacheAlignment());
141        iBuilder->CreateAlignedFree(array);
142        iBuilder->CreateBr(zeroBlock);
143
144        iBuilder->SetInsertPoint(zeroBlock);
145
146        iBuilder->CreateMemZero(iBuilder->CreateGEP(newArray, capacity), iBuilder->CreateSub(newCapacity, capacity), iBuilder->getCacheAlignment());
147        iBuilder->CreateStore(newCapacity, capacityPtr);
148        iBuilder->CreateStore(newArray, arrayPtr);
149
150        iBuilder->CreateBr(codeBlock);
151
152        // Load the appropriate carry stat block
153        iBuilder->SetInsertPoint(codeBlock);
154
155        mCurrentFrame = iBuilder->CreateGEP(iBuilder->CreateLoad(arrayPtr), index);
156
157    }
158}
159
160/** ------------------------------------------------------------------------------------------------------------- *
161 * @brief leaveLoopBody
162 ** ------------------------------------------------------------------------------------------------------------- */
163void CarryManager::leaveLoopBody(BasicBlock * const exitBlock) {
164    if (mCarryInfo->hasSummary()) {
165        const auto n = mCarrySummary.size(); assert (n > 1);
166        cast<PHINode>(mCarrySummary[n - 2])->addIncoming(mCarrySummary[n - 1], exitBlock);
167        mCarrySummary.pop_back();
168    }
169    if (LLVM_UNLIKELY(mCarryInfo->variableLength)) {
170        assert (mLoopIndicies.size() > 0);
171        PHINode * index = mLoopIndicies.back();
172        index->addIncoming(iBuilder->CreateAdd(index, iBuilder->getSize(1)), exitBlock);
173        mLoopIndicies.pop_back();
174    }
175}
176
177/** ------------------------------------------------------------------------------------------------------------- *
178 * @brief leaveLoopScope
179 ** ------------------------------------------------------------------------------------------------------------- */
180void CarryManager::leaveLoopScope(BasicBlock * const entryBlock, BasicBlock * const exitBlock) {
181    assert (mLoopDepth > 0);
182    if (--mLoopDepth == 0) {
183        mLoopSelector = nullptr;
184    }
185    leaveScope();
186}
187
188/** ------------------------------------------------------------------------------------------------------------- *
189 * @brief enterIfScope
190 ** ------------------------------------------------------------------------------------------------------------- */
191void CarryManager::enterIfScope(PabloBlock * const scope) {
192    ++mIfDepth;
193    enterScope(scope);
194    mCarrySummary.push_back(Constant::getNullValue(mCarryPackType));
195}
196
197/** ------------------------------------------------------------------------------------------------------------- *
198 * @brief generateSummaryTest
199 ** ------------------------------------------------------------------------------------------------------------- */
200Value * CarryManager::generateSummaryTest(Value * condition) {
201    if (LLVM_LIKELY(mCarryInfo->hasSummary())) {
202        ConstantInt * zero = iBuilder->getInt32(0);
203        std::vector<Value *> indicies;
204        // enter the (potentially nested) struct and extract the summary element (always element 0)
205        unsigned count = 2;
206        if (LLVM_UNLIKELY(mCarryInfo->hasBorrowedSummary())) {
207            Type * frameTy = mCurrentFrame->getType()->getPointerElementType();
208            count = 1;
209            while (frameTy->isStructTy()) {
210                ++count;
211                frameTy = frameTy->getStructElementType(0);
212            }
213        }
214        indicies.assign(count, zero);
215        if (LLVM_UNLIKELY(mCarryInfo->hasImplicitSummary() && mLoopDepth > 0)) {
216            indicies.push_back(zero);
217            indicies.push_back(mLoopSelector);
218        }
219        Value * ptr = iBuilder->CreateGEP(mCurrentFrame, indicies);
220        // Sanity check: make sure we're accessing a summary value
221        assert (ptr->getType()->getPointerElementType()->canLosslesslyBitCastTo(condition->getType()));
222        Value * summary = iBuilder->CreateBlockAlignedLoad(ptr);
223        condition = iBuilder->simd_or(condition, summary);
224    }
225    return condition;
226}
227
228/** ------------------------------------------------------------------------------------------------------------- *
229 * @brief enterIfBody
230 ** ------------------------------------------------------------------------------------------------------------- */
231void CarryManager::enterIfBody(BasicBlock * const entryBlock) { assert (entryBlock);
232
233}
234
235/** ------------------------------------------------------------------------------------------------------------- *
236 * @brief leaveIfBody
237 ** ------------------------------------------------------------------------------------------------------------- */
238void CarryManager::leaveIfBody(BasicBlock * const exitBlock) { assert (exitBlock);
239    const auto n = mCarrySummary.size();
240    if (LLVM_LIKELY(mCarryInfo->hasExplicitSummary())) {
241        assert (mCarrySummary.size() > 0);
242        Value * ptr = iBuilder->CreateGEP(mCurrentFrame, {iBuilder->getInt32(0), iBuilder->getInt32(0)});
243        Value * const value = iBuilder->CreateBitCast(mCarrySummary.back(), mBitBlockType);
244        iBuilder->CreateBlockAlignedStore(value, ptr);
245    }
246    if (n > 1) {
247        mCarrySummary[n - 1] = iBuilder->CreateOr(mCarrySummary[n - 1], mCarrySummary[n - 2], "summary");
248    }
249}
250
251/** ------------------------------------------------------------------------------------------------------------- *
252 * @brief leaveIfScope
253 ** ------------------------------------------------------------------------------------------------------------- */
254void CarryManager::leaveIfScope(BasicBlock * const entryBlock, BasicBlock * const exitBlock) {
255    assert (mIfDepth > 0);
256    if (mCarryInfo->hasSummary()) {
257        const auto n = mCarrySummary.size(); assert (n > 0);
258        if (n > 1) {
259            // When leaving a nested If scope with a summary value, phi out the summary to ensure the
260            // appropriate summary is stored in the outer scope.
261            Value * nested = mCarrySummary[n - 1];
262            Value * outer = mCarrySummary[n - 2];
263            if (LLVM_LIKELY(nested != outer)) {
264                assert (nested->getType() == outer->getType());
265                PHINode * const phi = iBuilder->CreatePHI(nested->getType(), 2, "summary");
266                phi->addIncoming(outer, entryBlock);
267                phi->addIncoming(nested, exitBlock);
268                mCarrySummary[n - 2] = phi;
269            }
270        }       
271    }
272    --mIfDepth;
273    leaveScope();
274    mCarrySummary.pop_back();
275}
276
277/** ------------------------------------------------------------------------------------------------------------ *
278 * @brief enterScope
279 ** ------------------------------------------------------------------------------------------------------------- */
280void CarryManager::enterScope(PabloBlock * const scope) {
281    assert (scope);
282    // Store the state of the current frame and update the scope state
283    mCarryFrame.emplace_back(mCurrentFrame, mCurrentFrameIndex + 1);
284    mCurrentScope = scope;
285    mCarryInfo = &mCarryMetadata[scope->getScopeIndex()];
286    // Check whether we're still within our struct bounds; if this fails, either the Pablo program changed within
287    // compilation or a memory corruption has occured.
288    assert (mCurrentFrameIndex < mCurrentFrame->getType()->getPointerElementType()->getStructNumElements());
289    mCurrentFrame = iBuilder->CreateGEP(mCurrentFrame, {iBuilder->getInt32(0), iBuilder->getInt32(mCurrentFrameIndex)});
290    // Verify we're pointing to a carry frame struct
291    assert(mCurrentFrame->getType()->getPointerElementType()->isStructTy());
292    // We always use the 0-th slot for the summary value, even when it's implicit
293    mCurrentFrameIndex = mCarryInfo->hasExplicitSummary() ? 1 : 0;
294}
295
296/** ------------------------------------------------------------------------------------------------------------- *
297 * @brief leaveScope
298 ** ------------------------------------------------------------------------------------------------------------- */
299void CarryManager::leaveScope() {
300
301    // Did we use all of the packs in this carry struct?
302    assert (mCurrentFrameIndex == mCurrentFrame->getType()->getPointerElementType()->getStructNumElements());
303    // Sanity test: are there remaining carry frames?
304    assert (mCarryFrame.size() > 0);
305
306    std::tie(mCurrentFrame, mCurrentFrameIndex) = mCarryFrame.back();
307
308    assert(mCurrentFrame->getType()->getPointerElementType()->isStructTy());
309
310    mCarryFrame.pop_back();
311
312    mCurrentScope = mCurrentScope->getPredecessor();
313    assert (mCurrentScope);
314    mCarryInfo = &mCarryMetadata[mCurrentScope->getScopeIndex()];   
315}
316
317/** ------------------------------------------------------------------------------------------------------------- *
318 * @brief addCarryInCarryOut
319 ** ------------------------------------------------------------------------------------------------------------- */
320Value * CarryManager::addCarryInCarryOut(const Statement * operation, Value * const e1, Value * const e2) {
321    assert (dyn_cast_or_null<ScanThru>(operation) || dyn_cast_or_null<MatchStar>(operation));
322    Value * const carryIn = getNextCarryIn();
323    Value * carryOut, * result;
324    std::tie(carryOut, result) = iBuilder->bitblock_add_with_carry(e1, e2, carryIn);
325    setNextCarryOut(carryOut);
326    assert (result->getType() == mBitBlockType);
327    return result;
328}
329
330/** ------------------------------------------------------------------------------------------------------------- *
331 * @brief advanceCarryInCarryOut
332 ** ------------------------------------------------------------------------------------------------------------- */
333Value * CarryManager::advanceCarryInCarryOut(const Advance * advance, Value * const value) {
334    const auto shiftAmount = advance->getAmount();
335    if (LLVM_LIKELY(shiftAmount <= mBitBlockWidth)) {
336        Value * const carryIn = getNextCarryIn();
337        Value * carryOut, * result;
338        if (LLVM_UNLIKELY(shiftAmount == mBitBlockWidth)) {
339            result = carryIn;
340            carryOut = value;
341        } else {
342            std::tie(carryOut, result) = iBuilder->bitblock_advance(value, carryIn, shiftAmount);
343        }
344        setNextCarryOut(carryOut);
345        assert (result->getType() == mBitBlockType);
346        return result;
347    } else {
348        return longAdvanceCarryInCarryOut(shiftAmount, value);
349    }
350}
351
352/** ------------------------------------------------------------------------------------------------------------- *
353 * @brief longAdvanceCarryInCarryOut
354 ** ------------------------------------------------------------------------------------------------------------- */
355Value * CarryManager::longAdvanceCarryInCarryOut(const unsigned shiftAmount, Value * value) {
356
357    assert (shiftAmount > mBitBlockWidth);
358
359    Type * const streamVectorTy = iBuilder->getIntNTy(mBitBlockWidth);
360    value = iBuilder->CreateBitCast(value, mBitBlockType);
361    Value * buffer = iBuilder->CreateGEP(mCurrentFrame, {iBuilder->getInt32(0), iBuilder->getInt32(mCurrentFrameIndex++), iBuilder->getInt32(0)});
362
363    const unsigned blockShift = shiftAmount % mBitBlockWidth;
364    const unsigned entries = ceil_udiv(shiftAmount, mBitBlockWidth);
365
366    if (LLVM_LIKELY(mCarryInfo->hasExplicitSummary())) {
367        Value * const summaryPtr = iBuilder->CreateGEP(buffer, iBuilder->getInt32(0));
368        assert (summaryPtr->getType()->getPointerElementType() == mBitBlockType);
369        Value * carry = iBuilder->CreateZExtOrBitCast(iBuilder->bitblock_any(value), streamVectorTy);
370        const auto limit = ceil_udiv(shiftAmount, std::pow(mBitBlockWidth, 2));
371        assert (limit == summaryPtr->getType()->getPointerElementType()->getArrayNumElements());
372        for (unsigned i = 0;;++i) {
373            Value * ptr = iBuilder->CreateGEP(summaryPtr, iBuilder->getInt32(i));
374            Value * prior = iBuilder->CreateBitCast(iBuilder->CreateBlockAlignedLoad(ptr), streamVectorTy);
375            Value * stream = iBuilder->CreateOr(iBuilder->CreateShl(prior, 1), carry);
376            if (LLVM_LIKELY(i == limit)) {
377                stream = iBuilder->CreateAnd(stream, iBuilder->bitblock_mask_from(iBuilder->getInt32(entries % mBitBlockWidth)));
378                addToSummary(stream);
379                iBuilder->CreateBlockAlignedStore(stream, ptr);               
380                buffer = iBuilder->CreateGEP(buffer, iBuilder->getInt32(1));
381                break;
382            }
383            addToSummary(stream);
384            iBuilder->CreateBlockAlignedStore(stream, ptr);
385            carry = iBuilder->CreateLShr(prior, mBitBlockWidth - 1);
386        }
387    }
388    assert (buffer->getType()->getPointerElementType() == mBitBlockType);
389
390    // Create a mask to implement circular buffer indexing
391    Value * indexMask = iBuilder->getSize(nearest_pow2(entries) - 1);
392    Value * blockIndex = mKernel->getScalarField(mSelf, blockNoScalar);
393    Value * carryIndex0 = iBuilder->CreateSub(blockIndex, iBuilder->getSize(entries));
394    Value * loadIndex0 = iBuilder->CreateAnd(carryIndex0, indexMask);
395    Value * storeIndex = iBuilder->CreateAnd(blockIndex, indexMask);
396    Value * carryIn = iBuilder->CreateBlockAlignedLoad(iBuilder->CreateGEP(buffer, loadIndex0));
397    assert (carryIn->getType() == mBitBlockType);
398    // If the long advance is an exact multiple of mBitBlockWidth, we simply return the oldest
399    // block in the long advance carry data area. 
400    if (blockShift == 0) {
401        iBuilder->CreateBlockAlignedStore(value, iBuilder->CreateGEP(buffer, storeIndex));
402        return carryIn;
403    }
404    // Otherwise we need to combine data from the two oldest blocks.
405    Value * carryIndex1 = iBuilder->CreateSub(blockIndex, iBuilder->getSize(entries - 1));
406    Value * loadIndex1 = iBuilder->CreateAnd(carryIndex1, indexMask);
407    Value * carry_block1 = iBuilder->CreateBlockAlignedLoad(iBuilder->CreateGEP(buffer, loadIndex1));
408    Value * block0_shr = iBuilder->CreateLShr(iBuilder->CreateBitCast(carryIn, streamVectorTy), mBitBlockWidth - blockShift);
409    Value * block1_shl = iBuilder->CreateShl(iBuilder->CreateBitCast(carry_block1, streamVectorTy), blockShift);
410    iBuilder->CreateBlockAlignedStore(value, iBuilder->CreateGEP(buffer, storeIndex));
411    return iBuilder->CreateBitCast(iBuilder->CreateOr(block1_shl, block0_shr), mBitBlockType);
412}
413
414/** ------------------------------------------------------------------------------------------------------------- *
415 * @brief getNextCarryIn
416 ** ------------------------------------------------------------------------------------------------------------- */
417Value * CarryManager::getNextCarryIn() {
418    assert (mCurrentFrameIndex < mCurrentFrame->getType()->getPointerElementType()->getStructNumElements());
419    Value * carryInPtr = iBuilder->CreateGEP(mCurrentFrame, {iBuilder->getInt32(0), iBuilder->getInt32(mCurrentFrameIndex++)});
420    mCarryPackPtr = carryInPtr;
421    if (mLoopDepth > 0) {
422        carryInPtr = iBuilder->CreateGEP(carryInPtr, {iBuilder->getInt32(0), mLoopSelector});
423    }
424    assert (carryInPtr->getType()->getPointerElementType() == mCarryPackType);
425    Value * const carryIn = iBuilder->CreateBlockAlignedLoad(carryInPtr);
426    if (mLoopDepth > 0) {
427        iBuilder->CreateBlockAlignedStore(Constant::getNullValue(mCarryPackType), carryInPtr);
428    }
429    return carryIn;
430}
431
432/** ------------------------------------------------------------------------------------------------------------- *
433 * @brief setNextCarryOut
434 ** ------------------------------------------------------------------------------------------------------------- */
435void CarryManager::setNextCarryOut(Value * carryOut) {
436    if (LLVM_LIKELY(mCarryInfo->hasExplicitSummary())) {       
437        addToSummary(carryOut);
438    }
439    Value * carryOutPtr = mCarryPackPtr;
440    if (mLoopDepth > 0) {
441        Value * selector = iBuilder->CreateXor(mLoopSelector, ConstantInt::get(mLoopSelector->getType(), 1));
442        carryOutPtr = iBuilder->CreateGEP(mCarryPackPtr, {iBuilder->getInt32(0), selector});
443    }
444    carryOut = iBuilder->CreateBitCast(carryOut, mCarryPackType);
445    if (inCollapsingCarryMode()) {
446        Value * accum = iBuilder->CreateBlockAlignedLoad(carryOutPtr);
447        carryOut = iBuilder->CreateOr(carryOut, accum);
448    }
449    assert (carryOutPtr->getType()->getPointerElementType() == mCarryPackType);
450    iBuilder->CreateBlockAlignedStore(carryOut, carryOutPtr);
451}
452
453/** ------------------------------------------------------------------------------------------------------------- *
454 * @brief addToSummary
455 ** ------------------------------------------------------------------------------------------------------------- */
456void CarryManager::addToSummary(Value * value) { assert (value);
457    assert (mIfDepth > 0 && mCarrySummary.size() > 0);
458    Value * const summary = mCarrySummary.back(); assert (summary);
459    if (LLVM_UNLIKELY(summary == value)) {
460        return;  //Nothing to add.
461    }
462    value = iBuilder->CreateBitCast(value, mCarryPackType);
463    if (LLVM_UNLIKELY(isa<Constant>(value))) {
464        if (LLVM_UNLIKELY(cast<Constant>(value)->isZeroValue())) {
465            return;
466        } else if (LLVM_UNLIKELY(cast<Constant>(value)->isAllOnesValue())) {
467            mCarrySummary.back() = value;
468            return;
469        }
470    } else if (LLVM_UNLIKELY(isa<Constant>(summary))) {
471        if (LLVM_UNLIKELY(cast<Constant>(summary)->isZeroValue())) {
472            mCarrySummary.back() = value;
473            return;
474        } else if (LLVM_UNLIKELY(cast<Constant>(summary)->isAllOnesValue())) {
475            return;
476        }
477    }   
478    mCarrySummary.back() = iBuilder->CreateOr(summary, value);
479}
480
481/** ------------------------------------------------------------------------------------------------------------- *
482 * @brief collapsingCarryMode
483 ** ------------------------------------------------------------------------------------------------------------- */
484bool CarryManager::inCollapsingCarryMode() const {
485    return (mCurrentScope->getBranch() && isa<While>(mCurrentScope->getBranch()) && !mCarryInfo->variableLength);
486}
487
488/** ------------------------------------------------------------------------------------------------------------- *
489 * @brief enumerate
490 ** ------------------------------------------------------------------------------------------------------------- */
491unsigned CarryManager::enumerate(PabloBlock * const scope, unsigned index) {
492    scope->setScopeIndex(index++);
493    for (Statement * stmt : *scope) {
494        if (LLVM_UNLIKELY(isa<Branch>(stmt))) {
495            index = enumerate(cast<Branch>(stmt)->getBody(), index);
496        }
497    }
498    return index;
499}
500
501/** ------------------------------------------------------------------------------------------------------------- *
502 * @brief requiresVariableLengthMode
503 ** ------------------------------------------------------------------------------------------------------------- */
504bool CarryManager::requiresVariableLengthMode(const PabloBlock * const scope) {
505    if (const Branch * const br = scope->getBranch()) {
506        for (const Var * var : br->getEscaped()) {
507            for (const PabloAST * user : var->users()) {
508                if (const Extract * e = dyn_cast<Extract>(user)) {
509                    if (LLVM_UNLIKELY(e->getIndex() == var)) {
510                        // If we assign this Var a value and read the value as the index parameter
511                        // of a nested Extract statement, then we cannot collapse the carries.
512                        const PabloBlock * parent = e->getParent();
513                        for (;;) {
514                            if (parent == scope) {
515                                return true;
516                            }
517                            parent = parent->getPredecessor();
518                            if (parent == nullptr) {
519                                break;
520                            }
521                        }
522                    }
523                }
524            }
525        }
526    }
527    return false;
528}
529
530/** ------------------------------------------------------------------------------------------------------------- *
531 * @brief analyse
532 ** ------------------------------------------------------------------------------------------------------------- */
533StructType * CarryManager::analyse(PabloBlock * const scope, const unsigned ifDepth, const unsigned loopDepth) {
534
535    std::vector<Type *> state;
536
537    assert (mCarryPackType);
538
539    Type * const carryPackType = (loopDepth == 0) ? mCarryPackType : ArrayType::get(mCarryPackType, 2);
540
541    bool hasLongAdvances = false;
542    for (Statement * stmt : *scope) {
543        if (LLVM_UNLIKELY(isa<Advance>(stmt))) {
544            const auto amount = cast<Advance>(stmt)->getAmount();
545            if (LLVM_LIKELY(amount <= mBitBlockWidth)) {
546                state.push_back(carryPackType);
547            } else {
548                const auto blocks = ceil_udiv(amount, mBitBlockWidth); assert (blocks > 1);
549                Type * type = ArrayType::get(mBitBlockType, nearest_pow2(blocks));
550                if (LLVM_UNLIKELY(ifDepth > 0)) {
551                    Type * carryType = ArrayType::get(mBitBlockType, ceil_udiv(amount, std::pow(mBitBlockWidth, 2)));
552                    type = StructType::get(carryType, type, nullptr);
553                    hasLongAdvances = true;
554                }
555                state.push_back(type);
556            }
557        } else if (LLVM_UNLIKELY(isa<ScanThru>(stmt) || isa<MatchStar>(stmt))) {
558            state.push_back(carryPackType);
559        } else if (LLVM_UNLIKELY(isa<If>(stmt))) {
560            state.push_back(analyse(cast<If>(stmt)->getBody(), ifDepth + 1, loopDepth));
561        } else if (LLVM_UNLIKELY(isa<While>(stmt))) {
562            state.push_back(analyse(cast<While>(stmt)->getBody(), ifDepth, loopDepth + 1));
563        }
564    }
565
566    assert (scope->getScopeIndex() < mCarryMetadata.size());
567
568    CarryData & cd = mCarryMetadata[scope->getScopeIndex()];
569
570    StructType * carryState = nullptr;
571
572    // Add the summary pack if needed.
573    cd.summaryType = CarryData::NoSummary;
574    if (LLVM_UNLIKELY(state.empty())) {
575        carryState = StructType::get(iBuilder->getContext());
576    } else {
577        cd.variableLength = loopDepth > 0 && requiresVariableLengthMode(scope);
578        if (ifDepth > 0) {
579            // A non-collapsing loop requires a unique summary for each iteration. Thus whenever
580            // we have a non-collapsing While within an If scope with an implicit summary, the If
581            // scope requires an explicit summary.
582
583            if (LLVM_LIKELY(state.size() > 1 || hasLongAdvances)) {
584                cd.summaryType = CarryData::ExplicitSummary;
585                state.insert(state.begin(), mCarryPackType);
586            } else {
587                cd.summaryType = CarryData::ImplicitSummary;
588                if (state[0]->isStructTy()) {
589                    cd.summaryType = CarryData::BorrowedSummary;
590                }
591            }
592        }
593        carryState = StructType::get(iBuilder->getContext(), state);
594        // If we in a loop and cannot use collapsing carry mode, convert the struct into a capacity and pointer pair.
595        if (LLVM_UNLIKELY(cd.variableLength)) {
596            carryState = StructType::get(iBuilder->getSizeTy(), carryState->getPointerTo(), nullptr);
597        }
598    }
599    return carryState;
600}
601
602}
603
Note: See TracBrowser for help on using the repository browser.