source: icGREP/icgrep-devel/icgrep/kernels/pdep_kernel.cpp @ 6055

Last change on this file since 6055 was 6055, checked in by cameron, 11 months ago

Various small fixes

File size: 19.5 KB
Line 
1/*
2 *  Copyright (c) 2017 International Characters.
3 *  This software is licensed to the public under the Open Software License 3.0.
4 */
5#include "pdep_kernel.h"
6#include <kernels/kernel_builder.h>
7#include <llvm/Support/raw_ostream.h>
8#include <toolchain/toolchain.h>
9#include <toolchain/driver.h>
10#include <toolchain/cpudriver.h>
11#include <IR_Gen/idisa_target.h>
12#include <llvm/IR/Intrinsics.h>
13#include <llvm/IR/Module.h>
14
15
16using namespace llvm;
17
18namespace kernel {
19
20PDEPkernel::PDEPkernel(const std::unique_ptr<kernel::KernelBuilder> & b, const unsigned swizzleFactor, std::string name)
21: MultiBlockKernel(std::move(name),
22// input stream sets
23{Binding{b->getStreamSetTy(), "marker", FixedRate(), Principal()},
24Binding{b->getStreamSetTy(swizzleFactor), "source", PopcountOf("marker"), BlockSize(b->getBitBlockWidth() / swizzleFactor) }},
25// output stream set
26{Binding{b->getStreamSetTy(swizzleFactor), "output", FixedRate(), BlockSize(b->getBitBlockWidth() / swizzleFactor)}},
27{}, {}, {})
28, mSwizzleFactor(swizzleFactor) {
29
30}
31
32void PDEPkernel::generateMultiBlockLogic(const std::unique_ptr<KernelBuilder> & b, Value * const numOfBlocks) {
33    BasicBlock * const entry = b->GetInsertBlock();
34    BasicBlock * const processBlock = b->CreateBasicBlock("processBlock");
35    BasicBlock * const finishedStrides = b->CreateBasicBlock("finishedStrides");
36    const auto pdepWidth = b->getBitBlockWidth() / mSwizzleFactor;
37    ConstantInt * const BLOCK_WIDTH = b->getSize(b->getBitBlockWidth());
38    ConstantInt * const PDEP_WIDTH = b->getSize(pdepWidth);
39
40    Constant * const ZERO = b->getSize(0);
41    Value * const sourceItemCount = b->getProcessedItemCount("source");
42
43    Value * const initialSourceOffset = b->CreateURem(sourceItemCount, BLOCK_WIDTH);
44    b->CreateBr(processBlock);
45
46    b->SetInsertPoint(processBlock);
47    PHINode * const strideIndex = b->CreatePHI(b->getSizeTy(), 2);
48    strideIndex->addIncoming(ZERO, entry);
49    PHINode * const bufferPhi = b->CreatePHI(b->getBitBlockType(), 2);
50    bufferPhi->addIncoming(Constant::getNullValue(b->getBitBlockType()), entry);
51    PHINode * const sourceOffsetPhi = b->CreatePHI(b->getSizeTy(), 2);
52    sourceOffsetPhi->addIncoming(initialSourceOffset, entry);
53    PHINode * const bufferSizePhi = b->CreatePHI(b->getSizeTy(), 2);
54    bufferSizePhi->addIncoming(ZERO, entry);
55
56    // Extract the values we will use in the main processing loop
57    Value * const markerStream = b->getInputStreamBlockPtr("marker", ZERO, strideIndex);
58    Value * const markerValue = b->CreateBlockAlignedLoad(markerStream);
59    Value * const selectors = b->fwCast(pdepWidth, markerValue);
60    Value * const numOfSelectors = b->simd_popcount(pdepWidth, selectors);
61
62    // For each element of the marker block
63    Value * bufferSize = bufferSizePhi;
64    Value * sourceOffset = sourceOffsetPhi;
65    Value * buffer = bufferPhi;
66    for (unsigned i = 0; i < mSwizzleFactor; i++) {
67
68        // How many bits will we deposit?
69        Value * const required = b->CreateExtractElement(numOfSelectors, b->getSize(i));
70
71        // Aggressively enqueue any additional bits
72        BasicBlock * const entry = b->GetInsertBlock();
73        BasicBlock * const enqueueBits = b->CreateBasicBlock();
74        b->CreateBr(enqueueBits);
75
76        b->SetInsertPoint(enqueueBits);
77        PHINode * const updatedBufferSize = b->CreatePHI(bufferSize->getType(), 2);
78        updatedBufferSize->addIncoming(bufferSize, entry);
79        PHINode * const updatedSourceOffset = b->CreatePHI(sourceOffset->getType(), 2);
80        updatedSourceOffset->addIncoming(sourceOffset, entry);
81        PHINode * const updatedBuffer = b->CreatePHI(buffer->getType(), 2);
82        updatedBuffer->addIncoming(buffer, entry);
83
84        // Calculate the block and swizzle index of the current swizzle row
85        Value * const blockOffset = b->CreateUDiv(updatedSourceOffset, BLOCK_WIDTH);
86        Value * const swizzleIndex = b->CreateUDiv(b->CreateURem(updatedSourceOffset, BLOCK_WIDTH), PDEP_WIDTH);
87        Value * const swizzle = b->CreateBlockAlignedLoad(b->getInputStreamBlockPtr("source", swizzleIndex, blockOffset));
88        Value * const swizzleOffset = b->CreateURem(updatedSourceOffset, PDEP_WIDTH);
89
90        // Shift the swizzle to the right to clear off any used bits ...
91        Value * const swizzleShift = b->simd_fill(pdepWidth, swizzleOffset);
92        Value * const unreadBits = b->CreateLShr(swizzle, swizzleShift);
93
94        // ... then to the left to align the bits with the buffer and combine them.
95        Value * const bufferShift = b->simd_fill(pdepWidth, updatedBufferSize);
96        Value * const pendingBits = b->CreateShl(unreadBits, bufferShift);
97
98        buffer = b->CreateOr(updatedBuffer, pendingBits);
99        updatedBuffer->addIncoming(buffer, enqueueBits);
100
101        // Update the buffer size with the number of bits we have actually enqueued
102        Value * const maxBufferSize = b->CreateAdd(b->CreateSub(PDEP_WIDTH, swizzleOffset), updatedBufferSize);
103        bufferSize = b->CreateUMin(maxBufferSize, PDEP_WIDTH);
104        updatedBufferSize->addIncoming(bufferSize, enqueueBits);
105
106        // ... and increment the source offset by the number we actually inserted
107        Value * const inserted = b->CreateSub(bufferSize, updatedBufferSize);
108        sourceOffset = b->CreateAdd(updatedSourceOffset, inserted);
109        updatedSourceOffset->addIncoming(sourceOffset, enqueueBits);
110
111        // INVESTIGATE: we can branch at most once here. I'm not sure whether the potential
112        // branch misprediction is better or worse than always filling from two swizzles to
113        // ensure that we have enough bits to deposit.
114        BasicBlock * const depositBits = b->CreateBasicBlock();
115        b->CreateUnlikelyCondBr(b->CreateICmpULT(bufferSize, required), enqueueBits, depositBits);
116
117        b->SetInsertPoint(depositBits);
118
119        // Apply PDEP to each element of the combined swizzle using the current PDEP mask
120        Value * const mask = b->CreateExtractElement(selectors, i);
121        Value* result = b->simd_pdep(pdepWidth, buffer, b->simd_fill(pdepWidth, mask));
122
123        // Store the result
124        Value * const outputStreamPtr = b->getOutputStreamBlockPtr("output", b->getSize(i), strideIndex);
125        b->CreateBlockAlignedStore(result, outputStreamPtr);
126
127        // Shift away any used bits from the buffer and decrement our buffer size by the number we used
128        Value * const usedShift = b->simd_fill(pdepWidth, required);
129        buffer = b->CreateLShr(buffer, usedShift);
130        bufferSize = b->CreateSub(bufferSize, required);
131    }
132
133    BasicBlock * const finishedBlock = b->GetInsertBlock();
134    sourceOffsetPhi->addIncoming(sourceOffset, finishedBlock);
135    bufferSizePhi->addIncoming(bufferSize, finishedBlock);
136    bufferPhi->addIncoming(buffer, finishedBlock);
137    Value * const nextStrideIndex = b->CreateAdd(strideIndex, b->getSize(1));
138    strideIndex->addIncoming(nextStrideIndex, finishedBlock);
139    b->CreateLikelyCondBr(b->CreateICmpNE(nextStrideIndex, numOfBlocks), processBlock, finishedStrides);
140
141    b->SetInsertPoint(finishedStrides);
142}
143   
144StreamExpandKernel::StreamExpandKernel(const std::unique_ptr<kernel::KernelBuilder> & kb, const unsigned fieldWidth, const unsigned streamCount)
145: MultiBlockKernel("streamExpand" + std::to_string(fieldWidth) + "_" + std::to_string(streamCount),
146                   {Binding{kb->getStreamSetTy(), "marker", FixedRate(), Principal()},
147                       Binding{kb->getStreamSetTy(streamCount), "source", PopcountOf("marker")}},
148                   {Binding{kb->getStreamSetTy(streamCount), "output", FixedRate()}},
149                   {}, {}, {})
150, mFieldWidth(fieldWidth)
151, mStreamCount(streamCount) {
152    for (unsigned i = 0; i < streamCount; i++) {
153        addScalar(kb->getBitBlockType(), "pendingSourceBlock_" + std::to_string(i));
154    }
155}
156
157void StreamExpandKernel::generateMultiBlockLogic(const std::unique_ptr<KernelBuilder> & b, llvm::Value * const numOfBlocks) {
158    const unsigned fw = mFieldWidth;
159    Type * fwTy = b->getIntNTy(fw);
160    Type * sizeTy = b->getSizeTy();
161    const unsigned numFields = b->getBitBlockWidth()/fw;
162   
163    Constant * const ZERO = b->getSize(0);
164    Constant * bwConst = ConstantInt::get(sizeTy, b->getBitBlockWidth());
165    Constant * bw_sub1Const = ConstantInt::get(sizeTy, b->getBitBlockWidth() -1);
166    Constant * fwConst = ConstantInt::get(sizeTy, fw);
167    Constant * fw_sub1Const = ConstantInt::get(sizeTy, fw-1);
168    Constant * fwSplat = ConstantVector::getSplat(numFields, ConstantInt::get(fwTy, fw));
169    Constant * fw_sub1Splat = ConstantVector::getSplat(numFields, ConstantInt::get(fwTy, fw-1));
170   
171    BasicBlock * entry = b->GetInsertBlock();
172    BasicBlock * expandLoop = b->CreateBasicBlock("expandLoop");
173    BasicBlock * expansionDone = b->CreateBasicBlock("expansionDone");
174   
175    Value * processedSourceItems = b->getProcessedItemCount("source");
176    Value * sourceOffset = b->CreateURem(processedSourceItems, bwConst);
177   
178    std::vector<Value *> pendingData(mStreamCount);
179    for (unsigned i = 0; i < mStreamCount; i++) {
180        pendingData[i] = b->getScalarField("pendingSourceBlock_" + std::to_string(i));
181    }
182   
183    b->CreateBr(expandLoop);
184    // Main Loop
185    b->SetInsertPoint(expandLoop);
186    PHINode * blockNoPhi = b->CreatePHI(b->getSizeTy(), 2);
187    PHINode * pendingItemsPhi = b->CreatePHI(b->getSizeTy(), 2);
188    PHINode * pendingDataPhi[mStreamCount];
189    blockNoPhi->addIncoming(ZERO, entry);
190    pendingItemsPhi->addIncoming(sourceOffset, entry);
191    for (unsigned i = 0; i < mStreamCount; i++) {
192        pendingDataPhi[i] = b->CreatePHI(b->getBitBlockType(), 2);
193        pendingDataPhi[i]->addIncoming(pendingData[i], entry);
194    }
195    Value * deposit_mask = b->loadInputStreamBlock("marker", ZERO, blockNoPhi);
196    // The source stream may not be positioned at a block boundary.  Partial data
197    // has been saved in the kernel state, determine the next full block number
198    // for loading source streams.
199    Value * pendingBlockEnd = b->CreateAdd(pendingItemsPhi, bw_sub1Const);
200    Value * srcBlockNo = b->CreateUDiv(pendingBlockEnd, bwConst);
201   
202    // Calculate the field values and offsets we need for assembling a
203    // a full block of source bits.  Assembly will use the following operations.
204    // A = b->simd_srl(fw, b->mvmd_dsll(fw, source, pending, field_offset_lo), bit_offset);
205    // B = b->simd_sll(fw, b->mvmd_dsll(fw, source, pending, field_offset_hi), shift_fwd);
206    // all_source_bits = simd_or(A, B);
207    Value * pendingOffset = b->CreateURem(pendingBlockEnd, bwConst);
208    Value * field_offset_lo =  b->CreateUDiv(pendingOffset, fwConst);
209    Value * bit_offset = b->simd_fill(fw, b->CreateURem(pendingOffset, fwConst));
210   
211    // Carefully avoid a shift by the full fieldwith (which gives a poison value).
212    // field_offset_lo + 1 unless the bit_offset is 0, in which case it is just field_offset_lo.
213    Value * field_offset_hi =  b->CreateUDiv(b->CreateAdd(pendingOffset, fw_sub1Const), fwConst);
214    // fw - bit_offset, unless bit_offset is 0, in which case, the shift_fwd is 0.
215    Value * shift_fwd = b->CreateURem(b->CreateSub(fwSplat, bit_offset), fwSplat);
216   
217    // Once all source bits are assembled, they need to be distributed to the
218    // output fields in accord with the popcounts of the deposit mask fields.
219    // The bits for each output field will typically come from (at most) two
220    // source fields, with offsets.  Calculate the field numbers and offsets.
221   
222    Value * fieldPopCounts = b->simd_popcount(fw, deposit_mask);
223    // For each field determine the (partial) sum popcount of all fields prior to
224    // the current field.
225    Value * partialSum = fieldPopCounts;
226    for (unsigned i = 1; i < numFields; i *= 2) {
227        partialSum = b->simd_add(fw, partialSum, b->mvmd_slli(fw, partialSum, i));
228    }
229    Value * blockPopCount = b->CreateZExtOrTrunc(b->CreateExtractElement(partialSum, numFields-1), sizeTy);
230    partialSum = b->mvmd_slli(fw, partialSum, 1);
231   
232    Value * source_field_lo = b->CreateUDiv(partialSum, fwSplat);
233    Value * source_field_hi = b->CreateUDiv(b->CreateAdd(partialSum, fw_sub1Splat), fwSplat);
234    Value * source_shift_lo = b->CreateAnd(partialSum, fw_sub1Splat);  // parallel URem
235    Value * source_shift_hi = b->CreateAnd(b->CreateSub(fwSplat, source_shift_lo), fw_sub1Splat);
236   
237    // Now load and process source streams.
238    for (unsigned i = 0; i < mStreamCount; i++) {
239        Value * source = b->loadInputStreamBlock("source", b->getInt32(i), srcBlockNo);
240        Value * A = b->simd_srlv(fw, b->mvmd_dsll(fw, source, pendingDataPhi[i], field_offset_lo), bit_offset);
241        Value * B = b->simd_sllv(fw, b->mvmd_dsll(fw, source, pendingDataPhi[i], field_offset_hi), shift_fwd);
242        Value * full_source_block = b->simd_or(A, B);
243       
244        Value * C = b->simd_srlv(fw, b->mvmd_shuffle(fw, full_source_block, source_field_lo), source_shift_lo);
245        Value * D = b->simd_sllv(fw, b->mvmd_shuffle(fw, full_source_block, source_field_hi), source_shift_hi);
246        Value * output = b->bitCast(b->simd_or(C, D));
247        b->storeOutputStreamBlock("output", b->getInt32(i), blockNoPhi, output);
248        pendingDataPhi[i]->addIncoming(source, expandLoop);
249    }
250    //
251    // Update loop control Phis for the next iteration.
252    //
253    Value * nextBlk = b->CreateAdd(blockNoPhi, b->getSize(1));
254    blockNoPhi->addIncoming(nextBlk, expandLoop);
255    Value * newPending = b->CreateAdd(pendingItemsPhi, blockPopCount);
256    pendingItemsPhi->addIncoming(newPending, expandLoop);
257    //
258    // Now continue the loop if there are more blocks to process.
259    Value * moreToDo = b->CreateICmpNE(nextBlk, numOfBlocks);
260    b->CreateCondBr(moreToDo, expandLoop, expansionDone);
261   
262    b->SetInsertPoint(expansionDone);
263    // Update kernel state.
264    for (unsigned i = 0; i < mStreamCount; i++) {
265        b->setScalarField("pendingSourceBlock_" + std::to_string(i), b->bitCast(pendingDataPhi[i]));
266    }
267}
268
269FieldDepositKernel::FieldDepositKernel(const std::unique_ptr<kernel::KernelBuilder> & kb, const unsigned fieldWidth, const unsigned streamCount)
270: MultiBlockKernel("FieldDeposit" + std::to_string(fieldWidth) + "_" + std::to_string(streamCount),
271                   {Binding{kb->getStreamSetTy(), "depositMask"}, Binding{kb->getStreamSetTy(streamCount), "inputStreamSet"}},
272                   {Binding{kb->getStreamSetTy(streamCount), "outputStreamSet"}},
273                   {}, {}, {})
274, mFieldWidth(fieldWidth)
275, mStreamCount(streamCount) {
276}
277   
278void FieldDepositKernel::generateMultiBlockLogic(const std::unique_ptr<KernelBuilder> & kb, llvm::Value * const numOfBlocks) {
279    BasicBlock * entry = kb->GetInsertBlock();
280    BasicBlock * processBlock = kb->CreateBasicBlock("processBlock");
281    BasicBlock * done = kb->CreateBasicBlock("done");
282    Constant * const ZERO = kb->getSize(0);
283    kb->CreateBr(processBlock);
284    kb->SetInsertPoint(processBlock);
285    PHINode * blockOffsetPhi = kb->CreatePHI(kb->getSizeTy(), 2);
286    blockOffsetPhi->addIncoming(ZERO, entry);
287    Value * depositMask = kb->loadInputStreamBlock("depositMask", ZERO, blockOffsetPhi);
288    for (unsigned j = 0; j < mStreamCount; ++j) {
289        Value * input = kb->loadInputStreamBlock("inputStreamSet", kb->getInt32(j), blockOffsetPhi);
290        Value * output = kb->simd_pdep(mFieldWidth, input, depositMask);
291        kb->storeOutputStreamBlock("outputStreamSet", kb->getInt32(j), blockOffsetPhi, output);
292    }
293    Value * nextBlk = kb->CreateAdd(blockOffsetPhi, kb->getSize(1));
294    blockOffsetPhi->addIncoming(nextBlk, processBlock);
295    Value * moreToDo = kb->CreateICmpNE(nextBlk, numOfBlocks);
296    kb->CreateCondBr(moreToDo, processBlock, done);
297    kb->SetInsertPoint(done);
298}
299
300PDEPFieldDepositKernel::PDEPFieldDepositKernel(const std::unique_ptr<kernel::KernelBuilder> & kb, const unsigned fieldWidth, const unsigned streamCount)
301: MultiBlockKernel("PDEPFieldDeposit" + std::to_string(fieldWidth) + "_" + std::to_string(streamCount),
302                   {Binding{kb->getStreamSetTy(), "depositMask"}, Binding{kb->getStreamSetTy(streamCount), "inputStreamSet"}},
303                   {Binding{kb->getStreamSetTy(streamCount), "outputStreamSet"}},
304                   {}, {}, {})
305, mPDEPWidth(fieldWidth)
306, mStreamCount(streamCount) {
307    if ((fieldWidth != 32) && (fieldWidth != 64)) llvm::report_fatal_error("Unsupported PDEP width for PDEPFieldCompressKernel");
308}
309
310void PDEPFieldDepositKernel::generateMultiBlockLogic(const std::unique_ptr<KernelBuilder> & kb, llvm::Value * const numOfBlocks) {
311    Type * fieldTy = kb->getIntNTy(mPDEPWidth);
312    Type * fieldPtrTy = PointerType::get(fieldTy, 0);
313    Constant * PDEP_func = nullptr;
314    if (mPDEPWidth == 64) {
315        PDEP_func = Intrinsic::getDeclaration(kb->getModule(), Intrinsic::x86_bmi_pdep_64);
316    } else if (mPDEPWidth == 32) {
317        PDEP_func = Intrinsic::getDeclaration(kb->getModule(), Intrinsic::x86_bmi_pdep_32);
318    }
319    BasicBlock * entry = kb->GetInsertBlock();
320    BasicBlock * processBlock = kb->CreateBasicBlock("processBlock");
321    BasicBlock * done = kb->CreateBasicBlock("done");
322    Constant * const ZERO = kb->getSize(0);
323    const unsigned fieldsPerBlock = kb->getBitBlockWidth()/mPDEPWidth;
324    kb->CreateBr(processBlock);
325    kb->SetInsertPoint(processBlock);
326    PHINode * blockOffsetPhi = kb->CreatePHI(kb->getSizeTy(), 2);
327    blockOffsetPhi->addIncoming(ZERO, entry);
328    std::vector<Value *> mask(fieldsPerBlock);
329    Value * extractionMaskPtr = kb->getInputStreamBlockPtr("depositMask", ZERO, blockOffsetPhi);
330    extractionMaskPtr = kb->CreatePointerCast(extractionMaskPtr, fieldPtrTy);
331    for (unsigned i = 0; i < fieldsPerBlock; i++) {
332        mask[i] = kb->CreateLoad(kb->CreateGEP(extractionMaskPtr, kb->getInt32(i)));
333    }
334    for (unsigned j = 0; j < mStreamCount; ++j) {
335        Value * inputPtr = kb->getInputStreamBlockPtr("inputStreamSet", kb->getInt32(j), blockOffsetPhi);
336        inputPtr = kb->CreatePointerCast(inputPtr, fieldPtrTy);
337        Value * outputPtr = kb->getOutputStreamBlockPtr("outputStreamSet", kb->getInt32(j), blockOffsetPhi);
338        outputPtr = kb->CreatePointerCast(outputPtr, fieldPtrTy);
339        for (unsigned i = 0; i < fieldsPerBlock; i++) {
340            Value * field = kb->CreateLoad(kb->CreateGEP(inputPtr, kb->getInt32(i)));
341            Value * compressed = kb->CreateCall(PDEP_func, {field, mask[i]});
342            kb->CreateStore(compressed, kb->CreateGEP(outputPtr, kb->getInt32(i)));
343        }
344    }
345    Value * nextBlk = kb->CreateAdd(blockOffsetPhi, kb->getSize(1));
346    blockOffsetPhi->addIncoming(nextBlk, processBlock);
347    Value * moreToDo = kb->CreateICmpNE(nextBlk, numOfBlocks);
348    kb->CreateCondBr(moreToDo, processBlock, done);
349    kb->SetInsertPoint(done);
350}
351
352void StreamDepositCompiler::makeCall(parabix::StreamSetBuffer * depositMask, parabix::StreamSetBuffer * inputs, parabix::StreamSetBuffer * outputs) {
353    if (mBufferBlocks == 0) {
354        llvm::report_fatal_error("StreamDepositCompiler needs a non-zero bufferBlocks parameter (for now).");
355    }
356    auto & iBuilder = mDriver.getBuilder();
357    unsigned N = IDISA::getNumOfStreams(ssType);
358    if (IDISA::getStreamFieldWidth(ssType) != 1) {
359        llvm::report_fatal_error("StreamDepositCompiler only compresses bit streams (for now)");
360    }
361    parabix::StreamSetBuffer * expandedStreams = mDriver.addBuffer<parabix::StaticBuffer>(iBuilder, iBuilder->getStreamSetTy(N), mBufferBlocks);
362    Kernel * streamK = mDriver.addKernelInstance<StreamExpandKernel>(iBuilder, mFieldWidth, N);
363    mDriver.makeKernelCall(streamK, {depositMask, inputs}, {expandedStreams});
364
365    Kernel * depositK = nullptr;
366    if (AVX2_available()) {
367        depositK = mDriver.addKernelInstance<PDEPFieldDepositKernel>(iBuilder, mFieldWidth, N);
368    } else {
369        depositK = mDriver.addKernelInstance<FieldDepositKernel>(iBuilder, mFieldWidth, N);
370    }
371    mDriver.makeKernelCall(depositK, {depositMask, expandedStreams}, {outputs});
372}
373
374}
Note: See TracBrowser for help on using the repository browser.