source: icGREP/icgrep-devel/icgrep/u8u16.cpp @ 5169

Last change on this file since 5169 was 5154, checked in by cameron, 3 years ago

Fix for -gs mode from Xiangyu

File size: 18.3 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 *  icgrep is a trademark of International Characters.
5 */
6
7#include <string>
8#include <iostream>
9#include <fstream>
10#include <sstream>
11
12#include <llvm/IR/Function.h>
13#include <llvm/IR/Module.h>
14#include <llvm/ExecutionEngine/ExecutionEngine.h>
15#include <llvm/ExecutionEngine/MCJIT.h>
16#include <llvm/IRReader/IRReader.h>
17#include <llvm/IR/Verifier.h>
18#include <llvm/Support/Debug.h>
19
20#include <llvm/Support/CommandLine.h>
21
22#include <toolchain.h>
23#include <re/re_cc.h>
24#include <cc/cc_compiler.h>
25#include <pablo/pablo_toolchain.h>
26#include <pablo/pablo_kernel.h>
27#include <pablo/function.h>
28#include <IDISA/idisa_builder.h>
29#include <IDISA/idisa_target.h>
30#include <kernels/pipeline.h>
31#include <kernels/interface.h>
32#include <kernels/kernel.h>
33#include <kernels/s2p_kernel.h>
34#include <kernels/p2s_kernel.h>
35#include <kernels/deletion.h>
36#include <kernels/stdout_kernel.h>
37#include <llvm/IR/TypeBuilder.h>
38
39
40// mmap system
41#include <boost/filesystem.hpp>
42#include <boost/iostreams/device/mapped_file.hpp>
43
44#include <fcntl.h>
45static cl::OptionCategory u8u16Options("u8u16 Options",
46                                            "Transcoding control options.");
47
48static cl::list<std::string> inputFiles(cl::Positional, cl::desc("<input file ...>"), cl::OneOrMore, cl::cat(u8u16Options));
49
50static cl::opt<bool> pipelineParallel("enable-pipeline-parallel", cl::desc("Enable multithreading with pipeline parallelism."), cl::cat(u8u16Options));
51
52//
53//
54//
55namespace pablo {
56
57PabloFunction * u8u16_pablo() {
58    //  input: 8 basis bit streams
59    //  output: 16 u8-indexed streams, + delmask stream + error stream
60    PabloFunction * function = PabloFunction::Create("u8u16", 8, 18);
61    cc::CC_Compiler ccc(*function);
62   
63    PabloBuilder pBuilder(ccc.getBuilder().getPabloBlock(), ccc.getBuilder());
64    const std::vector<Var *> u8_bits = ccc.getBasisBits();
65    // Outputs
66    Assign * u16_hi[8];
67    Assign * u16_lo[8];
68    Assign * delmask;
69    Assign * error_mask;
70   
71    // The logic for processing non-ASCII bytes is to be embedded within an if-hierarchy.
72    PabloAST * nonASCII = ccc.compileCC(re::makeCC(0x80, 0xFF));
73   
74    // Builder for the if statement handling all non-ASCII logic
75    PabloBuilder nAb = PabloBuilder::Create(pBuilder);
76    // Bits 3 through 7 of a 2-byte prefix are data bits, needed to
77    // produce the UTF-16 code unit data ...,
78    PabloAST * bit3a1 = nAb.createAdvance(u8_bits[3], 1);
79    PabloAST * bit4a1 = nAb.createAdvance(u8_bits[4], 1);
80    PabloAST * bit5a1 = nAb.createAdvance(u8_bits[5], 1);
81    PabloAST * bit6a1 = nAb.createAdvance(u8_bits[6], 1);
82    PabloAST * bit7a1 = nAb.createAdvance(u8_bits[7], 1);
83   
84    // Entry condition for 3 or 4 byte sequences: we have a prefix byte in the range 0xE0-0xFF.
85    PabloAST * pfx34 = ccc.compileCC(re::makeCC(0xE0, 0xFF), nAb);
86    // Builder for the if statement handling all logic for 3- and 4-byte sequences.
87    PabloBuilder p34b = PabloBuilder::Create(nAb);
88    // Bits 4 through 7 of a 3-byte prefix are data bits.  They must be moved
89    // to the final position of the 3-byte sequence.
90    PabloAST * bit2a1 = p34b.createAdvance(u8_bits[2], 1);
91    PabloAST * bit4a2 = p34b.createAdvance(bit4a1, 1);
92    PabloAST * bit5a2 = p34b.createAdvance(bit5a1, 1);
93    PabloAST * bit6a2 = p34b.createAdvance(bit6a1, 1);
94    PabloAST * bit7a2 = p34b.createAdvance(bit7a1, 1);
95    //
96    // Logic for 4-byte UTF-8 sequences
97    //
98    // Entry condition  or 4 byte sequences: we have a prefix byte in the range 0xF0-0xFF.
99    PabloAST * pfx4 = ccc.compileCC(re::makeCC(0xF0, 0xFF), p34b);
100    // Builder for the if statement handling all logic for 4-byte sequences only.
101    PabloBuilder p4b = PabloBuilder::Create(p34b);
102    // Illegal 4-byte sequences
103    PabloAST * F0 = ccc.compileCC(re::makeCC(0xF0), p4b);
104    PabloAST * F4 = ccc.compileCC(re::makeCC(0xF4), p4b);
105    PabloAST * F0_err = p4b.createAnd(p4b.createAdvance(F0, 1), ccc.compileCC(re::makeCC(0x80, 0x8F), p4b));
106    PabloAST * F4_err = p4b.createAnd(p4b.createAdvance(F4, 1), ccc.compileCC(re::makeCC(0x90, 0xBF), p4b));
107    PabloAST * F5_FF = ccc.compileCC(re::makeCC(0xF5, 0xFF), p4b);
108    Assign * FX_err = p4b.createAssign("FX_err", p4b.createOr(F5_FF, p4b.createOr(F0_err, F4_err)));
109    //
110    // 4-byte prefixes have a scope that extends over the next 3 bytes.
111    Assign * u8scope42 = p4b.createAssign("u8scope42", p4b.createAdvance(pfx4, 1));
112    Assign * u8scope43 = p4b.createAssign("u8scope43", p4b.createAdvance(u8scope42, 1));
113    Assign * u8scope44 = p4b.createAssign("u8scope44", p4b.createAdvance(u8scope43, 1));
114    //
115   
116    //  From the 4-byte sequence 11110abc 10defghi 10jklmno 10pqrstu,
117    //  we must calculate the value abcde - 1 to produce the bit values
118    //  for u16_hi6, hi7, lo0, lo1 at the scope43 position.
119    Assign * s43_lo1 = p4b.createAssign("scope43_lo1", p4b.createAnd(u8scope43, p4b.createNot(bit3a1)));           // e - 1
120    Assign * s43_lo0 = p4b.createAssign("scope43_lo0", p4b.createAnd(u8scope43, p4b.createXor(bit2a1, s43_lo1)));  // d - borrow
121    PabloAST * brw1 = p4b.createAnd(s43_lo1, p4b.createNot(bit2a1));
122    Assign * s43_hi7 = p4b.createAssign("scope43_hi7", p4b.createAnd(u8scope43, p4b.createXor(bit7a2, brw1)));     // c - borrow
123    PabloAST * brw2 = p4b.createAnd(brw1, p4b.createNot(bit7a2));
124    Assign * s43_hi6 = p4b.createAssign("scope43_hi6", p4b.createAnd(u8scope43, p4b.createXor(bit6a2, brw2)));     // b - borrow
125    //
126    Assign * s43_lo2 = p4b.createAssign("scope43_lo2", p4b.createAnd(u8scope43, bit4a1));
127    Assign * s43_lo3 = p4b.createAssign("scope43_lo3", p4b.createAnd(u8scope43, bit5a1));
128    Assign * s43_lo4 = p4b.createAssign("scope43_lo4", p4b.createAnd(u8scope43, bit6a1));
129    Assign * s43_lo5 = p4b.createAssign("scope43_lo5", p4b.createAnd(u8scope43, bit7a1));
130    Assign * s43_lo6 = p4b.createAssign("scope43_lo6", p4b.createAnd(u8scope43, u8_bits[2]));
131    Assign * s43_lo7 = p4b.createAssign("scope43_lo7", p4b.createAnd(u8scope43, u8_bits[3]));
132    //
133    //
134    p34b.createIf(pfx4,
135                  {FX_err, u8scope42, u8scope43, u8scope44, s43_hi6, s43_hi7,
136                   s43_lo0, s43_lo1, s43_lo2, s43_lo3, s43_lo4, s43_lo5, s43_lo6, s43_lo7},
137                   p4b);
138    //
139    // Combined logic for 3 and 4 byte sequences
140    //
141    PabloAST * pfx3 = ccc.compileCC(re::makeCC(0xE0, 0xEF), p34b);
142    Assign * u8scope32 = p34b.createAssign("u8scope32", p34b.createAdvance(pfx3, 1));
143    Assign * u8scope33 = p34b.createAssign("u8scope33", p34b.createAdvance(u8scope32, 1));
144
145    // Illegal 3-byte sequences
146    PabloAST * E0 = ccc.compileCC(re::makeCC(0xE0), p34b);
147    PabloAST * ED = ccc.compileCC(re::makeCC(0xED), p34b);
148    PabloAST * E0_err = p34b.createAnd(p34b.createAdvance(E0, 1), ccc.compileCC(re::makeCC(0x80, 0x9F), p34b));
149    PabloAST * ED_err = p34b.createAnd(p34b.createAdvance(ED, 1), ccc.compileCC(re::makeCC(0xA0, 0xBF), p34b));
150    Assign * EX_FX_err = p34b.createAssign("EX_FX_err", p34b.createOr(p34b.createOr(E0_err, ED_err), FX_err));
151    // Two surrogate UTF-16 units are computed at the 3rd and 4th positions of 4-byte sequences.
152    PabloAST * surrogate = p34b.createOr(u8scope43, u8scope44);
153   
154    Assign * p34del = p34b.createAssign("p34del", p34b.createOr(u8scope32, u8scope42));
155
156
157    // The high 5 bits of the UTF-16 code unit are only nonzero for 3 and 4-byte
158    // UTF-8 sequences.
159    u16_hi[0] = p34b.createAssign("u16_hi0", p34b.createOr(p34b.createAnd(u8scope33, bit4a2), surrogate));
160    u16_hi[1] = p34b.createAssign("u16_hi1", p34b.createOr(p34b.createAnd(u8scope33, bit5a2), surrogate));
161    u16_hi[2] = p34b.createAssign("u16_hi2", p34b.createAnd(u8scope33, bit6a2));
162    u16_hi[3] = p34b.createAssign("u16_hi3", p34b.createOr(p34b.createAnd(u8scope33, bit7a2), surrogate));
163    u16_hi[4] = p34b.createAssign("u16_hi4", p34b.createOr(p34b.createAnd(u8scope33, bit2a1), surrogate));
164   
165    //
166    nAb.createIf(pfx34, 
167                 {u8scope33, EX_FX_err, p34del, 
168                  u16_hi[0], u16_hi[1], u16_hi[2], u16_hi[3], u16_hi[4], u8scope44, s43_hi6, s43_hi7,
169                  s43_lo0, s43_lo1, s43_lo2, s43_lo3, s43_lo4, s43_lo5, s43_lo6, s43_lo7},
170                 p34b);
171    //
172    // Combined logic for 2, 3 and 4 byte sequences
173    //
174    PabloAST * pfx2 = ccc.compileCC(re::makeCC(0xC0, 0xDF), nAb);
175    PabloAST * u8scope22 = nAb.createAdvance(pfx2, 1);
176    Assign * u8lastscope = nAb.createAssign("u8lastscope", nAb.createOr(u8scope22, nAb.createOr(u8scope33, u8scope44)));
177    PabloAST * u8anyscope = nAb.createOr(u8lastscope, p34del);
178
179    PabloAST * C0_C1_err = ccc.compileCC(re::makeCC(0xC0, 0xC1), nAb);
180    PabloAST * scope_suffix_mismatch = nAb.createXor(u8anyscope, ccc.compileCC(re::makeCC(0x80, 0xBF), nAb));
181    error_mask = nAb.createAssign("errormask", nAb.createOr(scope_suffix_mismatch, nAb.createOr(C0_C1_err, EX_FX_err)));
182    delmask = nAb.createAssign("delmask", nAb.createOr(p34del, ccc.compileCC(re::makeCC(0xC0, 0xFF), nAb)));
183   
184    // The low 3 bits of the high byte of the UTF-16 code unit as well as the high bit of the
185    // low byte are only nonzero for 2, 3 and 4 byte sequences.
186    u16_hi[5] = nAb.createAssign("u16_hi5", nAb.createOr(nAb.createAnd(u8lastscope, bit3a1), u8scope44));
187    u16_hi[6] = nAb.createAssign("u16_hi6", nAb.createOr(nAb.createAnd(u8lastscope, bit4a1), s43_hi6));
188    u16_hi[7] = nAb.createAssign("u16_hi7", nAb.createOr(nAb.createAnd(u8lastscope, bit5a1), s43_hi7));
189    u16_lo[0] = nAb.createAssign("u16_lo0", nAb.createOr(nAb.createAnd(u8lastscope, bit6a1), s43_lo0));
190    Assign * p234_lo1 = nAb.createAssign("p234_lo1", nAb.createOr(nAb.createAnd(u8lastscope, bit7a1), s43_lo1));
191
192    pBuilder.createIf(nonASCII, 
193                      {error_mask, delmask, u8lastscope,
194                       u16_hi[0], u16_hi[1], u16_hi[2], u16_hi[3], u16_hi[4], u16_hi[5], u16_hi[6], u16_hi[7],
195                       u16_lo[0], p234_lo1, s43_lo2, s43_lo3, s43_lo4, s43_lo5, s43_lo6, s43_lo7},
196                      nAb);
197    //
198    //
199    PabloAST * ASCII = ccc.compileCC(re::makeCC(0x0, 0x7F));
200    PabloAST * last_byte = pBuilder.createOr(ASCII, u8lastscope);
201    u16_lo[1] = pBuilder.createAssign("u16_lo1", pBuilder.createOr(pBuilder.createAnd(ASCII, u8_bits[1]), p234_lo1));
202    u16_lo[2] = pBuilder.createAssign("u16_lo2", pBuilder.createOr(pBuilder.createAnd(last_byte, u8_bits[2]), s43_lo2));
203    u16_lo[3] = pBuilder.createAssign("u16_lo3", pBuilder.createOr(pBuilder.createAnd(last_byte, u8_bits[3]), s43_lo3));
204    u16_lo[4] = pBuilder.createAssign("u16_lo4", pBuilder.createOr(pBuilder.createAnd(last_byte, u8_bits[4]), s43_lo4));
205    u16_lo[5] = pBuilder.createAssign("u16_lo5", pBuilder.createOr(pBuilder.createAnd(last_byte, u8_bits[5]), s43_lo5));
206    u16_lo[6] = pBuilder.createAssign("u16_lo6", pBuilder.createOr(pBuilder.createAnd(last_byte, u8_bits[6]), s43_lo6));
207    u16_lo[7] = pBuilder.createAssign("u16_lo7", pBuilder.createOr(pBuilder.createAnd(last_byte, u8_bits[7]), s43_lo7));
208   
209    for (unsigned i = 0; i < 8; i++) {
210        function->setResult(i, pBuilder.createAssign("u16_hi" + std::to_string(i), u16_hi[i]));
211        function->setResult(i+8, pBuilder.createAssign("u16_lo" + std::to_string(i), u16_lo[i]));
212    }
213    function->setResult(16, pBuilder.createAssign("delbits", delmask));
214    function->setResult(17, pBuilder.createAssign("errors", error_mask));
215
216    return function;
217}
218}
219
220
221
222using namespace kernel;
223using namespace parabix;
224
225const unsigned u16OutputBlocks = 64;
226
227Function * u8u16Pipeline(Module * mMod, IDISA::IDISA_Builder * iBuilder, pablo::PabloFunction * function) {
228    Type * mBitBlockType = iBuilder->getBitBlockType();
229
230    const unsigned segmentSize = codegen::SegmentSize;
231    const unsigned bufferSegments = codegen::BufferSegments;
232   
233    ExternalFileBuffer ByteStream(iBuilder, StreamSetType(1, i8));
234    //SingleBlockBuffer BasisBits(iBuilder, StreamSetType(8, i1));
235    CircularBuffer BasisBits(iBuilder, StreamSetType(8, i1), segmentSize * bufferSegments);
236
237    //SingleBlockBuffer U8u16Bits(iBuilder, StreamSetType(18, i1));
238    CircularBuffer U8u16Bits(iBuilder, StreamSetType(18, i1), segmentSize * bufferSegments);
239
240    //SingleBlockBuffer U16Bits(iBuilder, StreamSetType(16, i1));
241    CircularBuffer U16Bits(iBuilder, StreamSetType(16, i1), segmentSize * bufferSegments);
242   
243    //SingleBlockBuffer DeletionCounts(iBuilder, StreamSetType(1, i1));
244    CircularBuffer DeletionCounts(iBuilder, StreamSetType(1, i1), segmentSize * bufferSegments);
245   
246    CircularBuffer U16out(iBuilder, StreamSetType(1, i16), u16OutputBlocks);
247
248    s2pKernel  s2pk(iBuilder);
249    s2pk.generateKernel({&ByteStream}, {&BasisBits});
250
251    pablo_function_passes(function);
252    pablo::PabloKernel  u8u16k(iBuilder, "u8u16", function, {});
253    u8u16k.generateKernel({&BasisBits}, {&U8u16Bits});
254   
255    deletionKernel delK(iBuilder, iBuilder->getBitBlockWidth()/16, 16);
256    delK.generateKernel({&U8u16Bits}, {&U16Bits, &DeletionCounts});
257   
258    p2s_16Kernel_withCompressedOutput p2sk(iBuilder);
259    p2sk.generateKernel({&U16Bits, &DeletionCounts}, {&U16out});
260   
261    Type * const size_ty = iBuilder->getSizeTy();
262    Type * const voidTy = Type::getVoidTy(mMod->getContext());
263    Type * const inputType = PointerType::get(ArrayType::get(ArrayType::get(mBitBlockType, 8), 1), 0);
264    Type * const int32ty = iBuilder->getInt32Ty();
265    Type * const int8PtrTy = iBuilder->getInt8PtrTy();
266    Type * const voidPtrTy = TypeBuilder<void *, false>::get(mMod->getContext());
267
268   
269    Function * const main = cast<Function>(mMod->getOrInsertFunction("Main", voidTy, inputType, size_ty, nullptr));
270    main->setCallingConv(CallingConv::C);
271    Function::arg_iterator args = main->arg_begin();
272   
273    Value * const inputStream = &*(args++);
274    inputStream->setName("input");
275    Value * const fileSize = &*(args++);
276    fileSize->setName("fileSize");
277   
278    iBuilder->SetInsertPoint(BasicBlock::Create(mMod->getContext(), "entry", main,0));
279       
280
281    ByteStream.setStreamSetBuffer(inputStream, fileSize);
282    BasisBits.allocateBuffer();
283    U8u16Bits.allocateBuffer();
284    U16Bits.allocateBuffer();
285    DeletionCounts.allocateBuffer();
286    U16out.allocateBuffer();
287
288    Value * s2pInstance = s2pk.createInstance({});
289    Value * u8u16Instance = u8u16k.createInstance({});
290    Value * delInstance = delK.createInstance({});
291    Value * p2sInstance = p2sk.createInstance({});
292   
293    Type * pthreadTy = size_ty;
294    FunctionType * funVoidPtrVoidTy = FunctionType::get(voidTy, int8PtrTy, false);
295   
296    Function * pthreadCreateFunc = cast<Function>(mMod->getOrInsertFunction("pthread_create",
297                                                                         int32ty,
298                                                                         pthreadTy->getPointerTo(),
299                                                                         voidPtrTy,
300                                                                         static_cast<Type *>(funVoidPtrVoidTy)->getPointerTo(),
301                                                                         voidPtrTy, nullptr));
302    pthreadCreateFunc->setCallingConv(llvm::CallingConv::C);
303    Function * pthreadJoinFunc = cast<Function>(mMod->getOrInsertFunction("pthread_join",
304                                                                       int32ty,
305                                                                       pthreadTy,
306                                                                       PointerType::get(int8PtrTy, 0), nullptr));
307    pthreadJoinFunc->setCallingConv(llvm::CallingConv::C);
308   
309    Function * pthreadExitFunc = cast<Function>(mMod->getOrInsertFunction("pthread_exit",
310                                                                       voidTy, 
311                                                                       voidPtrTy, nullptr));
312    pthreadExitFunc->addFnAttr(llvm::Attribute::NoReturn);
313    pthreadExitFunc->setCallingConv(llvm::CallingConv::C);
314
315    if (pipelineParallel){
316        generatePipelineParallel(iBuilder, {&s2pk, &u8u16k, &delK, &p2sk}, {s2pInstance, u8u16Instance, delInstance, p2sInstance});
317    }
318    else{
319        generatePipelineLoop(iBuilder, {&s2pk, &u8u16k, &delK, &p2sk}, {s2pInstance, u8u16Instance, delInstance, p2sInstance}, fileSize);
320    }
321
322    iBuilder->CreateRetVoid();
323    return main;
324}
325
326
327
328
329
330typedef void (*u8u16FunctionType)(char * byte_data, size_t filesize);
331
332static ExecutionEngine * u8u16Engine = nullptr;
333
334u8u16FunctionType u8u16CodeGen(void) {
335                           
336    Module * M = new Module("u8u16", getGlobalContext());
337    IDISA::IDISA_Builder * idb = IDISA::GetIDISA_Builder(M);
338
339    pablo::PabloFunction * function = pablo::u8u16_pablo();
340   
341    llvm::Function * main_IR = u8u16Pipeline(M, idb, function);
342   
343    verifyModule(*M, &dbgs());
344    //std::cerr << "ExecuteKernels(); done\n";
345    u8u16Engine = JIT_to_ExecutionEngine(M);
346   
347    u8u16Engine->finalizeObject();
348    //std::cerr << "finalizeObject(); done\n";
349
350    delete idb;
351    return reinterpret_cast<u8u16FunctionType>(u8u16Engine->getPointerToFunction(main_IR));
352}
353
354void u8u16(u8u16FunctionType fn_ptr, const std::string & fileName) {
355    std::string mFileName = fileName;
356    size_t mFileSize;
357    char * mFileBuffer;
358   
359    const boost::filesystem::path file(mFileName);
360    if (exists(file)) {
361        if (is_directory(file)) {
362            return;
363        }
364    } else {
365        std::cerr << "Error: cannot open " << mFileName << " for processing. Skipped.\n";
366        return;
367    }
368   
369    mFileSize = file_size(file);
370    boost::iostreams::mapped_file_source mFile;
371    if (mFileSize == 0) {
372        mFileBuffer = nullptr;
373    }
374    else {
375        try {
376            mFile.open(mFileName);
377        } catch (std::exception &e) {
378            std::cerr << "Error: Boost mmap of " << mFileName << ": " << e.what() << std::endl;
379            return;
380        }
381        mFileBuffer = const_cast<char *>(mFile.data());
382    }
383    //std::cerr << "mFileSize =" << mFileSize << "\n";
384    //std::cerr << "fn_ptr =" << std::hex << reinterpret_cast<intptr_t>(fn_ptr) << "\n";
385
386    fn_ptr(mFileBuffer, mFileSize);
387
388    mFile.close();
389   
390}
391
392
393int main(int argc, char *argv[]) {
394    cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *>{&u8u16Options, pablo::pablo_toolchain_flags(), codegen::codegen_flags()});
395    cl::ParseCommandLineOptions(argc, argv);
396
397    u8u16FunctionType fn_ptr = u8u16CodeGen();
398
399    for (unsigned i = 0; i != inputFiles.size(); ++i) {
400        u8u16(fn_ptr, inputFiles[i]);
401    }
402
403    delete u8u16Engine;
404
405    return 0;
406}
407
408                       
Note: See TracBrowser for help on using the repository browser.