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

Last change on this file since 4748 was 4733, checked in by cameron, 4 years ago

Mac OS X requires alignment 16

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