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

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

Clean ups for compilation with gcc 4.8

File size: 30.5 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 (unsigned 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)), BLOCK_SIZE-1);
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#if (BLOCK_SIZE == 128)
355    Value * carryq_value = getCarryOpCarryIn(localIndex);
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    setCarryOpCarryOut(localIndex, carry_out_strm);
366    return sum;
367#else
368    //BLOCK_SIZE == 256, there is no other implementation
369    Value * carryq_value = getCarryOpCarryIn(localIndex);
370    Value* carrygen = mBuilder->CreateAnd(e1, e2, "carrygen");
371    Value* carryprop = mBuilder->CreateOr(e1, e2, "carryprop");
372    Value * sum = iBuilder->simd_add(BLOCK_SIZE, iBuilder->simd_add(BLOCK_SIZE, e1, e2), carryq_value);
373    Value* carry_out_strm = mBuilder->CreateOr(carrygen, mBuilder->CreateAnd(carryprop, mBuilder->CreateNot(sum)));
374    setCarryOpCarryOut(localIndex, carry_out_strm);
375    return sum;
376#endif         
377}
378
379
380Value * CarryManager::advanceCarryInCarryOut(int localIndex, unsigned shift_amount, Value * strm) {
381    if (shift_amount == 1) {
382        return unitAdvanceCarryInCarryOut(localIndex, strm);
383    }
384    else if (shift_amount < LongAdvanceBase) {
385        return shortAdvanceCarryInCarryOut(localIndex, shift_amount, strm);
386    }
387    else {
388        return longAdvanceCarryInCarryOut(localIndex, shift_amount, strm);
389    }
390}
391
392Value * CarryManager::unitAdvanceCarryInCarryOut(int localIndex, Value * strm) {
393    unsigned posn = advance1Position(localIndex);
394    if (mITEMS_PER_PACK > 1) {// #ifdef PACKING
395        extractAndSaveCarryOutBits(strm, posn, 1);
396        Value* carry_longint = mBuilder->CreateZExt(getCarryInBits(posn, 1), mBuilder->getIntNTy(BLOCK_SIZE));
397        Value* strm_longint = mBuilder->CreateBitCast(strm, mBuilder->getIntNTy(BLOCK_SIZE));
398        Value* adv_longint = mBuilder->CreateOr(mBuilder->CreateShl(strm_longint, 1), carry_longint);
399        Value* result_value = mBuilder->CreateBitCast(adv_longint, mBitBlockType);
400        return result_value;
401    }
402    mCarryOutPack[posn] = strm;
403    Value * carry_in = getCarryPack(posn);
404    if (mCarryInfo->getWhileDepth() == 0) {
405        storeCarryPack(posn);
406    }
407    Value* result_value;
408   
409#if (BLOCK_SIZE == 128) && !defined(USE_LONG_INTEGER_SHIFT)
410    Value * ahead64 = iBuilder->mvmd_dslli(64, carry_in, strm, 1);
411    result_value = mBuilder->CreateOr(iBuilder->simd_srli(64, ahead64, 63), iBuilder->simd_slli(64, strm, 1));
412#else
413    Value* advanceq_longint = mBuilder->CreateBitCast(carry_in, mBuilder->getIntNTy(BLOCK_SIZE));
414    Value* strm_longint = mBuilder->CreateBitCast(strm, mBuilder->getIntNTy(BLOCK_SIZE));
415    Value* adv_longint = mBuilder->CreateOr(mBuilder->CreateShl(strm_longint, 1), mBuilder->CreateLShr(advanceq_longint, BLOCK_SIZE - 1), "advance");
416    result_value = mBuilder->CreateBitCast(adv_longint, mBitBlockType);
417   
418#endif
419    return result_value;
420}
421
422Value * CarryManager::shortAdvanceCarryInCarryOut(int localIndex, unsigned shift_amount, Value * strm) {
423    unsigned posn = shortAdvancePosition(localIndex);
424    if (mITEMS_PER_PACK > 1) {// #ifdef PACKING
425        extractAndSaveCarryOutBits(strm, posn, shift_amount);
426        //std::cerr << "shortAdvanceCarryInCarryOut: posn = " << posn << ", shift_amount = " << shift_amount << std::endl;
427        Value* carry_longint = mBuilder->CreateZExt(getCarryInBits(posn, shift_amount), mBuilder->getIntNTy(BLOCK_SIZE));
428        Value* strm_longint = mBuilder->CreateBitCast(strm, mBuilder->getIntNTy(BLOCK_SIZE));
429        Value* adv_longint = mBuilder->CreateOr(mBuilder->CreateShl(strm_longint, shift_amount), carry_longint);
430        Value* result_value = mBuilder->CreateBitCast(adv_longint, mBitBlockType);
431        return result_value;
432    }
433    mCarryOutPack[posn] = strm;
434    Value * carry_in = getCarryPack(posn);
435    if (mCarryInfo->getWhileDepth() == 0) {
436        storeCarryPack(posn);
437    }
438    Value* advanceq_longint = mBuilder->CreateBitCast(carry_in, mBuilder->getIntNTy(BLOCK_SIZE));
439    Value* strm_longint = mBuilder->CreateBitCast(strm, mBuilder->getIntNTy(BLOCK_SIZE));
440    Value* adv_longint = mBuilder->CreateOr(mBuilder->CreateShl(strm_longint, shift_amount), mBuilder->CreateLShr(advanceq_longint, BLOCK_SIZE - shift_amount), "advance");
441    return mBuilder->CreateBitCast(adv_longint, mBitBlockType);
442}
443   
444
445/*  currently defined in carry_data.h
446 
447 static unsigned power2ceil (unsigned v) {
448 unsigned ceil = 1;
449 while (ceil < v) ceil *= 2;
450 return ceil;
451 }
452 
453 unsigned longAdvanceEntries(unsigned shift_amount) const {
454 return (shift_amount + BLOCK_SIZE - 1)/BLOCK_SIZE;
455 }
456 
457 unsigned longAdvanceBufferSize(unsigned shift_amount)  const {
458 return power2ceil(longAdvanceEntries(shift_amount));
459 }
460 */
461
462   
463Value * CarryManager::longAdvanceCarryInCarryOut(int localIndex, unsigned shift_amount, Value * carry_out) {
464    unsigned carryDataIndex = longAdvanceBitBlockPosition(localIndex);
465    Value * advBaseIndex = mBuilder->getInt64(carryDataIndex);
466    if (shift_amount <= BLOCK_SIZE) {
467        // special case using a single buffer entry and the carry_out value.
468        Value * advanceDataPtr = mBuilder->CreateGEP(mCarryBitBlockPtr, advBaseIndex);
469        Value * carry_block0 = mBuilder->CreateAlignedLoad(advanceDataPtr, BLOCK_SIZE/8);
470        mBuilder->CreateAlignedStore(carry_out, advanceDataPtr, BLOCK_SIZE/8);
471        /* Very special case - no combine */
472        if (shift_amount == BLOCK_SIZE) return carry_block0;
473        Value* block0_shr = mBuilder->CreateLShr(mBuilder->CreateBitCast(carry_block0, mBuilder->getIntNTy(BLOCK_SIZE)), BLOCK_SIZE - shift_amount);
474        Value* block1_shl = mBuilder->CreateShl(mBuilder->CreateBitCast(carry_out, mBuilder->getIntNTy(BLOCK_SIZE)), shift_amount);
475        return mBuilder->CreateBitCast(mBuilder->CreateOr(block1_shl, block0_shr), mBitBlockType);
476    }
477    // We need a buffer of at least two elements for storing the advance data.
478    const unsigned block_shift = shift_amount % BLOCK_SIZE;
479    const unsigned advanceEntries = mCarryInfo->longAdvanceEntries(shift_amount);
480    const unsigned bufsize = mCarryInfo->longAdvanceBufferSize(shift_amount);
481    Value * indexMask = mBuilder->getInt64(bufsize - 1);  // A mask to implement circular buffer indexing
482    Value * loadIndex0 = mBuilder->CreateAdd(mBuilder->CreateAnd(mBuilder->CreateSub(mBlockNo, mBuilder->getInt64(advanceEntries)), indexMask), advBaseIndex);
483    Value * storeIndex = mBuilder->CreateAdd(mBuilder->CreateAnd(mBlockNo, indexMask), advBaseIndex);
484    Value * carry_block0 = mBuilder->CreateAlignedLoad(mBuilder->CreateGEP(mCarryBitBlockPtr, loadIndex0), BLOCK_SIZE/8);
485    // If the long advance is an exact multiple of BLOCK_SIZE, we simply return the oldest
486    // block in the long advance carry data area. 
487    if (block_shift == 0) {
488        mBuilder->CreateAlignedStore(carry_out, mBuilder->CreateGEP(mCarryBitBlockPtr, storeIndex), BLOCK_SIZE/8);
489        return carry_block0;
490    }
491    // Otherwise we need to combine data from the two oldest blocks.
492    Value * loadIndex1 = mBuilder->CreateAdd(mBuilder->CreateAnd(mBuilder->CreateSub(mBlockNo, mBuilder->getInt64(advanceEntries-1)), indexMask), advBaseIndex);
493    Value * carry_block1 = mBuilder->CreateAlignedLoad(mBuilder->CreateGEP(mCarryBitBlockPtr, loadIndex1), BLOCK_SIZE/8);
494    Value* block0_shr = mBuilder->CreateLShr(mBuilder->CreateBitCast(carry_block0, mBuilder->getIntNTy(BLOCK_SIZE)), BLOCK_SIZE - block_shift);
495    Value* block1_shl = mBuilder->CreateShl(mBuilder->CreateBitCast(carry_block1, mBuilder->getIntNTy(BLOCK_SIZE)), block_shift);
496    mBuilder->CreateAlignedStore(carry_out, mBuilder->CreateGEP(mCarryBitBlockPtr, storeIndex), BLOCK_SIZE/8);
497    return mBuilder->CreateBitCast(mBuilder->CreateOr(block1_shl, block0_shr), mBitBlockType);
498}
499   
500
501/* Methods for getting and setting carry summary values */
502   
503bool CarryManager::blockHasCarries(){
504    return mCarryInfo->blockHasCarries();
505} 
506
507
508Value * CarryManager::getCarrySummaryExpr() {
509    unsigned summary_index = summaryPackIndex();
510    if (mITEMS_PER_PACK > 1) {// #ifdef PACKING
511        Value * pack = getCarryPack(summary_index);
512        Value * summary_bits = maskSelectBitRange(pack, summaryPosition() % mPACK_SIZE, summaryBits());
513        return mBuilder->CreateBitCast(mBuilder->CreateZExt(summary_bits, mBuilder->getIntNTy(BLOCK_SIZE)), mBitBlockType);
514    }
515    else {
516        return getCarryPack(summary_index);
517    }
518}
519
520void CarryManager::initializeCarryDataAtIfEntry() {
521    if (blockHasCarries()) {
522        if (mCarryOutPack[scopeBasePack()] == nullptr) {
523            mCarryInfo->ifEntryPack = mZeroInitializer;
524        }
525        else {
526            mCarryInfo->ifEntryPack = mCarryOutPack[scopeBasePack()];
527        }
528    }
529}
530   
531void CarryManager::buildCarryDataPhisAfterIfBody(BasicBlock * ifEntryBlock, BasicBlock * ifBodyFinalBlock) {
532    unsigned const ifScopeCarrySize = mCarryInfo->scopeCarryDataSize;
533    if (ifScopeCarrySize == 0) {
534        // No carry data, therefore no phi nodes.
535        return;
536    }
537    if (mITEMS_PER_PACK > 1) {// #ifdef PACKING
538        if (ifScopeCarrySize <= mPACK_SIZE) {
539            unsigned const ifPackIndex = scopeBasePack();
540            PHINode * ifPack_phi = mBuilder->CreatePHI(mCarryPackType, 2, "ifPack");
541            ifPack_phi->addIncoming(mCarryInfo->ifEntryPack, ifEntryBlock);
542            ifPack_phi->addIncoming(mCarryOutPack[ifPackIndex], ifBodyFinalBlock);
543            mCarryOutPack[ifPackIndex] = ifPack_phi;
544            return;
545        }
546    }
547    if (mCarryInfo->getIfDepth() > 1) {
548        const unsigned summaryIndex = summaryPackIndex();
549        PHINode * summary_phi = mBuilder->CreatePHI(mCarryPackType, 2, "summary");
550        summary_phi->addIncoming(mZeroInitializer, ifEntryBlock);
551        summary_phi->addIncoming(mCarryOutPack[summaryIndex], ifBodyFinalBlock);
552        mCarryOutPack[summaryIndex] = summary_phi;
553    }
554}
555   
556void CarryManager::addSummaryPhiIfNeeded(BasicBlock * ifEntryBlock, BasicBlock * ifBodyFinalBlock) {
557    if ((mCarryInfo->getIfDepth() <= 1) || !mCarryInfo->blockHasCarries()){
558        // For ifDepth == 1, the parent does not need a summary as it is not itself within an if.
559        // Therefore, it doesn't need access to this block's summary in building its own.
560        return;
561    }
562    const unsigned carrySummaryIndex = summaryPackIndex();
563    PHINode * summary_phi = mBuilder->CreatePHI(mCarryPackType, 2, "summary");
564    summary_phi->addIncoming(mZeroInitializer, ifEntryBlock);
565    summary_phi->addIncoming(mCarryOutPack[carrySummaryIndex], ifBodyFinalBlock);
566    mCarryOutPack[carrySummaryIndex] = summary_phi;
567}
568   
569void CarryManager::generateCarryOutSummaryCodeIfNeeded() {
570   
571    if (!mCarryInfo->explicitSummaryRequired()) {
572        // An explicit summary may not be required, if there is a single carry
573        // operation within the block, or the carries are packed and all carry
574        // bits fit within a single pack.
575        return;
576    }
577   
578    const unsigned carrySummaryIndex = summaryPackIndex();
579   
580    Value * carry_summary = mZeroInitializer;
581    if (mCarryInfo->blockHasLongAdvances()) { // Force if entry
582        carry_summary = mOneInitializer;
583    }
584    else {
585        unsigned localCarryIndex = localBasePack();
586        unsigned localCarryPacks = mCarryInfo->getLocalCarryPackCount();
587        if (localCarryPacks > 0) {
588            carry_summary = mCarryOutPack[localCarryIndex];
589            for (unsigned i = 1; i < localCarryPacks; i++) {
590                carry_summary = mBuilder->CreateOr(carry_summary, mCarryOutPack[localCarryIndex+i]);
591            }
592        }
593        for (Statement * stmt : *mCurrentScope) {
594            if (If * innerIf = dyn_cast<If>(stmt)) {
595                PabloBlock * inner_blk = & innerIf->getBody();
596                enterScope(inner_blk);
597                if (blockHasCarries()) {
598                  carry_summary = mBuilder->CreateOr(carry_summary, mCarryOutPack[summaryPackIndex()]);
599                }
600                leaveScope();
601            }
602            else if (While * innerWhile = dyn_cast<While>(stmt)) {
603                PabloBlock * inner_blk = & innerWhile->getBody();
604                enterScope(inner_blk);
605                if (blockHasCarries()) {
606                    carry_summary = mBuilder->CreateOr(carry_summary, mCarryOutPack[summaryPackIndex()]);
607                }
608                leaveScope();
609            }
610        }
611    }
612    // Calculation of the carry out summary is complete.   Store it and make it
613    // available in case it must included by parent blocks.
614    mCarryOutPack[carrySummaryIndex] = carry_summary;
615    storeCarryPack(carrySummaryIndex);
616}
617
618void CarryManager::ensureCarriesLoadedRecursive() {
619    const unsigned scopeCarryPacks = mCarryInfo->getScopeCarryPackCount();
620    const unsigned currentScopeBase = scopeBasePack();
621    if (mCarryInfo->getWhileDepth() == 1) {
622        for (auto i = currentScopeBase; i < currentScopeBase + scopeCarryPacks; ++i) {
623            getCarryPack(i);
624        }
625    }
626}
627
628
629void CarryManager::initializeCarryDataPhisAtWhileEntry(BasicBlock * whileEntryBlock) {
630    const unsigned scopeCarryPacks = mCarryInfo->getScopeCarryPackCount();
631    mCarryOutAccumPhis.resize(scopeCarryPacks);
632#ifdef SET_WHILE_CARRY_IN_TO_ZERO_AFTER_FIRST_ITERATION
633    const unsigned currentScopeBase = scopeBasePack();
634    mCarryInPhis.resize(scopeCarryPacks);
635#endif
636    for (unsigned index = 0; index < scopeCarryPacks; ++index) {
637#ifdef SET_WHILE_CARRY_IN_TO_ZERO_AFTER_FIRST_ITERATION
638        PHINode * phi_in = mBuilder->CreatePHI(mCarryPackType, 2);
639        phi_in->addIncoming(mCarryInPack[currentScopeBase+index], whileEntryBlock);
640        mCarryInPhis[index] = phi_in;
641#endif
642        PHINode * phi_out = mBuilder->CreatePHI(mCarryPackType, 2);
643        phi_out->addIncoming(mZeroInitializer, whileEntryBlock);
644        mCarryOutAccumPhis[index] = phi_out;
645    }
646}
647
648
649void CarryManager::extendCarryDataPhisAtWhileBodyFinalBlock(BasicBlock * whileBodyFinalBlock) {
650    const unsigned scopeCarryPacks = mCarryInfo->getScopeCarryPackCount();
651    const unsigned currentScopeBase = scopeBasePack();
652    for (unsigned index = 0; index < scopeCarryPacks; ++index) {
653#ifdef SET_WHILE_CARRY_IN_TO_ZERO_AFTER_FIRST_ITERATION
654        mCarryInPhis[index]->addIncoming(mZeroInitializer, whileBodyFinalBlock);
655#endif
656        PHINode * phi = mCarryOutAccumPhis[index];
657        Value * carryOut = mBuilder->CreateOr(phi, mCarryOutPack[currentScopeBase+index]);
658        phi->addIncoming(carryOut, whileBodyFinalBlock);
659        mCarryOutPack[currentScopeBase+index] = carryOut;
660    }
661}
662
663void CarryManager::ensureCarriesStoredRecursive() {
664    const unsigned scopeCarryPacks = mCarryInfo->getScopeCarryPackCount();
665    const unsigned currentScopeBase = scopeBasePack();
666    if (mCarryInfo->getWhileDepth() == 1) {
667        for (auto i = currentScopeBase; i < currentScopeBase + scopeCarryPacks; ++i) {
668            storeCarryPack(i);
669        }
670    }
671}
672
673/* Store all the full carry packs generated locally in this scope or the
674   single full pack for this scope*/
675void CarryManager::ensureCarriesStoredLocal() {
676    if (mITEMS_PER_PACK > 1) {// #ifdef PACKING
677        const unsigned scopeCarryPacks = mCarryInfo->getScopeCarryPackCount();
678        if ((scopeCarryPacks > 0) && ((mCurrentFrameIndex % mPACK_SIZE) == 0)) {
679            // We have carry data and we are not in the middle of a pack.
680            // Write out all local packs.
681            auto localCarryIndex = localBasePack();
682            auto localCarryPacks = mCarryInfo->getLocalCarryPackCount();
683            for (auto i = localCarryIndex; i < localCarryIndex + localCarryPacks; i++) {
684                storeCarryPack(i);
685            }
686            if ((localCarryPacks == 0) && (scopeCarryPacks == 1) && (mCarryInfo->nested.entries > 1)) {
687                storeCarryPack(localCarryIndex);
688            }
689        }
690    }
691}
692
693Value * CarryManager::popCount(Value * to_count, unsigned globalIdx) {
694    Value * countPtr = mBuilder->CreateGEP(mPopcountBasePtr, mBuilder->getInt64(globalIdx));
695    Value * countSoFar = mBuilder->CreateAlignedLoad(countPtr, 8);
696    Value * fieldCounts = iBuilder->simd_popcount(64, to_count);
697    for (int i = 0; i < BLOCK_SIZE/64; i++) {
698        countSoFar = mBuilder->CreateAdd(countSoFar, iBuilder->mvmd_extract(64, fieldCounts, i));
699    }
700    mBuilder->CreateAlignedStore(countSoFar, countPtr, 8);
701    return mBuilder->CreateBitCast(mBuilder->CreateZExt(countSoFar, mBuilder->getIntNTy(BLOCK_SIZE)), mBitBlockType);
702}
703
704CarryManager::~CarryManager() {
705    for (auto * cd : mCarryInfoVector) {
706        delete cd;
707    }
708}
709
710}
711
Note: See TracBrowser for help on using the repository browser.