-
-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathtable-lookup.ts
More file actions
381 lines (313 loc) · 10.1 KB
/
Copy pathtable-lookup.ts
File metadata and controls
381 lines (313 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
import * as assert from 'assert';
import * as frontend from 'llparse-frontend';
import { Node } from './base';
const MAX_CHAR = 0xff;
const TABLE_GROUP = 16;
// _mm_cmpestri takes 8 ranges
const SSE_RANGES_LEN = 16;
// _mm_cmpestri takes 128bit input
const SSE_RANGES_PAD = 16;
const MAX_SSE_CALLS = 2;
const MAX_NEON_RANGES = 6;
const MAX_WASM_RANGES = 6;
const SSE_ALIGNMENT = 16;
interface ITable {
readonly name: string;
readonly declaration: ReadonlyArray<string>;
}
export class TableLookup extends Node<frontend.node.TableLookup> {
public doBuild(out: string[]): void {
const ctx = this.compilation;
const table = this.buildTable();
for (const line of table.declaration) {
out.push(line);
}
this.prologue(out);
const transform = ctx.unwrapTransform(this.ref.transform!);
// Try to vectorize nodes matching characters and looping to themselves
// NOTE: `switch` below triggers when there is not enough characters in the
// stream for vectorized processing.
if (this.canVectorize()) {
this.buildSSE(out);
this.buildNeon(out);
this.buildWASM(out);
}
const current = transform.build(ctx, `*${ctx.posArg()}`);
out.push(`switch (${table.name}[(uint8_t) ${current}]) {`);
for (const [ index, edge ] of this.ref.edges.entries()) {
out.push(` case ${index + 1}: {`);
const tmp: string[] = [];
this.tailTo(tmp, {
noAdvance: edge.noAdvance,
node: edge.node,
value: undefined,
});
ctx.indent(out, tmp, ' ');
out.push(' }');
}
out.push(` default: {`);
const tmp: string[] = [];
this.tailTo(tmp, this.ref.otherwise!);
ctx.indent(out, tmp, ' ');
out.push(' }');
out.push('}');
}
private canVectorize(): boolean {
// Transformation is not supported atm
if (this.ref.transform && this.ref.transform.ref.name !== 'id') {
return false;
}
if (this.ref.edges.length !== 1) {
return false;
}
const edge = this.ref.edges[0];
if (
!edge ||
edge.node.ref !== this.ref
) {
return false;
}
assert.strictEqual(edge.noAdvance, false);
return true;
}
private buildRanges(edge: frontend.node.TableLookup["edges"][0]): number[] {
// NOTE: keys are sorted
const ranges: number[] = [];
let first: number | undefined;
let last: number | undefined;
for (const key of edge.keys) {
if (first === undefined) {
first = key;
}
if (last === undefined) {
last = key;
}
if (key - last > 1) {
ranges.push(first, last);
first = key;
}
last = key;
}
if (first !== undefined && last !== undefined) {
ranges.push(first, last);
}
return ranges;
}
private buildSSE(out: string[]): boolean {
const ctx = this.compilation;
const edge = this.ref.edges[0];
assert(edge !== undefined);
const ranges = this.buildRanges(edge);
if (ranges.length === 0) {
return false;
}
// Way too many calls would be required
if (ranges.length > MAX_SSE_CALLS * SSE_RANGES_LEN) {
return false;
}
out.push('#ifdef __SSE4_2__');
out.push(`if (${ctx.endPosArg()} - ${ctx.posArg()} >= 16) {`);
out.push(' __m128i ranges;');
out.push(' __m128i input;');
out.push(' int match_len;');
out.push('');
out.push(' /* Load input */');
out.push(` input = _mm_loadu_si128((__m128i const*) ${ctx.posArg()});`);
for (let off = 0; off < ranges.length; off += SSE_RANGES_LEN) {
const subRanges = ranges.slice(off, off + SSE_RANGES_LEN);
let paddedRanges = subRanges.slice();
while (paddedRanges.length < SSE_RANGES_PAD) {
paddedRanges.push(0);
}
const blob = ctx.blob(Buffer.from(paddedRanges), SSE_ALIGNMENT);
out.push(` ranges = _mm_loadu_si128((__m128i const*) ${blob});`);
out.push('');
out.push(' /* Find first character that does not match `ranges` */');
out.push(` match_len = _mm_cmpestri(ranges, ${subRanges.length},`);
out.push(' input, 16,');
out.push(' _SIDD_UBYTE_OPS | _SIDD_CMP_RANGES |');
out.push(' _SIDD_NEGATIVE_POLARITY);');
out.push('');
out.push(' if (match_len != 0) {');
out.push(` ${ctx.posArg()} += match_len;`);
const tmp: string[] = [];
this.tailTo(tmp, {
noAdvance: true,
node: edge.node,
});
ctx.indent(out, tmp, ' ');
out.push(' }');
}
{
const tmp: string[] = [];
this.tailTo(tmp, this.ref.otherwise!);
ctx.indent(out, tmp, ' ');
}
out.push('}');
out.push('#endif /* __SSE4_2__ */');
return true;
}
private buildNeon(out: string[]): boolean {
const ctx = this.compilation;
const edge = this.ref.edges[0];
assert(edge !== undefined);
const ranges = this.buildRanges(edge);
if (ranges.length === 0) {
return false;
}
// Way too many calls would be required
if (ranges.length > MAX_NEON_RANGES) {
return false;
}
out.push('#if defined(__ARM_NEON__) || defined(__ARM_NEON)');
out.push(`while (${ctx.endPosArg()} - ${ctx.posArg()} >= 16) {`);
out.push(' uint8x16_t input;');
out.push(' uint8x16_t single;');
out.push(' uint8x16_t mask;');
out.push(' uint8x8_t narrow;');
out.push(' uint64_t match_mask;');
out.push(' int match_len;');
out.push('');
out.push(' /* Load input */');
out.push(` input = vld1q_u8(${ctx.posArg()});`);
out.push(' /* Find first character that does not match `ranges` */');
function v128(value: number): string {
return `vdupq_n_u8(${ctx.toChar(value)})`;
}
for (let off = 0; off < ranges.length; off += 2) {
const start = ranges[off];
const end = ranges[off + 1];
assert(start !== undefined);
assert(end !== undefined);
// Same character, equality is sufficient (and faster)
if (start === end) {
out.push(` single = vceqq_u8(input, ${v128(start)});`);
} else {
out.push(` single = vandq_u16(`);
out.push(` vcgeq_u8(input, ${v128(start)}),`);
out.push(` vcleq_u8(input, ${v128(end)})`);
out.push(' );');
}
if (off === 0) {
out.push(' mask = single;');
} else {
out.push(' mask = vorrq_u16(mask, single);');
}
}
// https://community.arm.com/arm-community-blogs/b/servers-and-cloud-computing-blog/posts/porting-x86-vector-bitmask-optimizations-to-arm-neon
out.push(' narrow = vshrn_n_u16(mask, 4);');
out.push(' match_mask = ~vget_lane_u64(vreinterpret_u64_u8(narrow), 0);');
out.push(' match_len = __builtin_ctzll(match_mask) >> 2;');
out.push(' if (match_len != 16) {');
out.push(` ${ctx.posArg()} += match_len;`);
{
const tmp: string[] = [];
this.tailTo(tmp, this.ref.otherwise!);
ctx.indent(out, tmp, ' ');
}
out.push(' }');
out.push(` ${ctx.posArg()} += 16;`);
out.push('}');
out.push(`if (${ctx.posArg()} == ${ctx.endPosArg()}) {`);
{
const tmp: string[] = [];
this.pause(tmp);
this.compilation.indent(out, tmp, ' ');
}
out.push('}');
out.push('#endif /* __ARM_NEON__ */');
return true;
}
private buildWASM(out: string[]): boolean {
const ctx = this.compilation;
const edge = this.ref.edges[0];
assert(edge !== undefined);
const ranges = this.buildRanges(edge);
if (ranges.length === 0) {
return false;
}
// Way too many calls would be required
if (ranges.length > MAX_WASM_RANGES) {
return false;
}
out.push('#ifdef __wasm_simd128__');
out.push(`while (${ctx.endPosArg()} - ${ctx.posArg()} >= 16) {`);
out.push(' v128_t input;');
out.push(' v128_t mask;');
out.push(' v128_t single;');
out.push(' int match_len;');
out.push('');
out.push(' /* Load input */');
out.push(` input = wasm_v128_load(${ctx.posArg()});`);
out.push(' /* Find first character that does not match `ranges` */');
function v128(value: number): string {
return `wasm_u8x16_const_splat(${ctx.toChar(value)})`;
}
for (let off = 0; off < ranges.length; off += 2) {
const start = ranges[off];
const end = ranges[off + 1];
assert(start !== undefined);
assert(end !== undefined);
// Same character, equality is sufficient (and faster)
if (start === end) {
out.push(` single = wasm_i8x16_eq(input, ${v128(start)});`);
} else {
out.push(` single = wasm_v128_and(`);
out.push(` wasm_i8x16_ge(input, ${v128(start)}),`);
out.push(` wasm_i8x16_le(input, ${v128(end)})`);
out.push(' );');
}
if (off === 0) {
out.push(' mask = single;');
} else {
out.push(' mask = wasm_v128_or(mask, single);');
}
}
out.push(' match_len = __builtin_ctz(');
out.push(' ~wasm_i8x16_bitmask(mask)');
out.push(' );');
out.push(' if (match_len != 16) {');
out.push(` ${ctx.posArg()} += match_len;`);
{
const tmp: string[] = [];
this.tailTo(tmp, this.ref.otherwise!);
ctx.indent(out, tmp, ' ');
}
out.push(' }');
out.push(` ${ctx.posArg()} += 16;`);
out.push('}');
out.push(`if (${ctx.posArg()} == ${ctx.endPosArg()}) {`);
{
const tmp: string[] = [];
this.pause(tmp);
this.compilation.indent(out, tmp, ' ');
}
out.push('}');
out.push('#endif /* __wasm_simd128__ */');
return true;
}
private buildTable(): ITable {
const table: number[] = new Array(MAX_CHAR + 1).fill(0);
for (const [ index, edge ] of this.ref.edges.entries()) {
edge.keys.forEach((key) => {
assert.strictEqual(table[key], 0);
table[key] = index + 1;
});
}
const lines = [
'static uint8_t lookup_table[] = {',
];
for (let i = 0; i < table.length; i += TABLE_GROUP) {
let line = ` ${table.slice(i, i + TABLE_GROUP).join(', ')}`;
if (i + TABLE_GROUP < table.length) {
line += ',';
}
lines.push(line);
}
lines.push('};');
return {
name: 'lookup_table',
declaration: lines,
};
}
}