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

Last change on this file since 5782 was 5771, checked in by nmedfort, 21 months ago

Minor changes and hopefully a fix for bug exposed by base64 test

File size: 53.4 KB
RevLine 
[4644]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
[5267]7#include "carry_manager.h"
[4683]8#include <pablo/carry_data.h>
9#include <pablo/codegenstate.h>
[4726]10#include <llvm/IR/BasicBlock.h>
[5267]11#include <llvm/IR/DerivedTypes.h>
[5586]12#include <llvm/Transforms/Utils/Local.h>
[5267]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>
[5440]18#include <kernels/kernel_builder.h>
[5493]19#include <toolchain/toolchain.h>
20#include <array>
[5371]21
[5267]22using namespace llvm;
23
[4925]24namespace pablo {
[4715]25
[5586]26inline static bool is_power_2(const unsigned n) {
27    return (n && ((n & (n - 1)) == 0));
28}
29
[5371]30inline static unsigned ceil_log2(const unsigned v) {
31    assert ("log2(0) is undefined!" && v != 0);
[5586]32    return (sizeof(unsigned) * CHAR_BIT) - __builtin_clz(v - 1U);
[5371]33}
34
[5361]35inline static unsigned floor_log2(const unsigned v) {
36    assert ("log2(0) is undefined!" && v != 0);
[5586]37    return ((sizeof(unsigned) * CHAR_BIT) - 1U) - __builtin_clz(v);
[5361]38}
39
[5371]40inline static unsigned nearest_pow2(const unsigned v) {
[5586]41    assert (v > 0 && v < (UINT32_MAX / 2));
42    return (v < 2) ? 1 : (1U << ceil_log2(v));
[5227]43}
44
[5586]45inline static unsigned nearest_multiple(const unsigned n, const unsigned m) {
46    assert (is_power_2(m));
47    const unsigned r = (n + m - 1U) & -m;
48    assert (r >= n);
49    return r;
50}
51
52inline static bool is_multiple_of(const unsigned n, const unsigned m) {
53    return nearest_multiple(n, m) == n;
54}
55
56inline static unsigned udiv(const unsigned x, const unsigned y) {
57    assert (is_power_2(y));
58    const unsigned z = x >> floor_log2(y);
59    assert (z == (x / y));
60    return z;
61}
62
[5227]63inline static unsigned ceil_udiv(const unsigned x, const unsigned y) {
64    return (((x - 1) | (y - 1)) + 1) / y;
65}
66
[5329]67using TypeId = PabloAST::ClassTypeId;
68
69inline static bool isNonAdvanceCarryGeneratingStatement(const Statement * const stmt) {
[5705]70    return isa<CarryProducingStatement>(stmt) && !isa<Advance>(stmt) && !isa<IndexedAdvance>(stmt);
[5329]71}
72
[5371]73#define LONG_ADVANCE_BREAKPOINT 64
74
[4925]75/** ------------------------------------------------------------------------------------------------------------- *
[5063]76 * @brief initializeCarryData
[4925]77 ** ------------------------------------------------------------------------------------------------------------- */
[5712]78void CarryManager::initializeCarryData(const std::unique_ptr<kernel::KernelBuilder> & b, PabloKernel * const kernel) {
[5045]79
[5227]80    // Each scope constructs its own CarryData struct, which will be added to the final "carries" struct
81    // that is added to the Kernel. The scope index will indicate which struct to access.
[5045]82
[5227]83    // A CarryData struct either contains an array of CarryPackBlocks or an integer indicating the capacity of
84    // the variable length CarryData struct and pointer. A variable length CarryData struct is required whenever
85    // the streams accessed by a loop could vary between iterations. When resizing a CarryData struct for a
86    // particular loop, the current loop struct and all nested structs need to be resized. This accommodates
87    // the fact every pablo While loop must be executed at least once.
88
89    // A nested loop may also contain a variable length CarryData struct
90
91    // To determine whether we require a variable length CarryData struct, we test the escaped variables of
92    // each loop branch to see whether they are used as the index parameter of a nested Extract statement.
93    // Any scope that requires variable length CarryData, requires that all nested branches have a unique
94    // set of carries for that iteration.
95
[5435]96    assert (mKernel == nullptr);
97    mCurrentScope = kernel->getEntryBlock();
98    mKernel = kernel;
[5227]99
[5340]100    mCarryScopes = 0;
[5227]101
[5435]102    mCarryMetadata.resize(getScopeCount(mCurrentScope));
[5340]103
[5712]104    Type * const carryStateTy = analyse(b, mCurrentScope);
[5307]105
[5435]106    kernel->addScalar(carryStateTy, "carries");
[5366]107
[5307]108    if (mHasLoop) {
[5712]109        kernel->addScalar(b->getInt32Ty(), "selector");
[5307]110    }
[5311]111    if (mHasLongAdvance) {
[5712]112        kernel->addScalar(b->getSizeTy(), "CarryBlockIndex");
[5311]113    }
[5708]114    for (unsigned i = 0; i < mIndexedLongAdvanceTotal; i++) {
[5715]115        kernel->addScalar(b->getSizeTy(), "IndexedAdvancePosition" + std::to_string(i));
[5708]116    }
[5493]117}
[5435]118
[5493]119bool isDynamicallyAllocatedType(const Type * const ty) {
120    if (isa<StructType>(ty) && ty->getStructNumElements() == 3) {
121        return (ty->getStructElementType(1)->isPointerTy() && ty->getStructElementType(2)->isPointerTy() && ty->getStructElementType(0)->isIntegerTy());
122    }
123    return false;
[4939]124}
125
[5493]126bool containsDynamicallyAllocatedType(const Type * const ty) {
127    if (isa<StructType>(ty)) {
128        for (unsigned i = 0; i < ty->getStructNumElements(); ++i) {
129            if (isDynamicallyAllocatedType(ty->getStructElementType(i))) {
130                return true;
131            }
132        }
133    }
134    return false;
135}
136
137void freeDynamicallyAllocatedMemory(const std::unique_ptr<kernel::KernelBuilder> & idb, Value * const frame) {
138    StructType * const ty = cast<StructType>(frame->getType()->getPointerElementType());
139    std::array<Value *, 3> indices;
140    indices[0] = idb->getInt32(0);
141    for (unsigned i = 0; i < ty->getStructNumElements(); ++i) {
142        if (isDynamicallyAllocatedType(ty->getStructElementType(i))) {
143            indices[1] = idb->getInt32(i);
144            indices[2] = idb->getInt32(1);
145            Value * const innerFrame = idb->CreateLoad(idb->CreateGEP(frame, ArrayRef<Value*>(indices.data(), 3)));
146            if (containsDynamicallyAllocatedType(innerFrame->getType())) {
147                indices[2] = indices[0];
148                Value *  const count = idb->CreateLoad(idb->CreateGEP(frame, ArrayRef<Value*>(indices.data(), 3)));
149                BasicBlock * const entry = idb->GetInsertBlock();
150                BasicBlock * const cond = idb->CreateBasicBlock("freeCarryDataCond");
151                BasicBlock * const body = idb->CreateBasicBlock("freeCarryDataLoop");
152                BasicBlock * const exit = idb->CreateBasicBlock("freeCarryDataExit");
153                idb->CreateBr(cond);
154                idb->SetInsertPoint(cond);
155                PHINode * const index = idb->CreatePHI(count->getType(), 2);
156                index->addIncoming(ConstantInt::getNullValue(count->getType()), entry);
157                Value * test = idb->CreateICmpNE(index, count);
158                idb->CreateCondBr(test, body, exit);
159                idb->SetInsertPoint(body);
160                freeDynamicallyAllocatedMemory(idb, idb->CreateGEP(innerFrame, index));
161                index->addIncoming(idb->CreateAdd(index, ConstantInt::get(count->getType(), 1)), body);
162                idb->CreateBr(cond);
163                idb->SetInsertPoint(exit);
164            }
165            idb->CreateFree(innerFrame);
166            indices[2] = idb->getInt32(2);
167            Value *  const summary = idb->CreateLoad(idb->CreateGEP(frame, ArrayRef<Value*>(indices.data(), 3)));
168            idb->CreateFree(summary);
169        }
170    }
171}
172
[4959]173/** ------------------------------------------------------------------------------------------------------------- *
[5486]174 * @brief releaseCarryData
175 ** ------------------------------------------------------------------------------------------------------------- */
[5493]176void CarryManager::releaseCarryData(const std::unique_ptr<kernel::KernelBuilder> & idb) {
177    if (mHasNonCarryCollapsingLoops) {
178        freeDynamicallyAllocatedMemory(idb, idb->getScalarFieldPtr("carries"));
179    }
[5486]180}
181
182/** ------------------------------------------------------------------------------------------------------------- *
[5063]183 * @brief initializeCodeGen
[4959]184 ** ------------------------------------------------------------------------------------------------------------- */
[5712]185void CarryManager::initializeCodeGen(const std::unique_ptr<kernel::KernelBuilder> & b) {
[5227]186
[5292]187    assert(!mCarryMetadata.empty());
[5227]188    mCarryInfo = &mCarryMetadata[0];
189    assert (!mCarryInfo->hasSummary());
190
[5712]191    mCurrentFrame = b->getScalarFieldPtr("carries");
[4691]192    mCurrentFrameIndex = 0;
[5340]193    mCarryScopes = 0;
194    mCarryScopeIndex.push_back(0);
[5361]195
[5366]196    assert (mCarryFrameStack.empty());
[5361]197
[5368]198    assert (mCarrySummaryStack.empty());
[5361]199
[5712]200    Type * const carryTy = b->getBitBlockType();
[5435]201
202    mCarrySummaryStack.push_back(Constant::getNullValue(carryTy));
203
[5431]204    if (mHasLoop) {       
[5712]205        mLoopSelector = b->getScalarField("selector");
206        mNextLoopSelector = b->CreateXor(mLoopSelector, ConstantInt::get(mLoopSelector->getType(), 1));
[5307]207    }
[5431]208
[4644]209}
210
[4959]211/** ------------------------------------------------------------------------------------------------------------- *
[5307]212 * @brief finalizeCodeGen
213 ** ------------------------------------------------------------------------------------------------------------- */
[5712]214void CarryManager::finalizeCodeGen(const std::unique_ptr<kernel::KernelBuilder> & b) {
[5307]215    if (mHasLoop) {
[5712]216        b->setScalarField("selector", mNextLoopSelector);
[5307]217    }
[5311]218    if (mHasLongAdvance) {
[5712]219        Value * idx = b->getScalarField("CarryBlockIndex");
220        idx = b->CreateAdd(idx, b->getSize(1));
221        b->setScalarField("CarryBlockIndex", idx);
[5311]222    }
[5368]223    assert (mCarryFrameStack.empty());   
[5371]224    assert ("base summary value was deleted!" && mCarrySummaryStack.size() == 1);
225    assert ("base summary value was overwritten with non-zero value!" && isa<Constant>(mCarrySummaryStack[0]) && cast<Constant>(mCarrySummaryStack[0])->isNullValue());
[5368]226    mCarrySummaryStack.clear();
[5340]227    assert (mCarryScopeIndex.size() == 1);
228    mCarryScopeIndex.clear();
[5307]229}
230
231/** ------------------------------------------------------------------------------------------------------------- *
[5227]232 * @brief enterLoopScope
[4925]233 ** ------------------------------------------------------------------------------------------------------------- */
[5712]234void CarryManager::enterLoopScope(const std::unique_ptr<kernel::KernelBuilder> & b, const PabloBlock * const scope) {
[5227]235    assert (scope);
[5366]236    assert (mHasLoop);
[5307]237    ++mLoopDepth;
[5712]238    enterScope(b, scope);
[4670]239}
240
[4925]241/** ------------------------------------------------------------------------------------------------------------- *
[5227]242 * @brief enterLoopBody
[4925]243 ** ------------------------------------------------------------------------------------------------------------- */
[5712]244void CarryManager::enterLoopBody(const std::unique_ptr<kernel::KernelBuilder> & b, BasicBlock * const entryBlock) {
[5227]245    if (mCarryInfo->hasSummary()) {
[5712]246        Type * const carryTy = b->getBitBlockType();
247        PHINode * phiCarryOutSummary = b->CreatePHI(carryTy, 2, "summary");
[5368]248        assert (!mCarrySummaryStack.empty());
249        phiCarryOutSummary->addIncoming(mCarrySummaryStack.back(), entryBlock);
250        // Replace the incoming carry summary with the phi node and add the phi node to the stack  so that we can
251        // properly OR it into the outgoing summary value.
252        // NOTE: this may change the base summary value; when exiting to the base scope, replace this summary with
253        // a null value to prevent subsequent nested scopes from inheriting the summary of this scope.
254        mCarrySummaryStack.back() = phiCarryOutSummary;
255        mCarrySummaryStack.push_back(phiCarryOutSummary);
[5227]256    }
[5366]257    if (LLVM_UNLIKELY(mCarryInfo->nonCarryCollapsingMode())) {
[4708]258
[5366]259        assert (mCarryInfo->hasSummary());
[5361]260
[5712]261        Type * const int8PtrTy = b->getInt8PtrTy();
262        Type * const carryTy = b->getBitBlockType();
[5435]263        PointerType * const carryPtrTy = carryTy->getPointerTo();
264
[5227]265        // Check whether we need to resize the carry state
[5712]266        PHINode * index = b->CreatePHI(b->getSizeTy(), 2);
[5227]267        mLoopIndicies.push_back(index);
[5712]268        index->addIncoming(b->getSize(0), entryBlock);
269        Value * capacityPtr = b->CreateGEP(mCurrentFrame, {b->getInt32(0), b->getInt32(0)});
270        Value * capacity = b->CreateLoad(capacityPtr, "capacity");
[5361]271        Constant * const ONE = ConstantInt::get(capacity->getType(), 1);
[5712]272        Value * arrayPtr = b->CreateGEP(mCurrentFrame, {b->getInt32(0), b->getInt32(1)});
273        Value * array = b->CreateLoad(arrayPtr, "array");
274        BasicBlock * const entry = b->GetInsertBlock();
275        BasicBlock * const resizeCarryState = b->CreateBasicBlock("ResizeCarryState");
276        BasicBlock * const reallocExisting = b->CreateBasicBlock("ReallocExisting");
277        BasicBlock * const createNew = b->CreateBasicBlock("CreateNew");
278        BasicBlock * const resumeKernel = b->CreateBasicBlock("ResumeKernel");
279        b->CreateLikelyCondBr(b->CreateICmpNE(index, capacity), resumeKernel, resizeCarryState);
[5227]280
[5361]281        // RESIZE CARRY BLOCK
[5712]282        b->SetInsertPoint(resizeCarryState);
283        const auto BlockWidth = b->getBitBlockWidth() / 8;
[5361]284        const auto Log2BlockWidth = floor_log2(BlockWidth);
[5712]285        Constant * const carryStateWidth = ConstantExpr::getIntegerCast(ConstantExpr::getSizeOf(array->getType()->getPointerElementType()), b->getSizeTy(), false);
286        Value * const summaryPtr = b->CreateGEP(mCurrentFrame, {b->getInt32(0), b->getInt32(2)});
287        Value * const hasCarryState = b->CreateICmpNE(array, ConstantPointerNull::get(cast<PointerType>(array->getType())));
288        b->CreateLikelyCondBr(hasCarryState, reallocExisting, createNew);
[5245]289
[5361]290        // REALLOCATE EXISTING
[5712]291        b->SetInsertPoint(reallocExisting);
292        Value * const capacitySize = b->CreateMul(capacity, carryStateWidth);
293        Value * const newCapacitySize = b->CreateShl(capacitySize, 1); // x 2
294        Value * const newArray = b->CreateCacheAlignedMalloc(newCapacitySize);
295        b->CreateMemCpy(newArray, array, capacitySize, b->getCacheAlignment());
296        b->CreateFree(array);
297        b->CreateStore(newArray, arrayPtr);
298        Value * const startNewArrayPtr = b->CreateGEP(b->CreatePointerCast(newArray, int8PtrTy), capacitySize);
299        b->CreateMemZero(startNewArrayPtr, capacitySize, BlockWidth);
300        Value * const newCapacity = b->CreateShl(capacity, 1);
301        b->CreateStore(newCapacity, capacityPtr);
302        Value * const summary = b->CreateLoad(summaryPtr, false);
303        Value * const summarySize = b->CreateShl(b->CreateAdd(b->CreateCeilLog2(capacity), ONE), Log2BlockWidth + 1);
304        Constant * const additionalSpace = b->getSize(2 * BlockWidth);
305        Value * const newSummarySize = b->CreateAdd(summarySize, additionalSpace);
306        Value * const newSummary = b->CreateBlockAlignedMalloc(newSummarySize);
307        b->CreateMemCpy(newSummary, summary, summarySize, BlockWidth);
308        b->CreateFree(summary);
309        b->CreateStore(b->CreatePointerCast(newSummary, carryPtrTy), summaryPtr);
310        Value * const startNewSummaryPtr = b->CreateGEP(b->CreatePointerCast(newSummary, int8PtrTy), summarySize);
311        b->CreateMemZero(startNewSummaryPtr, additionalSpace, BlockWidth);
312        b->CreateBr(resumeKernel);
[5227]313
[5361]314        // CREATE NEW
[5712]315        b->SetInsertPoint(createNew);
316        Constant * const initialLog2Capacity = b->getInt64(4);
[5361]317        Constant * const initialCapacity = ConstantExpr::getShl(ONE, initialLog2Capacity);
[5712]318        b->CreateStore(initialCapacity, capacityPtr);
[5361]319        Constant * const initialCapacitySize = ConstantExpr::getMul(initialCapacity, carryStateWidth);
[5712]320        Value * initialArray = b->CreateCacheAlignedMalloc(initialCapacitySize);
321        b->CreateMemZero(initialArray, initialCapacitySize, BlockWidth);
322        initialArray = b->CreatePointerCast(initialArray, array->getType());
323        b->CreateStore(initialArray, arrayPtr);
324        Constant * initialSummarySize = ConstantExpr::getShl(ConstantExpr::getAdd(initialLog2Capacity, b->getInt64(1)), b->getInt64(Log2BlockWidth + 1));
325        Value * initialSummary = b->CreateBlockAlignedMalloc(initialSummarySize);
326        b->CreateMemZero(initialSummary, initialSummarySize, BlockWidth);
327        initialSummary = b->CreatePointerCast(initialSummary, carryPtrTy);
328        b->CreateStore(initialSummary, summaryPtr);
329        b->CreateBr(resumeKernel);
[5361]330
331        // RESUME KERNEL
[5712]332        b->SetInsertPoint(resumeKernel);
333        PHINode * phiArrayPtr = b->CreatePHI(array->getType(), 3);
[5361]334        phiArrayPtr->addIncoming(array, entry);
335        phiArrayPtr->addIncoming(initialArray, createNew);
336        phiArrayPtr->addIncoming(newArray, reallocExisting);
337
[5366]338        // NOTE: the 3 here is only to pass the assertion later. It refers to the number of elements in the carry data struct.
339        mCarryFrameStack.emplace_back(mCurrentFrame, 3);
[5712]340        mCurrentFrame = b->CreateGEP(phiArrayPtr, index);
[4647]341    }
[4644]342}
343
[4925]344/** ------------------------------------------------------------------------------------------------------------- *
[5227]345 * @brief leaveLoopBody
[4925]346 ** ------------------------------------------------------------------------------------------------------------- */
[5712]347void CarryManager::leaveLoopBody(const std::unique_ptr<kernel::KernelBuilder> & b, BasicBlock * /* exitBlock */) {
[5361]348
[5712]349    Type * const carryTy = b->getBitBlockType();
[5435]350
[5366]351    if (LLVM_UNLIKELY(mCarryInfo->nonCarryCollapsingMode())) {
[5361]352
[5366]353        assert (mCarryInfo->hasSummary());
354
[5712]355        ConstantInt * const summaryIndex = b->getInt32(mCarryInfo->hasExplicitSummary() ? mCurrentFrameIndex : (mCurrentFrameIndex - 1));
[5366]356
[5712]357        Value * const carryInAccumulator = readCarryInSummary(b, summaryIndex);
[5368]358        Value * const carryOutAccumulator = mCarrySummaryStack.back();
[5361]359
[5366]360        if (mCarryInfo->hasExplicitSummary()) {
[5712]361            writeCarryOutSummary(b, carryOutAccumulator, summaryIndex);
[5366]362        }
363
364        std::tie(mCurrentFrame, mCurrentFrameIndex) = mCarryFrameStack.back();
365        mCarryFrameStack.pop_back();
366
[5361]367        // In non-carry-collapsing mode, we cannot rely on the fact that performing a single iteration of this
368        // loop will consume all of the incoming carries from the prior block. We need to subtract the carries
369        // consumed by this iteration from our carry summary state. To do so in parallel, we use the the half-
370        // subtractor circuit to do it in ceil log2 steps. Similarly, we compute our carry out summary state
371        // (for the subsequent block to subtract) using a half-adder circuit.
372
373        // NOTE: this requires that, for all loop iterations, i, and all block iterations, j, the carry in
374        // summary, CI_i,j, matches the carry out summary of the prior block iteration, CO_i,j - 1.
[5493]375        // Otherwise we will end up with an incorrect result or being trapped in an infinite loop.
[5361]376
[5712]377        Value * capacityPtr = b->CreateGEP(mCurrentFrame, {b->getInt32(0), b->getInt32(0)});
378        Value * capacity = b->CreateLoad(capacityPtr, false);
379        Value * summaryPtr = b->CreateGEP(mCurrentFrame, {b->getInt32(0), b->getInt32(2)});
380        Value * summary = b->CreateLoad(summaryPtr, false);
[5361]381
382        Constant * const ONE = ConstantInt::get(capacity->getType(), 1);
383
[5712]384        Value * loopSelector = b->CreateZExt(mLoopSelector, capacity->getType());
[5361]385
[5712]386        BasicBlock * entry = b->GetInsertBlock();
387        BasicBlock * update = b->CreateBasicBlock("UpdateNonCarryCollapsingSummary");
388        BasicBlock * resume = b->CreateBasicBlock("ResumeAfterUpdatingNonCarryCollapsingSummary");
[5361]389
[5712]390        b->CreateBr(update);
[5361]391
[5712]392        b->SetInsertPoint(update);
393        PHINode * i = b->CreatePHI(capacity->getType(), 2);
[5361]394        i->addIncoming(ConstantInt::getNullValue(capacity->getType()), entry);
[5712]395        PHINode * const borrow = b->CreatePHI(carryInAccumulator->getType(), 2);
[5361]396        borrow->addIncoming(carryInAccumulator, entry);
[5712]397        PHINode * const carry = b->CreatePHI(carryOutAccumulator->getType(), 2);
[5361]398        carry->addIncoming(carryOutAccumulator, entry);
399        // OR the updated carry in summary later for the summaryTest
[5712]400        PHINode * const carryInSummary = b->CreatePHI(carryTy, 2);
[5435]401        carryInSummary->addIncoming(Constant::getNullValue(carryTy), entry);
[5361]402
403        // half subtractor
[5712]404        Value * const carryInOffset = b->CreateOr(b->CreateShl(i, 1), loopSelector);
405        Value * const carryInPtr = b->CreateGEP(summary, carryInOffset);
406        Value * const carryIn = b->CreateBlockAlignedLoad(carryInPtr);
407        Value * const nextCarryIn = b->CreateXor(carryIn, borrow);
408        Value * const nextSummary = b->CreateOr(carryInSummary, nextCarryIn);
[5586]409
[5712]410        b->CreateBlockAlignedStore(nextCarryIn, carryInPtr);
[5368]411        carryInSummary->addIncoming(nextSummary, update);
[5712]412        Value * finalBorrow = b->CreateAnd(b->CreateNot(carryIn), borrow);
[5361]413        borrow->addIncoming(finalBorrow, update);
414
415        // half adder
[5712]416        Value * const carryOutOffset = b->CreateXor(carryInOffset, ConstantInt::get(carryInOffset->getType(), 1));
417        Value * const carryOutPtr = b->CreateGEP(summary, carryOutOffset);
418        Value * const carryOut = b->CreateBlockAlignedLoad(carryOutPtr);
419        Value * const nextCarryOut = b->CreateXor(carryOut, carry);
[5586]420
[5712]421        b->CreateBlockAlignedStore(nextCarryOut, carryOutPtr);
422        Value * finalCarry = b->CreateAnd(carryOut, carry);
[5361]423        carry->addIncoming(finalCarry, update);
424
425        // loop condition
[5712]426        i->addIncoming(b->CreateAdd(i, ONE), update);
427        b->CreateCondBr(b->CreateICmpNE(b->CreateShl(ONE, i), capacity), update, resume);
[5361]428
[5712]429        b->SetInsertPoint(resume);
[5361]430
[5771]431        b->CreateAssertZero(b->CreateOr(finalBorrow, finalCarry),
432                                   "CarryManager: loop post-condition violated: final borrow and carry must be zero!");
[5368]433
[5292]434        assert (!mLoopIndicies.empty());
[5227]435        PHINode * index = mLoopIndicies.back();
[5712]436        index->addIncoming(b->CreateAdd(index, b->getSize(1)), resume);
[5227]437        mLoopIndicies.pop_back();
[5366]438
[5368]439        mNextSummaryTest = nextSummary;
[4647]440    }
[5361]441    if (mCarryInfo->hasSummary()) {
[5368]442        const auto n = mCarrySummaryStack.size(); assert (n > 1);
443        Value * carryOut = mCarrySummaryStack.back();
444        mCarrySummaryStack.pop_back();
445        PHINode * phiCarryOut = cast<PHINode>(mCarrySummaryStack.back());
[5712]446        phiCarryOut->addIncoming(carryOut, b->GetInsertBlock());
[5368]447        // If we're returning to the base scope, reset our accumulated summary value.
448        if (n == 2) {
[5435]449            carryOut = Constant::getNullValue(carryTy);
[5368]450        }
451        mCarrySummaryStack.back() = carryOut;
[5361]452    }
[4644]453}
[4647]454
[4925]455/** ------------------------------------------------------------------------------------------------------------- *
[5227]456 * @brief leaveLoopScope
[4925]457 ** ------------------------------------------------------------------------------------------------------------- */
[5712]458void CarryManager::leaveLoopScope(const std::unique_ptr<kernel::KernelBuilder> & b, BasicBlock * const /* entryBlock */, BasicBlock * const /* exitBlock */) {
[5227]459    assert (mLoopDepth > 0);
[5307]460    --mLoopDepth;
[5712]461    leaveScope(b);
[4644]462}
463
[4925]464/** ------------------------------------------------------------------------------------------------------------- *
[5227]465 * @brief enterIfScope
[4925]466 ** ------------------------------------------------------------------------------------------------------------- */
[5712]467void CarryManager::enterIfScope(const std::unique_ptr<kernel::KernelBuilder> & b, const PabloBlock * const scope) {
[5227]468    ++mIfDepth;
[5712]469    enterScope(b, scope);
[5368]470    // We zero-initialized the nested summary value and later OR in the current summary into the escaping summary
471    // so that upon processing the subsequent block iteration, we branch into this If scope iff a carry out was
472    // generated by a statement within this If scope and not by a dominating statement in the outer scope.
[5366]473    if (LLVM_LIKELY(mCarryInfo->hasSummary())) {
474        assert (mCurrentFrameIndex == 0);
[5712]475        mNextSummaryTest = readCarryInSummary(b, b->getInt32(0));
[5366]476        if (mCarryInfo->hasExplicitSummary()) {
477            mCurrentFrameIndex = 1;
478        }
479    }
[5712]480    Type * const carryTy = b->getBitBlockType();
[5435]481    mCarrySummaryStack.push_back(Constant::getNullValue(carryTy));
[4644]482}
483
[4925]484/** ------------------------------------------------------------------------------------------------------------- *
[5227]485 * @brief generateSummaryTest
[4925]486 ** ------------------------------------------------------------------------------------------------------------- */
[5712]487Value * CarryManager::generateSummaryTest(const std::unique_ptr<kernel::KernelBuilder> & b, Value * condition) {
[5227]488    if (LLVM_LIKELY(mCarryInfo->hasSummary())) {
[5366]489        assert ("summary test was not generated" && mNextSummaryTest);
[5712]490        condition = b->simd_or(condition, mNextSummaryTest);
[5366]491        mNextSummaryTest = nullptr;
[4703]492    }
[5366]493    assert ("summary test was not consumed" && (mNextSummaryTest == nullptr));
[5227]494    return condition;
[4704]495}
[4925]496
497/** ------------------------------------------------------------------------------------------------------------- *
[5227]498 * @brief enterIfBody
[4925]499 ** ------------------------------------------------------------------------------------------------------------- */
[5712]500void CarryManager::enterIfBody(const std::unique_ptr<kernel::KernelBuilder> & /* b */, BasicBlock * const entryBlock) {
[5366]501    assert (entryBlock);
[4644]502}
[4922]503
[4925]504/** ------------------------------------------------------------------------------------------------------------- *
[5227]505 * @brief leaveIfBody
[4925]506 ** ------------------------------------------------------------------------------------------------------------- */
[5712]507void CarryManager::leaveIfBody(const std::unique_ptr<kernel::KernelBuilder> & b, BasicBlock * const exitBlock) {
[5366]508    assert (exitBlock);
[5368]509    const auto n = mCarrySummaryStack.size();
510    if (LLVM_LIKELY(mCarryInfo->hasExplicitSummary())) {
[5712]511        writeCarryOutSummary(b, mCarrySummaryStack[n - 1], b->getInt32(0));
[4644]512    }
[5366]513    if (n > 2) {
[5712]514        mCarrySummaryStack[n - 1] = b->CreateOr(mCarrySummaryStack[n - 1], mCarrySummaryStack[n - 2], "summary");
[4644]515    }
516}
517
[4925]518/** ------------------------------------------------------------------------------------------------------------- *
[5227]519 * @brief leaveIfScope
[4925]520 ** ------------------------------------------------------------------------------------------------------------- */
[5712]521void CarryManager::leaveIfScope(const std::unique_ptr<kernel::KernelBuilder> & b, BasicBlock * const entryBlock, BasicBlock * const exitBlock) {
[5227]522    assert (mIfDepth > 0);
[5366]523    if (LLVM_LIKELY(mCarryInfo->hasSummary())) {
[5368]524        const auto n = mCarrySummaryStack.size(); assert (n > 0);
[5366]525        if (n > 2) {
[5227]526            // When leaving a nested If scope with a summary value, phi out the summary to ensure the
527            // appropriate summary is stored in the outer scope.
[5368]528            Value * nested = mCarrySummaryStack[n - 1];
529            Value * outer = mCarrySummaryStack[n - 2];
530            assert (nested->getType() == outer->getType());
[5712]531            PHINode * const phi = b->CreatePHI(nested->getType(), 2, "summary");
[5368]532            phi->addIncoming(outer, entryBlock);
533            phi->addIncoming(nested, exitBlock);
534            mCarrySummaryStack[n - 2] = phi;
[5366]535        }
[4644]536    }
[5227]537    --mIfDepth;
[5712]538    leaveScope(b);
[5368]539    mCarrySummaryStack.pop_back();
[4644]540}
541
[5227]542/** ------------------------------------------------------------------------------------------------------------ *
543 * @brief enterScope
[4925]544 ** ------------------------------------------------------------------------------------------------------------- */
[5712]545void CarryManager::enterScope(const std::unique_ptr<kernel::KernelBuilder> & b, const PabloBlock * const scope) {
[5227]546    assert (scope);
547    // Store the state of the current frame and update the scope state
[5366]548    mCarryFrameStack.emplace_back(mCurrentFrame, mCurrentFrameIndex + 1);
[5227]549    mCurrentScope = scope;
[5340]550    mCarryScopeIndex.push_back(++mCarryScopes);
551    mCarryInfo = &mCarryMetadata[mCarryScopes];
[5353]552    // Check whether we're still within our struct bounds; if this fails, either the Pablo program changed during
[5227]553    // compilation or a memory corruption has occured.
554    assert (mCurrentFrameIndex < mCurrentFrame->getType()->getPointerElementType()->getStructNumElements());
[5712]555    mCurrentFrame = b->CreateGEP(mCurrentFrame, {b->getInt32(0), b->getInt32(mCurrentFrameIndex)});
[5227]556    // Verify we're pointing to a carry frame struct
557    assert(mCurrentFrame->getType()->getPointerElementType()->isStructTy());
[5366]558    mCurrentFrameIndex = 0;
[4644]559}
560
[4925]561/** ------------------------------------------------------------------------------------------------------------- *
[5227]562 * @brief leaveScope
[4925]563 ** ------------------------------------------------------------------------------------------------------------- */
[5712]564void CarryManager::leaveScope(const std::unique_ptr<kernel::KernelBuilder> & /* b */) {
[4925]565
[5227]566    // Did we use all of the packs in this carry struct?
567    assert (mCurrentFrameIndex == mCurrentFrame->getType()->getPointerElementType()->getStructNumElements());
568    // Sanity test: are there remaining carry frames?
[5366]569    assert (!mCarryFrameStack.empty());
[5227]570
[5366]571    std::tie(mCurrentFrame, mCurrentFrameIndex) = mCarryFrameStack.back();
[5227]572
573    assert(mCurrentFrame->getType()->getPointerElementType()->isStructTy());
574
[5366]575    mCarryFrameStack.pop_back();
[5340]576    mCarryScopeIndex.pop_back();
577    assert (!mCarryScopeIndex.empty());
[5227]578    mCurrentScope = mCurrentScope->getPredecessor();
579    assert (mCurrentScope);
[5340]580    mCarryInfo = &mCarryMetadata[mCarryScopeIndex.back()];
[4644]581}
582
[4925]583/** ------------------------------------------------------------------------------------------------------------- *
[5227]584 * @brief addCarryInCarryOut
[4925]585 ** ------------------------------------------------------------------------------------------------------------- */
[5712]586Value * CarryManager::addCarryInCarryOut(const std::unique_ptr<kernel::KernelBuilder> & b, const Statement * const operation, Value * const e1, Value * const e2) {
[5329]587    assert (operation && (isNonAdvanceCarryGeneratingStatement(operation)));
[5712]588    Value * const carryIn = getNextCarryIn(b);
[5227]589    Value * carryOut, * result;
[5712]590    std::tie(carryOut, result) = b->bitblock_add_with_carry(e1, e2, carryIn);
591    setNextCarryOut(b, carryOut);
592    assert (result->getType() == b->getBitBlockType());
[5227]593    return result;
[4925]594}
595
596/** ------------------------------------------------------------------------------------------------------------- *
[5227]597 * @brief advanceCarryInCarryOut
[4925]598 ** ------------------------------------------------------------------------------------------------------------- */
[5712]599Value * CarryManager::advanceCarryInCarryOut(const std::unique_ptr<kernel::KernelBuilder> & b, const Advance * const advance, Value * const value) {
[5227]600    const auto shiftAmount = advance->getAmount();
[5371]601    if (LLVM_LIKELY(shiftAmount < LONG_ADVANCE_BREAKPOINT)) {
[5712]602        Value * const carryIn = getNextCarryIn(b);
[5227]603        Value * carryOut, * result;
[5712]604        std::tie(carryOut, result) = b->bitblock_advance(value, carryIn, shiftAmount);
605        setNextCarryOut(b, carryOut);
606        assert (result->getType() == b->getBitBlockType());
[5227]607        return result;
608    } else {
[5712]609        return longAdvanceCarryInCarryOut(b, value, shiftAmount);
[4925]610    }
611}
612
[5712]613/** ------------------------------------------------------------------------------------------------------------- *
614 * @brief indexedAdvanceCarryInCarryOut
615 ** ------------------------------------------------------------------------------------------------------------- */
[5708]616Value * CarryManager::indexedAdvanceCarryInCarryOut(const std::unique_ptr<kernel::KernelBuilder> & b, const IndexedAdvance * const advance, Value * const strm, Value * const index_strm) {
617    const auto shiftAmount = advance->getAmount();
[5713]618    if (LLVM_LIKELY(shiftAmount < LONG_ADVANCE_BREAKPOINT)) {
[5708]619        Value * const carryIn = getNextCarryIn(b);
[5713]620        Value * carryOut, * result;
621        std::tie(carryOut, result) = b->bitblock_indexed_advance(strm, index_strm, carryIn, shiftAmount);
[5710]622        setNextCarryOut(b, carryOut);
[5708]623        return result;
[5711]624    } else if (shiftAmount <= b->getBitBlockWidth()) {
[5713]625        Value * carryPtr = b->CreateGEP(mCurrentFrame, {b->getInt32(0), b->getInt32(mCurrentFrameIndex++), b->getInt32(0)});
626        Value * carryIn = b->CreateBlockAlignedLoad(carryPtr);
627        Value * carryOut, * result;
628        std::tie(carryOut, result) = b->bitblock_indexed_advance(strm, index_strm, carryIn, shiftAmount);
629        b->CreateBlockAlignedStore(carryOut, carryPtr);
[5712]630        if ((mIfDepth > 0) && mCarryInfo->hasExplicitSummary()) {
631            addToCarryOutSummary(b, strm);
632        }
[5711]633        return result;
[5708]634    } else {
[5715]635        unsigned summaryFrame = mCurrentFrameIndex;
636        if (mIfDepth > 0) {
637            // Skip over summary frame to perform the long indexed advance.
638            mCurrentFrameIndex++;
639        }
640        Type * iBitBlock = b->getIntNTy(b->getBitBlockWidth());
641        Constant * blockWidth = b->getSize(b->getBitBlockWidth());
642        Constant * blockWidth_1 = b->getSize(b->getBitBlockWidth() - 1);
643        Value * carryPosition = b->getScalarField("IndexedAdvancePosition" + std::to_string(mIndexedLongAdvanceIndex));
644        Value * carryBlockEndPos = b->CreateAdd(carryPosition, blockWidth_1);
[5716]645        unsigned carry_blocks = nearest_pow2(1+ceil_udiv(shiftAmount, b->getBitBlockWidth()));
[5715]646        Constant * carryQueueBlocks = b->getSize(carry_blocks);
647        Value * carryBlock = b->CreateTrunc(b->CreateURem(b->CreateUDiv(carryPosition, blockWidth), carryQueueBlocks), b->getInt32Ty());
648        Value * carryEndBlock = b->CreateTrunc(b->CreateURem(b->CreateUDiv(carryBlockEndPos, blockWidth), carryQueueBlocks), b->getInt32Ty());
649        Value * lo_GEP = b->CreateGEP(mCurrentFrame, {b->getInt32(0), b->getInt32(mCurrentFrameIndex), carryBlock});
650        Value * hi_GEP = b->CreateGEP(mCurrentFrame, {b->getInt32(0), b->getInt32(mCurrentFrameIndex), carryEndBlock});
651        Value * c_lo = b->CreateBitCast(b->CreateBlockAlignedLoad(lo_GEP), iBitBlock);
652        Value * c_hi = b->CreateBitCast(b->CreateBlockAlignedLoad(hi_GEP), iBitBlock);
653        Value * lo_shift = b->CreateZExt(b->CreateURem(carryPosition, blockWidth), iBitBlock);
654        Value * hi_shift = b->CreateZExt(b->CreateSub(blockWidth_1, b->CreateURem(carryBlockEndPos, blockWidth)), iBitBlock);
655        Value * carryIn = b->CreateOr(b->CreateLShr(c_lo, lo_shift), b->CreateShl(c_hi, hi_shift));
656        Value * carryOut, * result;
657        std::tie(carryOut, result) = b->bitblock_indexed_advance(strm, index_strm, carryIn, shiftAmount);
658        carryOut = b->CreateBitCast(carryOut, iBitBlock);
659        Value * adv = b->mvmd_extract(sizeof(size_t) * 8, b->simd_popcount(b->getBitBlockWidth(), index_strm), 0);
660        b->setScalarField("IndexedAdvancePosition" + std::to_string(mIndexedLongAdvanceIndex), b->CreateAdd(carryPosition, adv));
661        Value * carryOutPosition = b->CreateAdd(carryPosition, b->getSize(shiftAmount));
662        Value * carryOutEndPos = b->CreateAdd(carryOutPosition, blockWidth_1);
663        carryBlock = b->CreateTrunc(b->CreateURem(b->CreateUDiv(carryOutPosition, blockWidth), carryQueueBlocks), b->getInt32Ty());
664        carryEndBlock = b->CreateTrunc(b->CreateURem(b->CreateUDiv(carryOutEndPos, blockWidth), carryQueueBlocks), b->getInt32Ty());
665        lo_GEP = b->CreateGEP(mCurrentFrame, {b->getInt32(0), b->getInt32(mCurrentFrameIndex), carryBlock});
666        hi_GEP = b->CreateGEP(mCurrentFrame, {b->getInt32(0), b->getInt32(mCurrentFrameIndex), carryEndBlock});
667        lo_shift = b->CreateZExt(b->CreateURem(carryOutPosition, blockWidth), iBitBlock);
668        hi_shift = b->CreateZExt(b->CreateSub(blockWidth_1, b->CreateURem(carryOutEndPos, blockWidth)), iBitBlock);
669        c_lo = b->CreateOr(b->CreateBitCast(b->CreateBlockAlignedLoad(lo_GEP), iBitBlock), b->CreateShl(carryOut, lo_shift));
670        c_hi = b->CreateLShr(carryOut, hi_shift);
671        b->CreateBlockAlignedStore(b->CreateBitCast(c_lo, b->getBitBlockType()), lo_GEP);
672        b->CreateBlockAlignedStore(b->CreateBitCast(c_hi, b->getBitBlockType()), hi_GEP);
[5711]673        mIndexedLongAdvanceIndex++;
[5715]674        mCurrentFrameIndex++;
675        // Now handle the summary.
676        if (mIfDepth > 0) {
677            const auto summaryBlocks = ceil_udiv(shiftAmount, b->getBitBlockWidth());
678            const auto summarySize = ceil_udiv(summaryBlocks, b->getBitBlockWidth());
679            for (unsigned i = 0; i < summarySize; i++) {
680                // All ones summary for now.
681                b->CreateBlockAlignedStore(b->allOnes(), b->CreateGEP(mCurrentFrame, {b->getInt32(0), b->getInt32(summaryFrame), b->getInt32(i)}));
682            }
683        }
684        return result;
[5708]685    }
[5705]686}
687
[5708]688
[4925]689/** ------------------------------------------------------------------------------------------------------------- *
[5227]690 * @brief longAdvanceCarryInCarryOut
[4925]691 ** ------------------------------------------------------------------------------------------------------------- */
[5712]692inline Value * CarryManager::longAdvanceCarryInCarryOut(const std::unique_ptr<kernel::KernelBuilder> & b, Value * const value, const unsigned shiftAmount) {
[4925]693
[5311]694    assert (mHasLongAdvance);
[5371]695    assert (shiftAmount >= LONG_ADVANCE_BREAKPOINT);
[5706]696    assert (value);
[4925]697
[5712]698    const auto blockWidth = b->getBitBlockWidth();
699    Type * const streamTy = b->getIntNTy(blockWidth);
[5227]700
[5586]701    Value * indices[3];
702
[5712]703    indices[0] = b->getInt32(0);
[5586]704
[5371]705    if (mIfDepth > 0) {
[5586]706        if (shiftAmount > blockWidth) {
707
[5706]708            // TODO: once CEILING(shiftAmount / 256) > 2, consider using a half-adder/subtractor strategy?
709
[5712]710            Value * carry = b->CreateZExt(b->bitblock_any(value), streamTy);
[5586]711            const auto summaryBlocks = ceil_udiv(shiftAmount, blockWidth);
712            const auto summarySize = ceil_udiv(summaryBlocks, blockWidth);
[5712]713            VectorType * const bitBlockTy = b->getBitBlockType();
[5586]714            IntegerType * const laneTy = cast<IntegerType>(bitBlockTy->getVectorElementType());
715            const auto laneWidth = laneTy->getIntegerBitWidth();
716
717            assert (summarySize > 0);
718            assert (is_power_2(laneWidth));
719
[5712]720            indices[1] = b->getInt32(mCurrentFrameIndex++);
[5586]721
722            for (unsigned i = 1;;++i) {
723
724                assert (i <= summarySize);
725
[5712]726                indices[2] = b->getInt32(i - 1);
[5586]727
[5712]728                Value * const ptr = b->CreateGEP(mCurrentFrame, indices);
729                Value * const prior = b->CreateBitCast(b->CreateBlockAlignedLoad(ptr), streamTy);
[5586]730
731                Value * advanced = nullptr;
732                if (LLVM_LIKELY(summaryBlocks < laneWidth)) {
[5712]733                    advanced = b->CreateOr(b->CreateShl(prior, 1), carry);
734                    carry = b->CreateLShr(prior, summaryBlocks - 1);
[5586]735                } else {
[5712]736                    std::tie(advanced, carry) = b->bitblock_advance(prior, carry, 1);
[5586]737                }
[5712]738                Value * stream = b->CreateBitCast(advanced, bitBlockTy);
[5371]739                if (LLVM_LIKELY(i == summarySize)) {
[5586]740                    const auto n = bitBlockTy->getVectorNumElements();
741                    Constant * mask[n];                                       
742                    const auto m = udiv(summaryBlocks, laneWidth);
743                    if (m) {
744                        std::fill_n(mask, m, ConstantInt::getAllOnesValue(laneTy));
745                    }
746                    mask[m] = ConstantInt::get(laneTy, (1UL << (summaryBlocks & (laneWidth - 1))) - 1UL);
747                    if (n > m) {
748                        std::fill_n(mask + m + 1, n - m, UndefValue::get(laneTy));
749                    }
[5712]750                    stream = b->CreateAnd(stream, ConstantVector::get(ArrayRef<Constant *>(mask, n)));
751                    addToCarryOutSummary(b, stream);
752                    b->CreateBlockAlignedStore(stream, ptr);
[5371]753                    break;
754                }
[5712]755                addToCarryOutSummary(b, stream);
756                b->CreateBlockAlignedStore(stream, ptr);
[4715]757            }
[5586]758
[5371]759        } else if (LLVM_LIKELY(mCarryInfo->hasExplicitSummary())) {
[5712]760            addToCarryOutSummary(b, value);
[4710]761        }
762    }
[5586]763
[5712]764    indices[1] = b->getInt32(mCurrentFrameIndex++);
[5586]765
[5371]766    // special case using a single buffer entry and the carry_out value.
[5586]767    if (LLVM_LIKELY((shiftAmount < blockWidth) && (mLoopDepth == 0))) {
768
[5712]769        indices[2] = indices[0]; // b->getInt32(0)
[5586]770        assert (cast<ConstantInt>(indices[2])->isNullValue());
771
[5712]772        Value * const buffer = b->CreateGEP(mCurrentFrame, indices);
773        assert (buffer->getType()->getPointerElementType() == b->getBitBlockType());
774        Value * carryIn = b->CreateBlockAlignedLoad(buffer);
[5586]775
[5712]776        b->CreateBlockAlignedStore(value, buffer);
[5371]777        /* Very special case - no combine */
[5586]778        if (LLVM_UNLIKELY(shiftAmount == blockWidth)) {
[5712]779            return b->CreateBitCast(carryIn, b->getBitBlockType());
[5371]780        }
[5712]781        Value* block0_shr = b->CreateLShr(b->CreateBitCast(carryIn, streamTy), blockWidth - shiftAmount);
782        Value* block1_shl = b->CreateShl(b->CreateBitCast(value, streamTy), shiftAmount);
783        return b->CreateBitCast(b->CreateOr(block1_shl, block0_shr), b->getBitBlockType());
[5371]784    } else { //
[5586]785        const unsigned blockShift = shiftAmount & (blockWidth - 1);
786        const unsigned summaryBlocks = ceil_udiv(shiftAmount, blockWidth);
787
[5371]788        // Create a mask to implement circular buffer indexing
[5712]789        Value * indexMask = b->getSize(nearest_pow2(summaryBlocks) - 1);
790        Value * blockIndex = b->getScalarField("CarryBlockIndex");
[5586]791
[5712]792        Value * carryIndex0 = b->CreateSub(blockIndex, b->getSize(summaryBlocks));
793        indices[2] = b->CreateAnd(carryIndex0, indexMask);
794        Value * const carryInPtr = b->CreateGEP(mCurrentFrame, indices);
795        Value * carryIn = b->CreateBlockAlignedLoad(carryInPtr);
[4925]796
[5712]797        indices[2] = b->CreateAnd(blockIndex, indexMask);
798        Value * const carryOutPtr = b->CreateGEP(mCurrentFrame, indices);
799        assert (carryIn->getType() == b->getBitBlockType());
[5366]800
[5371]801        // If the long advance is an exact multiple of BitBlockWidth, we simply return the oldest
802        // block in the long advance carry data area.
803        if (LLVM_UNLIKELY(blockShift == 0)) {
[5712]804            b->CreateBlockAlignedStore(value, carryOutPtr);
[5371]805            return carryIn;
806        } else { // Otherwise we need to combine data from the two oldest blocks.
[5712]807            Value * const carryIndex1 = b->CreateSub(blockIndex, b->getSize(summaryBlocks - 1));
808            indices[2] = b->CreateAnd(carryIndex1, indexMask);
[5586]809
[5712]810            Value * const carryInPtr2 = b->CreateGEP(mCurrentFrame, indices);
811            Value * const carryIn2 = b->CreateBlockAlignedLoad(carryInPtr2);
[5706]812            assert (carryOutPtr->getType()->getPointerElementType() == value->getType());
[5712]813            b->CreateBlockAlignedStore(value, carryOutPtr);
[5586]814
[5712]815            Value * const b0 = b->CreateLShr(b->CreateBitCast(carryIn, streamTy), blockWidth - blockShift);
816            Value * const b1 = b->CreateShl(b->CreateBitCast(carryIn2, streamTy), blockShift);
817            return b->CreateBitCast(b->CreateOr(b1, b0), b->getBitBlockType());
[5371]818        }
[5227]819    }
820}
[4925]821
[5227]822/** ------------------------------------------------------------------------------------------------------------- *
823 * @brief getNextCarryIn
824 ** ------------------------------------------------------------------------------------------------------------- */
[5712]825Value * CarryManager::getNextCarryIn(const std::unique_ptr<kernel::KernelBuilder> & b) {
[5227]826    assert (mCurrentFrameIndex < mCurrentFrame->getType()->getPointerElementType()->getStructNumElements());
[5366]827    if (mLoopDepth == 0) {
[5712]828        mCarryPackPtr = b->CreateGEP(mCurrentFrame, {b->getInt32(0), b->getInt32(mCurrentFrameIndex)});
[5366]829    } else {
[5712]830        mCarryPackPtr = b->CreateGEP(mCurrentFrame, {b->getInt32(0), b->getInt32(mCurrentFrameIndex), mLoopSelector});
[5366]831    }
[5712]832    Type * const carryTy = b->getBitBlockType();
[5435]833    assert (mCarryPackPtr->getType()->getPointerElementType() == carryTy);
[5712]834    Value * const carryIn = b->CreateBlockAlignedLoad(mCarryPackPtr);
[5233]835    if (mLoopDepth > 0) {
[5712]836        b->CreateBlockAlignedStore(Constant::getNullValue(carryTy), mCarryPackPtr);
[5233]837    }
838    return carryIn;
[5227]839}
[4925]840
[5227]841/** ------------------------------------------------------------------------------------------------------------- *
842 * @brief setNextCarryOut
843 ** ------------------------------------------------------------------------------------------------------------- */
[5712]844void CarryManager::setNextCarryOut(const std::unique_ptr<kernel::KernelBuilder> & b, Value * carryOut) {
845    Type * const carryTy = b->getBitBlockType();
[5366]846    assert (mCurrentFrameIndex < mCurrentFrame->getType()->getPointerElementType()->getStructNumElements());
[5712]847    carryOut = b->CreateBitCast(carryOut, carryTy);
[5368]848    if (mCarryInfo->hasSummary()) {
[5712]849        addToCarryOutSummary(b, carryOut);
[5227]850    }
[5371]851    if (mLoopDepth != 0) {
[5712]852        mCarryPackPtr = b->CreateGEP(mCurrentFrame, {b->getInt32(0), b->getInt32(mCurrentFrameIndex), mNextLoopSelector});
[5368]853        if (LLVM_LIKELY(!mCarryInfo->nonCarryCollapsingMode())) {
[5712]854            Value * accum = b->CreateBlockAlignedLoad(mCarryPackPtr);
855            carryOut = b->CreateOr(carryOut, accum);
[5368]856        }
[5227]857    }
[5366]858    ++mCurrentFrameIndex;
[5435]859    assert (mCarryPackPtr->getType()->getPointerElementType() == carryTy);
[5712]860    b->CreateBlockAlignedStore(carryOut, mCarryPackPtr);
[4644]861}
862
[4925]863/** ------------------------------------------------------------------------------------------------------------- *
[5366]864 * @brief readCarryInSummary
[4925]865 ** ------------------------------------------------------------------------------------------------------------- */
[5712]866Value * CarryManager::readCarryInSummary(const std::unique_ptr<kernel::KernelBuilder> & b, ConstantInt * index) const {
[5366]867    assert (mCarryInfo->hasSummary());
868    unsigned count = 2;
869    if (LLVM_UNLIKELY(mCarryInfo->hasBorrowedSummary())) {
870        Type * frameTy = mCurrentFrame->getType()->getPointerElementType();
871        count = 1;
872        while (frameTy->isStructTy()) {
873            ++count;
[5586]874            assert (frameTy->getStructNumElements() > 0);
[5366]875            frameTy = frameTy->getStructElementType(0);
876        }
[5227]877    }
[5366]878    const unsigned length = (mLoopDepth == 0) ? count : (count + 1);
879    Value * indicies[length];
[5712]880    std::fill(indicies, indicies + count - 1, b->getInt32(0));
[5366]881    indicies[count - 1] = index;
[5368]882    if (mLoopDepth != 0) {
[5366]883        indicies[count] = mLoopSelector;
884    }
[5371]885
[5366]886    ArrayRef<Value *> ar(indicies, length);
[5712]887    Value * const ptr = b->CreateGEP(mCurrentFrame, ar);
888    Value * const summary = b->CreateBlockAlignedLoad(ptr);
[5368]889    if (mLoopDepth != 0 && mCarryInfo->hasExplicitSummary()) {
[5712]890        Type * const carryTy = b->getBitBlockType();
891        b->CreateBlockAlignedStore(Constant::getNullValue(carryTy), ptr);
[5366]892    }
893    return summary;
[4720]894}
[4726]895
[4925]896/** ------------------------------------------------------------------------------------------------------------- *
[5366]897 * @brief writeCarryOutSummary
[4925]898 ** ------------------------------------------------------------------------------------------------------------- */
[5712]899inline void CarryManager::writeCarryOutSummary(const std::unique_ptr<kernel::KernelBuilder> & b, Value * const summary, ConstantInt * index) const {
[5366]900    Value * ptr = nullptr;
901    assert (mCarryInfo->hasExplicitSummary());
902    if (mLoopDepth > 0) {
[5712]903        ptr = b->CreateGEP(mCurrentFrame, {b->getInt32(0), index, mNextLoopSelector});
[5366]904    } else {
[5712]905        ptr = b->CreateGEP(mCurrentFrame, {b->getInt32(0), index});
[5366]906    }
[5712]907    b->CreateBlockAlignedStore(summary, ptr);
[5227]908}
909
910/** ------------------------------------------------------------------------------------------------------------- *
[5366]911 * @brief addToCarryOutSummary
912 ** ------------------------------------------------------------------------------------------------------------- */
[5712]913inline void CarryManager::addToCarryOutSummary(const std::unique_ptr<kernel::KernelBuilder> & b, Value * const value) {
[5368]914    assert ("cannot add null summary value!" && value);   
915    assert ("summary stack is empty!" && !mCarrySummaryStack.empty());
916    assert (mCarryInfo->hasSummary());
[5712]917    mCarrySummaryStack.back() = b->CreateOr(value, mCarrySummaryStack.back());
[5366]918}
919
920/** ------------------------------------------------------------------------------------------------------------- *
[5227]921 * @brief enumerate
922 ** ------------------------------------------------------------------------------------------------------------- */
[5435]923unsigned CarryManager::getScopeCount(const PabloBlock * const scope, unsigned index) {
924    for (const Statement * stmt : *scope) {
[5227]925        if (LLVM_UNLIKELY(isa<Branch>(stmt))) {
[5340]926            index = getScopeCount(cast<Branch>(stmt)->getBody(), index);
[5227]927        }
[4925]928    }
[5340]929    return index + 1;
[4925]930}
931
932/** ------------------------------------------------------------------------------------------------------------- *
[5353]933 * @brief hasIterationSpecificAssignment
[4925]934 ** ------------------------------------------------------------------------------------------------------------- */
[5706]935bool isNonRegularLanguage(const PabloBlock * const scope) {
936    if (const Branch * br = scope->getBranch()) {
937        return !br->isRegular();
[5227]938    }
939    return false;
[4925]940}
941
[5586]942static bool hasNonEmptyCarryStruct(const Type * const frameTy) {
943    if (frameTy->isStructTy()) {
944        for (unsigned i = 0; i < frameTy->getStructNumElements(); ++i) {
945            if (hasNonEmptyCarryStruct(frameTy->getStructElementType(i))) {
946                return true;
947            }
948        }
949        return false;
950    }
951    return true;
952}
953
954static bool hasNonEmptyCarryStruct(const std::vector<Type *> & state) {
955    for (const Type * const frameTy : state) {
956        if (hasNonEmptyCarryStruct(frameTy)) {
957            return true;
958        }
959    }
960    return false;
961}
962
[5227]963/** ------------------------------------------------------------------------------------------------------------- *
964 * @brief analyse
965 ** ------------------------------------------------------------------------------------------------------------- */
[5712]966StructType * CarryManager::analyse(const std::unique_ptr<kernel::KernelBuilder> & b, const PabloBlock * const scope,
[5493]967                                   const unsigned ifDepth, const unsigned loopDepth, const bool isNestedWithinNonCarryCollapsingLoop) {
[5435]968    assert ("scope cannot be null!" && scope);
[5493]969    assert ("entry scope (and only the entry scope) must be in scope 0"
970            && (mCarryScopes == 0 ? (scope == mKernel->getEntryBlock()) : (scope != mKernel->getEntryBlock())));
[5347]971    assert (mCarryScopes < mCarryMetadata.size());
[5712]972    Type * const carryTy = b->getBitBlockType();
973    Type * const blockTy = b->getBitBlockType();
[4925]974
[5366]975    const unsigned carryScopeIndex = mCarryScopes++;
[5706]976    const bool nonCarryCollapsingMode = isNonRegularLanguage(scope);
[5435]977    Type * const carryPackType = (loopDepth == 0) ? carryTy : ArrayType::get(carryTy, 2);
[5347]978    std::vector<Type *> state;
[5435]979    for (const Statement * stmt : *scope) {
[5708]980        if (LLVM_UNLIKELY(isa<Advance>(stmt) || isa<IndexedAdvance>(stmt))) {
981            int64_t amount;
982            if (isa<Advance>(stmt)) amount = cast<Advance>(stmt)->getAmount();
983            else amount = cast<IndexedAdvance>(stmt)->getAmount();
[5366]984            Type * type = carryPackType;
[5371]985            if (LLVM_UNLIKELY(amount >= LONG_ADVANCE_BREAKPOINT)) {
[5712]986                const auto blockWidth = b->getBitBlockWidth();
[5586]987                const auto blocks = ceil_udiv(amount, blockWidth);
[5716]988                type = ArrayType::get(blockTy, nearest_pow2(blocks + (isa<IndexedAdvance>(stmt) ? 1:0) + ((loopDepth != 0) ? 1 : 0)));
[5586]989                if (LLVM_UNLIKELY(ifDepth > 0 && blocks != 1)) {
990                    const auto summarySize = ceil_udiv(blocks, blockWidth);
[5371]991                    // 1 bit will mark the presense of any bit in each block.
[5586]992                    state.push_back(ArrayType::get(blockTy, summarySize));
[5227]993                }
[5708]994                mHasLongAdvance = true;
995                if (isa<IndexedAdvance>(stmt)) mIndexedLongAdvanceTotal++;
[5227]996            }
[5366]997            state.push_back(type);
[5329]998        } else if (LLVM_UNLIKELY(isNonAdvanceCarryGeneratingStatement(stmt))) {
[5227]999            state.push_back(carryPackType);
1000        } else if (LLVM_UNLIKELY(isa<If>(stmt))) {
[5712]1001            state.push_back(analyse(b, cast<If>(stmt)->getBody(), ifDepth + 1, loopDepth, nonCarryCollapsingMode | isNestedWithinNonCarryCollapsingLoop));
[5227]1002        } else if (LLVM_UNLIKELY(isa<While>(stmt))) {
[5307]1003            mHasLoop = true;
[5712]1004            state.push_back(analyse(b, cast<While>(stmt)->getBody(), ifDepth, loopDepth + 1, nonCarryCollapsingMode | isNestedWithinNonCarryCollapsingLoop));
[5227]1005        }
1006    }
[5366]1007    // Build the carry state struct and add the summary pack if needed.
1008    CarryData & cd = mCarryMetadata[carryScopeIndex];
[5227]1009    StructType * carryState = nullptr;
[5354]1010    CarryData::SummaryType summaryType = CarryData::NoSummary;
[5227]1011    if (LLVM_UNLIKELY(state.empty())) {
[5712]1012        carryState = StructType::get(b->getContext());
[5227]1013    } else {
[5586]1014        // do we have a summary or a sequence of nested empty structs?
1015        if (hasNonEmptyCarryStruct(state)) {
1016            if (dyn_cast_or_null<If>(scope->getBranch()) || nonCarryCollapsingMode || isNestedWithinNonCarryCollapsingLoop) {
1017                if (LLVM_LIKELY(state.size() > 1)) {
1018                    summaryType = CarryData::ExplicitSummary;
1019                    // NOTE: summaries are stored differently depending whether we're entering an If or While branch. With an If branch, they
1020                    // preceed the carry state data and with a While loop they succeed it. This is to help cache prefectching performance.
1021                    state.insert(isa<If>(scope->getBranch()) ? state.begin() : state.end(), carryPackType);
1022                } else {
1023                    summaryType = CarryData::ImplicitSummary;
1024                    if (hasNonEmptyCarryStruct(state[0])) {
1025                        summaryType = CarryData::BorrowedSummary;
1026                    }
[5227]1027                }
[5586]1028            }
[5227]1029        }
[5712]1030        carryState = StructType::get(b->getContext(), state);
[5361]1031        // If we're in a loop and cannot use collapsing carry mode, convert the carry state struct into a capacity,
1032        // carry state pointer, and summary pointer struct.
1033        if (LLVM_UNLIKELY(nonCarryCollapsingMode)) {
[5493]1034            mHasNonCarryCollapsingLoops = true;
[5733]1035            carryState = StructType::get(b->getContext(), {b->getSizeTy(), carryState->getPointerTo(), carryTy->getPointerTo()});
[5493]1036            assert (isDynamicallyAllocatedType(carryState));
[5227]1037        }
[5366]1038        cd.setNonCollapsingCarryMode(nonCarryCollapsingMode);
[4712]1039    }
[5354]1040    cd.setSummaryType(summaryType);
[5227]1041    return carryState;
[4710]1042}
1043
[5267]1044/** ------------------------------------------------------------------------------------------------------------- *
1045 * @brief constructor
1046 ** ------------------------------------------------------------------------------------------------------------- */
[5435]1047CarryManager::CarryManager() noexcept
1048: mKernel(nullptr)
[5307]1049, mCurrentFrame(nullptr)
[5267]1050, mCurrentFrameIndex(0)
1051, mCurrentScope(nullptr)
1052, mCarryInfo(nullptr)
[5366]1053, mNextSummaryTest(nullptr)
[5267]1054, mIfDepth(0)
[5311]1055, mHasLongAdvance(false)
[5708]1056, mIndexedLongAdvanceTotal(0)
1057, mIndexedLongAdvanceIndex(0)
[5493]1058, mHasNonCarryCollapsingLoops(false)
[5307]1059, mHasLoop(false)
1060, mLoopDepth(0)
[5340]1061, mLoopSelector(nullptr)
[5366]1062, mNextLoopSelector(nullptr)
[5371]1063, mCarryPackPtr(nullptr)
[5340]1064, mCarryScopes(0) {
[5267]1065
[4712]1066}
1067
[5267]1068}
Note: See TracBrowser for help on using the repository browser.