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

Last change on this file since 5233 was 5233, checked in by nmedfort, 22 months ago

Bug fixes for Carry Manager and issues reported by Fahad

File size: 28.5 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->getInt32Ty(), 2);
110        mLoopIndicies.push_back(index);
111        index->addIncoming(iBuilder->getInt32(0), entryBlock);
112        Value * capacityPtr = iBuilder->CreateGEP(mCurrentFrame, {iBuilder->getInt32(0), iBuilder->getInt32(0)});
113        Value * capacity = iBuilder->CreateLoad(capacityPtr, false, "carryCapacity");
114        Value * arrayPtr = iBuilder->CreateGEP(mCurrentFrame, {iBuilder->getInt32(0), iBuilder->getInt32(1)});
115
116        BasicBlock * resizeBlock = BasicBlock::Create(iBuilder->getContext(), "", mFunction);
117        BasicBlock * codeBlock = BasicBlock::Create(iBuilder->getContext(), "", mFunction);
118
119        Value * cond = iBuilder->CreateICmpULT(index, capacity);
120        iBuilder->CreateCondBr(cond, codeBlock, resizeBlock);
121        iBuilder->SetInsertPoint(resizeBlock);
122
123        Type * const carryStateType = arrayPtr->getType()->getPointerElementType()->getPointerElementType();
124        Value * newCapacity = iBuilder->CreateMul(iBuilder->CreateAdd(index, iBuilder->getInt32(1)), iBuilder->getInt32(2));
125        Value * newArrayPtr = iBuilder->CreateAlignedMalloc(carryStateType, newCapacity, iBuilder->getCacheAlignment());
126        iBuilder->CreateMemCpy(newArrayPtr, arrayPtr, capacity, iBuilder->getCacheAlignment());
127        iBuilder->CreateMemZero(iBuilder->CreateGEP(newArrayPtr, capacity), iBuilder->CreateSub(newCapacity, capacity), iBuilder->getCacheAlignment());
128        iBuilder->CreateAlignedFree(arrayPtr);
129        iBuilder->CreateStore(newCapacity, capacityPtr);
130        iBuilder->CreateStore(newArrayPtr, arrayPtr);
131        iBuilder->CreateBr(codeBlock);
132
133        // Load the appropriate carry stat block
134        iBuilder->SetInsertPoint(codeBlock);
135
136        mCurrentFrame = iBuilder->CreateGEP(iBuilder->CreateLoad(arrayPtr), index);
137
138    }
139}
140
141/** ------------------------------------------------------------------------------------------------------------- *
142 * @brief leaveLoopBody
143 ** ------------------------------------------------------------------------------------------------------------- */
144void CarryManager::leaveLoopBody(BasicBlock * const exitBlock) {
145    if (mCarryInfo->hasSummary()) {
146        const auto n = mCarrySummary.size(); assert (n > 1);
147        cast<PHINode>(mCarrySummary[n - 2])->addIncoming(mCarrySummary[n - 1], exitBlock);
148        mCarrySummary.pop_back();
149    }
150    if (LLVM_UNLIKELY(mCarryInfo->variableLength)) {
151        assert (mLoopIndicies.size() > 0);
152        PHINode * index = mLoopIndicies.back();
153        index->addIncoming(iBuilder->CreateAdd(index, iBuilder->getInt32(1)), exitBlock);
154        mLoopIndicies.pop_back();
155    }
156}
157
158/** ------------------------------------------------------------------------------------------------------------- *
159 * @brief leaveLoopScope
160 ** ------------------------------------------------------------------------------------------------------------- */
161void CarryManager::leaveLoopScope(BasicBlock * const entryBlock, BasicBlock * const exitBlock) {
162    assert (mLoopDepth > 0);
163    if (--mLoopDepth == 0) {
164        mLoopSelector = nullptr;
165    }
166    leaveScope();
167}
168
169/** ------------------------------------------------------------------------------------------------------------- *
170 * @brief enterIfScope
171 ** ------------------------------------------------------------------------------------------------------------- */
172void CarryManager::enterIfScope(PabloBlock * const scope) {
173    ++mIfDepth;
174    enterScope(scope);
175    mCarrySummary.push_back(Constant::getNullValue(mCarryPackType));
176}
177
178/** ------------------------------------------------------------------------------------------------------------- *
179 * @brief generateSummaryTest
180 ** ------------------------------------------------------------------------------------------------------------- */
181Value * CarryManager::generateSummaryTest(Value * condition) {
182    if (LLVM_LIKELY(mCarryInfo->hasSummary())) {
183        ConstantInt * zero = iBuilder->getInt32(0);
184        std::vector<Value *> indicies;
185        // enter the (potentially nested) struct and extract the summary element (always element 0)
186        unsigned count = 2;
187        if (LLVM_UNLIKELY(mCarryInfo->hasBorrowedSummary())) {
188            Type * frameTy = mCurrentFrame->getType()->getPointerElementType();
189            count = 1;
190            while (frameTy->isStructTy()) {
191                ++count;
192                frameTy = frameTy->getStructElementType(0);
193            }
194        }
195        indicies.assign(count, zero);
196        if (LLVM_UNLIKELY(mCarryInfo->hasImplicitSummary() && mLoopDepth > 0)) {
197            indicies.push_back(zero);
198            indicies.push_back(mLoopSelector);
199        }
200        Value * ptr = iBuilder->CreateGEP(mCurrentFrame, indicies);
201        // Sanity check: make sure we're accessing a summary value
202        assert (ptr->getType()->getPointerElementType()->canLosslesslyBitCastTo(condition->getType()));
203        Value * summary = iBuilder->CreateBlockAlignedLoad(ptr);
204        condition = iBuilder->simd_or(condition, summary);
205    }
206    return condition;
207}
208
209/** ------------------------------------------------------------------------------------------------------------- *
210 * @brief enterIfBody
211 ** ------------------------------------------------------------------------------------------------------------- */
212void CarryManager::enterIfBody(BasicBlock * const entryBlock) { assert (entryBlock);
213
214}
215
216/** ------------------------------------------------------------------------------------------------------------- *
217 * @brief leaveIfBody
218 ** ------------------------------------------------------------------------------------------------------------- */
219void CarryManager::leaveIfBody(BasicBlock * const exitBlock) { assert (exitBlock);
220    const auto n = mCarrySummary.size();
221    if (LLVM_LIKELY(mCarryInfo->hasExplicitSummary())) {
222        assert (mCarrySummary.size() > 0);
223        Value * ptr = iBuilder->CreateGEP(mCurrentFrame, {iBuilder->getInt32(0), iBuilder->getInt32(0)});
224        Value * const value = iBuilder->CreateBitCast(mCarrySummary.back(), mBitBlockType);
225        iBuilder->CreateBlockAlignedStore(value, ptr);
226    }
227    if (n > 1) {
228        mCarrySummary[n - 1] = iBuilder->CreateOr(mCarrySummary[n - 1], mCarrySummary[n - 2], "summary");
229    }
230}
231
232/** ------------------------------------------------------------------------------------------------------------- *
233 * @brief leaveIfScope
234 ** ------------------------------------------------------------------------------------------------------------- */
235void CarryManager::leaveIfScope(BasicBlock * const entryBlock, BasicBlock * const exitBlock) {
236    assert (mIfDepth > 0);
237    if (mCarryInfo->hasSummary()) {
238        const auto n = mCarrySummary.size(); assert (n > 0);
239        if (n > 1) {
240            // When leaving a nested If scope with a summary value, phi out the summary to ensure the
241            // appropriate summary is stored in the outer scope.
242            Value * nested = mCarrySummary[n - 1];
243            Value * outer = mCarrySummary[n - 2];
244            if (LLVM_LIKELY(nested != outer)) {
245                assert (nested->getType() == outer->getType());
246                PHINode * const phi = iBuilder->CreatePHI(nested->getType(), 2, "summary");
247                phi->addIncoming(outer, entryBlock);
248                phi->addIncoming(nested, exitBlock);
249                mCarrySummary[n - 2] = phi;
250            }
251        }       
252    }
253    --mIfDepth;
254    leaveScope();
255    mCarrySummary.pop_back();
256}
257
258/** ------------------------------------------------------------------------------------------------------------ *
259 * @brief enterScope
260 ** ------------------------------------------------------------------------------------------------------------- */
261void CarryManager::enterScope(PabloBlock * const scope) {
262    assert (scope);
263    // Store the state of the current frame and update the scope state
264    mCarryFrame.emplace_back(mCurrentFrame, mCurrentFrameIndex + 1);
265    mCurrentScope = scope;
266    mCarryInfo = &mCarryMetadata[scope->getScopeIndex()];
267    // Check whether we're still within our struct bounds; if this fails, either the Pablo program changed within
268    // compilation or a memory corruption has occured.
269    assert (mCurrentFrameIndex < mCurrentFrame->getType()->getPointerElementType()->getStructNumElements());
270    mCurrentFrame = iBuilder->CreateGEP(mCurrentFrame, {iBuilder->getInt32(0), iBuilder->getInt32(mCurrentFrameIndex)});
271    // Verify we're pointing to a carry frame struct
272    assert(mCurrentFrame->getType()->getPointerElementType()->isStructTy());
273    // We always use the 0-th slot for the summary value, even when it's implicit
274    mCurrentFrameIndex = mCarryInfo->hasExplicitSummary() ? 1 : 0;
275
276}
277
278/** ------------------------------------------------------------------------------------------------------------- *
279 * @brief leaveScope
280 ** ------------------------------------------------------------------------------------------------------------- */
281void CarryManager::leaveScope() {
282
283    // Did we use all of the packs in this carry struct?
284    assert (mCurrentFrameIndex == mCurrentFrame->getType()->getPointerElementType()->getStructNumElements());
285    // Sanity test: are there remaining carry frames?
286    assert (mCarryFrame.size() > 0);
287
288    std::tie(mCurrentFrame, mCurrentFrameIndex) = mCarryFrame.back();
289
290    assert(mCurrentFrame->getType()->getPointerElementType()->isStructTy());
291
292    mCarryFrame.pop_back();
293
294    mCurrentScope = mCurrentScope->getPredecessor();
295    assert (mCurrentScope);
296    mCarryInfo = &mCarryMetadata[mCurrentScope->getScopeIndex()];   
297}
298
299/** ------------------------------------------------------------------------------------------------------------- *
300 * @brief addCarryInCarryOut
301 ** ------------------------------------------------------------------------------------------------------------- */
302Value * CarryManager::addCarryInCarryOut(const Statement * operation, Value * const e1, Value * const e2) {
303    assert (dyn_cast_or_null<ScanThru>(operation) || dyn_cast_or_null<MatchStar>(operation));
304    Value * const carryIn = getNextCarryIn();
305    Value * carryOut, * result;
306    std::tie(carryOut, result) = iBuilder->bitblock_add_with_carry(e1, e2, carryIn);
307    setNextCarryOut(carryOut);
308    assert (result->getType() == mBitBlockType);
309    return result;
310}
311
312/** ------------------------------------------------------------------------------------------------------------- *
313 * @brief advanceCarryInCarryOut
314 ** ------------------------------------------------------------------------------------------------------------- */
315Value * CarryManager::advanceCarryInCarryOut(const Advance * advance, Value * const value) {
316    const auto shiftAmount = advance->getAmount();
317    if (LLVM_LIKELY(shiftAmount <= mBitBlockWidth)) {
318        Value * const carryIn = getNextCarryIn();
319        Value * carryOut, * result;
320        if (LLVM_UNLIKELY(shiftAmount == mBitBlockWidth)) {
321            result = carryIn;
322            carryOut = value;
323        } else {
324            std::tie(carryOut, result) = iBuilder->bitblock_advance(value, carryIn, shiftAmount);
325        }
326        setNextCarryOut(carryOut);
327        assert (result->getType() == mBitBlockType);
328        return result;
329    } else {
330        return longAdvanceCarryInCarryOut(shiftAmount, value);
331    }
332}
333
334/** ------------------------------------------------------------------------------------------------------------- *
335 * @brief longAdvanceCarryInCarryOut
336 ** ------------------------------------------------------------------------------------------------------------- */
337Value * CarryManager::longAdvanceCarryInCarryOut(const unsigned shiftAmount, Value * value) {
338
339    assert (shiftAmount > mBitBlockWidth);
340
341    Type * const streamVectorTy = iBuilder->getIntNTy(mBitBlockWidth);
342    value = iBuilder->CreateBitCast(value, mBitBlockType);
343    Value * buffer = iBuilder->CreateGEP(mCurrentFrame, {iBuilder->getInt32(0), iBuilder->getInt32(mCurrentFrameIndex++), iBuilder->getInt32(0)});
344
345    const unsigned blockShift = shiftAmount % mBitBlockWidth;
346    const unsigned entries = ceil_udiv(shiftAmount, mBitBlockWidth);
347
348    if (LLVM_LIKELY(mCarryInfo->hasExplicitSummary())) {
349        Value * const summaryPtr = iBuilder->CreateGEP(buffer, iBuilder->getInt32(0));
350        assert (summaryPtr->getType()->getPointerElementType() == mBitBlockType);
351        Value * carry = iBuilder->CreateZExtOrBitCast(iBuilder->bitblock_any(value), streamVectorTy);
352        const auto limit = ceil_udiv(shiftAmount, std::pow(mBitBlockWidth, 2));
353        assert (limit == summaryPtr->getType()->getPointerElementType()->getArrayNumElements());
354        for (unsigned i = 0;;++i) {
355            Value * ptr = iBuilder->CreateGEP(summaryPtr, iBuilder->getInt32(i));
356            Value * prior = iBuilder->CreateBitCast(iBuilder->CreateBlockAlignedLoad(ptr), streamVectorTy);
357            Value * stream = iBuilder->CreateOr(iBuilder->CreateShl(prior, 1), carry);
358            if (LLVM_LIKELY(i == limit)) {
359                stream = iBuilder->CreateAnd(stream, iBuilder->bitblock_mask_from(iBuilder->getInt32(entries % mBitBlockWidth)));
360                addToSummary(stream);
361                iBuilder->CreateBlockAlignedStore(stream, ptr);               
362                buffer = iBuilder->CreateGEP(buffer, iBuilder->getInt32(1));
363                break;
364            }
365            addToSummary(stream);
366            iBuilder->CreateBlockAlignedStore(stream, ptr);
367            carry = iBuilder->CreateLShr(prior, mBitBlockWidth - 1);
368        }
369    }
370    assert (buffer->getType()->getPointerElementType() == mBitBlockType);
371
372    // Create a mask to implement circular buffer indexing
373    Value * indexMask = ConstantInt::get(iBuilder->getSizeTy(), nearest_pow2(entries) - 1);
374    Value * blockIndex = mKernel->getScalarField(mSelf, blockNoScalar);
375    Value * carryIndex0 = iBuilder->CreateSub(blockIndex, iBuilder->getSize(entries));
376    Value * loadIndex0 = iBuilder->CreateAnd(carryIndex0, indexMask);
377    Value * storeIndex = iBuilder->CreateAnd(blockIndex, indexMask);
378    Value * carryIn = iBuilder->CreateBlockAlignedLoad(iBuilder->CreateGEP(buffer, loadIndex0));
379    assert (carryIn->getType() == mBitBlockType);
380    // If the long advance is an exact multiple of mBitBlockWidth, we simply return the oldest
381    // block in the long advance carry data area. 
382    if (blockShift == 0) {
383        iBuilder->CreateBlockAlignedStore(value, iBuilder->CreateGEP(buffer, storeIndex));
384        return carryIn;
385    }
386    // Otherwise we need to combine data from the two oldest blocks.
387    Value * carryIndex1 = iBuilder->CreateSub(blockIndex, iBuilder->getSize(entries - 1));
388    Value * loadIndex1 = iBuilder->CreateAnd(carryIndex1, indexMask);
389    Value * carry_block1 = iBuilder->CreateBlockAlignedLoad(iBuilder->CreateGEP(buffer, loadIndex1));
390    Value * block0_shr = iBuilder->CreateLShr(iBuilder->CreateBitCast(carryIn, streamVectorTy), mBitBlockWidth - blockShift);
391    Value * block1_shl = iBuilder->CreateShl(iBuilder->CreateBitCast(carry_block1, streamVectorTy), blockShift);
392    iBuilder->CreateBlockAlignedStore(value, iBuilder->CreateGEP(buffer, storeIndex));
393    return iBuilder->CreateBitCast(iBuilder->CreateOr(block1_shl, block0_shr), mBitBlockType);
394}
395
396/** ------------------------------------------------------------------------------------------------------------- *
397 * @brief getNextCarryIn
398 ** ------------------------------------------------------------------------------------------------------------- */
399Value * CarryManager::getNextCarryIn() {
400    assert (mCurrentFrameIndex < mCurrentFrame->getType()->getPointerElementType()->getStructNumElements());
401    Value * carryInPtr = iBuilder->CreateGEP(mCurrentFrame, {iBuilder->getInt32(0), iBuilder->getInt32(mCurrentFrameIndex++)});
402    mCarryPackPtr = carryInPtr;
403    if (mLoopDepth > 0) {
404        carryInPtr = iBuilder->CreateGEP(carryInPtr, {iBuilder->getInt32(0), mLoopSelector});
405    }
406    assert (carryInPtr->getType()->getPointerElementType() == mCarryPackType);
407    Value * const carryIn = iBuilder->CreateBlockAlignedLoad(carryInPtr);
408    if (mLoopDepth > 0) {
409        iBuilder->CreateBlockAlignedStore(Constant::getNullValue(mCarryPackType), carryInPtr);
410    }
411    return carryIn;
412}
413
414/** ------------------------------------------------------------------------------------------------------------- *
415 * @brief setNextCarryOut
416 ** ------------------------------------------------------------------------------------------------------------- */
417void CarryManager::setNextCarryOut(Value * carryOut) {
418    if (LLVM_LIKELY(mCarryInfo->hasExplicitSummary())) {       
419        addToSummary(carryOut);
420    }
421    Value * carryOutPtr = mCarryPackPtr;
422    if (mLoopDepth > 0) {
423        Value * selector = iBuilder->CreateXor(mLoopSelector, ConstantInt::get(mLoopSelector->getType(), 1));
424        carryOutPtr = iBuilder->CreateGEP(mCarryPackPtr, {iBuilder->getInt32(0), selector});
425    }
426    carryOut = iBuilder->CreateBitCast(carryOut, mCarryPackType);
427    if (inCollapsingCarryMode()) {
428        Value * accum = iBuilder->CreateBlockAlignedLoad(carryOutPtr);
429        carryOut = iBuilder->CreateOr(carryOut, accum);
430    }
431    assert (carryOutPtr->getType()->getPointerElementType() == mCarryPackType);
432    iBuilder->CreateBlockAlignedStore(carryOut, carryOutPtr);
433}
434
435/** ------------------------------------------------------------------------------------------------------------- *
436 * @brief addToSummary
437 ** ------------------------------------------------------------------------------------------------------------- */
438void CarryManager::addToSummary(Value * value) { assert (value);
439    assert (mIfDepth > 0 && mCarrySummary.size() > 0);
440    Value * const summary = mCarrySummary.back(); assert (summary);
441    if (LLVM_UNLIKELY(summary == value)) {
442        return;  //Nothing to add.
443    }
444    value = iBuilder->CreateBitCast(value, mCarryPackType);
445    if (LLVM_UNLIKELY(isa<Constant>(value))) {
446        if (LLVM_UNLIKELY(cast<Constant>(value)->isZeroValue())) {
447            return;
448        } else if (LLVM_UNLIKELY(cast<Constant>(value)->isAllOnesValue())) {
449            mCarrySummary.back() = value;
450            return;
451        }
452    } else if (LLVM_UNLIKELY(isa<Constant>(summary))) {
453        if (LLVM_UNLIKELY(cast<Constant>(summary)->isZeroValue())) {
454            mCarrySummary.back() = value;
455            return;
456        } else if (LLVM_UNLIKELY(cast<Constant>(summary)->isAllOnesValue())) {
457            return;
458        }
459    }   
460    mCarrySummary.back() = iBuilder->CreateOr(summary, value);
461}
462
463/** ------------------------------------------------------------------------------------------------------------- *
464 * @brief collapsingCarryMode
465 ** ------------------------------------------------------------------------------------------------------------- */
466bool CarryManager::inCollapsingCarryMode() const {
467    return (mCurrentScope->getBranch() && isa<While>(mCurrentScope->getBranch()) && !mCarryInfo->variableLength);
468}
469
470/** ------------------------------------------------------------------------------------------------------------- *
471 * @brief enumerate
472 ** ------------------------------------------------------------------------------------------------------------- */
473unsigned CarryManager::enumerate(PabloBlock * const scope, unsigned index) {
474    scope->setScopeIndex(index++);
475    for (Statement * stmt : *scope) {
476        if (LLVM_UNLIKELY(isa<Branch>(stmt))) {
477            index = enumerate(cast<Branch>(stmt)->getBody(), index);
478        }
479    }
480    return index;
481}
482
483/** ------------------------------------------------------------------------------------------------------------- *
484 * @brief requiresVariableLengthMode
485 ** ------------------------------------------------------------------------------------------------------------- */
486bool CarryManager::requiresVariableLengthMode(const PabloBlock * const scope) {
487    if (const Branch * const br = scope->getBranch()) {
488        for (const Var * var : br->getEscaped()) {
489            for (const PabloAST * user : var->users()) {
490                if (const Extract * e = dyn_cast<Extract>(user)) {
491                    if (LLVM_UNLIKELY(e->getIndex() == var)) {
492                        // If we assign this Var a value and read the value as the index parameter
493                        // of a nested Extract statement, then we cannot collapse the carries.
494                        const PabloBlock * parent = e->getParent();
495                        for (;;) {
496                            if (parent == scope) {
497                                return true;
498                            }
499                            parent = parent->getPredecessor();
500                            if (parent == nullptr) {
501                                break;
502                            }
503                        }
504                    }
505                }
506            }
507        }
508    }
509    return false;
510}
511
512/** ------------------------------------------------------------------------------------------------------------- *
513 * @brief analyse
514 ** ------------------------------------------------------------------------------------------------------------- */
515StructType * CarryManager::analyse(PabloBlock * const scope, const unsigned ifDepth, const unsigned loopDepth) {
516
517    std::vector<Type *> state;
518
519    assert (mCarryPackType);
520
521    Type * const carryPackType = (loopDepth == 0) ? mCarryPackType : ArrayType::get(mCarryPackType, 2);
522
523    bool hasLongAdvances = false;
524    for (Statement * stmt : *scope) {
525        if (LLVM_UNLIKELY(isa<Advance>(stmt))) {
526            const auto amount = cast<Advance>(stmt)->getAmount();
527            if (LLVM_LIKELY(amount <= mBitBlockWidth)) {
528                state.push_back(carryPackType);
529            } else {
530                const auto blocks = ceil_udiv(amount, mBitBlockWidth); assert (blocks > 1);
531                Type * type = ArrayType::get(mBitBlockType, nearest_pow2(blocks));
532                if (LLVM_UNLIKELY(ifDepth > 0)) {
533                    Type * carryType = ArrayType::get(mBitBlockType, ceil_udiv(amount, std::pow(mBitBlockWidth, 2)));
534                    type = StructType::get(carryType, type, nullptr);
535                    hasLongAdvances = true;
536                }
537                state.push_back(type);
538            }
539        } else if (LLVM_UNLIKELY(isa<ScanThru>(stmt) || isa<MatchStar>(stmt))) {
540            state.push_back(carryPackType);
541        } else if (LLVM_UNLIKELY(isa<If>(stmt))) {
542            state.push_back(analyse(cast<If>(stmt)->getBody(), ifDepth + 1, loopDepth));
543        } else if (LLVM_UNLIKELY(isa<While>(stmt))) {
544            state.push_back(analyse(cast<While>(stmt)->getBody(), ifDepth, loopDepth + 1));
545        }
546    }
547
548    assert (scope->getScopeIndex() < mCarryMetadata.size());
549
550    CarryData & cd = mCarryMetadata[scope->getScopeIndex()];
551
552    StructType * carryState = nullptr;
553
554    // Add the summary pack if needed.
555    cd.summaryType = CarryData::NoSummary;
556    if (LLVM_UNLIKELY(state.empty())) {
557        carryState = StructType::get(iBuilder->getContext());
558    } else {
559        cd.variableLength = loopDepth > 0 && requiresVariableLengthMode(scope);
560        if (ifDepth > 0) {
561            // A non-collapsing loop requires a unique summary for each iteration. Thus whenever
562            // we have a non-collapsing While within an If scope with an implicit summary, the If
563            // scope requires an explicit summary.
564
565            if (LLVM_LIKELY(state.size() > 1 || hasLongAdvances)) {
566                cd.summaryType = CarryData::ExplicitSummary;
567                state.insert(state.begin(), mCarryPackType);
568            } else {
569                cd.summaryType = CarryData::ImplicitSummary;
570                if (state[0]->isStructTy()) {
571                    cd.summaryType = CarryData::BorrowedSummary;
572                }
573            }
574        }
575        carryState = StructType::get(iBuilder->getContext(), state);
576        // If we in a loop and cannot use collapsing carry mode, convert the struct into a capacity and pointer pair.
577        if (LLVM_UNLIKELY(cd.variableLength)) {
578            carryState = StructType::get(iBuilder->getSizeTy(), carryState->getPointerTo(), nullptr);
579        }
580    }
581    return carryState;
582}
583
584}
585
Note: See TracBrowser for help on using the repository browser.