js-confuser-vm 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +281 -147
  2. package/dist/build-runtime.js +41 -15
  3. package/dist/compiler.js +714 -265
  4. package/dist/disassembler.js +367 -0
  5. package/dist/index.js +7 -2
  6. package/dist/runtime.js +160 -119
  7. package/dist/template.js +163 -42
  8. package/dist/transforms/bytecode/aliasedOpcodes.js +4 -1
  9. package/dist/transforms/bytecode/concealConstants.js +2 -2
  10. package/dist/transforms/bytecode/controlFlowFlattening.js +569 -0
  11. package/dist/transforms/bytecode/dispatcher.js +15 -111
  12. package/dist/transforms/bytecode/macroOpcodes.js +2 -2
  13. package/{src/transforms/bytecode/resolveContants.ts → dist/transforms/bytecode/resolveConstants.js} +30 -56
  14. package/dist/transforms/bytecode/resolveRegisters.js +23 -4
  15. package/dist/transforms/bytecode/selfModifying.js +88 -21
  16. package/dist/transforms/bytecode/semanticOpcodes.js +162 -0
  17. package/dist/transforms/bytecode/specializedOpcodes.js +23 -12
  18. package/dist/transforms/bytecode/stringConcealing.js +288 -0
  19. package/dist/transforms/runtime/classObfuscation.js +43 -0
  20. package/dist/transforms/runtime/handlerTable.js +91 -0
  21. package/dist/transforms/runtime/semanticOpcodes.js +35 -0
  22. package/dist/transforms/runtime/specializedOpcodes.js +11 -5
  23. package/dist/types.js +1 -1
  24. package/dist/utils/ast-utils.js +75 -0
  25. package/dist/utils/op-utils.js +1 -2
  26. package/dist/utils/pass-utils.js +100 -0
  27. package/dist/utils/profile-utils.js +3 -0
  28. package/package.json +8 -1
  29. package/.gitmodules +0 -4
  30. package/.prettierignore +0 -1
  31. package/CHANGELOG.md +0 -335
  32. package/babel-plugin-inline-runtime.cjs +0 -34
  33. package/babel.config.json +0 -23
  34. package/index.ts +0 -38
  35. package/jest-strip-types.js +0 -10
  36. package/jest.config.js +0 -52
  37. package/src/build-runtime.ts +0 -78
  38. package/src/compiler.ts +0 -2593
  39. package/src/index.ts +0 -14
  40. package/src/minify.ts +0 -21
  41. package/src/options.ts +0 -18
  42. package/src/runtime.ts +0 -923
  43. package/src/template.ts +0 -141
  44. package/src/transforms/bytecode/aliasedOpcodes.ts +0 -148
  45. package/src/transforms/bytecode/concealConstants.ts +0 -52
  46. package/src/transforms/bytecode/dispatcher.ts +0 -398
  47. package/src/transforms/bytecode/macroOpcodes.ts +0 -193
  48. package/src/transforms/bytecode/microOpcodes.ts +0 -291
  49. package/src/transforms/bytecode/resolveLabels.ts +0 -112
  50. package/src/transforms/bytecode/resolveRegisters.ts +0 -221
  51. package/src/transforms/bytecode/selfModifying.ts +0 -121
  52. package/src/transforms/bytecode/specializedOpcodes.ts +0 -153
  53. package/src/transforms/runtime/aliasedOpcodes.ts +0 -191
  54. package/src/transforms/runtime/internalVariables.ts +0 -270
  55. package/src/transforms/runtime/macroOpcodes.ts +0 -138
  56. package/src/transforms/runtime/microOpcodes.ts +0 -93
  57. package/src/transforms/runtime/minify.ts +0 -1
  58. package/src/transforms/runtime/shuffleOpcodes.ts +0 -24
  59. package/src/transforms/runtime/specializedOpcodes.ts +0 -156
  60. package/src/types.ts +0 -93
  61. package/src/utils/op-utils.ts +0 -48
  62. package/src/utils/random-utils.ts +0 -31
  63. package/tsconfig.json +0 -12
@@ -1,398 +0,0 @@
1
- // Routes simple unconditional and conditional jumps through a per-function
2
- // central dispatcher block so that static analysis cannot read jump targets
3
- // directly from the bytecode operands.
4
- //
5
- // ── How it works ─────────────────────────────────────────────────────────────
6
- //
7
- // Each function that contains at least one routable jump gets:
8
- //
9
- // rDisp — a stable register shared across the whole function.
10
- // At every jump site, the per-site encoded target PC is written
11
- // here before jumping to the dispatcher block.
12
- // rKey — a stable register written at every jump site with that site's
13
- // unique XOR key. The dispatcher passes it to the decode closure.
14
- // rClosure — holds the decode closure, created ONCE at function entry
15
- // (hoisted). All dispatch calls reuse the same closure object.
16
- //
17
- // Dispatcher block (appended after the function body, never reached by fall-through):
18
- //
19
- // <dispatcher_N>:
20
- // CALL rDisp, rClosure, 2, rDisp, rKey // rDisp = decode(rDisp, rKey)
21
- // JUMP_REG rDisp // indirect jump to recovered PC
22
- //
23
- // The decode function is compiled ONCE PER FUNCTION from a Template that
24
- // embeds a per-function constant (fnSalt). Every function gets its own
25
- // distinct decode closure body, so identifying one does not help with others.
26
- //
27
- // function decode(x, k) { return ((x ^ k) + FN_SALT) & 0xFFFF; }
28
- //
29
- // Jump site transformations (each site has its own random siteKey):
30
- //
31
- // Original: JUMP target_label
32
- // Becomes: LOAD_INT rDisp, (target_label_pc - fnSalt) ^ siteKey
33
- // LOAD_INT rKey, siteKey
34
- // JUMP <dispatcher_N>
35
- //
36
- // Original: JUMP_IF_FALSE cond, target_label
37
- // Becomes: JUMP_IF_TRUE cond, <skip_N>
38
- // LOAD_INT rDisp, (target_label_pc - fnSalt) ^ siteKey
39
- // LOAD_INT rKey, siteKey
40
- // JUMP <dispatcher_N>
41
- // <skip_N>:
42
- //
43
- // Original: JUMP_IF_TRUE cond, target_label
44
- // Becomes: JUMP_IF_FALSE cond, <skip_N>
45
- // LOAD_INT rDisp, (target_label_pc - fnSalt) ^ siteKey
46
- // LOAD_INT rKey, siteKey
47
- // JUMP <dispatcher_N>
48
- // <skip_N>:
49
- //
50
- // ── Encoding scheme ──────────────────────────────────────────────────────────
51
- // Two-key mixed encoding: XOR (per-site) + SUB/ADD (per-function).
52
- //
53
- // encode(pc, siteKey, fnSalt) = (pc - fnSalt) ^ siteKey
54
- // decode(x, k, fnSalt) = (x ^ k) + fnSalt
55
- //
56
- // The siteKey is a random nonzero u16 unique per jump site — stored as a plain
57
- // integer operand in the bytecode.
58
- // The fnSalt is a random nonzero u16 unique per function — it is never stored
59
- // as an operand anywhere; it is compiled as a literal constant inside the
60
- // function's own decode Template body.
61
- //
62
- // Attack resistance:
63
- // • Brute-forcing a single jump requires enumerating siteKey × fnSalt
64
- // (~4 billion combinations) rather than just siteKey (65 535).
65
- // • Assuming pure XOR fails: un-XOR-ing with siteKey yields (pc - fnSalt),
66
- // not pc. Valid-PC heuristics produce wrong answers.
67
- // • Each function emits its own decode closure bytecode with a different
68
- // fnSalt literal baked in. There is no shared signature to fingerprint.
69
- // • The encode and decode operations differ structurally (SUB vs ADD),
70
- // removing the self-inverse property that makes XOR-only schemes obvious.
71
- //
72
- // To change the scheme:
73
- // 1. Change the Template source in processFunctionBlock() to match new decode.
74
- // 2. Change applyEncoding() to return the matching encode transform.
75
- // Only these two places need updating; everything else is scheme-agnostic.
76
- //
77
- // ── Pipeline position ─────────────────────────────────────────────────────────
78
- // Runs BEFORE resolveRegisters (so injected RegisterOperands are picked up by
79
- // liveness analysis) and BEFORE resolveLabels (so label operands with transforms
80
- // are resolved as part of the normal label-resolution pass).
81
- //
82
- // Enabled by options.dispatcher = true.
83
-
84
- import type {
85
- Bytecode,
86
- Instruction,
87
- RegisterOperand,
88
- InstrOperand,
89
- } from "../../types.ts";
90
- import * as b from "../../types.ts";
91
- import { Compiler } from "../../compiler.ts";
92
- import { getRandomInt } from "../../utils/random-utils.ts";
93
- import { U16_MAX } from "../../utils/op-utils.ts";
94
- import { Template } from "../../template.ts";
95
-
96
- // VERY IMPORTANT: All object operands should be unique objects for the entire compilation process.
97
- // This ensures that other passes that may reference/modify operands (e.g. specializedOpcodes) don't accidentally break behavior by mutating cloned objects.
98
- function ref(r: RegisterOperand): RegisterOperand {
99
- return b.registerOperand(r.id, r.fnId);
100
- }
101
-
102
- // Monotonically increasing counter that makes every encoded label operand
103
- // JSON.stringify-distinguishable. specializedOpcodes keys candidates by
104
- // JSON.stringify(operands), which drops the transform function. Without this
105
- // counter, two LOAD_INT instructions for the same label but different siteKeys
106
- // would serialize identically and be coalesced into one specialized opcode
107
- // sharing a single operand object — causing both sites to decode with the
108
- // first site's key rather than their own.
109
- let _encodedLabelId = 0;
110
-
111
- function encodedLabelOperand(
112
- label: string,
113
- siteKey: number,
114
- fnSalt: number,
115
- ): InstrOperand {
116
- return {
117
- type: "label",
118
- label,
119
- _id: _encodedLabelId++, // unique per site — survives JSON.stringify
120
- transform: (pc) => applyEncoding(pc, siteKey, fnSalt),
121
- } as InstrOperand;
122
- }
123
-
124
- // ── Encoding scheme (XOR + SUB/ADD, u16 modular) ────────────────────────────
125
- // applyEncoding(pc, siteKey, fnSalt): the value stored in rDisp at the jump site.
126
- // Must be the inverse of the decode function compiled by the Template.
127
- // encode: ((pc - fnSalt) & 0xFFFF) ^ siteKey → always a valid u16
128
- // decode: ((x ^ siteKey) + fnSalt) & 0xFFFF ← compiled into the per-function Template
129
- // The & 0xFFFF mask keeps both sides in [0, 65535], preventing negative LOAD_INT operands.
130
- function applyEncoding(pc: number, siteKey: number, fnSalt: number): number {
131
- return ((pc - fnSalt) & U16_MAX) ^ siteKey;
132
- }
133
-
134
- // ── Register allocation helpers ───────────────────────────────────────────────
135
- // At pass time FnContext objects are gone; we allocate new virtual registers by
136
- // scanning the bytecode for the highest existing id per fnId and incrementing.
137
- function buildMaxIdMap(bc: Bytecode): Map<number, number> {
138
- const maxId = new Map<number, number>();
139
- for (const instr of bc) {
140
- for (let j = 1; j < instr.length; j++) {
141
- const op = instr[j] as any;
142
- if (op && op.type === "register") {
143
- const cur = maxId.get(op.fnId) ?? -1;
144
- if (op.id > cur) maxId.set(op.fnId, op.id);
145
- }
146
- }
147
- }
148
- return maxId;
149
- }
150
-
151
- // Allocate a new virtual register for fnId, updating maxId in-place.
152
- function allocReg(fnId: number, maxId: Map<number, number>): RegisterOperand {
153
- const next = (maxId.get(fnId) ?? -1) + 1;
154
- maxId.set(fnId, next);
155
- return b.registerOperand(next, fnId);
156
- }
157
-
158
- // ── Label operand extraction ──────────────────────────────────────────────────
159
- // Returns the label string if the operand is a { type:"label" } object,
160
- // otherwise returns null. Used to identify routable jump targets.
161
- function extractLabel(op: InstrOperand | undefined): string | null {
162
- if (op && typeof op === "object" && (op as any).type === "label")
163
- return (op as any).label as string;
164
- return null;
165
- }
166
-
167
- // buildDispatcherBlock: emits the dispatcher label + call + indirect jump.
168
- // rClosure is already live (created at function entry); this block simply
169
- // calls the decode closure and jumps to the result.
170
- function buildDispatcherBlock(
171
- compiler: Compiler,
172
- rDisp: RegisterOperand,
173
- rKey: RegisterOperand,
174
- rClosure: RegisterOperand,
175
- dispatcherLabel: string,
176
- ): Instruction[] {
177
- const OP = compiler.OP;
178
- return [
179
- [null, { type: "defineLabel", label: dispatcherLabel }],
180
-
181
- // decode(rDisp, rKey) → rDisp. Args are read before dst is written.
182
- [
183
- OP.CALL!,
184
- ref(rDisp), // dst — receives decoded PC
185
- ref(rClosure), // the hoisted decode closure
186
- 2, // argc
187
- ref(rDisp), // arg[0] = encoded value
188
- ref(rKey), // arg[1] = per-site key
189
- ],
190
-
191
- [OP.JUMP_REG!, ref(rDisp)],
192
- ];
193
- }
194
-
195
- // ── Per-function transformation ───────────────────────────────────────────────
196
- // Returns the transformed instruction stream and the template bytecode block
197
- // for the per-function decode closure (to be appended at the end of the output).
198
- function processFunctionBlock(
199
- instrs: Bytecode,
200
- fnId: number,
201
- compiler: Compiler,
202
- maxId: Map<number, number>,
203
- labelCounter: () => string,
204
- ): { instrs: Bytecode; templateBytecode: Bytecode } {
205
- const OP = compiler.OP;
206
-
207
- // Only transform functions that actually contain simple jumps.
208
- const hasRoutableJump = instrs.some((instr) => {
209
- const op = instr[0];
210
- return op === OP.JUMP || op === OP.JUMP_IF_FALSE || op === OP.JUMP_IF_TRUE;
211
- });
212
- if (!hasRoutableJump) return { instrs, templateBytecode: [] };
213
-
214
- // Per-function salt baked into this function's decode Template.
215
- // Never stored as an operand — lives only inside the decode closure body.
216
- const fnSalt = getRandomInt(1, U16_MAX);
217
-
218
- // Compile a unique decode closure for this function.
219
- // The fnSalt literal is inlined into the source so each function's closure
220
- // body is structurally distinct; no single signature covers all functions.
221
- const tmpl = new Template(
222
- `function decode(x, k) { return ((x ^ k) + ${fnSalt}) & ${U16_MAX}; }`,
223
- ).compile({}, compiler);
224
- const decodeDesc = tmpl.functions[0];
225
-
226
- const dispatcherLabel = labelCounter();
227
- const rDisp = allocReg(fnId, maxId); // carries encoded PC to dispatcher
228
- const rKey = allocReg(fnId, maxId); // carries per-site key to dispatcher
229
- const rClosure = allocReg(fnId, maxId); // holds the hoisted decode closure
230
-
231
- const out: Bytecode = [];
232
-
233
- // ── Hoist: create the decode closure once at function entry ───────────────
234
- out.push([
235
- OP.MAKE_CLOSURE!,
236
- ref(rClosure),
237
- { type: "label", label: decodeDesc.entryLabel },
238
- decodeDesc.paramCount, // 2 (x, k)
239
- b.fnRegCountOperand(decodeDesc._fnIdx), // resolved by resolveRegisters()
240
- 0, // no upvalues
241
- ]);
242
-
243
- // ── Transform each instruction ────────────────────────────────────────────
244
- for (const instr of instrs) {
245
- const op = instr[0];
246
-
247
- if (op === OP.JUMP) {
248
- // [JUMP, label] → [LOAD_INT rDisp, encoded] + [LOAD_INT rKey, siteKey] + [JUMP dispatcher]
249
- const targetLabel = extractLabel(instr[1]);
250
- if (targetLabel === null) {
251
- out.push(instr);
252
- continue;
253
- }
254
-
255
- const siteKey = getRandomInt(1, U16_MAX);
256
- out.push([
257
- OP.LOAD_INT!,
258
- ref(rDisp),
259
- encodedLabelOperand(targetLabel, siteKey, fnSalt),
260
- ]);
261
- out.push([OP.LOAD_INT!, ref(rKey), siteKey]);
262
- out.push([OP.JUMP!, { type: "label", label: dispatcherLabel }]);
263
- } else if (op === OP.JUMP_IF_FALSE) {
264
- // Invert to JUMP_IF_TRUE so the false path (jump taken) falls into dispatch.
265
- const cond = instr[1] as RegisterOperand;
266
- const targetLabel = extractLabel(instr[2]);
267
- if (targetLabel === null) {
268
- out.push(instr);
269
- continue;
270
- }
271
-
272
- const siteKey = getRandomInt(1, U16_MAX);
273
- const skipLabel = compiler._makeLabel(targetLabel + "_skip");
274
- out.push([OP.JUMP_IF_TRUE!, cond, { type: "label", label: skipLabel }]);
275
- out.push([
276
- OP.LOAD_INT!,
277
- ref(rDisp),
278
- encodedLabelOperand(targetLabel, siteKey, fnSalt),
279
- ]);
280
- out.push([OP.LOAD_INT!, ref(rKey), siteKey]);
281
- out.push([OP.JUMP!, { type: "label", label: dispatcherLabel }]);
282
- out.push([null, { type: "defineLabel", label: skipLabel }]);
283
- } else if (op === OP.JUMP_IF_TRUE) {
284
- // Invert to JUMP_IF_FALSE so the true path (jump taken) falls into dispatch.
285
- const cond = instr[1] as RegisterOperand;
286
- const targetLabel = extractLabel(instr[2]);
287
- if (targetLabel === null) {
288
- out.push(instr);
289
- continue;
290
- }
291
-
292
- const siteKey = getRandomInt(1, U16_MAX);
293
- const skipLabel = compiler._makeLabel(targetLabel + "_skip");
294
- out.push([OP.JUMP_IF_FALSE!, cond, { type: "label", label: skipLabel }]);
295
- out.push([
296
- OP.LOAD_INT!,
297
- ref(rDisp),
298
- encodedLabelOperand(targetLabel, siteKey, fnSalt),
299
- ]);
300
- out.push([OP.LOAD_INT!, ref(rKey), siteKey]);
301
- out.push([OP.JUMP!, { type: "label", label: dispatcherLabel }]);
302
- out.push([null, { type: "defineLabel", label: skipLabel }]);
303
- } else {
304
- out.push(instr);
305
- }
306
- }
307
-
308
- // Dispatcher block appended after the function body. Never reached by
309
- // fall-through; all entries are via the JUMP dispatcher instructions above.
310
- out.push(
311
- ...buildDispatcherBlock(compiler, rDisp, rKey, rClosure, dispatcherLabel),
312
- );
313
-
314
- return { instrs: out, templateBytecode: tmpl.bytecode };
315
- }
316
-
317
- // ── Pass entry point ──────────────────────────────────────────────────────────
318
- export function dispatcher(
319
- bc: Bytecode,
320
- compiler: Compiler,
321
- ): { bytecode: Bytecode } {
322
- // Pre-compute max virtual register id per function across the whole bytecode.
323
- const maxId = buildMaxIdMap(bc);
324
-
325
- // Label factory that delegates to the compiler's own counter so labels
326
- // produced here never collide with compiler-generated or pass-generated ones.
327
- const labelCounter = () => compiler._makeLabel("dispatcher");
328
-
329
- // Build a set of entry labels so we can detect function boundaries.
330
- const entryLabels = new Set(compiler.fnDescriptors.map((d) => d.entryLabel));
331
- // Build a map from entry label → fnId.
332
- const entryLabelToFnId = new Map(
333
- compiler.fnDescriptors.map((d) => [d.entryLabel!, d._fnIdx!]),
334
- );
335
-
336
- const result: Bytecode = [];
337
- // Collect each function's decode Template bytecode; appended at the end so
338
- // all MAKE_CLOSURE instructions can reference their entryLabels regardless
339
- // of where in the bytecode the function appears.
340
- const decodeBytecodes: Bytecode[] = [];
341
- let i = 0;
342
-
343
- while (i < bc.length) {
344
- const instr = bc[i];
345
- const [op, operand0] = instr;
346
- const isEntryLabel =
347
- op === null &&
348
- (operand0 as any)?.type === "defineLabel" &&
349
- entryLabels.has((operand0 as any).label);
350
-
351
- if (!isEntryLabel) {
352
- result.push(instr);
353
- i++;
354
- continue;
355
- }
356
-
357
- // Found a function entry label. Collect all instructions belonging to
358
- // this function (until the next entry label or end of bytecode).
359
- const entryLabel = (operand0 as any).label as string;
360
- const fnId = entryLabelToFnId.get(entryLabel)!;
361
- i++; // step past the defineLabel itself
362
-
363
- const fnInstrs: Bytecode = [];
364
- while (i < bc.length) {
365
- const next = bc[i];
366
- const [nextOp, nextOp0] = next;
367
- if (
368
- nextOp === null &&
369
- (nextOp0 as any)?.type === "defineLabel" &&
370
- entryLabels.has((nextOp0 as any).label)
371
- )
372
- break; // next function starts here
373
- fnInstrs.push(next);
374
- i++;
375
- }
376
-
377
- // Emit the entry defineLabel, then the (potentially transformed) body.
378
- result.push(instr); // the defineLabel
379
- const { instrs: processed, templateBytecode } = processFunctionBlock(
380
- fnInstrs,
381
- fnId,
382
- compiler,
383
- maxId,
384
- labelCounter,
385
- );
386
- result.push(...processed);
387
- if (templateBytecode.length > 0) decodeBytecodes.push(templateBytecode);
388
- }
389
-
390
- // Append all per-function decode closure bodies at the end of the bytecode.
391
- // Each block defines the entryLabel that the corresponding MAKE_CLOSURE
392
- // instruction references.
393
- for (const tb of decodeBytecodes) {
394
- result.push(...tb);
395
- }
396
-
397
- return { bytecode: result };
398
- }
@@ -1,193 +0,0 @@
1
- import type { Bytecode, Instruction } from "../../types.ts";
2
- import { Compiler, SOURCE_NODE_SYM } from "../../compiler.ts";
3
- import { nextFreeSlot } from "../../utils/op-utils.ts";
4
- import { ok } from "assert";
5
-
6
- // Opcodes that must not appear in a non-terminal position inside a macro window.
7
- // Jump ops: modifying frame._pc mid-execution causes the macro handler to
8
- // run subsequent sub-bodies even after the jump already fired.
9
- // Frame-changing ops (CALL, CALL_METHOD, NEW, RETURN, THROW): push/pop call
10
- // frames mid-macro, leaving the `frame` variable stale for later sub-bodies.
11
- // When one of these is the LAST instruction in the macro sequence there are no
12
- // following sub-bodies, so editing _pc or the call frame is safe.
13
- // Variable-operand ops (MAKE_CLOSURE): the number of _operand() calls depends
14
- // on uvCount at runtime, so a static handler cannot be generated.
15
- // Infrastructure ops (PATCH, TRY_SETUP, TRY_END, DEBUGGER):
16
- // either illegal here or nonsensical to fold.
17
-
18
- // Scan bytecode for repeating instruction sequences and fold them into
19
- // macro opcodes. Runs after selfModifying but before resolveLabels so
20
- // IR-ref operands (label/constant) are carried through transparently.
21
- //
22
- // Algorithm:
23
- // 1. Count every eligible window of length 2–5 by its op-code signature.
24
- // 2. Keep sequences that appear >= 2 times; sort by frequency then length.
25
- // 3. Use nextFreeSlot() to assign a new opcode to each of the best candidates
26
- // 4. Re-scan bytecode, replacing each matched sequence with a single
27
- // multi-operand instruction:
28
- // [macroOpCode, operands_of_instr_0..., operands_of_instr_1..., ...]
29
- // The runtime macro handler inlines each sub-instruction body; those
30
- // bodies call this._operand() themselves to consume the inline operands.
31
- export function macroOpcodes(
32
- bc: Bytecode,
33
- compiler: Compiler,
34
- ): { bytecode: Bytecode } {
35
- const originalOpToName = new Map<number, string>();
36
- for (const name in compiler.OP) {
37
- const opVal = compiler.OP[name];
38
- originalOpToName.set(opVal, name);
39
- }
40
-
41
- // Names are used instead of codes as specialized opcodes may generate based off these and it should not be considered eligible still
42
- const alwaysExcluded = [
43
- "PATCH",
44
- "TRY_SETUP",
45
- "TRY_END",
46
- "DEBUGGER",
47
- "MAKE_CLOSURE",
48
- ];
49
-
50
- const nonTerminalExcluded = ["RETURN", "CALL", "CALL_METHOD", "NEW", "THROW"];
51
-
52
- function isEligible(
53
- op: number | null,
54
- compiler: Compiler,
55
- isLast: boolean = false,
56
- ): boolean {
57
- if (op === null) return false;
58
- const { OP, JUMP_OPS, OP_NAME } = compiler;
59
- // Infrastructure and variable-length ops are never eligible.
60
- const opName = OP_NAME[op];
61
- ok(opName, `Unknown opcode ${op} (not in OP_NAME)`);
62
- if (alwaysExcluded.find((name) => opName.includes(name))) return false;
63
-
64
- // Jump and frame-changing ops are only eligible as the terminal instruction.
65
- if (!isLast) {
66
- if (JUMP_OPS.has(op)) return false;
67
-
68
- if (nonTerminalExcluded.find((name) => opName.includes(name)))
69
- return false;
70
- }
71
- return OP_NAME[op] !== undefined;
72
- }
73
-
74
- // ── Step 1: count window frequencies ──────────────────────────────────────
75
- const freqMap = new Map<string, { ops: number[]; count: number }>();
76
-
77
- for (let i = 0; i < bc.length; i++) {
78
- for (let len = 2; len <= 5; len++) {
79
- if (i + len > bc.length) break;
80
-
81
- const ops: number[] = [];
82
- let valid = true;
83
- for (let j = 0; j < len; j++) {
84
- const instr = bc[i + j];
85
- const op = instr[0];
86
- const isLast = j === len - 1;
87
- if (!isEligible(op, compiler, isLast)) {
88
- valid = false;
89
- break;
90
- }
91
- ops.push(op as number);
92
- }
93
- // If position (i+j) is ineligible even as a terminal, longer windows from
94
- // i are also invalid (it would be non-terminal there too).
95
- if (!valid) break;
96
-
97
- const key = ops.join(",");
98
- const entry = freqMap.get(key);
99
- if (entry) {
100
- entry.count++;
101
- } else {
102
- freqMap.set(key, { ops, count: 1 });
103
- }
104
- }
105
- }
106
-
107
- // ── Step 2: keep repeated candidates, prioritise by frequency then length ─
108
- const candidates = Array.from(freqMap.values())
109
- .filter((e) => e.count >= 2)
110
- .sort((a, b) => b.count - a.count || b.ops.length - a.ops.length);
111
-
112
- if (candidates.length === 0) return { bytecode: bc };
113
-
114
- // ── Step 3: assign free opcode slots to the best candidates ───────────────
115
- for (let i = 0; i < candidates.length; i++) {
116
- const macroOp = nextFreeSlot(compiler);
117
- if (macroOp === -1) break;
118
- const ops = candidates[i].ops;
119
- compiler.MACRO_OPS[macroOp] = ops;
120
- // Register a combined name so OP_NAME and comment generation both work.
121
- let combinedName = ops
122
- .map((v) => compiler.OP_NAME[v] ?? `OP_${v}`)
123
- .join(",");
124
- compiler.OP_NAME[macroOp] = combinedName;
125
- }
126
-
127
- // ── Step 4: build signature → macro opcode lookup ─────────────────────────
128
- const sigToMacro = new Map<string, number>();
129
- for (const [macroOpStr, ops] of Object.entries(compiler.MACRO_OPS)) {
130
- sigToMacro.set((ops as number[]).join(","), Number(macroOpStr));
131
- }
132
-
133
- // ── Step 5: replace sequences with a single multi-operand macro instruction ─
134
- // Emit [macroOpCode, ...all operands from all constituent instructions].
135
- // The runtime handler inlines each sub-instruction body; those bodies call
136
- // this._operand() themselves to consume the operands in order.
137
- const result: Bytecode = [];
138
- let i = 0;
139
-
140
- while (i < bc.length) {
141
- let matched = false;
142
-
143
- for (let len = 5; len >= 2; len--) {
144
- if (i + len > bc.length) continue;
145
-
146
- const instructions: Instruction[] = [];
147
- let valid = true;
148
- for (let j = 0; j < len; j++) {
149
- const instr = bc[i + j];
150
- const op = instr[0];
151
- const isLast = j === len - 1;
152
- if (!isEligible(op, compiler, isLast)) {
153
- valid = false;
154
- break;
155
- }
156
- instructions.push(instr);
157
- }
158
- if (!valid) continue;
159
-
160
- const key = instructions.map((instr) => instr[0]).join(",");
161
- if (!sigToMacro.has(key)) continue;
162
-
163
- const macroOpCode = sigToMacro.get(key)!;
164
-
165
- // Collect all operands from every constituent instruction, in order.
166
- // Each instruction contributes instr.slice(1) — zero or more operands.
167
- const allOperands: any[] = [];
168
- for (let j = 0; j < len; j++) {
169
- var instr = bc[i + j];
170
- var operands = instr.slice(1);
171
- allOperands.push(...operands);
172
- }
173
-
174
- const newInstr: Instruction = [macroOpCode, ...allOperands];
175
- (newInstr as any)[SOURCE_NODE_SYM] = (instructions[0] as any)[
176
- SOURCE_NODE_SYM
177
- ];
178
-
179
- result.push(newInstr);
180
-
181
- i += len;
182
- matched = true;
183
- break;
184
- }
185
-
186
- if (!matched) {
187
- result.push(bc[i]);
188
- i++;
189
- }
190
- }
191
-
192
- return { bytecode: result };
193
- }