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

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

Added enable asserts (-ea) command line flag + restructured BlockOrientedKernels? to allow for inlined code.

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