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

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

Fix conversion from carry out bit to bitblock

File size: 34.1 KB
Line 
1/*
2 *  Copyright (c) 2015 International Characters.
3 *  This software is licensed to the public under the Open Software License 3.0.
4 *  icgrep is a trademark of International Characters.
5 */
6
7
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 = iBuilder->saveIP();
55    iBuilder->SetInsertPoint(BasicBlock::Create(m->getContext(), "entry1", f,0));
56    iBuilder->CreateMemSet(mCarryBitBlockPtr, iBuilder->getInt8(0), mTotalCarryDataBitBlocks * mBITBLOCK_WIDTH/8, 4);
57    ReturnInst::Create(m->getContext(), iBuilder->GetInsertBlock());
58    iBuilder->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 = iBuilder->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 = iBuilder->CreateBitCast(cdArray, PointerType::get(mCarryPackType, 0));
100    mCarryBitBlockPtr = iBuilder->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(iBuilder->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 = iBuilder->CreateBitCast(pcArray, Type::getInt64PtrTy(iBuilder->getContext()));
112    }
113    // Carry Data area will have one extra bit block to store the block number.
114    GlobalVariable* blkNo = new GlobalVariable(*m, iBuilder->getIntNTy(64), /*isConstant=*/false, GlobalValue::CommonLinkage, 0, "blockNo");
115    blkNo->setAlignment(16);
116    blkNo->setInitializer(iBuilder->getInt64(0));
117    mBlockNoPtr = blkNo;
118    mBlockNo = iBuilder->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    iBuilder->CreateStore(iBuilder->CreateAdd(mBlockNo, iBuilder->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 = iBuilder->CreateGEP(mCarryPackBasePtr, iBuilder->getInt64(packIndex));
280        // Save the computed pointer - so that it can be used in storeCarryPack.
281        mCarryPackPtr[packIndex] = packPtr;
282        mCarryInPack[packIndex] = iBuilder->CreateAlignedLoad(packPtr, mPACK_SIZE/8);
283    }
284    return mCarryInPack[packIndex];
285}
286   
287void CarryManager::storeCarryPack(unsigned packIndex) {
288    iBuilder->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 iBuilder->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 iBuilder->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 = iBuilder->CreateLShr(field, iBuilder->getInt64(rshift));
322    }
323    if (packOffset != 0) {
324        field = iBuilder->CreateAnd(field, iBuilder->getInt64(mask));
325    }
326    if (mCarryOutPack[packIndex] == nullptr) {
327        mCarryOutPack[packIndex] = field;
328    }
329    else {
330        mCarryOutPack[packIndex] = iBuilder->CreateOr(mCarryOutPack[packIndex], field);
331    }
332}
333
334Value * CarryManager::pack2bitblock(Value * pack) {
335    return iBuilder->bitCast(iBuilder->CreateZExt(pack, iBuilder->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 = iBuilder->CreateLShr(iBuilder->CreateBitCast(carry_out_strm, iBuilder->getIntNTy(mBITBLOCK_WIDTH)), mBITBLOCK_WIDTH-1);
364        mCarryOutPack[posn] = iBuilder->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, iBuilder->CreateNot(partial)));
383        Value* mid_carry_in = iBuilder->simd_slli(128, iBuilder->CreateLShr(digitcarry, 63), 64);
384        Value* sum = iBuilder->simd_add(64, partial, iBuilder->CreateBitCast(mid_carry_in, mBitBlockType));
385        Value* carry_out_strm = iBuilder->simd_or(carrygen, iBuilder->simd_and(carryprop, iBuilder->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, iBuilder->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, iBuilder->CreateNot(digitsum)));
405        Value * carryMask = iBuilder->hsimd_signmask(64, digitcarry);
406        Value * carryMask2 = iBuilder->CreateOr(iBuilder->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 = iBuilder->CreateXor(iBuilder->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(), iBuilder->CreateLShr(incrementMask, iBuilder->getBitBlockWidth()/64), 0);
413        Value * carry_out_strm = iBuilder->CreateZExt(iBuilder->CreateLShr(incrementMask, iBuilder->getBitBlockWidth()/64), iBuilder->getIntNTy(mBITBLOCK_WIDTH));
414        setCarryOpCarryOut(localIndex, iBuilder->bitCast(carry_out_strm));
415        return sum;
416#endif
417    }
418}
419
420
421Value * CarryManager::advanceCarryInCarryOut(int localIndex, unsigned shift_amount, Value * strm) {
422    if (shift_amount == 1) {
423        return unitAdvanceCarryInCarryOut(localIndex, strm);
424    }
425    else if (shift_amount < LongAdvanceBase) {
426        return shortAdvanceCarryInCarryOut(localIndex, shift_amount, strm);
427    }
428    else {
429        return longAdvanceCarryInCarryOut(localIndex, shift_amount, strm);
430    }
431}
432
433#define DSSLI_FIELDWIDTH 64
434
435Value * CarryManager::unitAdvanceCarryInCarryOut(int localIndex, Value * strm) {
436    unsigned posn = advance1Position(localIndex);
437    if (mITEMS_PER_PACK > 1) {// #ifdef PACKING
438        extractAndSaveCarryOutBits(strm, posn, 1);
439        Value* carry_longint = iBuilder->CreateZExt(getCarryInBits(posn, 1), iBuilder->getIntNTy(mBITBLOCK_WIDTH));
440        Value* strm_longint = iBuilder->CreateBitCast(strm, iBuilder->getIntNTy(mBITBLOCK_WIDTH));
441        Value* adv_longint = iBuilder->CreateOr(iBuilder->CreateShl(strm_longint, 1), carry_longint);
442        Value* result_value = iBuilder->CreateBitCast(adv_longint, mBitBlockType);
443        return result_value;
444    }
445    mCarryOutPack[posn] = strm;
446    Value * carry_in = getCarryPack(posn);
447    if (mCarryInfo->getWhileDepth() == 0) {
448        storeCarryPack(posn);
449    }
450    Value * ahead = iBuilder->mvmd_dslli(DSSLI_FIELDWIDTH, strm, carry_in, iBuilder->getBitBlockWidth()/DSSLI_FIELDWIDTH -1);
451    return iBuilder->simd_or(iBuilder->simd_srli(DSSLI_FIELDWIDTH, ahead, DSSLI_FIELDWIDTH-1), iBuilder->simd_slli(DSSLI_FIELDWIDTH, strm, 1));
452}
453
454Value * CarryManager::shortAdvanceCarryInCarryOut(int localIndex, unsigned shift_amount, Value * strm) {
455    unsigned posn = shortAdvancePosition(localIndex);
456    if (mITEMS_PER_PACK > 1) {// #ifdef PACKING
457        extractAndSaveCarryOutBits(strm, posn, shift_amount);
458        //std::cerr << "shortAdvanceCarryInCarryOut: posn = " << posn << ", shift_amount = " << shift_amount << std::endl;
459        Value* carry_longint = iBuilder->CreateZExt(getCarryInBits(posn, shift_amount), iBuilder->getIntNTy(mBITBLOCK_WIDTH));
460        Value* strm_longint = iBuilder->CreateBitCast(strm, iBuilder->getIntNTy(mBITBLOCK_WIDTH));
461        Value* adv_longint = iBuilder->CreateOr(iBuilder->CreateShl(strm_longint, shift_amount), carry_longint);
462        Value* result_value = iBuilder->CreateBitCast(adv_longint, mBitBlockType);
463        return result_value;
464    }
465    mCarryOutPack[posn] = strm;
466    Value * carry_in = getCarryPack(posn);
467    if (mCarryInfo->getWhileDepth() == 0) {
468        storeCarryPack(posn);
469    }
470    // Use a single whole-byte shift, if possible.
471    if (shift_amount % 8 == 0) {
472        return iBuilder->mvmd_dslli(8, strm, carry_in, iBuilder->getBitBlockWidth()/8 - shift_amount/8);
473    }
474    else if (shift_amount < DSSLI_FIELDWIDTH) {
475        Value * ahead = iBuilder->mvmd_dslli(DSSLI_FIELDWIDTH, strm, carry_in, iBuilder->getBitBlockWidth()/DSSLI_FIELDWIDTH - 1);
476        return iBuilder->simd_or(iBuilder->simd_srli(DSSLI_FIELDWIDTH, ahead, DSSLI_FIELDWIDTH-shift_amount), iBuilder->simd_slli(DSSLI_FIELDWIDTH, strm, shift_amount));
477    }
478    Value* advanceq_longint = iBuilder->CreateBitCast(carry_in, iBuilder->getIntNTy(mBITBLOCK_WIDTH));
479    Value* strm_longint = iBuilder->CreateBitCast(strm, iBuilder->getIntNTy(mBITBLOCK_WIDTH));
480    Value* adv_longint = iBuilder->CreateOr(iBuilder->CreateShl(strm_longint, shift_amount), iBuilder->CreateLShr(advanceq_longint, mBITBLOCK_WIDTH - shift_amount), "advance");
481    return iBuilder->CreateBitCast(adv_longint, mBitBlockType);
482}
483   
484
485/*  currently defined in carry_data.h
486 
487 static unsigned power2ceil (unsigned v) {
488 unsigned ceil = 1;
489 while (ceil < v) ceil *= 2;
490 return ceil;
491 }
492 
493 unsigned longAdvanceEntries(unsigned shift_amount) const {
494 return (shift_amount + mBITBLOCK_WIDTH - 1)/mBITBLOCK_WIDTH;
495 }
496 
497 unsigned longAdvanceBufferSize(unsigned shift_amount)  const {
498 return power2ceil(longAdvanceEntries(shift_amount));
499 }
500 */
501
502   
503Value * CarryManager::longAdvanceCarryInCarryOut(int localIndex, unsigned shift_amount, Value * carry_out) {
504    unsigned carryDataIndex = longAdvanceBitBlockPosition(localIndex);
505    Value * advBaseIndex = iBuilder->getInt64(carryDataIndex);
506    if (shift_amount <= mBITBLOCK_WIDTH) {
507        // special case using a single buffer entry and the carry_out value.
508        Value * advanceDataPtr = iBuilder->CreateGEP(mCarryBitBlockPtr, advBaseIndex);
509        Value * carry_block0 = iBuilder->CreateAlignedLoad(advanceDataPtr, mBITBLOCK_WIDTH/8);
510        iBuilder->CreateAlignedStore(carry_out, advanceDataPtr, mBITBLOCK_WIDTH/8);
511        /* Very special case - no combine */
512        if (shift_amount == mBITBLOCK_WIDTH) return carry_block0;
513        Value* block0_shr = iBuilder->CreateLShr(iBuilder->CreateBitCast(carry_block0, iBuilder->getIntNTy(mBITBLOCK_WIDTH)), mBITBLOCK_WIDTH - shift_amount);
514        Value* block1_shl = iBuilder->CreateShl(iBuilder->CreateBitCast(carry_out, iBuilder->getIntNTy(mBITBLOCK_WIDTH)), shift_amount);
515        return iBuilder->CreateBitCast(iBuilder->CreateOr(block1_shl, block0_shr), mBitBlockType);
516    }
517    // We need a buffer of at least two elements for storing the advance data.
518    const unsigned block_shift = shift_amount % mBITBLOCK_WIDTH;
519    const unsigned advanceEntries = mCarryInfo->longAdvanceEntries(shift_amount);
520    const unsigned bufsize = mCarryInfo->longAdvanceBufferSize(shift_amount);
521    Value * indexMask = iBuilder->getInt64(bufsize - 1);  // A mask to implement circular buffer indexing
522    Value * loadIndex0 = iBuilder->CreateAdd(iBuilder->CreateAnd(iBuilder->CreateSub(mBlockNo, iBuilder->getInt64(advanceEntries)), indexMask), advBaseIndex);
523    Value * storeIndex = iBuilder->CreateAdd(iBuilder->CreateAnd(mBlockNo, indexMask), advBaseIndex);
524    Value * carry_block0 = iBuilder->CreateAlignedLoad(iBuilder->CreateGEP(mCarryBitBlockPtr, loadIndex0), mBITBLOCK_WIDTH/8);
525    // If the long advance is an exact multiple of mBITBLOCK_WIDTH, we simply return the oldest
526    // block in the long advance carry data area. 
527    if (block_shift == 0) {
528        iBuilder->CreateAlignedStore(carry_out, iBuilder->CreateGEP(mCarryBitBlockPtr, storeIndex), mBITBLOCK_WIDTH/8);
529        return carry_block0;
530    }
531    // Otherwise we need to combine data from the two oldest blocks.
532    Value * loadIndex1 = iBuilder->CreateAdd(iBuilder->CreateAnd(iBuilder->CreateSub(mBlockNo, iBuilder->getInt64(advanceEntries-1)), indexMask), advBaseIndex);
533    Value * carry_block1 = iBuilder->CreateAlignedLoad(iBuilder->CreateGEP(mCarryBitBlockPtr, loadIndex1), mBITBLOCK_WIDTH/8);
534    Value* block0_shr = iBuilder->CreateLShr(iBuilder->CreateBitCast(carry_block0, iBuilder->getIntNTy(mBITBLOCK_WIDTH)), mBITBLOCK_WIDTH - block_shift);
535    Value* block1_shl = iBuilder->CreateShl(iBuilder->CreateBitCast(carry_block1, iBuilder->getIntNTy(mBITBLOCK_WIDTH)), block_shift);
536    iBuilder->CreateAlignedStore(carry_out, iBuilder->CreateGEP(mCarryBitBlockPtr, storeIndex), mBITBLOCK_WIDTH/8);
537    return iBuilder->CreateBitCast(iBuilder->CreateOr(block1_shl, block0_shr), mBitBlockType);
538}
539   
540
541/* Methods for getting and setting carry summary values */
542   
543bool CarryManager::blockHasCarries(){
544    return mCarryInfo->blockHasCarries();
545} 
546
547
548Value * CarryManager::generateBitBlockOrSummaryTest(Value * bitblock) {
549    Value * test_expr = bitblock;
550    if (mCarryInfo->blockHasCarries()) {
551        Value * summary_pack = getCarryPack(summaryPackIndex());
552        if (mITEMS_PER_PACK > 1) {// #ifdef PACKING
553            Value * summary_bits = maskSelectBitRange(summary_pack, summaryPosition() % mPACK_SIZE, summaryBits());
554            test_expr = iBuilder->simd_or(test_expr, iBuilder->CreateZExt(summary_bits, iBuilder->getIntNTy(mBITBLOCK_WIDTH)));
555        }
556        else {
557            test_expr = iBuilder->simd_or(test_expr, summary_pack);
558        }
559    }
560    return iBuilder->bitblock_any(test_expr);
561}
562
563void CarryManager::initializeCarryDataAtIfEntry() {
564    if (blockHasCarries()) {
565        if (mCarryOutPack[scopeBasePack()] == nullptr) {
566            mCarryInfo->ifEntryPack = Constant::getNullValue(mCarryPackType);
567        }
568        else {
569            mCarryInfo->ifEntryPack = mCarryOutPack[scopeBasePack()];
570        }
571    }
572}
573   
574void CarryManager::buildCarryDataPhisAfterIfBody(BasicBlock * ifEntryBlock, BasicBlock * ifBodyFinalBlock) {
575    if (mCarryInfo->getWhileDepth() > 0) {
576        // We need to phi out everything for the while carry accumulation process.
577        const unsigned scopeCarryPacks = mCarryInfo->getScopeCarryPackCount();
578        const unsigned currentScopeBase = scopeBasePack();
579        for (unsigned index = currentScopeBase; index < currentScopeBase + scopeCarryPacks; ++index) {
580            PHINode * phi_out = iBuilder->CreatePHI(mCarryPackType, 2);
581            phi_out->addIncoming(Constant::getNullValue(mCarryPackType),ifEntryBlock);
582            phi_out->addIncoming(mCarryOutPack[index], ifBodyFinalBlock);
583            mCarryOutPack[index] = phi_out;
584        }
585        return;
586    }
587    unsigned const ifScopeCarrySize = mCarryInfo->scopeCarryDataSize;
588    if (ifScopeCarrySize == 0) {
589        // No carry data, therefore no phi nodes.
590        return;
591    }
592    if (mITEMS_PER_PACK > 1) {// #ifdef PACKING
593        if (ifScopeCarrySize <= mPACK_SIZE) {
594            unsigned const ifPackIndex = scopeBasePack();
595            PHINode * ifPack_phi = iBuilder->CreatePHI(mCarryPackType, 2, "ifPack");
596            ifPack_phi->addIncoming(mCarryInfo->ifEntryPack, ifEntryBlock);
597            ifPack_phi->addIncoming(mCarryOutPack[ifPackIndex], ifBodyFinalBlock);
598            mCarryOutPack[ifPackIndex] = ifPack_phi;
599            return;
600        }
601    }
602    if (mCarryInfo->getIfDepth() > 1) {
603        // Our parent block is also an if.  It needs access to our summary to compute
604        // its own summary.
605        const unsigned summaryIndex = summaryPackIndex();
606        PHINode * summary_phi = iBuilder->CreatePHI(mCarryPackType, 2, "summary");
607        summary_phi->addIncoming(Constant::getNullValue(mCarryPackType), ifEntryBlock);
608        summary_phi->addIncoming(mCarryOutPack[summaryIndex], ifBodyFinalBlock);
609        mCarryOutPack[summaryIndex] = summary_phi;
610    }
611}
612   
613void CarryManager::addSummaryPhiIfNeeded(BasicBlock * ifEntryBlock, BasicBlock * ifBodyFinalBlock) {
614    if ((mCarryInfo->getIfDepth() <= 1) || !mCarryInfo->blockHasCarries()){
615        // For ifDepth == 1, the parent does not need a summary as it is not itself within an if.
616        // Therefore, it doesn't need access to this block's summary in building its own.
617        return;
618    }
619    const unsigned carrySummaryIndex = summaryPackIndex();
620    PHINode * summary_phi = iBuilder->CreatePHI(mCarryPackType, 2, "summary");
621    summary_phi->addIncoming(Constant::getNullValue(mCarryPackType), ifEntryBlock);
622    summary_phi->addIncoming(mCarryOutPack[carrySummaryIndex], ifBodyFinalBlock);
623    mCarryOutPack[carrySummaryIndex] = summary_phi;
624}
625   
626void CarryManager::generateCarryOutSummaryCodeIfNeeded() {
627   
628    if (!mCarryInfo->explicitSummaryRequired()) {
629        // An explicit summary may not be required, if there is a single carry
630        // operation within the block, or the carries are packed and all carry
631        // bits fit within a single pack.
632        return;
633    }
634   
635    const unsigned carrySummaryIndex = summaryPackIndex();
636   
637    Value * carry_summary = Constant::getNullValue(mCarryPackType);
638    if (mCarryInfo->blockHasLongAdvances()) { // Force if entry
639        carry_summary = Constant::getAllOnesValue(mCarryPackType);
640    }
641    else {
642        unsigned localCarryIndex = localBasePack();
643        unsigned localCarryPacks = mCarryInfo->getLocalCarryPackCount();
644        if (localCarryPacks > 0) {
645            carry_summary = mCarryOutPack[localCarryIndex];
646            for (unsigned i = 1; i < localCarryPacks; i++) {
647                carry_summary = iBuilder->CreateOr(carry_summary, mCarryOutPack[localCarryIndex+i]);
648            }
649        }
650        for (Statement * stmt : *mCurrentScope) {
651            if (If * innerIf = dyn_cast<If>(stmt)) {
652                PabloBlock * inner_blk = innerIf->getBody();
653                enterScope(inner_blk);
654                if (blockHasCarries()) {
655                  carry_summary = iBuilder->CreateOr(carry_summary, mCarryOutPack[summaryPackIndex()]);
656                }
657                leaveScope();
658            }
659            else if (While * innerWhile = dyn_cast<While>(stmt)) {
660                PabloBlock * inner_blk = innerWhile->getBody();
661                enterScope(inner_blk);
662                if (blockHasCarries()) {
663                    carry_summary = iBuilder->CreateOr(carry_summary, mCarryOutPack[summaryPackIndex()]);
664                }
665                leaveScope();
666            }
667        }
668    }
669    // Calculation of the carry out summary is complete.   Store it and make it
670    // available in case it must included by parent blocks.
671    mCarryOutPack[carrySummaryIndex] = carry_summary;
672    storeCarryPack(carrySummaryIndex);
673}
674
675void CarryManager::ensureCarriesLoadedRecursive() {
676    const unsigned scopeCarryPacks = mCarryInfo->getScopeCarryPackCount();
677    const unsigned currentScopeBase = scopeBasePack();
678    if (mCarryInfo->getWhileDepth() == 1) {
679        for (auto i = currentScopeBase; i < currentScopeBase + scopeCarryPacks; ++i) {
680            getCarryPack(i);
681        }
682    }
683}
684
685
686void CarryManager::initializeCarryDataPhisAtWhileEntry(BasicBlock * whileEntryBlock) {
687    const unsigned scopeCarryPacks = mCarryInfo->getScopeCarryPackCount();
688    mCarryOutAccumPhis.resize(scopeCarryPacks);
689#ifdef SET_WHILE_CARRY_IN_TO_ZERO_AFTER_FIRST_ITERATION
690    const unsigned currentScopeBase = scopeBasePack();
691    mCarryInPhis.resize(scopeCarryPacks);
692#endif
693    for (unsigned index = 0; index < scopeCarryPacks; ++index) {
694#ifdef SET_WHILE_CARRY_IN_TO_ZERO_AFTER_FIRST_ITERATION
695        PHINode * phi_in = iBuilder->CreatePHI(mCarryPackType, 2);
696        phi_in->addIncoming(mCarryInPack[currentScopeBase+index], whileEntryBlock);
697        mCarryInPhis[index] = phi_in;
698#endif
699        PHINode * phi_out = iBuilder->CreatePHI(mCarryPackType, 2);
700        phi_out->addIncoming(Constant::getNullValue(mCarryPackType), whileEntryBlock);
701        mCarryOutAccumPhis[index] = phi_out;
702    }
703}
704
705
706void CarryManager::extendCarryDataPhisAtWhileBodyFinalBlock(BasicBlock * whileBodyFinalBlock) {
707    const unsigned scopeCarryPacks = mCarryInfo->getScopeCarryPackCount();
708    const unsigned currentScopeBase = scopeBasePack();
709    for (unsigned index = 0; index < scopeCarryPacks; ++index) {
710#ifdef SET_WHILE_CARRY_IN_TO_ZERO_AFTER_FIRST_ITERATION
711        mCarryInPhis[index]->addIncoming(Constant::getNullValue(mCarryPackType), whileBodyFinalBlock);
712#endif
713        PHINode * phi = mCarryOutAccumPhis[index];
714        Value * carryOut = iBuilder->CreateOr(phi, mCarryOutPack[currentScopeBase+index]);
715        phi->addIncoming(carryOut, whileBodyFinalBlock);
716        mCarryOutPack[currentScopeBase+index] = carryOut;
717    }
718}
719
720void CarryManager::ensureCarriesStoredRecursive() {
721    const unsigned scopeCarryPacks = mCarryInfo->getScopeCarryPackCount();
722    const unsigned currentScopeBase = scopeBasePack();
723    if (mCarryInfo->getWhileDepth() == 1) {
724        for (auto i = currentScopeBase; i < currentScopeBase + scopeCarryPacks; ++i) {
725            storeCarryPack(i);
726        }
727    }
728}
729
730/* Store all the full carry packs generated locally in this scope or the
731   single full pack for this scope*/
732void CarryManager::ensureCarriesStoredLocal() {
733    if (mITEMS_PER_PACK > 1) {// #ifdef PACKING
734        const unsigned scopeCarryPacks = mCarryInfo->getScopeCarryPackCount();
735        if ((scopeCarryPacks > 0) && ((mCurrentFrameIndex % mPACK_SIZE) == 0)) {
736            // We have carry data and we are not in the middle of a pack.
737            // Write out all local packs.
738            auto localCarryIndex = localBasePack();
739            auto localCarryPacks = mCarryInfo->getLocalCarryPackCount();
740            for (auto i = localCarryIndex; i < localCarryIndex + localCarryPacks; i++) {
741                storeCarryPack(i);
742            }
743            if ((localCarryPacks == 0) && (scopeCarryPacks == 1) && (mCarryInfo->nested.entries > 1)) {
744                storeCarryPack(localCarryIndex);
745            }
746        }
747    }
748}
749
750Value * CarryManager::popCount(Value * to_count, unsigned globalIdx) {
751    Value * countPtr = iBuilder->CreateGEP(mPopcountBasePtr, iBuilder->getInt64(globalIdx));
752    Value * countSoFar = iBuilder->CreateAlignedLoad(countPtr, 8);
753    Value * fieldCounts = iBuilder->simd_popcount(64, to_count);
754    for (int i = 0; i < mBITBLOCK_WIDTH/64; i++) {
755        countSoFar = iBuilder->CreateAdd(countSoFar, iBuilder->mvmd_extract(64, fieldCounts, i));
756    }
757    iBuilder->CreateAlignedStore(countSoFar, countPtr, 8);
758    return iBuilder->bitCast(iBuilder->CreateZExt(countSoFar, iBuilder->getIntNTy(mBITBLOCK_WIDTH)));
759}
760
761CarryManager::~CarryManager() {
762    for (auto * cd : mCarryInfoVector) {
763        delete cd;
764    }
765}
766
767}
768
Note: See TracBrowser for help on using the repository browser.