Skip to content
Source
Sign inSign up
TanStack/container
Open History to see the last commit

stage-opcode-patterns.mjs

32 lines1.8 KB

1import {readFileSync,writeFileSync} from 'node:fs'
2​
3const original = '#define M4(op1, op2, op3, op4) ((op1) | ((op2) << 8) | ((op3) << 16) | ((op4) << 24))'
4const replacement = `/* Pack opcode alternatives without signed-shift overflow. */
5static inline int code_pattern4(int op1, int op2, int op3, int op4)
6{
7 uint32_t pattern = (uint32_t)op1 | ((uint32_t)op2 << 8) |
8 ((uint32_t)op3 << 16) | ((uint32_t)op4 << 24);
9 /* code_match reads int varargs. Convert the high-bit representation
10 without an out-of-range unsigned-to-signed conversion. */
11 if (pattern & UINT32_C(0x80000000))
12 return (int)(pattern & INT32_MAX) - INT32_MAX - 1;
13 return (int)pattern;
15#define M4(op1, op2, op3, op4) code_pattern4((op1), (op2), (op3), (op4))`
16const shifts = [8,16,24].map(bits => [`(uint8_t)(op1 >> ${bits})`, `(uint8_t)((uint32_t)op1 >> ${bits})`])
17​
18/** Preserve code_match's signed int varargs while packing all four opcode bytes. */
19export function stageOpcodePatterns(path) {
20 let source = readFileSync(path, 'utf8')
21 if (source.includes('static inline int code_pattern4(')) {
22 if (source.split(replacement).length !== 2 || source.includes(original) || shifts.some(([from,to]) => source.includes(from) || source.split(to).length !== 2)) throw new Error('Unexpected partial opcode pattern stage')
23 return
24 }
25 if (source.split(original).length !== 2 || source.split('static BOOL code_match(CodeContext *s, int pos, ...)').length !== 2 || !source.includes('op1 = va_arg(ap, int);')) throw new Error('Unexpected opcode pattern packing site')
26 source = source.replace(original, replacement)
27 for (const [from,to] of shifts) {
28 if (source.split(from).length !== 2) throw new Error('Unexpected opcode pattern byte extraction site')
29 source = source.replace(from, to)
30 }
31 writeFileSync(path, source)