diff --git a/src/main.c b/src/main.c index 347d860..f9b45b8 100644 --- a/src/main.c +++ b/src/main.c @@ -152,11 +152,20 @@ static int nbsp_ws; * split across cores (see count_mapped_mb). */ static int utf8_mb; +/* AVX-512 is here and the text is UTF-8: dense CJK can be counted a + * window at a time (see cjk_window). */ +static int cjk_fast; + /* Whether a single file may be sliced across cores. The file-list pool * turns this off: a worker per core is already the parallelism, and a * second layer on top of it only oversubscribes. */ static int slice_files = 1; +/* -c alone, or -m where a character is a byte: the file size is the + * count, so the file never has to be read. Set once the locale is + * known. */ +static int units_only; + /* * Word separators for the byte path match GNU wc 9.11: the locale's * isspace() bytes plus U+00A0, which GNU reaches through btoc32's @@ -651,6 +660,8 @@ static count_lw_fn count_lw = count_lw_scalar; /* chosen by pick_kernel() */ static int pick_threads(size_t n); /* the slicers below pick their width */ +static long page_size(void); /* a page-aligned size is not trusted */ + static void count_mapped(const unsigned char *p, size_t n, counts_t *c, int need_high, int *high); @@ -703,6 +714,13 @@ static void init_count_state(void) /* Only UTF-8 can be split: every other multibyte encoding in * practice carries shift state or partial sequences. */ utf8_mb = cs != NULL && strstr(cs, "UTF-8") != NULL; +#if defined(__x86_64__) || defined(__i386__) + if (utf8_mb) + { + __builtin_cpu_init(); + cjk_fast = __builtin_cpu_supports("avx512bw"); + } +#endif } if (flags & F_WORDS) { @@ -723,6 +741,8 @@ static void init_count_state(void) count_lw = pick_kernel(); if (flags & F_MAXLEN) width_count = pick_width(); + units_only = (flags & ~(F_BYTES | F_CHARS)) == 0 && + ((flags & F_CHARS) == 0 || MB_CUR_MAX <= 1); } /* @@ -1196,7 +1216,12 @@ static size_t find_line_end(const unsigned char *s, size_t n, size_t from) static width_fn pick_width(void) { #if defined(__x86_64__) || defined(__i386__) - if (in_c_locale) + /* The C locale and any UTF-8 locale agree on what a width kernel + * needs to know: isprint() covers exactly 0x20..0x7e and every byte + * from 0x80 up is part of a sequence, never a column. Other single + * byte locales (ISO-8859-1 and friends) print their high bytes, so + * they keep the scalar walk. */ + if (in_c_locale || utf8_mb) { __builtin_cpu_init(); if (__builtin_cpu_supports("avx512vbmi2")) @@ -1492,6 +1517,200 @@ static int sample_high(const unsigned char *p, size_t n) return 0; } +/* + * The Unicode white space set, as the three-byte UTF-8 sequences that + * carry it. count_stream_mb asks is_wspace(); this answers the same + * question without a call, which is what dense CJK text needs - every + * character there is a three-byte sequence, and almost none of them are + * white space. + */ +static int mb_ws3(unsigned char b0, unsigned char b1, unsigned char b2) +{ + if (b0 == 0xe1) + return b1 == 0x9a && b2 == 0x80; /* U+1680 ogham space */ + if (b0 == 0xe2) + { + if (b1 == 0x80) + { + if (b2 <= 0x8a) + return b2 != 0x87 || !posixly_correct; /* U+2000..200A */ + return b2 == 0xa8 || b2 == 0xa9 || + (b2 == 0xaf && !posixly_correct); /* 2028 2029 202F */ + } + return b1 == 0x81 && b2 == 0x9f; /* U+205F */ + } + return b0 == 0xe3 && b1 == 0x80 && b2 == 0x80; /* U+3000 */ +} + +/* + * Code points whose display width is two in every wcwidth this program + * is ever built against: CJK unified ideographs and extension A, Hangul + * syllables, and the Hangul Jamo block. The kana block is deliberately + * not here: it contains combining marks (U+3099, U+309A) whose width is + * zero, and a blanket rule there is how a width count goes wrong by two. + * Everything else asks wcwidth(). + */ +static int wide_width(uint32_t cp) +{ + return (cp >= 0x1100 && cp <= 0x115f) || (cp >= 0x3400 && cp <= 0x4dbf) || + (cp >= 0x4e00 && cp <= 0x9fff) || (cp >= 0xac00 && cp <= 0xd7a3); +} + +/* + * One 64-byte block of ASCII and three-byte characters, counted from + * masks instead of a character loop. Dense CJK is exactly this shape: + * ideographs and ASCII punctuation, no two- or four-byte sequences. + * + * The block is accepted only when every byte is ASCII, a three-byte lead + * or a continuation of one; when the continuations sit exactly one and + * two bytes after a lead; when no character runs off the end; and when + * no lead is an overlong or a surrogate. Then: + * + * characters = bytes - continuations (each lead has two) + * lines = the '\n' bytes + * words = transitions of a byte-level white-space mask, in which + * every byte of a white-space character is marked, so a + * byte transition is a character transition + * + * Returns 64 on success, 0 when the block is not that shape and the + * caller should decode a character at a time. -L is not served here: a + * display width needs the character, which this block never forms. + */ +#if defined(__x86_64__) || defined(__i386__) +__attribute__((target("avx512f,avx512bw"))) static int +cjk_block(const unsigned char *s, int need_lines, int need_words, + int need_chars, int *prev_ws, long long *lines, long long *words, + long long *chars) +{ + const __m512i v = _mm512_loadu_si512((const void *)s); + const __m512i low80 = _mm512_set1_epi8((char)0x80); + __mmask64 ascii = _mm512_cmplt_epu8_mask(v, low80); + __mmask64 lead3 = _mm512_cmpeq_epi8_mask( + _mm512_and_si512(v, _mm512_set1_epi8((char)0xf0)), + _mm512_set1_epi8((char)0xe0)); + __mmask64 cont = _mm512_cmpeq_epi8_mask( + _mm512_and_si512(v, _mm512_set1_epi8((char)0xc0)), + _mm512_set1_epi8((char)0x80)); + + if ((ascii | lead3 | cont) != ~(__mmask64)0) + return 0; /* a two- or four-byte lead, or a stray continuation */ + + { + /* Where the last complete character ends. A lead at 62 or 63 + * finishes past the block, so the block stops before it and the + * next one starts on that character: every block then begins and + * ends on a character boundary, and nothing has to be carried. */ + int last = 63 - __builtin_clzll((unsigned long long)lead3); + unsigned adv = last >= 62 ? (unsigned)last : 64u; + __mmask64 body = + adv == 64 ? ~(__mmask64)0 : (((__mmask64)1 << adv) - 1); + + if ((ascii | lead3 | cont) != ~(__mmask64)0) + return 0; + if ((cont & body) != (((lead3 << 1) | (lead3 << 2)) & body)) + return 0; /* a continuation not where a lead put it */ + + { + __mmask64 at_e0 = + _mm512_cmpeq_epi8_mask(v, _mm512_set1_epi8((char)0xe0)); + __mmask64 at_ed = + _mm512_cmpeq_epi8_mask(v, _mm512_set1_epi8((char)0xed)); + + /* U+0800 and up needs a second byte of at least 0xA0; the + * surrogate range stops at 0x9F. */ + if ((at_e0 & + (_mm512_cmplt_epu8_mask(v, _mm512_set1_epi8((char)0xa0)) >> + 1)) || + (at_ed & + (_mm512_cmpgt_epu8_mask(v, _mm512_set1_epi8((char)0x9f)) >> + 1))) + return 0; + } + + if (need_chars) + *chars += (long long)__builtin_popcountll(~cont & body); + + if (need_lines) + *lines += (long long)__builtin_popcountll( + _mm512_cmpeq_epi8_mask(v, _mm512_set1_epi8('\n')) & body); + + if (need_words) + { + __m512i d = _mm512_sub_epi8(v, _mm512_set1_epi8(9)); + __mmask64 ws = (_mm512_cmple_epu8_mask(d, _mm512_set1_epi8(4)) | + _mm512_cmpeq_epi8_mask(v, _mm512_set1_epi8(' '))) & + body; + + /* The Unicode spaces that are three bytes long, matched on + * their bytes. A lead that could be one is looked at; every + * other lead is a word character. */ + if ((lead3 & body & + _mm512_cmple_epu8_mask(v, _mm512_set1_epi8((char)0xe3))) != 0) + { + __mmask64 e1 = + _mm512_cmpeq_epi8_mask(v, _mm512_set1_epi8((char)0xe1)); + __mmask64 e2 = + _mm512_cmpeq_epi8_mask(v, _mm512_set1_epi8((char)0xe2)); + __mmask64 e3 = + _mm512_cmpeq_epi8_mask(v, _mm512_set1_epi8((char)0xe3)); + __mmask64 b80 = + _mm512_cmpeq_epi8_mask(v, _mm512_set1_epi8((char)0x80)); + __mmask64 b81 = + _mm512_cmpeq_epi8_mask(v, _mm512_set1_epi8((char)0x81)); + __mmask64 le8a = + _mm512_cmple_epu8_mask(v, _mm512_set1_epi8((char)0x8a)); + __mmask64 hit; + + if (posixly_correct) + le8a &= ~_mm512_cmpeq_epi8_mask( + v, _mm512_set1_epi8((char)0x87)); + hit = + (e1 & + (_mm512_cmpeq_epi8_mask(v, _mm512_set1_epi8((char)0x9a)) >> + 1) & + (b80 >> 2)) | /* U+1680 */ + (e2 & (b80 >> 1) & (le8a >> 2)) | /* 2000..200A */ + (e2 & (b80 >> 1) & + ((_mm512_cmpeq_epi8_mask(v, _mm512_set1_epi8((char)0xa8)) | + _mm512_cmpeq_epi8_mask(v, + _mm512_set1_epi8((char)0xa9))) >> + 2)) | /* 2028, 2029 */ + (e2 & (b81 >> 1) & + (_mm512_cmpeq_epi8_mask(v, _mm512_set1_epi8((char)0x9f)) >> + 2)) | /* U+205F */ + (e3 & (b80 >> 1) & (b80 >> 2)); /* U+3000 */ + if (!posixly_correct) + hit |= e2 & (b80 >> 1) & + (_mm512_cmpeq_epi8_mask( + v, _mm512_set1_epi8((char)0xaf)) >> + 2); /* U+202F */ + ws |= (hit | (hit << 1) | (hit << 2)) & body; + } + *words += (long long)__builtin_popcountll( + ~ws & (((ws << 1) | (__mmask64)(*prev_ws != 0)) & body)); + *prev_ws = (int)((ws >> (adv - 1)) & 1); + } + return (int)adv; + } +} +#else +/* No AVX-512: the character loop counts this text, correctly and slowly. */ +static int cjk_block(const unsigned char *s, int need_lines, int need_words, + int need_chars, int *prev_ws, long long *lines, + long long *words, long long *chars) +{ + (void)s; + (void)need_lines; + (void)need_words; + (void)need_chars; + (void)prev_ws; + (void)lines; + (void)words; + (void)chars; + return 0; +} +#endif /* x86 */ + typedef struct { const unsigned char *s; @@ -1513,6 +1732,7 @@ static int count_chunk_mb(const unsigned char *s, size_t n, mbjob_t *j) int need_chars = (flags & F_CHARS) != 0; int need_maxlen = (flags & F_MAXLEN) != 0; int prev_ws = 1; + int block_budget = 8; /* consecutive refused blocks before giving up */ long long linepos = 0, maxlen = 0; size_t i = 0; @@ -1535,29 +1755,63 @@ static int count_chunk_mb(const unsigned char *s, size_t n, mbjob_t *j) if (need_maxlen) linepos = width_count(s + i, e - i, linepos, &maxlen); i = e; + block_budget = 8; /* a fresh stretch, a fresh chance */ } if (i >= n) break; + /* Sixty-four bytes of ASCII and three-byte characters at a + * time. A block that is not exactly that shape is decoded below, + * one character at a time; after a few refusals in a row the + * block check stops being worth its cost until the next ASCII + * stretch. */ + if (cjk_fast && !need_maxlen && block_budget > 0 && i + 64 <= n) + { + int used = cjk_block(s + i, need_lines, need_words, need_chars, + &prev_ws, &j->lines, &j->words, &j->chars); + + if (used) + { + block_budget = 8; + i += (size_t)used; + continue; + } + block_budget--; + } + + unsigned char b0 = s[i]; uint32_t cp; - int len = utf8_decode(s + i, n - i, &cp); + int len, ws, w = 0; - if (len == 0) + if (b0 >= 0xe1 && b0 <= 0xef && b0 != 0xed && i + 3 <= n && + (s[i + 1] & 0xc0) == 0x80 && (s[i + 2] & 0xc0) == 0x80) { - j->ok = 0; - return 0; + /* Three bytes, no overlong and no surrogate: the shape of + * every CJK character, and the answer without a call. */ + cp = ((uint32_t)(b0 & 0x0f) << 12) | + ((uint32_t)(s[i + 1] & 0x3f) << 6) | + (uint32_t)(s[i + 2] & 0x3f); + len = 3; + ws = mb_ws3(b0, s[i + 1], s[i + 2]); + if (need_maxlen) + w = wide_width(cp) ? 2 : wcwidth((wchar_t)cp); } - if (need_maxlen) + else { - int w = wcwidth((wchar_t)cp); - - if (w > 0) - linepos += w; + len = utf8_decode(s + i, n - i, &cp); + if (len == 0) + { + j->ok = 0; + return 0; + } + ws = is_wspace((wchar_t)cp); + if (need_maxlen) + w = wcwidth((wchar_t)cp); } + if (need_maxlen && w > 0) + linepos += w; if (need_words) { - int ws = is_wspace((wchar_t)cp); - if (prev_ws && !ws) j->words++; prev_ws = ws; @@ -1712,25 +1966,17 @@ static void count_stream(FILE *fp, counts_t *c) * byte): GNU sizes regular files with lseek instead of reading, but * a page-aligned st_size (proc-like files report an approximate * size) gets a tail read. */ - int units_only = (flags & ~(F_BYTES | F_CHARS)) == 0 && - ((flags & F_CHARS) == 0 || MB_CUR_MAX <= 1); - if (units_only) { - static long page; off_t end, cur, hi; - if (page <= 0) - page = sysconf(_SC_PAGESIZE); - if (page <= 0) - page = 4096; if (fstat(fd, &st) == 0 && S_ISREG(st.st_mode) && st.st_size >= 0) { cur = lseek(fd, 0, SEEK_CUR); if (cur >= 0) { end = st.st_size; - if (end % page != 0) + if (end % page_size() != 0) { c->bytes = end > cur ? end - cur : 0; if (c->bytes && lseek(fd, c->bytes, SEEK_CUR) >= 0) @@ -1788,10 +2034,15 @@ static void count_stream(FILE *fp, counts_t *c) /* The byte-path counts are invalid here. Discard them * and decode - split across cores when the mapping is * well-formed UTF-8, serially when it is not. The - * stream is still at 0 (mmap never advanced it). */ + * stream is still at 0 (mmap never advanced it), and + * a chunked pass that bailed left partial counts + * behind, so the snapshot is restored either way. */ *c = save; if (!decode || !count_mapped_mb(p, n, c)) + { + *c = save; count_stream_mb(fp, c); + } } munmap(m, n); if (ferror(fp)) @@ -2203,6 +2454,63 @@ static void count_mapped(const unsigned char *p, size_t n, counts_t *c, * calls and stdio only locks them one by one. */ static pthread_mutex_t err_lock = PTHREAD_MUTEX_INITIALIZER; +/* The page size, once. A page-aligned st_size may be an estimate from a + * proc-like file, so it gets a tail read instead of being trusted. */ +static long page_size(void) +{ + static long page; + + if (page <= 0) + { + page = sysconf(_SC_PAGESIZE); + if (page <= 0) + page = 4096; + } + return page; +} + +/* + * A bytes-only count is the file's size, so this path opens the file, + * asks, and closes it: no FILE, no buffer, no read. On a thousand small + * files that difference is most of the run. + * + * Returns 1 when the count is settled, 0 when the caller has to read the + * file (not a regular file, or a size that could be an estimate), -1 + * when the file could not be opened. + */ +static int count_units(const char *path, const struct stat *known, counts_t *c) +{ + struct stat st; + off_t end; + int fd = open(path, O_RDONLY); + + if (fd < 0) + return -1; + if (known != NULL) + st = *known; + else if (fstat(fd, &st) != 0) + { + close(fd); + return 0; + } + if (!S_ISREG(st.st_mode) || st.st_size < 0) + { + close(fd); + return 0; + } + end = st.st_size; + if (end % page_size() == 0) + { + close(fd); + return 0; /* page-aligned: count_stream reads the tail */ + } + c->bytes = end; + if (flags & F_CHARS) + c->chars = end; + close(fd); + return 1; +} + static void report_err(const char *name, int err) { pthread_mutex_lock(&err_lock); @@ -2229,6 +2537,20 @@ static void count_file(const char *path, counts_t *c) return; } + if (units_only) + { + int r = count_units(path, NULL, c); + + if (r > 0) + return; + if (r < 0) + { + report_err(path, errno); + c->ok = 0; + return; + } + } + fp = fopen(path, "rb"); if (fp == NULL) { @@ -2446,6 +2768,7 @@ static int process_name(const char *name, long record, counts_t *c) typedef struct { char *const *names; + const fstatus_t *fs; /* sizes already asked for, when there are any */ long n; long next; counts_t *res; @@ -2465,14 +2788,23 @@ static void *fpool_worker(void *arg) pthread_mutex_unlock(&p->lock); if (i >= p->n) break; - count_file(p->names[i], &p->res[i]); + if (units_only && p->fs != NULL && p->fs[i].failed == 0 && + S_ISREG(p->fs[i].st.st_mode) && p->fs[i].st.st_size >= 0) + { /* the size is the count, and we already asked */ + p->res[i].bytes = (long long)p->fs[i].st.st_size; + if (flags & F_CHARS) + p->res[i].chars = p->res[i].bytes; + } + else + count_file(p->names[i], &p->res[i]); } return NULL; } /* Count a whole list, in order, on a worker pool when the list is long * enough to pay for one. Returns 0 if any input failed. */ -static int count_names(char *const *names, long n, total_t *tot) +static int count_names(char *const *names, long n, const fstatus_t *fs, + total_t *tot) { counts_t *res; unsigned char *bad; @@ -2536,6 +2868,7 @@ static int count_names(char *const *names, long n, total_t *tot) } p.names = names; + p.fs = fs; p.n = n; p.next = 0; p.res = res; @@ -2834,10 +3167,10 @@ int main(int argc, char **argv) get_input_fstatus((int)n, names, fs); number_width = total_mode == TOTAL_ONLY ? 1 : compute_number_width((int)n, fs); - free(fs); - if (!count_names(names, n, &totals)) + if (!count_names(names, n, fs, &totals)) ok = 0; + free(fs); n_args = n; free(names); /* NOLINT: multi-level free is valid C */ free(names_buf); @@ -2919,11 +3252,11 @@ int main(int argc, char **argv) get_input_fstatus(nfiles, argv + optind, fs); number_width = total_mode == TOTAL_ONLY ? 1 : compute_number_width(nfiles, fs); - free(fs); n_args = nfiles; - if (!count_names(argv + optind, nfiles, &totals)) + if (!count_names(argv + optind, nfiles, fs, &totals)) ok = 0; + free(fs); } }