source: icGREP/icgrep-devel/icgrep/kernels/lz4/lz4_index_builder.cpp @ 5959

Last change on this file since 5959 was 5959, checked in by xwa163, 14 months ago
  1. Minor bug fixing for availableItemCount in SegmentOriented? lz4_index_builder
  2. Adjust the way to clear output buffer in lz4_index_builder to improve the performance
File size: 24.4 KB
Line 
1//
2// Created by wxy325 on 2018/3/16.
3//
4
5#include "lz4_index_builder.h"
6
7
8#include <kernels/kernel_builder.h>
9#include <iostream>
10#include <string>
11#include <llvm/Support/raw_ostream.h>
12#include <kernels/streamset.h>
13
14using namespace llvm;
15using namespace kernel;
16using namespace std;
17
18namespace kernel{
19
20    LZ4IndexBuilderKernel::LZ4IndexBuilderKernel(const std::unique_ptr<kernel::KernelBuilder> &iBuilder)
21    : SegmentOrientedKernel("LZ4IndexBuilderKernel",
22    // Inputs
23    {
24           Binding{iBuilder->getStreamSetTy(1, 8), "byteStream", BoundedRate(0, 1)},
25           Binding{iBuilder->getStreamSetTy(1, 1), "extender", RateEqualTo("byteStream")},
26
27           // block data
28           Binding{iBuilder->getStreamSetTy(1, 1), "isCompressed", BoundedRate(0, 1),
29                   AlwaysConsume()},
30           Binding{iBuilder->getStreamSetTy(1, 64), "blockStart", BoundedRate(0, 1),
31                   AlwaysConsume()},
32           Binding{iBuilder->getStreamSetTy(1, 64), "blockEnd", BoundedRate(0, 1),
33                   AlwaysConsume()}
34
35    },
36    //Outputs
37    {
38           // Uncompressed_data
39           Binding{iBuilder->getStreamSetTy(1, 64), "uncompressedStartPos",
40                   BoundedRate(0, 1)},
41           Binding{iBuilder->getStreamSetTy(1, 64), "uncompressedLength",
42                   BoundedRate(0, 1)},
43           Binding{iBuilder->getStreamSetTy(1, 64), "uncompressedOutputPos",
44                   BoundedRate(0, 1)},
45
46           Binding{iBuilder->getStreamSetTy(1, 1), "deletionMarker", BoundedRate(0, 1)},
47           Binding{iBuilder->getStreamSetTy(1, 64), "m0Start", BoundedRate(0, 1)},
48           Binding{iBuilder->getStreamSetTy(1, 64), "m0End", BoundedRate(0, 1)},
49           Binding{iBuilder->getStreamSetTy(1, 64), "matchOffset", BoundedRate(0, 1)},
50           Binding{iBuilder->getStreamSetTy(1, 1), "M0Marker", BoundedRate(0, 1)}
51    },
52    //Arguments
53    {
54           Binding{iBuilder->getSizeTy(), "fileSize"}
55    },
56    {},
57    //Internal states:
58    {
59           Binding{iBuilder->getSizeTy(), "blockDataIndex"},
60           Binding{iBuilder->getInt64Ty(), "m0OutputPos"}
61    }) {
62        this->setStride(4 * 1024 * 1024);
63        addAttribute(MustExplicitlyTerminate());
64    }
65
66    void LZ4IndexBuilderKernel::generateDoSegmentMethod(const std::unique_ptr<KernelBuilder> &iBuilder) {
67
68        BasicBlock* exitBlock = iBuilder->CreateBasicBlock("exitBlock");
69        BasicBlock* blockEndConBlock = iBuilder->CreateBasicBlock("blockEndConBlock");
70
71        Value * blockDataIndex = iBuilder->getScalarField("blockDataIndex");
72
73        // In MultiblockKernel, availableItemCount + processedItemCount == producedItemCount from previous kernel
74        // While in SegmentOrigentedKernel, availableItemCount == producedItemCount from previous kernel
75        Value * totalNumber = iBuilder->getAvailableItemCount("blockEnd");
76        Value * totalExtender = iBuilder->getAvailableItemCount("extender");
77
78        Value * blockEnd = this->generateLoadInt64NumberInput(iBuilder, "blockEnd", blockDataIndex);
79
80        iBuilder->CreateCondBr(iBuilder->CreateICmpULT(blockDataIndex, totalNumber), blockEndConBlock, exitBlock);
81
82        iBuilder->SetInsertPoint(blockEndConBlock);
83        Value * blockStart = this->generateLoadInt64NumberInput(iBuilder, "blockStart", blockDataIndex);
84        BasicBlock * processBlock = iBuilder->CreateBasicBlock("processBlock");
85        iBuilder->CreateCondBr(iBuilder->CreateICmpULE(blockEnd, totalExtender), processBlock, exitBlock);
86
87        iBuilder->SetInsertPoint(processBlock);
88
89        //TODO handle uncompressed block
90
91        this->generateProcessCompressedBlock(iBuilder, blockStart, blockEnd);
92
93        Value * newBlockDataIndex = iBuilder->CreateAdd(blockDataIndex, iBuilder->getInt64(1));
94        iBuilder->setScalarField("blockDataIndex", newBlockDataIndex);
95        iBuilder->setProcessedItemCount("blockEnd", newBlockDataIndex);
96        iBuilder->setProcessedItemCount("blockStart", newBlockDataIndex);
97        iBuilder->setProcessedItemCount("isCompressed", newBlockDataIndex);
98
99        iBuilder->setProcessedItemCount("byteStream", blockEnd);
100        iBuilder->CreateBr(exitBlock);
101
102        iBuilder->SetInsertPoint(exitBlock);
103    }
104
105    Value* LZ4IndexBuilderKernel::processLiteral(const std::unique_ptr<KernelBuilder> &iBuilder, Value* token, Value* tokenPos, Value* blockEnd) {
106        BasicBlock* entryBlock = iBuilder->GetInsertBlock();
107
108        Value * extendedLiteralValue = iBuilder->CreateICmpEQ(iBuilder->CreateAnd(token, iBuilder->getInt8(0xf0)), iBuilder->getInt8(0xf0));
109
110        BasicBlock* extendLiteralLengthBody = iBuilder->CreateBasicBlock("block_data_loop_handle_compressed_block_extend_literal_length_body");
111        BasicBlock* extendLiteralLengthExit = iBuilder->CreateBasicBlock("block_data_loop_handle_compressed_block_extend_literal_length_exit");
112
113        iBuilder->CreateCondBr(extendedLiteralValue, extendLiteralLengthBody, extendLiteralLengthExit);
114
115        iBuilder->SetInsertPoint(extendLiteralLengthBody);
116        Value* newCursorPos = this->advanceUntilNextZero(iBuilder, "extender", iBuilder->CreateAdd(tokenPos, iBuilder->getInt64(1)), blockEnd);
117        BasicBlock* advanceFinishBlock = iBuilder->GetInsertBlock();
118
119        iBuilder->CreateBr(extendLiteralLengthExit);
120
121        iBuilder->SetInsertPoint(extendLiteralLengthExit);
122
123        PHINode* phiCursorPosAfterLiteral = iBuilder->CreatePHI(iBuilder->getInt64Ty(), 2);
124        phiCursorPosAfterLiteral->addIncoming(newCursorPos, advanceFinishBlock);
125        phiCursorPosAfterLiteral->addIncoming(tokenPos, entryBlock);
126
127        Value * literalExtensionSize = iBuilder->CreateSub(phiCursorPosAfterLiteral, tokenPos);
128        Value * finalLengthByte = this->generateLoadSourceInputByte(iBuilder, phiCursorPosAfterLiteral);
129        finalLengthByte = iBuilder->CreateZExt(finalLengthByte, iBuilder->getInt64Ty());
130        Value * literalLengthExtendValue = iBuilder->CreateSelect(
131                iBuilder->CreateICmpUGT(literalExtensionSize, iBuilder->getSize(0)),
132                iBuilder->CreateAdd(
133                        iBuilder->CreateMul(
134                                iBuilder->CreateSub(literalExtensionSize, iBuilder->getSize(1)),
135                                iBuilder->getSize(255)
136                        ),
137                        finalLengthByte
138                ),
139                iBuilder->getSize(0)
140        );
141        literalLengthExtendValue = iBuilder->CreateZExt(literalLengthExtendValue, iBuilder->getInt64Ty());
142        Value* literalLengthBase = iBuilder->CreateLShr(iBuilder->CreateZExt(token, iBuilder->getInt64Ty()), iBuilder->getInt64(4));
143        Value* literalLength = iBuilder->CreateAdd(literalLengthBase, literalLengthExtendValue);
144
145        Value* offsetPos = iBuilder->CreateAdd(
146                iBuilder->CreateAdd(
147                        phiCursorPosAfterLiteral,
148                        literalLength),
149                iBuilder->getSize(1));
150
151        // TODO Clear Output Buffer at the beginning instead of marking 0
152        this->markCircularOutputBitstream(iBuilder, "deletionMarker", iBuilder->getProducedItemCount("deletionMarker"), iBuilder->CreateAdd(phiCursorPosAfterLiteral, iBuilder->getSize(1)), true);
153//        this->markCircularOutputBitstream(iBuilder, "deletionMarker", iBuilder->CreateAdd(phiCursorPosAfterLiteral, iBuilder->getSize(1)), offsetPos, false);
154        iBuilder->setProducedItemCount("deletionMarker", offsetPos);
155        this->increaseScalarField(iBuilder, "m0OutputPos", literalLength); //TODO m0OutputPos may be removed from scalar fields
156        return offsetPos;
157    }
158
159    Value* LZ4IndexBuilderKernel::processMatch(const std::unique_ptr<KernelBuilder> &iBuilder, Value* offsetPos, Value* token, Value* blockEnd) {
160        Constant* INT64_ONE = iBuilder->getInt64(1);
161
162        BasicBlock* entryBlock = iBuilder->GetInsertBlock();
163
164        Value* matchLengthStartPos = iBuilder->CreateAdd(offsetPos, INT64_ONE);
165        Value* extendedMatchValue = iBuilder->CreateICmpEQ(iBuilder->CreateAnd(token, iBuilder->getInt8(0xf)), iBuilder->getInt8(0xf));
166
167        BasicBlock* extendMatchBodyBlock = iBuilder->CreateBasicBlock("block_data_loop_handle_compressed_block_loop_extend_match_body");
168        BasicBlock* extendMatchExitBlock = iBuilder->CreateBasicBlock("block_data_loop_handle_compressed_block_loop_extend_match_exit");
169
170        iBuilder->CreateCondBr(extendedMatchValue, extendMatchBodyBlock, extendMatchExitBlock);
171
172        iBuilder->SetInsertPoint(extendMatchBodyBlock);
173
174        //ExtendMatchBodyBlock
175        Value* newCursorPos = this->advanceUntilNextZero(iBuilder, "extender", iBuilder->CreateAdd(matchLengthStartPos, INT64_ONE), blockEnd);
176        BasicBlock* advanceFinishBlock = iBuilder->GetInsertBlock();
177
178        // ----May be in a different segment now
179        iBuilder->CreateBr(extendMatchExitBlock);
180
181        //ExtendMatchExitBlock
182        iBuilder->SetInsertPoint(extendMatchExitBlock);
183        PHINode* phiCursorPosAfterMatch = iBuilder->CreatePHI(iBuilder->getInt64Ty(), 2);
184        phiCursorPosAfterMatch->addIncoming(newCursorPos, advanceFinishBlock);
185        phiCursorPosAfterMatch->addIncoming(matchLengthStartPos, entryBlock);
186
187        Value* oldMatchExtensionSize = iBuilder->CreateSub(phiCursorPosAfterMatch, matchLengthStartPos);
188        extendedMatchValue = iBuilder->CreateICmpEQ(iBuilder->CreateAnd(token, iBuilder->getInt8(0xf)), iBuilder->getInt8(0xf));
189        Value* matchExtensionSize = iBuilder->CreateSelect(
190                iBuilder->CreateICmpEQ(extendedMatchValue, iBuilder->getInt1(true)),
191                oldMatchExtensionSize,
192                iBuilder->getSize(0)
193        );
194        Value* matchLengthBase = iBuilder->CreateZExt(iBuilder->CreateAnd(token, iBuilder->getInt8(0x0f)), iBuilder->getInt64Ty());
195        Value* matchLength = iBuilder->CreateAdd(matchLengthBase, iBuilder->getInt64(4));
196
197
198        Value* extensionLastBitPos = iBuilder->CreateAdd(offsetPos, iBuilder->getSize(1));
199        extensionLastBitPos = iBuilder->CreateAdd(extensionLastBitPos, matchExtensionSize);
200
201        Value* extensionLastBitValue = this->generateLoadSourceInputByte(iBuilder, extensionLastBitPos);
202        extensionLastBitValue = iBuilder->CreateZExt(extensionLastBitValue, iBuilder->getSizeTy());
203
204
205        Value* matchLengthAddValue = iBuilder->CreateSelect(
206                iBuilder->CreateICmpUGT(matchExtensionSize, iBuilder->getSize(0)),
207                iBuilder->CreateAdd(
208                        iBuilder->CreateMul(
209                                iBuilder->CreateSub(matchExtensionSize, iBuilder->getSize(1)),
210                                iBuilder->getSize(255)
211                        ),
212                        extensionLastBitValue
213                )
214                ,
215                iBuilder->getSize(0)
216        );
217        matchLengthAddValue = iBuilder->CreateZExt(matchLengthAddValue, iBuilder->getInt64Ty());
218
219        matchLength = iBuilder->CreateAdd(matchLength, matchLengthAddValue);
220
221        Value* outputPos = iBuilder->getScalarField("m0OutputPos");
222
223        Value* outputEndPos = iBuilder->CreateSub(
224                iBuilder->CreateAdd(outputPos, matchLength),
225                iBuilder->getInt64(1)
226        );
227
228        Value* matchOffset = iBuilder->CreateAdd(
229                iBuilder->CreateZExt(this->generateLoadSourceInputByte(iBuilder, offsetPos), iBuilder->getSizeTy()),
230                iBuilder->CreateShl(iBuilder->CreateZExt(this->generateLoadSourceInputByte(iBuilder, iBuilder->CreateAdd(offsetPos, iBuilder->getSize(1))), iBuilder->getSizeTy()), iBuilder->getSize(8))
231        );
232        this->generateStoreNumberOutput(iBuilder, "m0Start", outputPos);
233        this->generateStoreNumberOutput(iBuilder, "m0End", outputEndPos);
234        this->generateStoreNumberOutput(iBuilder, "matchOffset", matchOffset);
235        this->increaseScalarField(iBuilder, "m0OutputPos", matchLength);
236        this->markCircularOutputBitstream(iBuilder, "M0Marker", outputPos, outputEndPos, true, false);
237
238        return iBuilder->CreateAdd(phiCursorPosAfterMatch, INT64_ONE);
239    }
240
241    void LZ4IndexBuilderKernel::generateProcessCompressedBlock(const std::unique_ptr<KernelBuilder> &iBuilder, Value* blockStart, Value* blockEnd) {
242        // Constant
243        this->markCircularOutputBitstream(iBuilder, "deletionMarker", blockStart, blockEnd, false, false);
244
245        BasicBlock* entryBlock = iBuilder->GetInsertBlock();
246
247        Value* m0OutputBlockPtr = iBuilder->getOutputStreamBlockPtr("M0Marker", iBuilder->getSize(0));
248        iBuilder->CreateMemSet(m0OutputBlockPtr, iBuilder->getInt8(0), 4 * 1024 * 1024 / 8, true);
249
250
251        Value* isTerminal = iBuilder->CreateICmpEQ(blockEnd, iBuilder->getScalarField("fileSize"));
252        iBuilder->setTerminationSignal(isTerminal);
253
254        //TODO use memset to clear output buffer for extract marker
255
256        BasicBlock* exitBlock = iBuilder->CreateBasicBlock("processCompressedExitBlock");
257
258        BasicBlock* processCon = iBuilder->CreateBasicBlock("processCompressedConBlock");
259        BasicBlock* processBody = iBuilder->CreateBasicBlock("processCompressedBodyBlock");
260
261        iBuilder->CreateBr(processCon);
262        iBuilder->SetInsertPoint(processCon);
263
264        PHINode* phiCursorValue = iBuilder->CreatePHI(iBuilder->getInt64Ty(), 3); // phiCursorValue should always be the position of next token except for the final sequence
265        phiCursorValue->addIncoming(blockStart, entryBlock);
266
267        iBuilder->CreateCondBr(iBuilder->CreateICmpULT(phiCursorValue, blockEnd), processBody, exitBlock);
268
269        // Process Body
270        iBuilder->SetInsertPoint(processBody);
271
272        //TODO add acceleration here
273        Value* token = this->generateLoadSourceInputByte(iBuilder, phiCursorValue);
274        // Process Literal
275        BasicBlock* processLiteralBlock = iBuilder->CreateBasicBlock("processLiteralBlock");
276        iBuilder->CreateBr(processLiteralBlock);
277        iBuilder->SetInsertPoint(processLiteralBlock);
278
279        Value* offsetPos = this->processLiteral(iBuilder, token, phiCursorValue, blockEnd);
280        // Process Match
281        BasicBlock* handleM0BodyBlock = iBuilder->CreateBasicBlock("block_data_loop_handle_compressed_block_loop_handle_m0_body");
282        BasicBlock* handleM0ElseBlock = iBuilder->CreateBasicBlock("block_data_loop_handle_compressed_block_loop_handle_m0_else");
283
284        iBuilder->CreateCondBr(
285                iBuilder->CreateICmpULT(offsetPos, blockEnd),
286                handleM0BodyBlock,
287                handleM0ElseBlock
288        );
289
290        // HandleM0Body
291        iBuilder->SetInsertPoint(handleM0BodyBlock);
292        Value* nextTokenPos = this->processMatch(iBuilder, offsetPos, token, blockEnd);
293        phiCursorValue->addIncoming(nextTokenPos, iBuilder->GetInsertBlock());
294
295        iBuilder->CreateBr(processCon);
296
297
298        // HandleM0Else
299        iBuilder->SetInsertPoint(handleM0ElseBlock);
300
301        phiCursorValue->addIncoming(offsetPos, handleM0ElseBlock);
302        // Store final M0 pos to make sure the bit stream will be long enough
303        Value* finalM0OutputPos = iBuilder->getScalarField("m0OutputPos");
304        this->generateStoreNumberOutput(iBuilder, "m0Start", finalM0OutputPos);
305        this->generateStoreNumberOutput(iBuilder, "m0End", finalM0OutputPos);
306        this->generateStoreNumberOutput(iBuilder, "matchOffset", iBuilder->getInt64(0));
307        iBuilder->setProducedItemCount("M0Marker", finalM0OutputPos);
308        // finalM0OutputPos should always be 4MB * n except for the final block
309
310        iBuilder->CreateBr(processCon);
311
312
313        iBuilder->SetInsertPoint(exitBlock);
314    }
315
316    Value * LZ4IndexBuilderKernel::advanceUntilNextZero(const unique_ptr<KernelBuilder> &iBuilder, string inputName, Value * startPos, Value * maxPos) {
317
318        unsigned int bitBlockWidth = iBuilder->getBitBlockWidth();
319        Constant* INT64_BIT_BLOCK_WIDTH = iBuilder->getInt64(bitBlockWidth);
320        Type* bitBlockType = iBuilder->getBitBlockType();
321        Type* bitBlockWidthIntTy = iBuilder->getIntNTy(bitBlockWidth);
322
323        BasicBlock* entryBlock = iBuilder->GetInsertBlock();
324
325        BasicBlock* advanceConBlock = iBuilder->CreateBasicBlock("advanceConBlock");
326        BasicBlock* advanceBodyBlock = iBuilder->CreateBasicBlock("advanceBodyBlock");
327        BasicBlock* advanceExitBlock = iBuilder->CreateBasicBlock("advanceExitBlock");
328
329        iBuilder->CreateBr(advanceConBlock);
330        // TODO special handling for the first advance may have better performance
331        iBuilder->SetInsertPoint(advanceConBlock);
332
333        PHINode* phiCurrentPos = iBuilder->CreatePHI(iBuilder->getInt64Ty(), 2);
334        phiCurrentPos->addIncoming(startPos, entryBlock);
335        PHINode* phiIsFinish = iBuilder->CreatePHI(iBuilder->getInt1Ty(), 2);
336        phiIsFinish->addIncoming(iBuilder->getInt1(false), entryBlock);
337        iBuilder->CreateCondBr(iBuilder->CreateNot(phiIsFinish), advanceBodyBlock, advanceExitBlock);
338
339        iBuilder->SetInsertPoint(advanceBodyBlock);
340
341        Value * currentBlockGlobalPos = iBuilder->CreateAnd(phiCurrentPos, ConstantExpr::getNeg(INT64_BIT_BLOCK_WIDTH));
342        Value * currentPosBitBlockOffset = iBuilder->CreateURem(phiCurrentPos, INT64_BIT_BLOCK_WIDTH);
343
344        Value * ptr = iBuilder->CreatePointerCast(iBuilder->getRawInputPointer(inputName, currentBlockGlobalPos), bitBlockType->getPointerTo());
345
346        Value * currentBitValue = iBuilder->CreateBitCast(iBuilder->CreateLoad(ptr), bitBlockWidthIntTy);
347        currentBitValue = iBuilder->CreateLShr(currentBitValue, iBuilder->CreateZExt(currentPosBitBlockOffset, bitBlockWidthIntTy));
348        currentBitValue = iBuilder->CreateNot(currentBitValue);
349
350        Value * forwardZeroCount = iBuilder->CreateTrunc(iBuilder->CreateCountForwardZeroes(currentBitValue), iBuilder->getInt64Ty());
351        Value * newOffset = iBuilder->CreateAdd(currentPosBitBlockOffset, forwardZeroCount);
352        newOffset = iBuilder->CreateUMin(newOffset, INT64_BIT_BLOCK_WIDTH);
353
354        Value * actualAdvanceValue = iBuilder->CreateSub(newOffset, currentPosBitBlockOffset);
355        Value * newPos = iBuilder->CreateAdd(phiCurrentPos, actualAdvanceValue);
356        if (maxPos) {
357            newPos = iBuilder->CreateUMin(maxPos, newPos);
358            actualAdvanceValue = iBuilder->CreateSub(newPos, phiCurrentPos);
359            newOffset = iBuilder->CreateAdd(currentPosBitBlockOffset, actualAdvanceValue);
360        }
361
362        phiIsFinish->addIncoming(iBuilder->CreateICmpNE(newOffset, INT64_BIT_BLOCK_WIDTH), iBuilder->GetInsertBlock());
363        phiCurrentPos->addIncoming(newPos, iBuilder->GetInsertBlock());
364        iBuilder->CreateBr(advanceConBlock);
365
366        iBuilder->SetInsertPoint(advanceExitBlock);
367        return phiCurrentPos;
368    }
369
370    Value * LZ4IndexBuilderKernel::generateLoadInt64NumberInput(const unique_ptr<KernelBuilder> &iBuilder, string inputBufferName, Value * globalOffset) {
371        Constant* SIZE_STRIDE_SIZE = iBuilder->getSize(getStride());
372        Value * processed = iBuilder->getProcessedItemCount(inputBufferName);
373        processed = iBuilder->CreateAnd(processed, ConstantExpr::getNeg(SIZE_STRIDE_SIZE));
374        Value * offset = iBuilder->CreateSub(globalOffset, processed);
375        Value * valuePtr = iBuilder->getRawInputPointer(inputBufferName, offset);
376        return iBuilder->CreateLoad(valuePtr);
377    }
378
379    Value *LZ4IndexBuilderKernel::generateLoadSourceInputByte(const std::unique_ptr<KernelBuilder> &iBuilder, Value * offset) {
380        Value * ptr = iBuilder->getRawInputPointer("byteStream", offset);
381        return iBuilder->CreateLoad(ptr);
382    }
383
384    void LZ4IndexBuilderKernel::increaseScalarField(const unique_ptr<KernelBuilder> &iBuilder, const string &fieldName, Value *value) {
385        Value *fieldValue = iBuilder->getScalarField(fieldName);
386        fieldValue = iBuilder->CreateAdd(fieldValue, value);
387        iBuilder->setScalarField(fieldName, fieldValue);
388    }
389
390    size_t LZ4IndexBuilderKernel::getOutputBufferSize(const unique_ptr<KernelBuilder> &iBuilder, string bufferName) {
391        return this->getOutputStreamSetBuffer(bufferName)->getBufferBlocks() * iBuilder->getStride();
392    }
393
394    // Assume we have enough output buffer
395    llvm::BasicBlock *LZ4IndexBuilderKernel::markCircularOutputBitstream(const std::unique_ptr<KernelBuilder> &iBuilder,
396                                                                         const std::string &bitstreamName,
397                                                                         llvm::Value *start, llvm::Value *end, bool isOne,
398                                                                         bool setProduced) {
399        const unsigned int bitBlockWidth = iBuilder->getBitBlockWidth();
400        Value* SIZE_BIT_BLOCK_WIDTH = iBuilder->getSize(bitBlockWidth);
401        Value* SIZE_ONE = iBuilder->getSize(1);
402        Type * const INT_BIT_BLOCK_TY = iBuilder->getIntNTy(bitBlockWidth);
403        Type * const BIT_BLOCK_TY = iBuilder->getBitBlockType();
404        Constant* INT_BIT_BLOCK_ONE = ConstantInt::get(INT_BIT_BLOCK_TY, 1);
405        Constant* INT_BIT_BLOCK_ZERO = ConstantInt::get(INT_BIT_BLOCK_TY, 0);
406
407        BasicBlock *entryBlock = iBuilder->GetInsertBlock();
408        BasicBlock *conBlock = iBuilder->CreateBasicBlock("mark_bit_one_con");
409        BasicBlock *bodyBlock = iBuilder->CreateBasicBlock("mark_bit_one_body");
410        BasicBlock *exitBlock = iBuilder->CreateBasicBlock("mark_bit_one_exit");
411
412        Value * startBlockLocalIndex = iBuilder->CreateUDiv(start, SIZE_BIT_BLOCK_WIDTH);
413
414        iBuilder->CreateBr(conBlock);
415
416        // Con
417        iBuilder->SetInsertPoint(conBlock);
418
419        PHINode *curBlockLocalIndex = iBuilder->CreatePHI(iBuilder->getSizeTy(), 2);
420        curBlockLocalIndex->addIncoming(startBlockLocalIndex, entryBlock);
421
422
423        iBuilder->CreateCondBr(
424                iBuilder->CreateICmpULT(iBuilder->CreateMul(curBlockLocalIndex, SIZE_BIT_BLOCK_WIDTH), end),
425                bodyBlock,
426                exitBlock
427        );
428
429        // Body
430        iBuilder->SetInsertPoint(bodyBlock);
431
432        Value * const currentPosition = iBuilder->CreateMul(curBlockLocalIndex, SIZE_BIT_BLOCK_WIDTH);
433        Value * lowestBitPosition = iBuilder->CreateURem(start, SIZE_BIT_BLOCK_WIDTH);
434        lowestBitPosition = iBuilder->CreateZExt(lowestBitPosition, INT_BIT_BLOCK_TY);
435        Value * outputLowestBitValue = iBuilder->CreateShl(INT_BIT_BLOCK_ONE, lowestBitPosition);
436        Value * const hasNotReachedStart = iBuilder->CreateICmpULE(currentPosition, start);
437        outputLowestBitValue = iBuilder->CreateSelect(hasNotReachedStart, outputLowestBitValue, INT_BIT_BLOCK_ONE);
438
439        Value * const nextPosition = iBuilder->CreateMul(iBuilder->CreateAdd(curBlockLocalIndex, SIZE_ONE), SIZE_BIT_BLOCK_WIDTH);
440        Value * const hasNotReachEnd = iBuilder->CreateICmpULE(nextPosition, end);
441        Value * producedItemsCount = iBuilder->CreateSelect(hasNotReachEnd, nextPosition, end);
442        Value * highestBitPosition = iBuilder->CreateURem(end, SIZE_BIT_BLOCK_WIDTH);
443        highestBitPosition = iBuilder->CreateZExt(highestBitPosition, INT_BIT_BLOCK_TY);
444        Value * outputHighestBitValue = iBuilder->CreateShl(INT_BIT_BLOCK_ONE, highestBitPosition);
445        outputHighestBitValue = iBuilder->CreateSelect(hasNotReachEnd, INT_BIT_BLOCK_ZERO, outputHighestBitValue);
446        Value * bitMask = iBuilder->CreateSub(outputHighestBitValue, outputLowestBitValue);
447        bitMask = iBuilder->CreateBitCast(bitMask, BIT_BLOCK_TY);
448
449        Value * targetPtr = iBuilder->CreatePointerCast(iBuilder->getRawOutputPointer(bitstreamName, currentPosition), iBuilder->getBitBlockType()->getPointerTo());
450        Value * oldValue = iBuilder->CreateBlockAlignedLoad(targetPtr);
451        Value * newValue = nullptr;
452        if (isOne) {
453            newValue = iBuilder->CreateOr(oldValue, bitMask);
454        } else {
455            newValue = iBuilder->CreateAnd(oldValue, iBuilder->CreateNot(bitMask));
456        }
457        iBuilder->CreateStore(newValue, targetPtr);
458
459        if (setProduced) {
460            iBuilder->setProducedItemCount(bitstreamName, producedItemsCount);
461        }
462
463        curBlockLocalIndex->addIncoming(iBuilder->CreateAdd(curBlockLocalIndex, SIZE_ONE), bodyBlock);
464        iBuilder->CreateBr(conBlock);
465
466        // Exit
467        iBuilder->SetInsertPoint(exitBlock);
468        return exitBlock;
469    }
470
471
472    void LZ4IndexBuilderKernel::generateStoreNumberOutput(const unique_ptr<KernelBuilder> &iBuilder,
473                                                          const string & outputBufferName,
474                                                          Value * value) {
475
476        Value * outputOffset = iBuilder->getProducedItemCount(outputBufferName);
477        Value * outputRawPtr = iBuilder->getRawOutputPointer(outputBufferName, outputOffset);
478        iBuilder->CreateStore(value, outputRawPtr);
479        iBuilder->setProducedItemCount(outputBufferName, iBuilder->CreateAdd(outputOffset, iBuilder->getSize(1)));
480    }
481
482}
Note: See TracBrowser for help on using the repository browser.