source: icGREP/icgrep-devel/icgrep/kernels/radix64.cpp @ 5276

Last change on this file since 5276 was 5276, checked in by cameron, 2 years ago

Elimination of StreamSetStructs? wrapping StreamSetBuffers?

File size: 36.5 KB
Line 
1/*
2 *  Copyright (c) 2016 International Characters.
3 *  This software is licensed to the public under the Open Software License 3.0.
4 */
5#include "radix64.h"
6#include <kernels/streamset.h>
7#include <IR_Gen/idisa_builder.h>
8#include <llvm/IR/Module.h>
9#include <llvm/Support/raw_ostream.h>
10
11using namespace llvm;
12
13namespace kernel {
14
15// This kernel produces an expanded input stream by duplicating every third byte.
16// It is implemented using SIMD shufflevector operations.  With 16-byte registers,
17// a single shufflevector operation produces 16 bytes of output data from the
18// 12 bytes of input data.   With 32-byte registers, 32 bytes of output data are
19// produced from 24 bytes of input data.
20//
21// Using aligned SIMD loads, an inner loop processes three registers full of input
22// data (i.e., three BytePacks) to produce four registers full of output.   This is
23// a 3 step process.
24// Step 1:  Load input_pack0, apply the shuffle operation to produce output_pack0.
25//          At this point 3/4 of the data in input_pack0 has been processed.
26// Step 2:  Load input_pack1, apply a shuffle operation to use the remaining
27//          1/4 of input_pack0 and 1/2 of input_pack1 to produce output_pack1.
28//          At this point 1/2 of the data in input_pack1 has been processed.
29// Step 3:  Load input_pack2, apply a shuffle operation to use the remaining 1/2
30//          of input_pack1 and 1/4 of input_pack2 to produce output_pack2.
31//          Then apply a further shuffle opertaion to use the remaining 3/4 of
32//          input_pack2 to produce output_pack3.
33
34// The doSegment method processes input in terms of tripleBlocks, 3 blocks of input,
35// producing 4 blocks of output.   Unless less than one tripleBlock remains, the
36// doSegment method always processes an integral number of tripleBlocks as a logical
37// segment.  Both input and output buffers are hence maintained at block boundaries,
38// with the input data completely processed for each tripleBlock.
39//
40// The pipeline must guarantee that the doSegment method is called with the
41// a continous buffer for the full segment (number of blocks).
42
43   
44expand3_4Kernel::expand3_4Kernel(IDISA::IDISA_Builder * iBuilder) :
45    KernelBuilder(iBuilder, "expand3_4",
46                  {Binding{iBuilder->getStreamSetTy(1, 8), "sourceStream"}},
47                  {Binding{iBuilder->getStreamSetTy(1, 8), "expandedStream"}},
48                  {}, {}, {}) {
49        setDoBlockUpdatesProducedItemCountsAttribute(true);
50    }
51   
52   
53void expand3_4Kernel::generateDoSegmentMethod() const {
54    IDISA::IDISA_Builder::InsertPoint savePoint = iBuilder->saveIP();
55    Module * m = iBuilder->getModule();
56    Function * doSegmentFunction = m->getFunction(mKernelName + doSegment_suffix);
57    BasicBlock * expand2_3entry = BasicBlock::Create(iBuilder->getContext(), "expand2_3entry", doSegmentFunction, 0);
58    iBuilder->SetInsertPoint(expand2_3entry);
59    BasicBlock * expand_3_4_loop = BasicBlock::Create(iBuilder->getContext(), "expand_3_4_loop", doSegmentFunction, 0);
60    BasicBlock * expand3_4_loop_exit = BasicBlock::Create(iBuilder->getContext(), "expand3_4_loop_exit", doSegmentFunction, 0);
61    BasicBlock * finalStep1 = BasicBlock::Create(iBuilder->getContext(), "finalStep1", doSegmentFunction, 0);
62    BasicBlock * finalStep2 = BasicBlock::Create(iBuilder->getContext(), "finalStep2", doSegmentFunction, 0);
63    BasicBlock * step2load = BasicBlock::Create(iBuilder->getContext(), "step2load", doSegmentFunction, 0);
64    BasicBlock * step2store = BasicBlock::Create(iBuilder->getContext(), "step2store", doSegmentFunction, 0);
65    BasicBlock * finalStep3 = BasicBlock::Create(iBuilder->getContext(), "finalStep3", doSegmentFunction, 0);
66    BasicBlock * step3load = BasicBlock::Create(iBuilder->getContext(), "step3load", doSegmentFunction, 0);
67    BasicBlock * step3store = BasicBlock::Create(iBuilder->getContext(), "step3store", doSegmentFunction, 0);
68    BasicBlock * step3store2 = BasicBlock::Create(iBuilder->getContext(), "step3store2", doSegmentFunction, 0);
69    BasicBlock * itemsDone = BasicBlock::Create(iBuilder->getContext(), "itemsDone", doSegmentFunction, 0);
70    BasicBlock * setTermination = BasicBlock::Create(iBuilder->getContext(), "setTermination", doSegmentFunction, 0);
71    BasicBlock * expand3_4_exit = BasicBlock::Create(iBuilder->getContext(), "expand3_4_exit", doSegmentFunction, 0);
72    BasicBlock * finalExit = BasicBlock::Create(iBuilder->getContext(), "finalExit", doSegmentFunction, 0);
73   
74    // Determine the require shufflevector constants.
75    const unsigned PACK_SIZE = iBuilder->getStride()/8;
76   
77    // Construct a list of indexes in  the form
78    // 0, 1, 2, 2, 3, 4, 5, 5, 6, 7, 8, 8, ...
79    unsigned sourceByteIndex = 0;
80    unsigned expand3_4_index[PACK_SIZE];
81    for (unsigned i = 0; i < PACK_SIZE; i++) {
82        expand3_4_index[i] = sourceByteIndex;
83        if (i % 4 != 2) sourceByteIndex++;
84    }
85    unsigned const expand3_4_offset[4] = {PACK_SIZE, 3*PACK_SIZE/4, PACK_SIZE/2, PACK_SIZE/4};
86    Value * expand_3_4_shuffle[4];
87    for (unsigned j = 0; j < 4; j++) {
88        std::vector<Constant *> Idxs;
89        for (unsigned i = 0; i < PACK_SIZE; i++) {
90            Idxs.push_back(ConstantInt::get(iBuilder->getInt32Ty(), expand3_4_offset[j] + expand3_4_index[i]));
91        }
92        expand_3_4_shuffle[j] = ConstantVector::get(Idxs);
93    }
94    Constant * Const3 = iBuilder->getSize(3);
95    Constant * Const4 = iBuilder->getSize(4);
96    Constant * stride = iBuilder->getSize(iBuilder->getStride());
97    Constant * packSize = iBuilder->getSize(PACK_SIZE);
98    Constant * loopItemCount = iBuilder->getSize(3 * PACK_SIZE); // 3 packs per loop.
99    UndefValue * undefPack = UndefValue::get(iBuilder->fwVectorType(8));
100   
101    const unsigned packAlign = iBuilder->getBitBlockWidth()/8;
102
103    Function::arg_iterator args = doSegmentFunction->arg_begin();
104    Value * self = &*(args++);
105    Value * doFinal = &*(args++);
106    Value * producerPos = &*(args++);
107    Value * processed = getProcessedItemCount(self, "sourceStream");
108    Value * itemsAvail = iBuilder->CreateSub(producerPos, processed);
109   
110    // Except for the final segment, we always process an integral number of triple blocks.
111    Value * tripleBlocksToDo = iBuilder->CreateMul(blocksToDo, Const3);
112    Constant * blockItems = iBuilder->getSize(iBuilder->getBitBlockWidth());
113    Value * tripleItemMax = iBuilder->CreateMul(tripleBlocksToDo, blockItems);
114
115    Value * lessThanFullSegment = iBuilder->CreateICmpULT(itemsAvail, tripleItemMax);
116    Value * tripleBlockItems = iBuilder->CreateSelect(lessThanFullSegment, itemsAvail, tripleItemMax);
117
118    Value * endSignal = iBuilder->CreateLoad(mStreamSetInputBuffers[0]->getEndOfInputPtr(streamStructPtr));
119    Value * inFinalSegment = iBuilder->CreateAnd(endSignal, lessThanFullSegment);
120    Value * itemsToDo = iBuilder->CreateSelect(inFinalSegment, itemsAvail, tripleBlockItems);
121
122//    iBuilder->CallPrintInt("itemsToDo", itemsToDo);
123
124    Value * blockNo = getScalarField(self, blockNoScalar);
125
126    // A block is made up of 8 packs.  Get the pointer to the first pack (changes the type of the pointer only).
127    Value * sourcePackPtr = getStream(self, "sourceStream", blockNo, iBuilder->getInt32(0), iBuilder->getInt32(0));
128
129    Value * outputGenerated = getProducedItemCount(self, "expandedStream"); // bytes previously generated to output
130    Value * outputBlockNo = iBuilder->CreateUDiv(outputGenerated, stride);
131    Value * outputPackPtr = getStream(self, "expandedStream", outputBlockNo, iBuilder->getInt32(0), iBuilder->getInt32(0));
132
133    Value * hasFullLoop = iBuilder->CreateICmpUGE(itemsToDo, loopItemCount);
134
135
136    iBuilder->CreateCondBr(hasFullLoop, expand_3_4_loop, expand3_4_loop_exit);
137    iBuilder->SetInsertPoint(expand_3_4_loop);
138    PHINode * loopInput_ptr = iBuilder->CreatePHI(sourcePackPtr->getType(), 2);
139    PHINode * loopOutput_ptr = iBuilder->CreatePHI(outputPackPtr->getType(), 2);
140    PHINode * loopItemsRemain = iBuilder->CreatePHI(iBuilder->getSizeTy(), 2);
141
142    loopInput_ptr->addIncoming(sourcePackPtr, expand2_3entry);
143    loopOutput_ptr->addIncoming(outputPackPtr, expand2_3entry);
144    loopItemsRemain->addIncoming(itemsToDo, expand2_3entry);
145
146    // Step 1 of the main loop.
147    Value * pack0 = iBuilder->fwCast(8, iBuilder->CreateAlignedLoad(loopInput_ptr, packAlign));
148    Value * expand0 = iBuilder->bitCast(iBuilder->CreateShuffleVector(undefPack, pack0, expand_3_4_shuffle[0]));
149    iBuilder->CreateAlignedStore(expand0, loopOutput_ptr, packAlign);
150    // Step 2 of the main loop.
151    Value * inPack1_ptr = iBuilder->CreateGEP(loopInput_ptr, iBuilder->getInt32(1));
152    Value * outPack1_ptr = iBuilder->CreateGEP(loopOutput_ptr, iBuilder->getInt32(1));
153    Value * pack1 = iBuilder->fwCast(8, iBuilder->CreateAlignedLoad(inPack1_ptr, packAlign));
154    Value * expand1 = iBuilder->bitCast(iBuilder->CreateShuffleVector(pack0, pack1, expand_3_4_shuffle[1]));
155    iBuilder->CreateAlignedStore(expand1, outPack1_ptr, packAlign);
156    // Step 3 of the main loop.
157    Value * inPack2_ptr = iBuilder->CreateGEP(loopInput_ptr, iBuilder->getInt32(2));
158    Value * outPack2_ptr = iBuilder->CreateGEP(loopOutput_ptr, iBuilder->getInt32(2));
159    Value * pack2 = iBuilder->fwCast(8, iBuilder->CreateAlignedLoad(inPack2_ptr, packAlign));
160    Value * expand2 = iBuilder->bitCast(iBuilder->CreateShuffleVector(pack1, pack2, expand_3_4_shuffle[2]));
161    iBuilder->CreateAlignedStore(expand2, outPack2_ptr, packAlign);
162    Value * outPack3_ptr = iBuilder->CreateGEP(loopOutput_ptr, iBuilder->getInt32(3));
163    Value * expand3 = iBuilder->bitCast(iBuilder->CreateShuffleVector(pack2, undefPack, expand_3_4_shuffle[3]));
164    iBuilder->CreateAlignedStore(expand3, outPack3_ptr, packAlign);
165
166    Value * loopNextInputPack = iBuilder->CreateGEP(loopInput_ptr, iBuilder->getInt32(3));
167
168
169
170    Value * remainingItems = iBuilder->CreateSub(loopItemsRemain, loopItemCount);
171
172    Value * loopProcessed = iBuilder->CreateSub(itemsToDo, remainingItems);
173    loopProcessed = iBuilder->CreateMul(iBuilder->CreateUDiv(loopProcessed, iBuilder->getInt64(3)), iBuilder->getInt64(4));
174
175    Value * loopNextOutputPack;
176    loopNextOutputPack = iBuilder->CreateGEP(loopOutput_ptr, iBuilder->getInt32(4));
177
178    loopInput_ptr->addIncoming(loopNextInputPack, expand_3_4_loop);
179    loopOutput_ptr->addIncoming(loopNextOutputPack, expand_3_4_loop);
180    loopItemsRemain->addIncoming(remainingItems, expand_3_4_loop);
181
182    Value * continueLoop = iBuilder->CreateICmpUGE(remainingItems, loopItemCount);
183    iBuilder->CreateCondBr(continueLoop, expand_3_4_loop, expand3_4_loop_exit);
184
185    // Except for the final segment, the number of items remaining is now 0.
186    // For the final segment, less than loopItemCount items remain.
187    iBuilder->SetInsertPoint(expand3_4_loop_exit);
188    PHINode * loopExitInput_ptr = iBuilder->CreatePHI(sourcePackPtr->getType(), 2);
189    PHINode * loopExitOutput_ptr = iBuilder->CreatePHI(outputPackPtr->getType(), 2);
190    PHINode * loopExitItemsRemain = iBuilder->CreatePHI(iBuilder->getSizeTy(), 2);
191    loopExitInput_ptr->addIncoming(sourcePackPtr, expand2_3entry);
192    loopExitOutput_ptr->addIncoming(outputPackPtr, expand2_3entry);
193    loopExitItemsRemain->addIncoming(itemsToDo, expand2_3entry);
194    loopExitInput_ptr->addIncoming(loopNextInputPack, expand_3_4_loop);
195    loopExitOutput_ptr->addIncoming(loopNextOutputPack, expand_3_4_loop);
196    loopExitItemsRemain->addIncoming(remainingItems, expand_3_4_loop);
197    // There may be one or two remaining full packs and/or a partial pack.
198    //
199    // We have several cases depending on the number of reumaing items.  Let N = packSize
200    // (a) 0 remaining items: all done
201    // (b) 1..3N/4 remaining items:  do Step1 only, no items or pending data will remain
202    // (c) 3N/4+1 .. N remaining items:  do Step 1, do Step 2 for pending data from Step 1 only, there is no more input.
203    // (d) N+1 .. 6N/4 remaining items:  do Step 1 and Step 2, no items or pending data will remain.
204    // (e) 6N/4+1 .. 2N remaining items: do Steps 1 and 2, do Step 3 for pending data only, there is no more input.
205    // (f) 2N+1 .. 9N/4 remaining items: do Steps 1 and 2, do Step 3 up to the first write only.
206    // (g) 9N/4+1 .. 3N - 1 remaining items: do Steps 1, 2 and 3.
207    Value * condition_a = iBuilder->CreateICmpEQ(loopExitItemsRemain, ConstantInt::getNullValue(iBuilder->getSizeTy()));
208    iBuilder->CreateCondBr(condition_a, itemsDone, finalStep1);
209    // Final Step1 processing
210    iBuilder->SetInsertPoint(finalStep1);
211    pack0 = iBuilder->fwCast(8, iBuilder->CreateAlignedLoad(loopExitInput_ptr, packAlign));
212    expand0 = iBuilder->bitCast(iBuilder->CreateShuffleVector(undefPack, pack0, expand_3_4_shuffle[0]));
213    iBuilder->CreateAlignedStore(expand0, loopExitOutput_ptr, packAlign);
214    Value * condition_b = iBuilder->CreateICmpULE(loopExitItemsRemain, iBuilder->getSize(3 * PACK_SIZE/4));
215    iBuilder->CreateCondBr(condition_b, itemsDone, finalStep2);
216    // Final Step 2 processing
217    iBuilder->SetInsertPoint(finalStep2);
218    Value * condition_c = iBuilder->CreateICmpULE(loopExitItemsRemain, packSize);
219    iBuilder->CreateCondBr(condition_c, step2store, step2load);
220    iBuilder->SetInsertPoint(step2load);
221    inPack1_ptr = iBuilder->CreateGEP(loopExitInput_ptr, iBuilder->getInt32(1));
222    pack1 = iBuilder->fwCast(8, iBuilder->CreateAlignedLoad(inPack1_ptr, packAlign));
223    iBuilder->CreateBr(step2store);
224    iBuilder->SetInsertPoint(step2store);
225    PHINode * pack1phi = iBuilder->CreatePHI(iBuilder->fwVectorType(8), 2);
226    pack1phi->addIncoming(undefPack, finalStep2);
227    pack1phi->addIncoming(pack1, step2load);
228    outPack1_ptr = iBuilder->CreateGEP(loopExitOutput_ptr, iBuilder->getInt32(1));
229    expand1 = iBuilder->bitCast(iBuilder->CreateShuffleVector(pack0, pack1phi, expand_3_4_shuffle[1]));
230    iBuilder->CreateAlignedStore(expand1, outPack1_ptr, packAlign);
231    Value * condition_d = iBuilder->CreateICmpULE(loopExitItemsRemain, iBuilder->getSize(6 * PACK_SIZE/4));
232    iBuilder->CreateCondBr(condition_d, itemsDone, finalStep3);
233    // Final Step 3
234    iBuilder->SetInsertPoint(finalStep3);
235    Value * condition_e = iBuilder->CreateICmpULE(loopExitItemsRemain, iBuilder->getSize(2 * PACK_SIZE));
236    iBuilder->CreateCondBr(condition_e, step3store, step3load);
237    iBuilder->SetInsertPoint(step3load);
238    inPack2_ptr = iBuilder->CreateGEP(loopExitInput_ptr, iBuilder->getInt32(2));
239    pack2 = iBuilder->fwCast(8, iBuilder->CreateAlignedLoad(inPack2_ptr, packAlign));
240    iBuilder->CreateBr(step3store);
241    iBuilder->SetInsertPoint(step3store);
242    PHINode * pack2phi = iBuilder->CreatePHI(iBuilder->fwVectorType(8), 2);
243    pack2phi->addIncoming(undefPack, finalStep3);
244    pack2phi->addIncoming(pack2, step3load);
245    outPack2_ptr = iBuilder->CreateGEP(loopExitOutput_ptr, iBuilder->getInt32(2));
246    expand2 = iBuilder->bitCast(iBuilder->CreateShuffleVector(pack1phi, pack2phi, expand_3_4_shuffle[2]));
247    iBuilder->CreateAlignedStore(expand2, outPack2_ptr, packAlign);
248    Value * condition_f = iBuilder->CreateICmpULE(loopExitItemsRemain, iBuilder->getSize(9 * PACK_SIZE/4));
249    iBuilder->CreateCondBr(condition_f, itemsDone, step3store2);
250    iBuilder->SetInsertPoint(step3store2);
251    outPack3_ptr = iBuilder->CreateGEP(loopExitOutput_ptr, iBuilder->getInt32(3));
252    expand3 = iBuilder->bitCast(iBuilder->CreateShuffleVector(pack2phi, undefPack, expand_3_4_shuffle[3]));
253    iBuilder->CreateAlignedStore(expand3, outPack3_ptr, packAlign);
254    iBuilder->CreateBr(itemsDone);
255    //
256    iBuilder->SetInsertPoint(itemsDone);
257
258    processed = iBuilder->CreateAdd(processed, itemsToDo);
259    setProcessedItemCount(self, "sourceStream", processed);
260
261    setScalarField(self, blockNoScalar, iBuilder->CreateUDiv(processed, stride));
262    // We have produced 4 output bytes for every 3 input bytes.  If the number of input
263    // bytes is not a multiple of 3, then we have one more output byte for each excess
264    // input byte.
265    Value * totalProduced = iBuilder->CreateAdd(iBuilder->CreateMul(iBuilder->CreateUDiv(processed, Const3), Const4), iBuilder->CreateURem(processed, Const3));
266    setProducedItemCount(self, "expandedStream", totalProduced);
267   
268    iBuilder->CreateCondBr(inFinalSegment, setTermination, expand3_4_exit);
269    iBuilder->SetInsertPoint(setTermination);
270#ifndef NDEBUG
271//    iBuilder->CallPrintInt(mKernelName + " termination in segment ", segmentNo);
272#endif
273    setTerminationSignal(self);
274    mStreamSetOutputBuffers[0]->setEndOfInput(ssStructPtr);
275    iBuilder->CreateBr(expand3_4_exit);
276    iBuilder->SetInsertPoint(expand3_4_exit);
277    // Must be the last action, for synchronization.
278    iBuilder->CreateBr(finalExit);
279   
280    iBuilder->SetInsertPoint(finalExit);
281    iBuilder->CreateRetVoid();
282    iBuilder->restoreIP(savePoint);
283}
284
285
286// The doBlock method is deprecated.   But in case it is used, just call doSegment with
287// 1 as the number of blocks to do.
288void expand3_4Kernel::generateDoBlockMethod() const {
289    auto savePoint = iBuilder->saveIP();
290    Module * m = iBuilder->getModule();
291    Function * doBlockFunction = m->getFunction(mKernelName + doBlock_suffix);
292    Function * doSegmentFunction = m->getFunction(mKernelName + doSegment_suffix);
293    iBuilder->SetInsertPoint(BasicBlock::Create(iBuilder->getContext(), "entry", doBlockFunction, 0));
294    Value * self = getParameter(doBlockFunction, "self");
295    iBuilder->CreateCall(doSegmentFunction, {self, iBuilder->getSize(1)});
296    iBuilder->CreateRetVoid();
297    iBuilder->restoreIP(savePoint);
298}
299
300// Radix 64 determination, converting 3 bytes to 4 6-bit values.
301//
302//  00000000|zyxwvuts|rqpmnlkj|hgfedcba    Original
303//           zy                            bits to move 6 positions right
304//             xwvuts                      bits to move 8 positions left
305//                    rqpm                 bits to move 4 positions right
306//                        nlkj             bits to move 10 positions left
307//                             hqfedc      bits to move 2 positions right
308//                                   ba    bits to move 12 positions left
309//    xwvuts|  nlkjzy|  barqpm|  hgfedc    Target
310void radix64Kernel::generateDoBlockLogic(Value * self, Value * blockNo) const {
311
312    Value * step_right_6 = iBuilder->simd_fill(32, ConstantInt::get(iBuilder->getInt32Ty(), 0x00C00000));
313    Value * step_left_8 = iBuilder->simd_fill(32, ConstantInt::get(iBuilder->getInt32Ty(), 0x003F0000));
314    Value * step_right_4 = iBuilder->simd_fill(32, ConstantInt::get(iBuilder->getInt32Ty(), 0x0000F000));
315    Value * step_left_10 = iBuilder->simd_fill(32, ConstantInt::get(iBuilder->getInt32Ty(), 0x00000F00));
316    Value * step_right_2 = iBuilder->simd_fill(32, ConstantInt::get(iBuilder->getInt32Ty(), 0x000000FC));
317    Value * step_left_12 = iBuilder->simd_fill(32, ConstantInt::get(iBuilder->getInt32Ty(), 0x00000003));
318   
319    for (unsigned i = 0; i < 8; i++) {
320        Value * expandedStream = getStream(self, "expandedStream", blockNo, iBuilder->getInt32(0), iBuilder->getInt32(i));
321        Value * bytepack = iBuilder->CreateBlockAlignedLoad(expandedStream);
322
323        Value * right_6_result = iBuilder->simd_srli(32, iBuilder->simd_and(bytepack, step_right_6), 6);
324        Value * right_4_result = iBuilder->simd_srli(32, iBuilder->simd_and(bytepack, step_right_4), 4);
325        Value * right_2_result = iBuilder->simd_srli(32, iBuilder->simd_and(bytepack, step_right_2), 2);
326        Value * left_8_result = iBuilder->simd_slli(32, iBuilder->simd_and(bytepack, step_left_8), 8);
327        Value * left_10_result = iBuilder->simd_slli(32, iBuilder->simd_and(bytepack, step_left_10), 10);
328        Value * left_12_result = iBuilder->simd_slli(32, iBuilder->simd_and(bytepack, step_left_12), 12);
329
330        Value * mid = right_6_result;
331        mid = iBuilder->simd_or(mid, right_4_result);
332        mid = iBuilder->simd_or(mid, right_2_result);
333        mid = iBuilder->simd_or(mid, left_8_result);
334        mid = iBuilder->simd_or(mid, left_10_result);
335        mid = iBuilder->simd_or(mid, left_12_result);
336        Value * radix64pack = iBuilder->bitCast(mid);
337
338        Value * radix64stream = getStream(self, "radix64stream",blockNo, iBuilder->getInt32(0), iBuilder->getInt32(i));
339        iBuilder->CreateBlockAlignedStore(radix64pack, radix64stream);
340    }
341    Value * produced = getProducedItemCount(self, "radix64stream");
342    produced = iBuilder->CreateAdd(produced, iBuilder->getSize(iBuilder->getStride()));
343    setProducedItemCount(self, "radix64stream", produced);   
344}
345
346void radix64Kernel::generateFinalBlockMethod() const {
347    auto savePoint = iBuilder->saveIP();
348    Module * m = iBuilder->getModule();
349    Function * finalBlockFunction = m->getFunction(mKernelName + finalBlock_suffix);
350    BasicBlock * radix64_fb_entry = BasicBlock::Create(iBuilder->getContext(), "radix64_fb_entry", finalBlockFunction, 0);
351    iBuilder->SetInsertPoint(radix64_fb_entry);
352    BasicBlock * radix64_loop = BasicBlock::Create(iBuilder->getContext(), "radix64_loop", finalBlockFunction, 0);
353    BasicBlock * loopExit = BasicBlock::Create(iBuilder->getContext(), "loopExit", finalBlockFunction, 0);
354    BasicBlock * handleRemainFirstByte = BasicBlock::Create(iBuilder->getContext(), "handleRemainFirstByte", finalBlockFunction, 0);
355    BasicBlock * handleRemainSecondByte = BasicBlock::Create(iBuilder->getContext(), "handleRemainSecondByte", finalBlockFunction, 0);
356    BasicBlock * handleNoRemainSecondByte = BasicBlock::Create(iBuilder->getContext(), "handleNoRemainSecondByte", finalBlockFunction, 0);
357    BasicBlock * fbExit = BasicBlock::Create(iBuilder->getContext(), "fbExit", finalBlockFunction, 0);
358    // Final Block arguments: self, remaining.
359    Function::arg_iterator args = finalBlockFunction->arg_begin();
360    Value * self = &*(args++);
361    Value * remainingBytes = &*(args++);
362    Value * remainMod4 = iBuilder->CreateAnd(remainingBytes, iBuilder->getSize(3));
363
364    const unsigned PACK_SIZE = iBuilder->getStride()/8;
365    Constant * packSize = iBuilder->getSize(PACK_SIZE);
366    Value * blockNo = getScalarField(self, blockNoScalar);
367
368    Value * step_right_6 = iBuilder->simd_fill(32, iBuilder->getInt32(0x00C00000));
369    Value * step_left_8 = iBuilder->simd_fill(32, iBuilder->getInt32(0x003F0000));
370    Value * step_right_4 = iBuilder->simd_fill(32, iBuilder->getInt32(0x0000F000));
371    Value * step_left_10 = iBuilder->simd_fill(32, iBuilder->getInt32(0x00000F00));
372    Value * step_right_2 = iBuilder->simd_fill(32, iBuilder->getInt32(0x000000FC));
373    Value * step_left_12 = iBuilder->simd_fill(32, iBuilder->getInt32(0x00000003));
374
375
376    // Enter the loop only if there is at least one byte remaining to process.
377    iBuilder->CreateCondBr(iBuilder->CreateICmpEQ(remainingBytes, iBuilder->getSize(0)), fbExit, radix64_loop);
378
379    iBuilder->SetInsertPoint(radix64_loop);
380    PHINode * idx = iBuilder->CreatePHI(iBuilder->getInt32Ty(), 2);
381    PHINode * loopRemain = iBuilder->CreatePHI(iBuilder->getSizeTy(), 2);
382    idx->addIncoming(ConstantInt::getNullValue(iBuilder->getInt32Ty()), radix64_fb_entry);
383    loopRemain->addIncoming(remainingBytes, radix64_fb_entry);
384
385    Value * expandedStreamLoopPtr = getStream(self, "expandedStream", blockNo, iBuilder->getInt32(0), idx);
386    Value * bytepack = iBuilder->CreateBlockAlignedLoad(expandedStreamLoopPtr);
387    Value * right_6_result = iBuilder->simd_srli(32, iBuilder->simd_and(bytepack, step_right_6), 6);
388    Value * right_4_result = iBuilder->simd_srli(32, iBuilder->simd_and(bytepack, step_right_4), 4);
389    Value * right_2_result = iBuilder->simd_srli(32, iBuilder->simd_and(bytepack, step_right_2), 2);
390    Value * left_8_result = iBuilder->simd_slli(32, iBuilder->simd_and(bytepack, step_left_8), 8);
391    Value * left_10_result = iBuilder->simd_slli(32, iBuilder->simd_and(bytepack, step_left_10), 10);
392    Value * left_12_result = iBuilder->simd_slli(32, iBuilder->simd_and(bytepack, step_left_12), 12);
393
394    Value * mid = right_6_result;
395    mid = iBuilder->simd_or(mid, right_4_result);
396    mid = iBuilder->simd_or(mid, right_2_result);
397    mid = iBuilder->simd_or(mid, left_8_result);
398    mid = iBuilder->simd_or(mid, left_10_result);
399    mid = iBuilder->simd_or(mid, left_12_result);
400    Value * radix64pack = iBuilder->bitCast(mid);
401
402    Value * radix64streamPtr = getStream(self, "radix64stream", blockNo, iBuilder->getInt32(0), idx);
403    iBuilder->CreateBlockAlignedStore(radix64pack, radix64streamPtr);
404
405    Value* nextIdx = iBuilder->CreateAdd(idx, ConstantInt::get(iBuilder->getInt32Ty(), 1));
406    idx->addIncoming(nextIdx, radix64_loop);
407    Value* remainAfterLoop = iBuilder->CreateSub(loopRemain, packSize);
408    loopRemain->addIncoming(remainAfterLoop, radix64_loop);
409
410    Value* continueLoop = iBuilder->CreateICmpULT(remainAfterLoop, packSize);
411    iBuilder->CreateCondBr(continueLoop, radix64_loop, loopExit);
412
413    iBuilder->SetInsertPoint(loopExit);
414    // All base64 data has been computed, but we may need to set one or two '=' padding bytes.
415    iBuilder->CreateCondBr(iBuilder->CreateICmpEQ(remainMod4, iBuilder->getSize(0)), fbExit, handleRemainFirstByte);
416    iBuilder->SetInsertPoint(handleRemainFirstByte);
417    // At least one padding byte required.
418    Value * i8input_ptr = getStreamView(iBuilder->getInt8PtrTy(), self, "expandedStream", blockNo, iBuilder->getInt32(0));
419    Value * remainOutputStart = iBuilder->CreateSub(remainingBytes, remainMod4);
420
421    Value * firstRemainByte = iBuilder->CreateLoad(i8input_ptr);
422
423    Value * first_move_right_2_mask = ConstantInt::get(iBuilder->getInt8Ty(), 0xFC);
424    Value * first_output_byte = iBuilder->CreateLShr(iBuilder->CreateAnd(firstRemainByte, first_move_right_2_mask), 2);
425
426    Value * first_move_left_4_mask = ConstantInt::get(iBuilder->getInt8Ty(), 0x03);
427    Value * first_move_left_4_byte = iBuilder->CreateShl(iBuilder->CreateAnd(firstRemainByte, first_move_left_4_mask), 4);
428
429
430    Value * i8OutPtr0 = getStreamView(iBuilder->getInt8PtrTy(), self, "radix64stream", blockNo, remainOutputStart);
431
432    iBuilder->CreateStore(first_output_byte, i8OutPtr0);
433
434    iBuilder->CreateCondBr(iBuilder->CreateICmpEQ(remainMod4, iBuilder->getSize(1)), handleNoRemainSecondByte, handleRemainSecondByte);
435    iBuilder->SetInsertPoint(handleRemainSecondByte);
436
437    Value * secondRemainByte = iBuilder->CreateLoad(iBuilder->CreateGEP(i8input_ptr, iBuilder->getInt32(1)));
438    Value * second_move_right_4_mask = ConstantInt::get(iBuilder->getInt8Ty(), 0xF0);
439    Value * second_move_right_4_byte = iBuilder->CreateLShr(iBuilder->CreateAnd(secondRemainByte, second_move_right_4_mask), 4);
440    Value * second_output_byte = iBuilder->CreateOr(first_move_left_4_byte, second_move_right_4_byte);
441
442    Value * i8OutPtr1 = getStreamView(iBuilder->getInt8PtrTy(), self, "radix64stream", blockNo, iBuilder->CreateAdd(remainOutputStart, iBuilder->getInt64(1)));
443
444    iBuilder->CreateStore(second_output_byte, i8OutPtr1);
445
446    Value * second_move_left_2_mask = ConstantInt::get(iBuilder->getInt8Ty(), 0x0F);
447    Value * second_move_left_2_byte = iBuilder->CreateShl(iBuilder->CreateAnd(secondRemainByte, second_move_left_2_mask), 2);
448
449    Value * i8OutPtr2 = getStreamView(iBuilder->getInt8PtrTy(), self, "radix64stream", blockNo, iBuilder->CreateAdd(remainOutputStart, iBuilder->getInt64(2)));
450
451    iBuilder->CreateStore(second_move_left_2_byte, i8OutPtr2);
452    iBuilder->CreateBr(fbExit);
453
454    iBuilder->SetInsertPoint(handleNoRemainSecondByte);
455
456    i8OutPtr1 = getStreamView(iBuilder->getInt8PtrTy(), self, "radix64stream", blockNo, iBuilder->CreateAdd(remainOutputStart, iBuilder->getInt64(1)));
457
458    iBuilder->CreateStore(first_move_left_4_byte, i8OutPtr1);
459    iBuilder->CreateBr(fbExit);
460
461    iBuilder->SetInsertPoint(fbExit);
462    Value * outputNumberAdd = iBuilder->CreateSelect(iBuilder->CreateICmpEQ(remainMod4, iBuilder->getSize(0)), iBuilder->getSize(0), iBuilder->getSize(1));
463    Value * produced = iBuilder->CreateAdd(getProducedItemCount(self, "radix64stream"), iBuilder->CreateAdd(remainingBytes, outputNumberAdd));
464    setProducedItemCount(self, "radix64stream", produced);
465
466    iBuilder->CreateRetVoid();
467    iBuilder->restoreIP(savePoint);
468}
469
470   
471radix64Kernel::radix64Kernel(IDISA::IDISA_Builder * iBuilder) :
472    KernelBuilder(iBuilder, "radix64",
473                  {Binding{iBuilder->getStreamSetTy(1, 8), "expandedStream"}},
474                  {Binding{iBuilder->getStreamSetTy(1, 8), "radix64stream"}},
475                  {}, {}, {}) {
476        setDoBlockUpdatesProducedItemCountsAttribute(true);
477}
478   
479void radix64Kernel::generateDoBlockMethod() const {
480    auto savePoint = iBuilder->saveIP();
481
482    Function * doBlockFunction = iBuilder->getModule()->getFunction(mKernelName + doBlock_suffix);
483
484    iBuilder->SetInsertPoint(BasicBlock::Create(iBuilder->getContext(), "entry", doBlockFunction, 0));
485
486    Value * self = getParameter(doBlockFunction, "self");
487    Value * blockNo = getScalarField(self, blockNoScalar);
488
489    generateDoBlockLogic(self, blockNo);
490
491    iBuilder->CreateRetVoid();
492    iBuilder->restoreIP(savePoint);
493}
494
495base64Kernel::base64Kernel(IDISA::IDISA_Builder * iBuilder) :
496    KernelBuilder(iBuilder, "base64",
497                  {Binding{iBuilder->getStreamSetTy(1, 8), "radix64stream"}},
498                  {Binding{iBuilder->getStreamSetTy(1, 8), "base64stream"}},
499                  {}, {}, {}) {
500        setDoBlockUpdatesProducedItemCountsAttribute(true);
501    }
502   
503
504void base64Kernel::generateDoBlockLogic(Value * self, Value * blockNo) const {       
505    for (unsigned i = 0; i < 8; i++) {
506        Value * radix64stream_ptr = getStream(self, "radix64stream", blockNo, iBuilder->getInt32(0), iBuilder->getInt32(i));
507        Value * bytepack = iBuilder->CreateBlockAlignedLoad(radix64stream_ptr);
508        Value * mask_gt_25 = iBuilder->simd_ugt(8, bytepack, iBuilder->simd_fill(8, iBuilder->getInt8(25)));
509        Value * mask_gt_51 = iBuilder->simd_ugt(8, bytepack, iBuilder->simd_fill(8, iBuilder->getInt8(51)));
510        Value * mask_eq_62 = iBuilder->simd_eq(8, bytepack, iBuilder->simd_fill(8, iBuilder->getInt8(62)));
511        Value * mask_eq_63 = iBuilder->simd_eq(8, bytepack, iBuilder->simd_fill(8, iBuilder->getInt8(63)));
512        // Strategy:
513        // 1. add ord('A') = 65 to all radix64 values, this sets the correct values for entries 0 to 25.
514        // 2. add ord('a') - ord('A') - (26 - 0) = 6 to all values >25, this sets the correct values for entries 0 to 51
515        // 3. subtract ord('a') - ord('0') + (52 - 26) = 75 to all values > 51, this sets the correct values for entries 0 to 61
516        // 4. subtract ord('0') - ord('+') + (62 - 52) = 15 for all values = 62
517        // 4. subtract ord('0') - ord('/') + (63 - 62) = 2 for all values = 63
518        Value * t0_25 = iBuilder->simd_add(8, bytepack, iBuilder->simd_fill(8, iBuilder->getInt8('A')));
519        Value * t0_51 = iBuilder->simd_add(8, t0_25, iBuilder->simd_and(mask_gt_25, iBuilder->simd_fill(8, iBuilder->getInt8(6))));
520        Value * t0_61 = iBuilder->simd_sub(8, t0_51, iBuilder->simd_and(mask_gt_51, iBuilder->simd_fill(8, iBuilder->getInt8(75))));
521        Value * t0_62 = iBuilder->simd_sub(8, t0_61, iBuilder->simd_and(mask_eq_62, iBuilder->simd_fill(8, iBuilder->getInt8(15))));
522        Value * base64pack = iBuilder->simd_sub(8, t0_62, iBuilder->simd_and(mask_eq_63, iBuilder->simd_fill(8, iBuilder->getInt8(2))));
523        Value * base64stream_ptr = getStream(self, "base64stream", blockNo, iBuilder->getInt32(0), iBuilder->getInt32(i));
524        iBuilder->CreateBlockAlignedStore(iBuilder->bitCast(base64pack), base64stream_ptr);
525    }
526    Value * produced = getProducedItemCount(self, "base64stream");
527    produced = iBuilder->CreateAdd(produced, iBuilder->getSize(iBuilder->getStride()));
528    setProducedItemCount(self, "base64stream", produced);
529}
530
531
532// Special processing for the base 64 format.   The output must always contain a multiple
533// of 4 bytes.   When the number of radix 64 values is not a multiple of 4
534// number of radix 64 values
535void base64Kernel::generateFinalBlockMethod() const {
536    auto savePoint = iBuilder->saveIP();
537    Module * m = iBuilder->getModule();
538    Function * finalBlockFunction = m->getFunction(mKernelName + finalBlock_suffix);
539    BasicBlock * base64_fb_entry = BasicBlock::Create(iBuilder->getContext(), "base64_fb_entry", finalBlockFunction, 0);
540    iBuilder->SetInsertPoint(base64_fb_entry);
541    BasicBlock * base64_loop = BasicBlock::Create(iBuilder->getContext(), "base64_loop", finalBlockFunction, 0);
542    BasicBlock * loopExit = BasicBlock::Create(iBuilder->getContext(), "loopExit", finalBlockFunction, 0);
543    BasicBlock * doPadding = BasicBlock::Create(iBuilder->getContext(), "doPadding", finalBlockFunction, 0);
544    BasicBlock * doPadding2 = BasicBlock::Create(iBuilder->getContext(), "doPadding2", finalBlockFunction, 0);
545    BasicBlock * fbExit = BasicBlock::Create(iBuilder->getContext(), "fbExit", finalBlockFunction, 0);
546    // Final Block arguments: self, remaining.
547    Function::arg_iterator args = finalBlockFunction->arg_begin();
548    Value * self = &*(args++);
549    Value * remainingBytes = &*(args++);
550    Value * remainMod4 = iBuilder->CreateAnd(remainingBytes, iBuilder->getSize(3));
551    Value * padBytes = iBuilder->CreateSub(iBuilder->getSize(4), remainMod4);
552    padBytes = iBuilder->CreateAnd(padBytes, iBuilder->getSize(3));
553
554    Constant * packSize = iBuilder->getSize(iBuilder->getStride() / 8);
555    Value * blockNo = getScalarField(self, blockNoScalar);
556
557    // Enter the loop only if there is at least one byte remaining to process.
558    iBuilder->CreateCondBr(iBuilder->CreateICmpEQ(remainingBytes, iBuilder->getSize(0)), fbExit, base64_loop);
559   
560    iBuilder->SetInsertPoint(base64_loop);
561    PHINode * idx = iBuilder->CreatePHI(iBuilder->getInt32Ty(), 2);
562    PHINode * loopRemain = iBuilder->CreatePHI(iBuilder->getSizeTy(), 2);
563    idx->addIncoming(ConstantInt::getNullValue(iBuilder->getInt32Ty()), base64_fb_entry);
564    loopRemain->addIncoming(remainingBytes, base64_fb_entry);
565    Value * radix64streamPtr = getStream(self, "radix64stream", blockNo, iBuilder->getInt32(0), idx);
566    Value * bytepack = iBuilder->CreateBlockAlignedLoad(radix64streamPtr);
567    Value * mask_gt_25 = iBuilder->simd_ugt(8, bytepack, iBuilder->simd_fill(8, iBuilder->getInt8(25)));
568    Value * mask_gt_51 = iBuilder->simd_ugt(8, bytepack, iBuilder->simd_fill(8, iBuilder->getInt8(51)));
569    Value * mask_eq_62 = iBuilder->simd_eq(8, bytepack, iBuilder->simd_fill(8, iBuilder->getInt8(62)));
570    Value * mask_eq_63 = iBuilder->simd_eq(8, bytepack, iBuilder->simd_fill(8, iBuilder->getInt8(63)));
571    Value * t0_25 = iBuilder->simd_add(8, bytepack, iBuilder->simd_fill(8, iBuilder->getInt8('A')));
572    Value * t0_51 = iBuilder->simd_add(8, t0_25, iBuilder->simd_and(mask_gt_25, iBuilder->simd_fill(8, iBuilder->getInt8(6))));
573    Value * t0_61 = iBuilder->simd_sub(8, t0_51, iBuilder->simd_and(mask_gt_51, iBuilder->simd_fill(8, iBuilder->getInt8(75))));
574    Value * t0_62 = iBuilder->simd_sub(8, t0_61, iBuilder->simd_and(mask_eq_62, iBuilder->simd_fill(8, iBuilder->getInt8(15))));
575    Value * base64pack = iBuilder->simd_sub(8, t0_62, iBuilder->simd_and(mask_eq_63, iBuilder->simd_fill(8, iBuilder->getInt8(2))));
576    Value * base64streamPtr = getStream(self, "base64stream", blockNo, iBuilder->getInt32(0), idx);
577    iBuilder->CreateBlockAlignedStore(iBuilder->bitCast(base64pack), base64streamPtr);
578    idx->addIncoming(iBuilder->CreateAdd(idx, ConstantInt::get(iBuilder->getInt32Ty(), 1)), base64_loop);
579    Value* remainAfterLoop = iBuilder->CreateSub(loopRemain, packSize);
580    loopRemain->addIncoming(remainAfterLoop, base64_loop);
581
582    Value* continueLoop = iBuilder->CreateICmpULT(remainAfterLoop, packSize);
583    iBuilder->CreateCondBr(continueLoop, base64_loop, loopExit);
584
585    iBuilder->SetInsertPoint(loopExit);
586    iBuilder->CreateCondBr(iBuilder->CreateICmpEQ(padBytes, iBuilder->getSize(0)), fbExit, doPadding);
587
588    iBuilder->SetInsertPoint(doPadding);
589    Value * i8output_ptr = getStreamView(iBuilder->getInt8PtrTy(), self, "base64stream", blockNo, iBuilder->getInt32(0));
590    iBuilder->CreateStore(ConstantInt::get(iBuilder->getInt8Ty(), '='), iBuilder->CreateGEP(i8output_ptr, remainingBytes));
591    iBuilder->CreateCondBr(iBuilder->CreateICmpEQ(remainMod4, iBuilder->getSize(3)), fbExit, doPadding2);
592    iBuilder->SetInsertPoint(doPadding2);
593    Value * finalPadPos = iBuilder->CreateAdd(remainingBytes, iBuilder->getSize(1));
594    iBuilder->CreateStore(ConstantInt::get(iBuilder->getInt8Ty(), '='), iBuilder->CreateGEP(i8output_ptr, finalPadPos));
595    iBuilder->CreateBr(fbExit);
596    iBuilder->SetInsertPoint(fbExit);
597    Value * produced = iBuilder->CreateAdd(getProducedItemCount(self, "base64stream"), iBuilder->CreateAdd(remainingBytes, padBytes));
598    setProducedItemCount(self, "base64stream", produced);
599    iBuilder->CreateRetVoid();
600    iBuilder->restoreIP(savePoint);
601}
602
603void base64Kernel::generateDoBlockMethod() const {
604    auto savePoint = iBuilder->saveIP();
605
606    Function * doBlockFunction = iBuilder->getModule()->getFunction(mKernelName + doBlock_suffix);
607
608    iBuilder->SetInsertPoint(BasicBlock::Create(iBuilder->getContext(), "entry", doBlockFunction, 0));
609
610    Value * self = getParameter(doBlockFunction, "self");
611    Value * blockNo = getScalarField(self, blockNoScalar);
612
613    generateDoBlockLogic(self, blockNo);
614
615    iBuilder->CreateRetVoid();
616    iBuilder->restoreIP(savePoint);
617}
618
619}
Note: See TracBrowser for help on using the repository browser.