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

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

Support for write function in CBuilder, use IRBuilder CreateMemMove? for llvm.memmove.p0i8.p0i8.i64

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