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

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

Eliminate need for mPackBuilder

File size: 34.0 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
8#include <include/simd-lib/bitblock.hpp>
9#include <stdexcept>
10#include <pablo/carry_data.h>
11#include <pablo/codegenstate.h>
12#include <pablo/carry_manager.h>
13#include <pablo/pabloAST.h>
14#include <iostream>
15#include <llvm/Support/CommandLine.h>
16#include <llvm/IR/BasicBlock.h>
17#include <llvm/IR/CallingConv.h>
18#include <llvm/IR/Function.h>
19
20static cl::opt<CarryManagerStrategy> Strategy(cl::desc("Choose carry management strategy:"),
21                                              cl::values(
22                                                         clEnumVal(BitBlockStrategy, "Unpacked, each carry in a separate bitblock."),
23                                                         clEnumVal(SequentialFullyPackedStrategy, "Sequential packing, up to 64 carries per pack."),
24                                                         clEnumValEnd));
25
26
27namespace pablo {
28 
29    unsigned doScopeCount(PabloBlock * pb) {
30        unsigned count = 1;
31       
32        for (Statement * stmt : *pb) {
33            if (If * ifStatement = dyn_cast<If>(stmt)) {
34                count += doScopeCount(ifStatement->getBody());
35            }
36            else if (While * whileStatement = dyn_cast<While>(stmt)) {
37                count += doScopeCount(whileStatement->getBody());
38            }
39        }
40        return count;
41       
42    }
43   
44void CarryManager::generateCarryDataInitializer(Module * m) {
45    FunctionType * functionType = FunctionType::get(Type::getVoidTy(m->getContext()), std::vector<Type *>({}), false);
46    SmallVector<AttributeSet, 1> Attrs;
47    Attrs.push_back(AttributeSet::get(m->getContext(), ~0U, std::vector<Attribute::AttrKind>({ Attribute::NoUnwind, Attribute::UWTable })));
48    AttributeSet AttrSet = AttributeSet::get(m->getContext(), Attrs);
49   
50    // Create the function that will be generated.
51    Function * f = Function::Create(functionType, GlobalValue::ExternalLinkage, "process_block_initialize_carries", m);
52    f->setCallingConv(CallingConv::C);
53    f->setAttributes(AttrSet);
54    llvm::IRBuilderBase::InsertPoint ip = mBuilder->saveIP();
55    mBuilder->SetInsertPoint(BasicBlock::Create(m->getContext(), "entry1", f,0));
56    mBuilder->CreateMemSet(mCarryBitBlockPtr, mBuilder->getInt8(0), mTotalCarryDataBitBlocks * mBITBLOCK_WIDTH/8, 4);
57    ReturnInst::Create(m->getContext(), mBuilder->GetInsertBlock());
58    mBuilder->restoreIP(ip);
59}
60   
61   
62
63void CarryManager::initialize(Module * m, PabloBlock * pb) {
64    mPabloRoot = pb;
65    unsigned scopeCount = doScopeCount(pb);
66    mCarryInfoVector.resize(scopeCount);
67    if (Strategy == SequentialFullyPackedStrategy) {
68        mPACK_SIZE = 64;
69        mITEMS_PER_PACK = 64;
70        mCarryPackType = mBuilder->getIntNTy(mPACK_SIZE);
71    }
72    else {
73        mPACK_SIZE = mBITBLOCK_WIDTH;
74        mITEMS_PER_PACK = 1;
75        mCarryPackType = mBitBlockType;
76    }
77    unsigned totalCarryDataSize = enumerate(pb, 0, 0);
78   
79    unsigned totalPackCount = (totalCarryDataSize + mITEMS_PER_PACK - 1)/mITEMS_PER_PACK;
80
81    mCarryPackPtr.resize(totalPackCount);
82    mCarryInPack.resize(totalPackCount);
83    mCarryOutPack.resize(totalPackCount);
84    for (unsigned i = 0; i < totalPackCount; i++) mCarryInPack[i]=nullptr;
85
86    if (Strategy == SequentialFullyPackedStrategy) {
87        mTotalCarryDataBitBlocks = (totalCarryDataSize + mBITBLOCK_WIDTH - 1)/mBITBLOCK_WIDTH;       
88    }
89    else {
90        mTotalCarryDataBitBlocks = totalCarryDataSize;
91    }
92   
93    ArrayType* cdArrayTy = ArrayType::get(mBitBlockType, mTotalCarryDataBitBlocks);
94    GlobalVariable* cdArray = new GlobalVariable(*m, cdArrayTy, /*isConstant=*/false, GlobalValue::CommonLinkage, /*Initializer=*/0, "process_block_carry_data");
95    cdArray->setAlignment(mBITBLOCK_WIDTH/8);
96    ConstantAggregateZero* cdInitData = ConstantAggregateZero::get(cdArrayTy);
97    cdArray->setInitializer(cdInitData);
98   
99    mCarryPackBasePtr = mBuilder->CreateBitCast(cdArray, PointerType::get(mCarryPackType, 0));
100    mCarryBitBlockPtr = mBuilder->CreateBitCast(cdArray, PointerType::get(mBitBlockType, 0));
101   
102    generateCarryDataInitializer(m);
103   
104    // Popcount data is stored after all the carry data.
105    if (mPabloCountCount > 0) {
106        ArrayType* pcArrayTy = ArrayType::get(mBuilder->getIntNTy(64), mPabloCountCount);
107        GlobalVariable* pcArray = new GlobalVariable(*m, pcArrayTy, /*isConstant=*/false, GlobalValue::CommonLinkage, 0, "popcount_data");
108        cdArray->setAlignment(mBITBLOCK_WIDTH/8);
109        ConstantAggregateZero* pcInitData = ConstantAggregateZero::get(pcArrayTy);
110        pcArray->setInitializer(pcInitData);
111        mPopcountBasePtr = mBuilder->CreateBitCast(pcArray, Type::getInt64PtrTy(mBuilder->getContext()));
112    }
113    // Carry Data area will have one extra bit block to store the block number.
114    GlobalVariable* blkNo = new GlobalVariable(*m, mBuilder->getIntNTy(64), /*isConstant=*/false, GlobalValue::CommonLinkage, 0, "blockNo");
115    blkNo->setAlignment(16);
116    blkNo->setInitializer(mBuilder->getInt64(0));
117    mBlockNoPtr = blkNo;
118    mBlockNo = mBuilder->CreateLoad(mBlockNoPtr);
119    /*  Set the current scope to PabloRoot */
120    mCurrentScope = mPabloRoot;
121    mCurrentFrameIndex = 0;
122    mCarryInfo = mCarryInfoVector[0];
123}
124   
125void CarryManager::generateBlockNoIncrement() {
126    mBuilder->CreateStore(mBuilder->CreateAdd(mBlockNo, mBuilder->getInt64(1)), mBlockNoPtr);
127}
128
129Value * CarryManager::getBlockNoPtr() {
130    return mBlockNoPtr;
131}
132
133
134unsigned CarryManager::enumerate(PabloBlock * blk, unsigned ifDepth, unsigned whileDepth) {
135    llvm::raw_os_ostream cerr(std::cerr);
136    unsigned idx = blk->getScopeIndex();
137    PabloBlockCarryData * cd = new PabloBlockCarryData(blk, mPACK_SIZE, mITEMS_PER_PACK);
138    mCarryInfoVector[idx] = cd;
139
140    cd->setIfDepth(ifDepth);
141    cd->setWhileDepth(whileDepth);
142    unsigned nestedOffset = cd->nested.frameOffset;
143 
144    for (Statement * stmt : *blk) {
145        if (Count * c = dyn_cast<Count>(stmt)) {
146            c->setGlobalCountIndex(mPabloCountCount);
147            mPabloCountCount++;
148        }
149        else if (If * ifStatement = dyn_cast<If>(stmt)) {
150            const unsigned ifCarryDataBits = enumerate(ifStatement->getBody(), ifDepth+1, whileDepth);
151            PabloBlockCarryData * nestedBlockData = mCarryInfoVector[ifStatement->getBody()->getScopeIndex()];
152            if (mITEMS_PER_PACK == mPACK_SIZE) {  // PACKING
153                if (cd->roomInFinalPack(nestedOffset) < ifCarryDataBits) {
154                    nestedOffset = alignCeiling(nestedOffset, mPACK_SIZE);
155                }
156            }
157            nestedBlockData->setFramePosition(nestedOffset);
158
159            nestedOffset += ifCarryDataBits;
160            if (cd->maxNestingDepth <= nestedBlockData->maxNestingDepth) cd->maxNestingDepth = nestedBlockData->maxNestingDepth + 1;
161            cd->nested.entries++;
162#ifdef CARRY_DEBUG
163            nestedBlockData->dumpCarryData(cerr);
164#endif
165        }
166        else if (While * whileStatement = dyn_cast<While>(stmt)) {
167            const unsigned whileCarryDataBits = enumerate(whileStatement->getBody(), ifDepth, whileDepth+1);
168            PabloBlockCarryData * nestedBlockData = mCarryInfoVector[whileStatement->getBody()->getScopeIndex()];
169            //if (whileStatement->isMultiCarry()) whileCarryDataBits *= whileStatement->getMaxIterations();
170            if (mITEMS_PER_PACK == mPACK_SIZE) {  // PACKING
171                if (cd->roomInFinalPack(nestedOffset) < whileCarryDataBits) {
172                    nestedOffset = alignCeiling(nestedOffset, mPACK_SIZE);
173                }
174            }
175            nestedBlockData->setFramePosition(nestedOffset);
176            nestedOffset += whileCarryDataBits;
177            if (cd->maxNestingDepth <= nestedBlockData->maxNestingDepth) cd->maxNestingDepth = nestedBlockData->maxNestingDepth + 1;
178            cd->nested.entries++;
179#ifdef CARRY_DEBUG
180            nestedBlockData->dumpCarryData(cerr);
181#endif
182        }
183    }
184   
185    cd->scopeCarryDataSize = nestedOffset;
186   
187    if (cd->explicitSummaryRequired()) {
188        // Need extra space for the summary variable, always the last
189        // entry within an if block.
190        if (mITEMS_PER_PACK == mPACK_SIZE) {  // PACKING
191            cd->scopeCarryDataSize = alignCeiling(cd->scopeCarryDataSize, mPACK_SIZE);
192        }
193        cd->summary.frameOffset = cd->scopeCarryDataSize;
194        cd->scopeCarryDataSize += mITEMS_PER_PACK;  //  computed summary is a full pack.
195    }
196    else {
197        cd->summary.frameOffset = 0;
198    }
199#ifdef CARRY_DEBUG
200    if (cd->ifDepth == 0) cd->dumpCarryData(cerr);
201#endif
202    return cd->scopeCarryDataSize;
203}
204
205
206/* Entering and leaving blocks. */
207
208void CarryManager::enterScope(PabloBlock * blk) {
209   
210    mCurrentScope = blk;
211    mCarryInfo = mCarryInfoVector[blk->getScopeIndex()];
212    mCurrentFrameIndex += mCarryInfo->getFrameIndex();
213    //std::cerr << "enterScope:  blk->getScopeIndex() = " << blk->getScopeIndex() << ", mCurrentFrameIndex = " << mCurrentFrameIndex << std::endl;
214}
215
216void CarryManager::leaveScope() {
217    mCurrentFrameIndex -= mCarryInfo->getFrameIndex();
218    if (mCurrentScope != mPabloRoot) {
219        mCurrentScope = mCurrentScope->getParent();
220        mCarryInfo = mCarryInfoVector[mCurrentScope->getScopeIndex()];
221    }
222    //std::cerr << "leaveScope:  mCurrentFrameIndex = " << mCurrentFrameIndex << std::endl;
223}
224
225
226/* Helper routines */
227
228unsigned CarryManager::absPosition(unsigned frameOffset, unsigned relPos) {
229    return mCurrentFrameIndex + frameOffset + relPos;
230}
231
232
233unsigned CarryManager::carryOpPosition(unsigned localIndex) {
234    //std::cerr << "carryOpPosition: addWithCarry.frameOffset = " << mCarryInfo->addWithCarry.frameOffset << ", localIndex = " <<localIndex << std::endl;
235    return absPosition(mCarryInfo->addWithCarry.frameOffset, localIndex);
236}
237
238unsigned CarryManager::advance1Position(unsigned localIndex) {
239    //std::cerr << "unsigned CarryManager::advance1Position: advance1.frameOffset = " << mCarryInfo->advance1.frameOffset << ", localIndex = " <<localIndex << std::endl;
240    return absPosition(mCarryInfo->advance1.frameOffset, localIndex);
241}
242
243unsigned CarryManager::shortAdvancePosition(unsigned localIndex) {
244    return absPosition(mCarryInfo->shortAdvance.frameOffset, localIndex);
245}
246
247unsigned CarryManager::longAdvanceBitBlockPosition(unsigned localIndex) {
248    return (mCurrentFrameIndex + mCarryInfo->longAdvance.frameOffset) / mITEMS_PER_PACK + localIndex;
249}
250   
251unsigned CarryManager::localBasePack() {
252    return (mCurrentFrameIndex + mCarryInfo->shortAdvance.frameOffset) / mITEMS_PER_PACK;
253}
254   
255unsigned CarryManager::scopeBasePack() {
256    return mCurrentFrameIndex / mITEMS_PER_PACK;
257}
258   
259
260
261unsigned CarryManager::summaryPosition() {
262    return absPosition(mCarryInfo->summary.frameOffset, 0);
263}
264
265
266unsigned CarryManager::summaryPackIndex() {
267    return summaryPosition()/mITEMS_PER_PACK;
268}
269
270unsigned CarryManager::summaryBits() {
271    if (mCarryInfo->scopeCarryDataSize > mITEMS_PER_PACK) return mPACK_SIZE;
272    else return mCarryInfo->scopeCarryDataSize;
273}
274
275
276
277Value * CarryManager::getCarryPack(unsigned packIndex) {
278    if (mCarryInPack[packIndex] == nullptr) {
279        Value * packPtr = mBuilder->CreateGEP(mCarryPackBasePtr, mBuilder->getInt64(packIndex));
280        // Save the computed pointer - so that it can be used in storeCarryPack.
281        mCarryPackPtr[packIndex] = packPtr;
282        mCarryInPack[packIndex] = mBuilder->CreateAlignedLoad(packPtr, mPACK_SIZE/8);
283    }
284    return mCarryInPack[packIndex];
285}
286   
287void CarryManager::storeCarryPack(unsigned packIndex) {
288    mBuilder->CreateAlignedStore(mCarryOutPack[packIndex], mCarryPackPtr[packIndex], mPACK_SIZE/8);
289}
290
291   
292/* maskSelectBitRange selects the bits of a pack from lo_bit through
293   lo_bit + bitCount - 1, setting all other bits to zero.  */
294   
295Value * CarryManager::maskSelectBitRange(Value * pack, unsigned lo_bit, unsigned bitCount) {
296    if (bitCount == mPACK_SIZE) {
297        assert(lo_bit == 0);
298        return pack;
299    }
300    uint64_t mask = ((((uint64_t) 1) << bitCount) - 1) << lo_bit;
301    return mBuilder->CreateAnd(pack, ConstantInt::get(mCarryPackType, mask));
302}
303   
304Value * CarryManager::getCarryInBits(unsigned carryBitPos, unsigned carryBitCount) {
305    unsigned packIndex = carryBitPos / mPACK_SIZE;
306    unsigned packOffset = carryBitPos % mPACK_SIZE;
307    Value * selected = maskSelectBitRange(getCarryPack(packIndex), packOffset, carryBitCount);
308    if (packOffset == 0) return selected;
309    return mBuilder->CreateLShr(selected, packOffset);
310}
311
312void CarryManager::extractAndSaveCarryOutBits(Value * bitblock, unsigned carryBit_pos, unsigned carryBitCount) {
313    unsigned packIndex = carryBit_pos / mPACK_SIZE;
314    unsigned packOffset = carryBit_pos % mPACK_SIZE;
315    unsigned rshift = mPACK_SIZE - packOffset - carryBitCount;
316    uint64_t mask = ((((uint64_t) 1) << carryBitCount) - 1)  << packOffset;
317    //std::cerr << "extractAndSaveCarryOutBits: packIndex =" << packIndex << ", packOffset = " << packOffset << ", mask = " << mask << std::endl;
318    Value * field = iBuilder->mvmd_extract(mPACK_SIZE, bitblock, mBITBLOCK_WIDTH/mPACK_SIZE - 1);
319    //Value * field = maskSelectBitRange(field, PACK_SIZE - carryBitCount, carryBitCount);
320    if (rshift != 0) {
321        field = mBuilder->CreateLShr(field, mBuilder->getInt64(rshift));
322    }
323    if (packOffset != 0) {
324        field = mBuilder->CreateAnd(field, mBuilder->getInt64(mask));
325    }
326    if (mCarryOutPack[packIndex] == nullptr) {
327        mCarryOutPack[packIndex] = field;
328    }
329    else {
330        mCarryOutPack[packIndex] = mBuilder->CreateOr(mCarryOutPack[packIndex], field);
331    }
332}
333
334Value * CarryManager::pack2bitblock(Value * pack) {
335    return iBuilder->bitCast(mBuilder->CreateZExt(pack, mBuilder->getIntNTy(mBITBLOCK_WIDTH)));
336}
337   
338   
339/* Methods for getting and setting individual carry values. */
340   
341Value * CarryManager::getCarryOpCarryIn(int localIndex) {
342    unsigned posn = carryOpPosition(localIndex);
343    if (mITEMS_PER_PACK > 1) {// #ifdef PACKING
344        return pack2bitblock(getCarryInBits(posn, 1));
345    }
346    else {
347        return getCarryPack(posn);
348    }
349}
350
351#if (BLOCK_SIZE==256)
352#define LONGADD 1
353#endif
354
355   
356void CarryManager::setCarryOpCarryOut(unsigned localIndex, Value * carry_out_strm) {
357    unsigned posn = carryOpPosition(localIndex);
358    if (mITEMS_PER_PACK > 1) {// #ifdef PACKING
359        extractAndSaveCarryOutBits(carry_out_strm, posn, 1);
360    }
361    else {
362#ifndef LONGADD
363        Value * carry_bit = mBuilder->CreateLShr(mBuilder->CreateBitCast(carry_out_strm, mBuilder->getIntNTy(mBITBLOCK_WIDTH)), mBITBLOCK_WIDTH-1);
364        mCarryOutPack[posn] = mBuilder->CreateBitCast(carry_bit, mBitBlockType);
365#else
366        mCarryOutPack[posn] = carry_out_strm;
367#endif
368        if (mCarryInfo->getWhileDepth() == 0) {
369            storeCarryPack(posn);
370        }
371    }
372}
373
374Value * CarryManager::addCarryInCarryOut(int localIndex, Value* e1, Value* e2) {
375    if (mBITBLOCK_WIDTH == 128) {
376        Value * carryq_value = getCarryOpCarryIn(localIndex);
377        //calculate carry through logical ops
378        Value* carrygen = iBuilder->simd_and(e1, e2);
379        Value* carryprop = iBuilder->simd_or(e1, e2);
380        Value* digitsum = iBuilder->simd_add(64, e1, e2);
381        Value* partial = iBuilder->simd_add(64, digitsum, carryq_value);
382        Value* digitcarry = iBuilder->simd_or(carrygen, iBuilder->simd_and(carryprop, mBuilder->CreateNot(partial)));
383        Value* mid_carry_in = iBuilder->simd_slli(128, mBuilder->CreateLShr(digitcarry, 63), 64);
384        Value* sum = iBuilder->simd_add(64, partial, mBuilder->CreateBitCast(mid_carry_in, mBitBlockType));
385        Value* carry_out_strm = iBuilder->simd_or(carrygen, iBuilder->simd_and(carryprop, mBuilder->CreateNot(sum)));
386        setCarryOpCarryOut(localIndex, carry_out_strm);
387        return sum;
388    }
389    else {
390#ifndef LONGADD
391        Value * carryq_value = getCarryOpCarryIn(localIndex);
392        Value* carrygen = iBuilder->simd_and(e1, e2);
393        Value* carryprop = iBuilder->simd_or(e1, e2);
394        Value * sum = iBuilder->simd_add(mBITBLOCK_WIDTH, iBuilder->simd_add(mBITBLOCK_WIDTH, e1, e2), carryq_value);
395        Value* carry_out_strm = iBuilder->simd_or(carrygen, iBuilder->simd_and(carryprop, mBuilder->CreateNot(sum)));
396        setCarryOpCarryOut(localIndex, carry_out_strm);
397        return sum;
398#else
399        Value * carryq_value = getCarryOpCarryIn(localIndex);
400        Value * carryin = iBuilder->mvmd_extract(32, carryq_value, 0);
401        Value * carrygen = iBuilder->simd_and(e1, e2);
402        Value * carryprop = iBuilder->simd_or(e1, e2);
403        Value * digitsum = iBuilder->simd_add(64, e1, e2);
404        Value * digitcarry = iBuilder->simd_or(carrygen, iBuilder->simd_and(carryprop, mBuilder->CreateNot(digitsum)));
405        Value * carryMask = iBuilder->hsimd_signmask(64, digitcarry);
406        Value * carryMask2 = mBuilder->CreateOr(mBuilder->CreateAdd(carryMask, carryMask), carryin);
407        Value * bubble = iBuilder->simd_eq(64, digitsum, iBuilder->allOnes());
408        Value * bubbleMask = iBuilder->hsimd_signmask(64, bubble);
409        Value * incrementMask = mBuilder->CreateXor(mBuilder->CreateAdd(bubbleMask, carryMask2), bubbleMask);
410        Value * increments = iBuilder->esimd_bitspread(64,incrementMask);
411        Value * sum = iBuilder->simd_add(64, digitsum, increments);
412        Value * carry_out_strm = iBuilder->mvmd_insert(32, iBuilder->allZeroes(), mBuilder->CreateLShr(incrementMask, iBuilder->getBitBlockWidth()/64), 0);
413        setCarryOpCarryOut(localIndex, carry_out_strm);
414        return sum;
415#endif
416    }
417}
418
419
420Value * CarryManager::advanceCarryInCarryOut(int localIndex, unsigned shift_amount, Value * strm) {
421    if (shift_amount == 1) {
422        return unitAdvanceCarryInCarryOut(localIndex, strm);
423    }
424    else if (shift_amount < LongAdvanceBase) {
425        return shortAdvanceCarryInCarryOut(localIndex, shift_amount, strm);
426    }
427    else {
428        return longAdvanceCarryInCarryOut(localIndex, shift_amount, strm);
429    }
430}
431
432#define DSSLI_FIELDWIDTH 64
433
434Value * CarryManager::unitAdvanceCarryInCarryOut(int localIndex, Value * strm) {
435    unsigned posn = advance1Position(localIndex);
436    if (mITEMS_PER_PACK > 1) {// #ifdef PACKING
437        extractAndSaveCarryOutBits(strm, posn, 1);
438        Value* carry_longint = mBuilder->CreateZExt(getCarryInBits(posn, 1), mBuilder->getIntNTy(mBITBLOCK_WIDTH));
439        Value* strm_longint = mBuilder->CreateBitCast(strm, mBuilder->getIntNTy(mBITBLOCK_WIDTH));
440        Value* adv_longint = mBuilder->CreateOr(mBuilder->CreateShl(strm_longint, 1), carry_longint);
441        Value* result_value = mBuilder->CreateBitCast(adv_longint, mBitBlockType);
442        return result_value;
443    }
444    mCarryOutPack[posn] = strm;
445    Value * carry_in = getCarryPack(posn);
446    if (mCarryInfo->getWhileDepth() == 0) {
447        storeCarryPack(posn);
448    }
449    Value * ahead = iBuilder->mvmd_dslli(DSSLI_FIELDWIDTH, strm, carry_in, iBuilder->getBitBlockWidth()/DSSLI_FIELDWIDTH -1);
450    return iBuilder->simd_or(iBuilder->simd_srli(DSSLI_FIELDWIDTH, ahead, DSSLI_FIELDWIDTH-1), iBuilder->simd_slli(DSSLI_FIELDWIDTH, strm, 1));
451}
452
453Value * CarryManager::shortAdvanceCarryInCarryOut(int localIndex, unsigned shift_amount, Value * strm) {
454    unsigned posn = shortAdvancePosition(localIndex);
455    if (mITEMS_PER_PACK > 1) {// #ifdef PACKING
456        extractAndSaveCarryOutBits(strm, posn, shift_amount);
457        //std::cerr << "shortAdvanceCarryInCarryOut: posn = " << posn << ", shift_amount = " << shift_amount << std::endl;
458        Value* carry_longint = mBuilder->CreateZExt(getCarryInBits(posn, shift_amount), mBuilder->getIntNTy(mBITBLOCK_WIDTH));
459        Value* strm_longint = mBuilder->CreateBitCast(strm, mBuilder->getIntNTy(mBITBLOCK_WIDTH));
460        Value* adv_longint = mBuilder->CreateOr(mBuilder->CreateShl(strm_longint, shift_amount), carry_longint);
461        Value* result_value = mBuilder->CreateBitCast(adv_longint, mBitBlockType);
462        return result_value;
463    }
464    mCarryOutPack[posn] = strm;
465    Value * carry_in = getCarryPack(posn);
466    if (mCarryInfo->getWhileDepth() == 0) {
467        storeCarryPack(posn);
468    }
469    // Use a single whole-byte shift, if possible.
470    if (shift_amount % 8 == 0) {
471        return iBuilder->mvmd_dslli(8, strm, carry_in, iBuilder->getBitBlockWidth()/8 - shift_amount/8);
472    }
473    else if (shift_amount < DSSLI_FIELDWIDTH) {
474        Value * ahead = iBuilder->mvmd_dslli(DSSLI_FIELDWIDTH, strm, carry_in, iBuilder->getBitBlockWidth()/DSSLI_FIELDWIDTH - 1);
475        return iBuilder->simd_or(iBuilder->simd_srli(DSSLI_FIELDWIDTH, ahead, DSSLI_FIELDWIDTH-shift_amount), iBuilder->simd_slli(DSSLI_FIELDWIDTH, strm, shift_amount));
476    }
477    Value* advanceq_longint = mBuilder->CreateBitCast(carry_in, mBuilder->getIntNTy(mBITBLOCK_WIDTH));
478    Value* strm_longint = mBuilder->CreateBitCast(strm, mBuilder->getIntNTy(mBITBLOCK_WIDTH));
479    Value* adv_longint = mBuilder->CreateOr(mBuilder->CreateShl(strm_longint, shift_amount), mBuilder->CreateLShr(advanceq_longint, mBITBLOCK_WIDTH - shift_amount), "advance");
480    return mBuilder->CreateBitCast(adv_longint, mBitBlockType);
481}
482   
483
484/*  currently defined in carry_data.h
485 
486 static unsigned power2ceil (unsigned v) {
487 unsigned ceil = 1;
488 while (ceil < v) ceil *= 2;
489 return ceil;
490 }
491 
492 unsigned longAdvanceEntries(unsigned shift_amount) const {
493 return (shift_amount + mBITBLOCK_WIDTH - 1)/mBITBLOCK_WIDTH;
494 }
495 
496 unsigned longAdvanceBufferSize(unsigned shift_amount)  const {
497 return power2ceil(longAdvanceEntries(shift_amount));
498 }
499 */
500
501   
502Value * CarryManager::longAdvanceCarryInCarryOut(int localIndex, unsigned shift_amount, Value * carry_out) {
503    unsigned carryDataIndex = longAdvanceBitBlockPosition(localIndex);
504    Value * advBaseIndex = mBuilder->getInt64(carryDataIndex);
505    if (shift_amount <= mBITBLOCK_WIDTH) {
506        // special case using a single buffer entry and the carry_out value.
507        Value * advanceDataPtr = mBuilder->CreateGEP(mCarryBitBlockPtr, advBaseIndex);
508        Value * carry_block0 = mBuilder->CreateAlignedLoad(advanceDataPtr, mBITBLOCK_WIDTH/8);
509        mBuilder->CreateAlignedStore(carry_out, advanceDataPtr, mBITBLOCK_WIDTH/8);
510        /* Very special case - no combine */
511        if (shift_amount == mBITBLOCK_WIDTH) return carry_block0;
512        Value* block0_shr = mBuilder->CreateLShr(mBuilder->CreateBitCast(carry_block0, mBuilder->getIntNTy(mBITBLOCK_WIDTH)), mBITBLOCK_WIDTH - shift_amount);
513        Value* block1_shl = mBuilder->CreateShl(mBuilder->CreateBitCast(carry_out, mBuilder->getIntNTy(mBITBLOCK_WIDTH)), shift_amount);
514        return mBuilder->CreateBitCast(mBuilder->CreateOr(block1_shl, block0_shr), mBitBlockType);
515    }
516    // We need a buffer of at least two elements for storing the advance data.
517    const unsigned block_shift = shift_amount % mBITBLOCK_WIDTH;
518    const unsigned advanceEntries = mCarryInfo->longAdvanceEntries(shift_amount);
519    const unsigned bufsize = mCarryInfo->longAdvanceBufferSize(shift_amount);
520    Value * indexMask = mBuilder->getInt64(bufsize - 1);  // A mask to implement circular buffer indexing
521    Value * loadIndex0 = mBuilder->CreateAdd(mBuilder->CreateAnd(mBuilder->CreateSub(mBlockNo, mBuilder->getInt64(advanceEntries)), indexMask), advBaseIndex);
522    Value * storeIndex = mBuilder->CreateAdd(mBuilder->CreateAnd(mBlockNo, indexMask), advBaseIndex);
523    Value * carry_block0 = mBuilder->CreateAlignedLoad(mBuilder->CreateGEP(mCarryBitBlockPtr, loadIndex0), mBITBLOCK_WIDTH/8);
524    // If the long advance is an exact multiple of mBITBLOCK_WIDTH, we simply return the oldest
525    // block in the long advance carry data area. 
526    if (block_shift == 0) {
527        mBuilder->CreateAlignedStore(carry_out, mBuilder->CreateGEP(mCarryBitBlockPtr, storeIndex), mBITBLOCK_WIDTH/8);
528        return carry_block0;
529    }
530    // Otherwise we need to combine data from the two oldest blocks.
531    Value * loadIndex1 = mBuilder->CreateAdd(mBuilder->CreateAnd(mBuilder->CreateSub(mBlockNo, mBuilder->getInt64(advanceEntries-1)), indexMask), advBaseIndex);
532    Value * carry_block1 = mBuilder->CreateAlignedLoad(mBuilder->CreateGEP(mCarryBitBlockPtr, loadIndex1), mBITBLOCK_WIDTH/8);
533    Value* block0_shr = mBuilder->CreateLShr(mBuilder->CreateBitCast(carry_block0, mBuilder->getIntNTy(mBITBLOCK_WIDTH)), mBITBLOCK_WIDTH - block_shift);
534    Value* block1_shl = mBuilder->CreateShl(mBuilder->CreateBitCast(carry_block1, mBuilder->getIntNTy(mBITBLOCK_WIDTH)), block_shift);
535    mBuilder->CreateAlignedStore(carry_out, mBuilder->CreateGEP(mCarryBitBlockPtr, storeIndex), mBITBLOCK_WIDTH/8);
536    return mBuilder->CreateBitCast(mBuilder->CreateOr(block1_shl, block0_shr), mBitBlockType);
537}
538   
539
540/* Methods for getting and setting carry summary values */
541   
542bool CarryManager::blockHasCarries(){
543    return mCarryInfo->blockHasCarries();
544} 
545
546
547Value * CarryManager::generateBitBlockOrSummaryTest(Value * bitblock) {
548    Value * test_expr = bitblock;
549    if (mCarryInfo->blockHasCarries()) {
550        Value * summary_pack = getCarryPack(summaryPackIndex());
551        if (mITEMS_PER_PACK > 1) {// #ifdef PACKING
552            Value * summary_bits = maskSelectBitRange(summary_pack, summaryPosition() % mPACK_SIZE, summaryBits());
553            test_expr = iBuilder->simd_or(test_expr, mBuilder->CreateZExt(summary_bits, mBuilder->getIntNTy(mBITBLOCK_WIDTH)));
554        }
555        else {
556            test_expr = iBuilder->simd_or(test_expr, summary_pack);
557        }
558    }
559    return iBuilder->bitblock_any(test_expr);
560}
561
562void CarryManager::initializeCarryDataAtIfEntry() {
563    if (blockHasCarries()) {
564        if (mCarryOutPack[scopeBasePack()] == nullptr) {
565            mCarryInfo->ifEntryPack = Constant::getNullValue(mCarryPackType);
566        }
567        else {
568            mCarryInfo->ifEntryPack = mCarryOutPack[scopeBasePack()];
569        }
570    }
571}
572   
573void CarryManager::buildCarryDataPhisAfterIfBody(BasicBlock * ifEntryBlock, BasicBlock * ifBodyFinalBlock) {
574    if (mCarryInfo->getWhileDepth() > 0) {
575        // We need to phi out everything for the while carry accumulation process.
576        const unsigned scopeCarryPacks = mCarryInfo->getScopeCarryPackCount();
577        const unsigned currentScopeBase = scopeBasePack();
578        for (unsigned index = currentScopeBase; index < currentScopeBase + scopeCarryPacks; ++index) {
579            PHINode * phi_out = mBuilder->CreatePHI(mCarryPackType, 2);
580            phi_out->addIncoming(Constant::getNullValue(mCarryPackType),ifEntryBlock);
581            phi_out->addIncoming(mCarryOutPack[index], ifBodyFinalBlock);
582            mCarryOutPack[index] = phi_out;
583        }
584        return;
585    }
586    unsigned const ifScopeCarrySize = mCarryInfo->scopeCarryDataSize;
587    if (ifScopeCarrySize == 0) {
588        // No carry data, therefore no phi nodes.
589        return;
590    }
591    if (mITEMS_PER_PACK > 1) {// #ifdef PACKING
592        if (ifScopeCarrySize <= mPACK_SIZE) {
593            unsigned const ifPackIndex = scopeBasePack();
594            PHINode * ifPack_phi = mBuilder->CreatePHI(mCarryPackType, 2, "ifPack");
595            ifPack_phi->addIncoming(mCarryInfo->ifEntryPack, ifEntryBlock);
596            ifPack_phi->addIncoming(mCarryOutPack[ifPackIndex], ifBodyFinalBlock);
597            mCarryOutPack[ifPackIndex] = ifPack_phi;
598            return;
599        }
600    }
601    if (mCarryInfo->getIfDepth() > 1) {
602        // Our parent block is also an if.  It needs access to our summary to compute
603        // its own summary.
604        const unsigned summaryIndex = summaryPackIndex();
605        PHINode * summary_phi = mBuilder->CreatePHI(mCarryPackType, 2, "summary");
606        summary_phi->addIncoming(Constant::getNullValue(mCarryPackType), ifEntryBlock);
607        summary_phi->addIncoming(mCarryOutPack[summaryIndex], ifBodyFinalBlock);
608        mCarryOutPack[summaryIndex] = summary_phi;
609    }
610}
611   
612void CarryManager::addSummaryPhiIfNeeded(BasicBlock * ifEntryBlock, BasicBlock * ifBodyFinalBlock) {
613    if ((mCarryInfo->getIfDepth() <= 1) || !mCarryInfo->blockHasCarries()){
614        // For ifDepth == 1, the parent does not need a summary as it is not itself within an if.
615        // Therefore, it doesn't need access to this block's summary in building its own.
616        return;
617    }
618    const unsigned carrySummaryIndex = summaryPackIndex();
619    PHINode * summary_phi = mBuilder->CreatePHI(mCarryPackType, 2, "summary");
620    summary_phi->addIncoming(Constant::getNullValue(mCarryPackType), ifEntryBlock);
621    summary_phi->addIncoming(mCarryOutPack[carrySummaryIndex], ifBodyFinalBlock);
622    mCarryOutPack[carrySummaryIndex] = summary_phi;
623}
624   
625void CarryManager::generateCarryOutSummaryCodeIfNeeded() {
626   
627    if (!mCarryInfo->explicitSummaryRequired()) {
628        // An explicit summary may not be required, if there is a single carry
629        // operation within the block, or the carries are packed and all carry
630        // bits fit within a single pack.
631        return;
632    }
633   
634    const unsigned carrySummaryIndex = summaryPackIndex();
635   
636    Value * carry_summary = Constant::getNullValue(mCarryPackType);
637    if (mCarryInfo->blockHasLongAdvances()) { // Force if entry
638        carry_summary = Constant::getAllOnesValue(mCarryPackType);
639    }
640    else {
641        unsigned localCarryIndex = localBasePack();
642        unsigned localCarryPacks = mCarryInfo->getLocalCarryPackCount();
643        if (localCarryPacks > 0) {
644            carry_summary = mCarryOutPack[localCarryIndex];
645            for (unsigned i = 1; i < localCarryPacks; i++) {
646                carry_summary = mBuilder->CreateOr(carry_summary, mCarryOutPack[localCarryIndex+i]);
647            }
648        }
649        for (Statement * stmt : *mCurrentScope) {
650            if (If * innerIf = dyn_cast<If>(stmt)) {
651                PabloBlock * inner_blk = innerIf->getBody();
652                enterScope(inner_blk);
653                if (blockHasCarries()) {
654                  carry_summary = mBuilder->CreateOr(carry_summary, mCarryOutPack[summaryPackIndex()]);
655                }
656                leaveScope();
657            }
658            else if (While * innerWhile = dyn_cast<While>(stmt)) {
659                PabloBlock * inner_blk = innerWhile->getBody();
660                enterScope(inner_blk);
661                if (blockHasCarries()) {
662                    carry_summary = mBuilder->CreateOr(carry_summary, mCarryOutPack[summaryPackIndex()]);
663                }
664                leaveScope();
665            }
666        }
667    }
668    // Calculation of the carry out summary is complete.   Store it and make it
669    // available in case it must included by parent blocks.
670    mCarryOutPack[carrySummaryIndex] = carry_summary;
671    storeCarryPack(carrySummaryIndex);
672}
673
674void CarryManager::ensureCarriesLoadedRecursive() {
675    const unsigned scopeCarryPacks = mCarryInfo->getScopeCarryPackCount();
676    const unsigned currentScopeBase = scopeBasePack();
677    if (mCarryInfo->getWhileDepth() == 1) {
678        for (auto i = currentScopeBase; i < currentScopeBase + scopeCarryPacks; ++i) {
679            getCarryPack(i);
680        }
681    }
682}
683
684
685void CarryManager::initializeCarryDataPhisAtWhileEntry(BasicBlock * whileEntryBlock) {
686    const unsigned scopeCarryPacks = mCarryInfo->getScopeCarryPackCount();
687    mCarryOutAccumPhis.resize(scopeCarryPacks);
688#ifdef SET_WHILE_CARRY_IN_TO_ZERO_AFTER_FIRST_ITERATION
689    const unsigned currentScopeBase = scopeBasePack();
690    mCarryInPhis.resize(scopeCarryPacks);
691#endif
692    for (unsigned index = 0; index < scopeCarryPacks; ++index) {
693#ifdef SET_WHILE_CARRY_IN_TO_ZERO_AFTER_FIRST_ITERATION
694        PHINode * phi_in = mBuilder->CreatePHI(mCarryPackType, 2);
695        phi_in->addIncoming(mCarryInPack[currentScopeBase+index], whileEntryBlock);
696        mCarryInPhis[index] = phi_in;
697#endif
698        PHINode * phi_out = mBuilder->CreatePHI(mCarryPackType, 2);
699        phi_out->addIncoming(Constant::getNullValue(mCarryPackType), whileEntryBlock);
700        mCarryOutAccumPhis[index] = phi_out;
701    }
702}
703
704
705void CarryManager::extendCarryDataPhisAtWhileBodyFinalBlock(BasicBlock * whileBodyFinalBlock) {
706    const unsigned scopeCarryPacks = mCarryInfo->getScopeCarryPackCount();
707    const unsigned currentScopeBase = scopeBasePack();
708    for (unsigned index = 0; index < scopeCarryPacks; ++index) {
709#ifdef SET_WHILE_CARRY_IN_TO_ZERO_AFTER_FIRST_ITERATION
710        mCarryInPhis[index]->addIncoming(Constant::getNullValue(mCarryPackType), whileBodyFinalBlock);
711#endif
712        PHINode * phi = mCarryOutAccumPhis[index];
713        Value * carryOut = mBuilder->CreateOr(phi, mCarryOutPack[currentScopeBase+index]);
714        phi->addIncoming(carryOut, whileBodyFinalBlock);
715        mCarryOutPack[currentScopeBase+index] = carryOut;
716    }
717}
718
719void CarryManager::ensureCarriesStoredRecursive() {
720    const unsigned scopeCarryPacks = mCarryInfo->getScopeCarryPackCount();
721    const unsigned currentScopeBase = scopeBasePack();
722    if (mCarryInfo->getWhileDepth() == 1) {
723        for (auto i = currentScopeBase; i < currentScopeBase + scopeCarryPacks; ++i) {
724            storeCarryPack(i);
725        }
726    }
727}
728
729/* Store all the full carry packs generated locally in this scope or the
730   single full pack for this scope*/
731void CarryManager::ensureCarriesStoredLocal() {
732    if (mITEMS_PER_PACK > 1) {// #ifdef PACKING
733        const unsigned scopeCarryPacks = mCarryInfo->getScopeCarryPackCount();
734        if ((scopeCarryPacks > 0) && ((mCurrentFrameIndex % mPACK_SIZE) == 0)) {
735            // We have carry data and we are not in the middle of a pack.
736            // Write out all local packs.
737            auto localCarryIndex = localBasePack();
738            auto localCarryPacks = mCarryInfo->getLocalCarryPackCount();
739            for (auto i = localCarryIndex; i < localCarryIndex + localCarryPacks; i++) {
740                storeCarryPack(i);
741            }
742            if ((localCarryPacks == 0) && (scopeCarryPacks == 1) && (mCarryInfo->nested.entries > 1)) {
743                storeCarryPack(localCarryIndex);
744            }
745        }
746    }
747}
748
749Value * CarryManager::popCount(Value * to_count, unsigned globalIdx) {
750    Value * countPtr = mBuilder->CreateGEP(mPopcountBasePtr, mBuilder->getInt64(globalIdx));
751    Value * countSoFar = mBuilder->CreateAlignedLoad(countPtr, 8);
752    Value * fieldCounts = iBuilder->simd_popcount(64, to_count);
753    for (int i = 0; i < mBITBLOCK_WIDTH/64; i++) {
754        countSoFar = mBuilder->CreateAdd(countSoFar, iBuilder->mvmd_extract(64, fieldCounts, i));
755    }
756    mBuilder->CreateAlignedStore(countSoFar, countPtr, 8);
757    return iBuilder->bitCast(mBuilder->CreateZExt(countSoFar, mBuilder->getIntNTy(mBITBLOCK_WIDTH)));
758}
759
760CarryManager::~CarryManager() {
761    for (auto * cd : mCarryInfoVector) {
762        delete cd;
763    }
764}
765
766}
767
Note: See TracBrowser for help on using the repository browser.