source: icGREP/icgrep-devel/icgrep/icgrep.cpp @ 4149

Last change on this file since 4149 was 4149, checked in by nmedfort, 5 years ago

Bug fix for empty file: outfile wasn't set prior to testing.

File size: 15.2 KB
Line 
1/*
2 *  Copyright (c) 2014 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 "icgrep.h"
8
9#include "utf_encoding.h"
10#include "re_compiler.h"
11
12#include <fstream>
13#include <sstream>
14#include <iostream>
15#include <string>
16#include <stdint.h>
17
18#include <stdio.h>
19#include <stdlib.h>
20#include <unistd.h>
21#include <errno.h>
22#include <sys/types.h>
23#include <sys/stat.h>
24
25#include <simd-lib/bitblock.hpp>
26#include <simd-lib/carryQ.hpp>
27#include <simd-lib/pabloSupport.hpp>
28#include <simd-lib/s2p.hpp>
29#include <simd-lib/buffer.hpp>
30#include <simd-lib/bitblock_iterator.hpp>
31
32// mmap system
33#include <sys/mman.h>
34#include <fcntl.h>
35
36
37#define SEGMENT_BLOCKS 7
38#define SEGMENT_SIZE (BLOCK_SIZE * SEGMENT_BLOCKS)
39
40#define BUFFER_SEGMENTS 15
41#define BUFFER_SIZE (BUFFER_SEGMENTS * SEGMENT_SIZE)
42
43#define BitBlock_declare(name)  BitBlock name
44
45#define ubitblock_declare(name, n) \
46  ubitblock name[n];\
47  do {int i;\
48      for (i = 0; i < n; i++) name[i]._128 = simd<1>::constant<0>();\
49     }\
50  while (0)
51
52BitBlock EOF_mask = simd<1>::constant<1>();
53
54struct Output {
55    BitBlock matches;
56    BitBlock LF;
57};
58
59#include <simd-lib/transpose.hpp>
60
61using namespace std;
62
63typedef void (*process_block_fcn)(const Basis_bits &basis_bits, BitBlock carry_q[], Output &output);
64
65
66#define USE_MMAP
67#ifndef USE_MMAP
68void do_process(FILE *infile, FILE *outfile, int count_only_option, int carry_count, process_block_fcn process_block);
69#endif
70#ifdef USE_MMAP
71void do_process(char * infile_buffer, size_t infile_size, FILE *outfile, int count_only_option, int carry_count, process_block_fcn process_block);
72#endif
73
74
75BitBlock get_category(Basis_bits &basis_bits, const char* category);
76
77int main(int argc, char *argv[])
78{
79    char * inregex, * fileregex, * infilename, * outfilename;
80    FILE *infile, *outfile, *regexfile;
81
82#ifdef USE_MMAP
83    int fdSrc;
84    struct stat infile_sb;
85    char * infile_buffer;
86#endif
87
88    int opt_code;
89    int count_only_option = 0;
90    int print_version_option = 0;
91    int regex_from_file_option = 0;
92    int ascii_only_option = 0;
93
94    int compile_time_option = 0;
95
96    unsigned long long cycles = 0;
97    double timer = 0;
98
99    long lSize = 0;
100
101    size_t result;
102
103    while ((opt_code = getopt(argc, argv, "cvfta")) != -1)
104    {
105        switch (opt_code)
106        {
107        case 'c':
108            count_only_option = 1;
109            break;
110        case 'v':
111            print_version_option = 1;
112            break;
113        case 'f':
114            regex_from_file_option = 1;
115            break;
116        case 't':
117            compile_time_option = 1;
118            break;
119        case 'a':
120            ascii_only_option = 1;
121            break;
122        case '?':
123            break;
124        default:
125            printf ("Invalid option: %c\n", opt_code);
126            printf("Usage: %s [-c] [-v] [-f] [-t] [-a] <regex|regexfile> <inputfile> [<outputfile>]\n", argv[0]);
127                    exit(-1);
128        }
129    }
130
131    if (optind >= argc)
132    {
133        printf ("Too few arguments\n");
134        printf("Usage: %s [-c] [-v] [-f] [-t] [-a] <regex|regexfile> <inputfile> [<outputfile>]\n", argv[0]);
135        exit(-1);
136    }
137
138    inregex = argv[optind++];
139    if (inregex == 0)
140    {
141        fprintf(stderr, "Error: cannot read the regular expression.\n");
142        exit(-1);
143    }
144
145    if (regex_from_file_option)
146    {
147        regexfile = fopen(inregex, "rb");
148        if (!regexfile){
149            fprintf(stderr, "Error: cannot open %s for processing.\n", inregex);
150            exit(-1);
151        }
152
153        fseek (regexfile , 0 , SEEK_END);
154        lSize = ftell (regexfile);
155        rewind (regexfile);
156
157        fileregex = (char*) malloc (sizeof(char)*lSize);
158        if (fileregex == NULL) {fputs ("Memory error",stderr); exit (2);}
159
160        result = fread (fileregex, 1, lSize, regexfile);
161        if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
162        fclose(regexfile);
163
164        if (fileregex[lSize - 1] == '\n') fileregex[lSize - 1] = '\0';
165    }
166
167    infilename = argv[optind++];
168#ifndef USE_MMAP
169    infile = fopen(infilename, "rb");
170    if (!infile) {
171        fprintf(stderr, "Error: cannot open %s for processing.\n", infilename);
172        exit(-1);
173    }
174#endif
175
176    if (optind >= argc) {
177        outfile = stdout;
178    }
179    else {
180        outfilename = argv[optind++];
181        if (optind != argc)
182        {
183            printf ("Too many arguments\n");
184            printf("Usage: %s [-c] [-v] [-f] [-t] [-a] <regex|regexfile> <inputfile> [<outputfile>]\n", argv[0]);
185            exit(-1);
186        }
187        outfile = fopen(outfilename, "wb");
188        if (!outfile)
189        {
190            fprintf(stderr, "Error: cannot open %s for writing.\n", outfilename);
191            exit(-1);
192        }
193    }
194
195#ifdef USE_MMAP
196    fdSrc = open(infilename, O_RDONLY);
197    if (fdSrc == -1) {
198        fprintf(stderr, "Error: cannot open %s for processing.\n", infilename);
199        exit(-1);
200    }
201    if (fstat(fdSrc, &infile_sb) == -1) {
202        fprintf(stderr, "Error: cannot stat %s for processing.\n", infilename);
203        exit(-1);
204    }
205    if (infile_sb.st_size == 0) {
206        if (count_only_option) fprintf(outfile, "Matching Lines: %d\n", 0);
207        exit(0);
208    }
209    infile_buffer = (char *) mmap(NULL, infile_sb.st_size, PROT_READ, MAP_PRIVATE, fdSrc, 0);
210    if (infile_buffer == MAP_FAILED) {
211        fprintf(stderr, "Error: mmap of %s failure.\n", infilename);
212        exit(-1);
213    }
214#endif
215
216    if (print_version_option)
217    {
218        fprintf(outfile, "Parabix icgrep implementation: August 2014\n");
219    }
220
221    UTF_Encoding encoding;
222    encoding.setName("UTF-8");
223    encoding.setBits(8);
224    encoding.setMask(0xFF);
225
226    RE_Compiler* re_compiler = new RE_Compiler();
227    if (compile_time_option)
228    {
229        cycles = get_hrcycles();
230        timer = getElapsedTime();
231    }
232    LLVM_Gen_RetVal llvm_codegen = re_compiler->compile(compile_time_option,
233                                                        ascii_only_option,
234                                                        "basis_bits.bit_",
235                                                        "temp",
236                                                        encoding ,
237                                                        (regex_from_file_option ? fileregex : inregex));
238
239    if (compile_time_option)
240    {
241        cycles = get_hrcycles() - cycles;
242        timer = getElapsedTime() - timer;
243        std::cout << "Total compile time - cycles:       " << cycles << std::endl;
244        std::cout << "Total compile time - milliseconds: " << timer << std::endl;
245    }
246
247    if (llvm_codegen.process_block_fptr != 0)
248    {
249        void (*FP)(const Basis_bits &basis_bits, BitBlock carry_q[], Output &output) = (void (*)(const Basis_bits &basis_bits, BitBlock carry_q[], Output &output))(void*)llvm_codegen.process_block_fptr;
250#ifndef USE_MMAP
251        do_process(infile, outfile, count_only_option, llvm_codegen.carry_q_size, FP);
252#endif
253#ifdef USE_MMAP
254        do_process(infile_buffer, infile_sb.st_size, outfile, count_only_option, llvm_codegen.carry_q_size, FP);
255#endif
256    }
257
258    delete re_compiler;
259#ifndef USE_MMAP
260    fclose(infile);
261#endif
262#ifdef USE_MMAP
263    munmap((void *) infile_buffer, infile_sb.st_size);
264    close(fdSrc);
265#endif
266    fclose(outfile);
267    if (regex_from_file_option) free(fileregex);
268
269    return 0;
270}
271
272
273typedef BitStreamScanner<BitBlock, uint32_t, uint32_t, SEGMENT_BLOCKS> ScannerT;
274
275//
276// Write matched lines from a buffer to an output file, given segment
277// scanners for line ends and matches (where matches are a subset of line ends).
278// The buffer pointer must point to the first byte of the segment
279// corresponding to the scanner indexes.   The first_line_start is the
280// start position of the first line relative to the buffer start position.
281// It must be zero or negative;  if negative, the buffer must permit negative
282// indexing so that the lineup to the buffer start position can also be printed.
283// The start position of the final line in the processed segment is returned.
284//
285
286ssize_t write_matches(FILE * outfile, ScannerT line_scanner, ScannerT match_scanner, char * buffer, ssize_t first_line_start) {
287
288  ssize_t line_start = first_line_start;
289  size_t match_pos;
290  size_t line_end;
291  while (match_scanner.has_next()) {
292    match_pos = match_scanner.scan_to_next();
293    // If we found a match, it must be at a line end.
294    line_end = line_scanner.scan_to_next();
295    while (line_end < match_pos) {
296      line_start = line_end + 1;
297      line_end = line_scanner.scan_to_next();
298    }
299    fwrite(&buffer[line_start], 1, line_end - line_start + 1, outfile);
300    line_start = line_end + 1;
301
302  }
303  while(line_scanner.has_next()) {
304    line_end = line_scanner.scan_to_next();
305    line_start = line_end+1;
306  }
307  return line_start;
308}
309
310
311
312#ifndef USE_MMAP
313void do_process(FILE *infile, FILE *outfile, int count_only_option, int carry_count, process_block_fcn process_block) {
314#endif
315#ifdef USE_MMAP
316void do_process(char * infile_buffer, size_t infile_size, FILE *outfile, int count_only_option, int carry_count, process_block_fcn process_block) {
317#endif
318
319    struct Basis_bits basis_bits;
320    struct Output output;
321
322    BitBlock carry_q[carry_count];
323    memset (carry_q, 0, sizeof(BitBlock) * carry_count);
324
325    BitBlock match_vector = simd<1>::constant<0>();
326    int match_count=0;
327    int blk = 0;
328    int block_base  = 0;
329    int block_pos   = 0;
330    int buffer_pos  = 0;
331    int chars_avail = 0;
332    int chars_read  = 0;
333
334    int line_start = 0;
335    int line_end = 0;
336    int match_pos = 0;
337    int line_no = 0;
338
339    ScannerT LF_scanner;
340    ScannerT match_scanner;
341
342    char * buffer_ptr;
343#ifndef USE_MMAP
344    ATTRIBUTE_SIMD_ALIGN char src_buffer[SEGMENT_SIZE];
345    buffer_ptr = &src_buffer;
346    chars_read = fread((void *)&src_buffer[0], 1, SEGMENT_SIZE, infile);
347    chars_avail = chars_read;
348    if (chars_avail >= SEGMENT_SIZE) chars_avail = SEGMENT_SIZE;
349#endif
350#ifdef USE_MMAP
351    int segment = 0;
352    int segment_base = 0;
353    chars_avail = infile_size;
354
355#endif
356//////////////////////////////////////////////////////////////////////////////////////////
357// Full Segments
358//////////////////////////////////////////////////////////////////////////////////////////
359
360
361
362    while (chars_avail >= SEGMENT_SIZE) {
363
364#ifdef USE_MMAP
365        segment_base = segment * SEGMENT_SIZE;
366#endif
367        LF_scanner.init();
368        match_scanner.init();
369
370        for (blk = 0; blk < SEGMENT_BLOCKS; blk++) {
371#ifndef USE_MMAP
372            block_base = blk*BLOCK_SIZE;
373            s2p_do_block((BytePack *) &src_buffer[block_base], basis_bits);
374#endif
375#ifdef USE_MMAP
376            block_base = blk*BLOCK_SIZE + segment_base;
377            s2p_do_block((BytePack *) &infile_buffer[block_base], basis_bits);
378#endif
379            process_block(basis_bits, carry_q, output);
380
381            LF_scanner.load_block(output.LF, blk);
382            match_scanner.load_block(output.matches, blk);
383            if (count_only_option){
384                if (bitblock::any(output.matches))
385                {
386                    if (bitblock::any(simd_and(match_vector, output.matches))){
387                        match_count += bitblock::popcount(match_vector);
388                        match_vector = output.matches;
389                    }
390                    else
391                    {
392                        match_vector = simd_or(match_vector, output.matches);
393                    }
394                }
395            }
396        }
397
398#ifndef USE_MMAP
399        int copy_back_pos = 0;
400
401
402        if (LF_scanner.count() > 0) {
403            copy_back_pos = LF_scanner.get_final_pos() + 1;
404            memset (carry_q, 0, sizeof(BitBlock) * carry_count);
405        }
406        else {
407            copy_back_pos =  SEGMENT_SIZE;
408        }
409
410        int  copy_back_size = SEGMENT_SIZE - copy_back_pos;
411#endif
412#ifdef USE_MMAP
413    buffer_ptr = &infile_buffer[segment_base];
414#endif
415
416        if (!count_only_option) {
417          line_start = write_matches(outfile, LF_scanner, match_scanner, buffer_ptr, line_start);
418        }
419#ifndef USE_MMAP
420        memmove(&src_buffer[0], &src_buffer[copy_back_pos], copy_back_size);
421
422        //Do another read.
423        chars_read = fread(&src_buffer[copy_back_size], 1, copy_back_pos, infile);
424        chars_avail = chars_read + copy_back_size;
425        if (chars_avail >= SEGMENT_SIZE) chars_avail = SEGMENT_SIZE;
426        buffer_pos += chars_avail;
427#endif
428#ifdef USE_MMAP
429        segment++;
430        line_start -= SEGMENT_SIZE;  /* Will be negative offset for use within next segment. */
431        chars_avail -= SEGMENT_SIZE;
432
433#endif
434    }
435
436
437//////////////////////////////////////////////////////////////////////////////////////////
438// For the Final Partial Segment.
439//////////////////////////////////////////////////////////////////////////////////////////
440
441#ifdef USE_MMAP
442    segment_base = segment * SEGMENT_SIZE;
443#endif
444    int remaining = chars_avail;
445
446    LF_scanner.init();
447    match_scanner.init();
448
449    /* Full Blocks */
450    blk = 0;
451    while (remaining >= BLOCK_SIZE) {
452    //fprintf(outfile, "Remaining = %i\n", remaining);
453#ifndef USE_MMAP
454        block_base = block_pos;
455        s2p_do_block((BytePack *) &src_buffer[block_base], basis_bits);
456#endif
457#ifdef USE_MMAP
458        block_base = block_pos + segment_base;
459        s2p_do_block((BytePack *) &infile_buffer[block_base], basis_bits);
460#endif
461        process_block(basis_bits, carry_q, output);
462
463        LF_scanner.load_block(output.LF, blk);
464        match_scanner.load_block(output.matches, blk);
465        if (count_only_option)
466        {
467            if (bitblock::any(output.matches))
468            {
469                if (bitblock::any(simd_and(match_vector, output.matches)))
470                {
471                    match_count += bitblock::popcount(match_vector);
472                    match_vector = output.matches;
473                }
474                else
475                {
476                    match_vector = simd_or(match_vector, output.matches);
477                }
478            }
479        }
480
481        block_pos += BLOCK_SIZE;
482        remaining -= BLOCK_SIZE;
483        blk++;
484    }
485    block_base = block_pos;
486    //fprintf(stderr, "Remaining = %i\n", remaining);
487
488    //For the last partial block, or for any carry.
489    EOF_mask = bitblock::srl(simd<1>::constant<1>(), convert(BLOCK_SIZE-remaining));
490#ifndef USE_MMAP
491     block_base = block_pos;
492     s2p_do_final_block((BytePack *) &src_buffer[block_base], basis_bits, EOF_mask);
493#endif
494#ifdef USE_MMAP
495     block_base = block_pos + segment_base;
496     s2p_do_final_block((BytePack *) &infile_buffer[block_base], basis_bits, EOF_mask);
497#endif
498    process_block(basis_bits, carry_q, output);
499
500    if (count_only_option)
501    {
502        match_count += bitblock::popcount(match_vector);
503        if (bitblock::any(output.matches))
504        {
505            match_count += bitblock::popcount(output.matches);
506        }
507        fprintf(outfile, "Matching Lines:%d\n", match_count);
508    }
509    else
510    {
511        LF_scanner.load_block(output.LF, blk);
512        match_scanner.load_block(output.matches, blk);
513        blk++;
514        for (int i = blk; i < SEGMENT_BLOCKS; i++)
515        {
516            LF_scanner.load_block(simd<1>::constant<0>(), i);
517            match_scanner.load_block(simd<1>::constant<0>(), i);
518        }
519#ifndef USE_MMAP
520        line_start = 0;
521#endif
522#ifdef USE_MMAP
523        buffer_ptr = &infile_buffer[segment_base];
524#endif
525        line_start = write_matches(outfile, LF_scanner, match_scanner, buffer_ptr, line_start);
526    }
527
528    buffer_pos += chars_avail;
529}
530
531
532
Note: See TracBrowser for help on using the repository browser.