-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLuaDecompExpr.inc
More file actions
908 lines (870 loc) · 35.1 KB
/
Copy pathLuaDecompExpr.inc
File metadata and controls
908 lines (870 loc) · 35.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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
function TDecompiler.BinOpStr(Op: TBinOp): AnsiString;
begin
case Op of
bopAdd: Result := '+';
bopSub: Result := '-';
bopMul: Result := '*';
bopDiv: Result := '/';
bopMod: Result := '%';
bopPow: Result := '^';
bopIDiv: Result := '//';
bopBAnd: Result := '&';
bopBOr: Result := '|';
bopBXor: Result := '~';
bopSHL: Result := '<<';
bopSHR: Result := '>>';
else Result := '?';
end;
end;
function TDecompiler.BinOpPrec(Op: TBinOp): Integer;
{ Returns Lua operator precedence level (higher = binds tighter).
Lua 5.3+ precedence:
^=12, unary(- # ~ not)=11, * / // %=10, + -=9,
..=8, <<>>=7, &=6, ~=5, |=4, < > <= >= ~= ==, and, or
For 5.1-5.2 (no bitwise): ^=7, * / %=6, + -=5 }
begin
case Op of
bopPow: Result := 12;
bopMul, bopDiv, bopIDiv, bopMod: Result := 10;
bopAdd, bopSub: Result := 9;
bopSHL, bopSHR: Result := 7;
bopBAnd: Result := 6;
bopBXor: Result := 5;
bopBOr: Result := 4;
else Result := 5;
end;
end;
function TDecompiler.UnOpStr(Op: TUnOp): AnsiString;
begin
case Op of
uopNeg: Result := '-';
uopNot: Result := 'not ';
uopLen: Result := '#';
uopBNot: Result := '~';
else Result := '?';
end;
end;
function TDecompiler.RelOpStr(Op: TRelOp; Invert: Boolean): AnsiString;
begin
case Op of
ropEQ: if Invert then Result := '~=' else Result := '==';
ropLT: if Invert then Result := '>=' else Result := '<';
ropLE: if Invert then Result := '>' else Result := '<=';
else
Result := '?';
end;
end;
function TDecompiler.FlippedRelOpStr(Op: TRelOp; Invert: Boolean): AnsiString;
{ Returns the operator with swapped operands: A < B ↔ B > A }
begin
case Op of
ropEQ: if Invert then Result := '~=' else Result := '=='; { symmetric }
ropLT: if Invert then Result := '<=' else Result := '>';
ropLE: if Invert then Result := '<' else Result := '>=';
else
Result := '?';
end;
end;
function TDecompiler.BuildCompare(const OpA, OpB: TSSARef;
Op: TRelOp; Invert: Boolean;
PC: Integer): AnsiString;
{ Build a comparison expression, normalizing operand order so that constants
appear on the right side. Lua 5.1 often emits "LT K(0) R(x)" for
source code "x > 0"; we recover the original order here.
Also: for LT/LE with two registers, if OpA.Reg > OpB.Reg the source
likely used > or >= (the compiler swapped operands to use LT/LE). }
var
LHS, RHS: AnsiString;
DoFlip: Boolean;
begin
DoFlip := False;
if (Op in [ropLT, ropLE]) then begin
if (OpA.Reg = SSA_CONST_REG) and (OpB.Reg <> SSA_CONST_REG) then
{ Constant on the left, register on the right --> swap to natural order }
DoFlip := True
else if (OpA.Reg <> SSA_CONST_REG) and (OpB.Reg <> SSA_CONST_REG) and
(OpA.Reg > OpB.Reg) then
{ Both registers, but OpA has higher reg number --> source probably used > or >= }
DoFlip := True;
end;
if DoFlip then begin
LHS := ExprOf(OpB, PC);
RHS := ExprOf(OpA, PC);
Result := LHS + ' ' + FlippedRelOpStr(Op, Invert) + ' ' + RHS;
end else begin
LHS := ExprOf(OpA, PC);
RHS := ExprOf(OpB, PC);
Result := LHS + ' ' + RelOpStr(Op, Invert) + ' ' + RHS;
end;
end;
{ Check if a value can be safely inlined into an expression (single-use temp) }
function TDecompiler.IsInlineable(const R: TSSARef): Boolean;
var
Idx: Integer;
begin
Result := False;
if (R.Reg < 0) or (R.Reg = SSA_CONST_REG) then Exit;
Idx := NodeIdx(R.Reg, R.Version);
if (Idx < 0) or (Idx >= Length(FUseCnt)) then Exit;
Result := FUseCnt[Idx] = 1;
end;
function TDecompiler.ExprOf(const R: TSSARef; PC: Integer): AnsiString;
var
Idx: Integer;
Node: PSSANode;
I: Integer;
Found: Boolean;
B, N: Integer;
Nd: PSSANode;
begin
{ Constant reference }
if R.Reg = SSA_CONST_REG then begin
Result := ConstStr(R.ConstIdx); Exit;
end;
if R.Reg < 0 then begin
Result := 'nil'; Exit;
end;
Idx := NodeIdx(R.Reg, R.Version);
{ Check cached expression - but for user-local registers where the cached
value might be stale (different scope), verify the cache matches.
This is critical for generic for loops where the same PHI register
is referenced from the body (where loop vars like 'word' are in scope)
and from elsewhere (where they're not).
Exception: compound expressions (containing 'or'/'and' operators or
parenthesized) are computed values from TryEmitOrAnd and should always
be returned as-is, since they represent the actual value of the PHI. }
if (Idx >= 0) and (Idx < Length(FExprStr)) and (FExprStr[Idx] <> '') then begin
{ Compound/computed expressions are always authoritative - return as-is.
This includes boolean (or/and), comparison, and arithmetic expressions
cached by accumulator detection or TryEmitOrAnd. }
if (Pos(' or ', FExprStr[Idx]) > 0) or
(Pos(' and ', FExprStr[Idx]) > 0) or
(Pos(' == ', FExprStr[Idx]) > 0) or
(Pos(' ~= ', FExprStr[Idx]) > 0) or
(Pos(' < ', FExprStr[Idx]) > 0) or
(Pos(' <= ', FExprStr[Idx]) > 0) or
(Pos(' > ', FExprStr[Idx]) > 0) or
(Pos(' >= ', FExprStr[Idx]) > 0) or
(Pos(' + ', FExprStr[Idx]) > 0) or
(Pos(' - ', FExprStr[Idx]) > 0) or
(Pos(' * ', FExprStr[Idx]) > 0) or
(Pos(' / ', FExprStr[Idx]) > 0) or
(Pos(' % ', FExprStr[Idx]) > 0) or
(Pos(' ^ ', FExprStr[Idx]) > 0) or
(Pos('..', FExprStr[Idx]) > 0) then begin
Result := FExprStr[Idx]; Exit;
end;
{ If the register has a user-local name at the current PC,
check if it matches the cached expression. If not, the cache
is from a different scope - use the local name instead. }
if (R.Reg >= 0) and IsUserLocal(R.Reg, PC) then begin
Result := LocalName(R.Reg, PC);
if Result <> FExprStr[Idx] then Exit;
end;
Result := FExprStr[Idx]; Exit;
end;
{ Cycle detection }
if (Idx >= 0) and (Idx < Length(FVisited)) and FVisited[Idx] then begin
Result := LocalName(R.Reg, PC); Exit;
end;
{ Depth limit to prevent stack overflow }
Inc(FExprDepth);
if FExprDepth > 200 then begin
Dec(FExprDepth);
Result := LocalName(R.Reg, PC); Exit;
end;
{ Mark as visiting }
if (Idx >= 0) and (Idx < Length(FVisited)) then
FVisited[Idx] := True;
try
{ Find the defining node }
Found := False;
Node := nil;
for B := 0 to High(FSF^.Blocks) do begin
for N := 0 to High(FSF^.Blocks[B].Nodes) do begin
Nd := FSF^.Blocks[B].Nodes[N];
if RefEqual(Nd^.Dest, R) then begin
Node := Nd;
Found := True;
Break;
end;
end;
if Found then Break;
end;
if not Found then begin
{ If this register is a user-local at the USE site, return the local name.
This handles registers defined implicitly by TFORLOOP/TFORCALL (generic
for-loop variables), FORLOOP (numeric for), or LOADNIL range extras -
cases where the rename pass tracks the definition on version stacks but
no SSA node has a Dest field matching this ref. }
if IsUserLocal(R.Reg, PC) then begin
Result := LocalName(R.Reg, PC); Exit;
end;
{ Check DefNodeMap for implicit extra defs (TFORLOOP loop vars,
CALL multi-return slots, SELF implicit copy). These map to the
parent node whose Dest ≠ R, so the block scan above missed them. }
Node := DefNodeFor(R);
if (Node <> nil) and (not RefEqual(Node^.Dest, R)) then begin
{ SELF special case: R(A+1) := R(B) - return the object expression,
not TempName, because R(A+1) is a copy of the object register and
has no defining statement in output.
Recursion guard: if OpA.Reg = R.Reg (e.g. B = A+1), fall back to TempName. }
if (Node^.Kind = SSA_SELF) and (R.Reg = Node^.ImmA) and
(Node^.OpA.Reg <> R.Reg) then
Result := ExprOf(Node^.OpA, PC)
else
Result := TempName(R.Reg);
if (Idx >= 0) and (Idx < Length(FExprStr)) then
FExprStr[Idx] := Result;
Exit;
end;
{ Check if this register was defined by a LOADNIL range (R[A]..R[B] := nil)
where the node's Dest is R[A] but this register is R[A+k] with k>0.
The SSA rename pass tracks these extra definitions on version stacks,
but no node has Dest matching R[A+k]. }
for B := 0 to High(FSF^.Blocks) do begin
for N := 0 to High(FSF^.Blocks[B].Nodes) do begin
Nd := FSF^.Blocks[B].Nodes[N];
if (Nd^.Kind = SSA_LOADNIL) and
(R.Reg > Nd^.ImmA) and (R.Reg <= Nd^.ImmB) then begin
{ If this register is a user local, return the local name }
if IsUserLocal(R.Reg, Nd^.PC) or IsUserLocal(R.Reg, Nd^.PC + 1) then begin
Result := LocalName(R.Reg, Nd^.PC + 1); Exit;
end;
Result := 'nil'; Exit;
end;
end;
end;
{ If the register is not a parameter and was never written to,
it defaults to nil in the Lua VM. Emit 'nil' instead of 't<N>'. }
if R.Reg >= FProto^.NumParams then begin
Result := 'nil'; Exit;
end;
Result := RegRef(R, PC); Exit;
end;
{ If the defining node writes to a user-local register, return the
local name instead of inlining the expression. This prevents
"local t = {}; t.w = 3" becoming "{}.w = 3" and
"local c = os.clock(); ... c" becoming "os.clock()".
Note: LocVar StartPC is typically DefPC+1 (local comes in scope after
the defining instruction), so check both DefPC and DefPC+1.
For NEWTABLE: LocVar may start much later (after SETTABLE/SETLIST
constructor initialization), so look ahead up to 32 PCs. }
if (Node^.Dest.Reg >= 0) and
(not (Node^.Kind in [SSA_PHI, SSA_FORLOOP, SSA_FORPREP, SSA_TFORLOOP,
SSA_CLOSURE])) then begin
{ Use strict scope check (PC < EndPC) for the defining node to prevent
boundary false positives where a dying LocVar at EndPC makes the
register look like a local when it's actually being reused as a temp. }
if IsUserLocalStrict(Node^.Dest.Reg, Node^.PC) or
IsUserLocalStrict(Node^.Dest.Reg, Node^.PC + 1) then begin
Result := LocalName(Node^.Dest.Reg, Node^.PC + 1);
if (Idx >= 0) and (Idx < Length(FExprStr)) then
FExprStr[Idx] := Result;
Exit;
end;
{ For NEWTABLE, look further ahead for the LocVar.
However, only claim the LocVar if no OTHER definition of the same
register exists between the NEWTABLE and the LocVar start - otherwise
the LocVar belongs to that later definition, not to this NEWTABLE.
Example: "path = path or {}" produces NEWTABLE R3 at pc 2, but
"local targetType" also uses R3 starting at pc 5 with a different
defining instruction. Without this check we'd wrongly return
"targetType" instead of "{}". }
if Node^.Kind = SSA_NEWTABLE then begin
for I := 2 to 32 do begin
if IsUserLocal(Node^.Dest.Reg, Node^.PC + I) then begin
{ Verify no other definition of this register exists between
NEWTABLE PC+1 and PC+I (exclusive). If one does, the LocVar
belongs to that other def, not the NEWTABLE. }
Found := False;
for B := 0 to High(FSF^.Blocks) do begin
for N := 0 to High(FSF^.Blocks[B].Nodes) do begin
Nd := FSF^.Blocks[B].Nodes[N];
if (Nd <> Node) and (Nd^.Kind <> SSA_PHI) and
(Nd^.Dest.Reg = Node^.Dest.Reg) and
(Nd^.PC > Node^.PC) and (Nd^.PC <= Node^.PC + I) then begin
Found := True; Break;
end;
end;
if Found then Break;
end;
if not Found then begin
Result := LocalName(Node^.Dest.Reg, Node^.PC + I);
if (Idx >= 0) and (Idx < Length(FExprStr)) then
FExprStr[Idx] := Result;
Exit;
end;
{ Another def exists - don't claim this LocVar, keep scanning
(but in practice the first match failing means all later will too) }
Break;
end;
end;
{ If the NEWTABLE has more than 1 real (non-PHI) use, assign a variable
name to prevent re-inlining '{}' which would produce wrong code like
"{}.w = 3". PHI references are SSA artifacts and don't count. }
if (Idx >= 0) and (Idx < Length(FUseCnt)) and
((FUseCnt[Idx] - CountPhiUses(Node^.Dest.Reg, Node^.Dest.Version)) > 1) then begin
Result := TempName(Node^.Dest.Reg);
if (Idx >= 0) and (Idx < Length(FExprStr)) then
FExprStr[Idx] := Result;
Exit;
end;
{ 0 or 1 uses - fall through to NodeExpr which returns '{}' }
end;
end;
{ For PHI nodes: check if the register has a user-local name at the
USE site (caller's PC) rather than the DEF site (PHI's PC).
This is critical for generic for loops where the loop variables
(k, v, etc.) are in scope at the body block but NOT at the
TFORLOOP block where the PHI lives. }
if (Node^.Kind = SSA_PHI) and (Node^.Dest.Reg >= 0) and
IsUserLocal(Node^.Dest.Reg, PC) then begin
Result := LocalName(Node^.Dest.Reg, PC);
{ Don't cache in FExprStr: the same PHI might be referenced from
different PCs where different locals are in scope. }
Exit;
end;
Result := NodeExpr(Node);
if (Idx >= 0) and (Idx < Length(FExprStr)) then
FExprStr[Idx] := Result;
finally
Dec(FExprDepth);
if (Idx >= 0) and (Idx < Length(FVisited)) then
FVisited[Idx] := False;
end;
end;
function TDecompiler.NodeExpr(Node: PSSANode): AnsiString;
var
LHS, RHS, Mid: AnsiString;
FuncExpr, Args, ArgExpr: AnsiString;
ArgI, I, J, B: Integer;
RhsNode, LhsNode, ArgNode: PSSANode;
TrivialPhi, IsNegLit: Boolean;
DefNode, FirstDef: PSSANode;
begin
case Node^.Kind of
SSA_MOVE: begin
Result := ExprOf(Node^.OpA, Node^.PC);
end;
SSA_LOADK: begin
Result := ConstStr(Node^.ConstIdx);
end;
SSA_LOADBOOL: begin
if Node^.ImmA <> 0 then Result := 'true' else Result := 'false';
end;
SSA_LOADNIL: begin
Result := 'nil';
end;
SSA_GETUPVAL: begin
Result := UpvalName(Node^.UpvalIdx);
end;
SSA_GETGLOBAL: begin
Result := ConstStr(Node^.ConstIdx);
{ Strip quotes if it's a string key used as global name }
if (Length(Result) >= 2) and (Result[1] = '"') then
Result := Copy(Result, 2, Length(Result) - 2);
end;
SSA_GETTABLE: begin
{ When OpA is SSA_NO_REF but UpvalIdx is set, this is an upvalue table
access (GETTABUP with non-_ENV upvalue). Use the upvalue name. }
if (Node^.OpA.Reg < 0) and (Node^.UpvalIdx >= 0) then
LHS := UpvalName(Node^.UpvalIdx)
else
LHS := ExprOf(Node^.OpA, Node^.PC);
RHS := ExprOf(Node^.OpB, Node^.PC);
{ Lua 5.1 does not allow indexing a table constructor directly:
"{...}[k]" must be written as "({...})[k]". }
if (Length(LHS) > 0) and (LHS[1] = '{') then
LHS := '(' + LHS + ')';
{ _ENV table access --> emit as plain global (e.g. _ENV.print --> print) }
if LHS = '_ENV' then begin
if (Length(RHS) >= 2) and (RHS[1] = '"') then begin
Mid := Copy(RHS, 2, Length(RHS) - 2);
if IsValidLuaIdent(Mid) then
Result := Mid
else
Result := '_ENV[' + RHS + ']';
Exit;
end;
Result := '_ENV[' + RHS + ']'; Exit;
end;
{ Use dot notation for string keys that are valid identifiers }
if (Length(RHS) >= 2) and (RHS[1] = '"') then begin
Mid := Copy(RHS, 2, Length(RHS) - 2);
if IsValidLuaIdent(Mid) then begin
Result := LHS + '.' + Mid; Exit;
end;
end;
Result := LHS + '[' + RHS + ']';
end;
SSA_NEWTABLE: begin
Result := '{}';
end;
SSA_BINOP: begin
LHS := ExprOf(Node^.OpA, Node^.PC);
RHS := ExprOf(Node^.OpB, Node^.PC);
{ Add parentheses around operands when needed for correctness.
Lua operator associativity:
Left-associative: + - * / %
Right-associative: ^
For LEFT-associative ops, the compiler naturally computes (LHS op RHS):
- RHS with strictly lower prec --> always needs parens.
- RHS with SAME prec --> needs parens because the natural
grouping is left-to-right but source had explicit right-grouping.
E.g., x + (y + z) differs from (x + y) + z in float semantics.
Exception: if outer op is ^ (right-assoc), RHS same prec is natural.
For RIGHT-associative op (^):
- LHS with same prec --> needs parens because natural grouping is
right-to-left but source had explicit left-grouping.
E.g., (x ^ y) ^ z differs from x ^ (y ^ z). }
begin
{ Find the defining node of the right operand }
RhsNode := nil;
if (Node^.OpB.Reg >= 0) and (Node^.OpB.Reg <> SSA_CONST_REG) then begin
for B := 0 to High(FSF^.AllNodes) do
if RefEqual(FSF^.AllNodes[B]^.Dest, Node^.OpB) then begin
RhsNode := FSF^.AllNodes[B]; Break;
end;
end;
if (RhsNode <> nil) and (RhsNode^.Kind = SSA_BINOP) then begin
if Pos(' ', RHS) > 0 then begin { only wrap if RHS contains an operator }
if (BinOpPrec(RhsNode^.BinOp) < BinOpPrec(Node^.BinOp)) then
RHS := '(' + RHS + ')'
else if (BinOpPrec(RhsNode^.BinOp) = BinOpPrec(Node^.BinOp)) and
(Node^.BinOp <> bopPow) then
{ Same precedence + left-associative outer op --> RHS was explicitly
parenthesized in source. Emit parens to preserve grouping. }
RHS := '(' + RHS + ')';
end;
end;
{ LHS parens: lower prec always needs parens.
Same prec + right-associative outer (^) --> LHS was explicitly grouped. }
LhsNode := nil;
if (Node^.OpA.Reg >= 0) and (Node^.OpA.Reg <> SSA_CONST_REG) then begin
for B := 0 to High(FSF^.AllNodes) do
if RefEqual(FSF^.AllNodes[B]^.Dest, Node^.OpA) then begin
LhsNode := FSF^.AllNodes[B]; Break;
end;
end;
if (LhsNode <> nil) and (LhsNode^.Kind = SSA_BINOP) then begin
if Pos(' ', LHS) > 0 then begin
if (BinOpPrec(LhsNode^.BinOp) < BinOpPrec(Node^.BinOp)) then
LHS := '(' + LHS + ')'
else if (BinOpPrec(LhsNode^.BinOp) = BinOpPrec(Node^.BinOp)) and
(Node^.BinOp = bopPow) then
{ Same prec + right-assoc outer --> LHS was explicitly grouped }
LHS := '(' + LHS + ')';
end;
end;
end;
{ Lua 5.4+ compiles `a - N` as ADDI/ADDK with negative constant,
producing `a + -N` in the SSA. Detect and emit `a - N` instead. }
if (Node^.BinOp = bopAdd) and (Length(RHS) > 1) and (RHS[1] = '-') then begin
{ Check RHS is a negative numeric literal (digits/dots after the minus) }
IsNegLit := True;
for B := 2 to Length(RHS) do
if not (RHS[B] in ['0'..'9', '.']) then begin
IsNegLit := False; Break;
end;
if IsNegLit then
Result := LHS + ' - ' + Copy(RHS, 2, Length(RHS) - 1)
else
Result := LHS + ' ' + BinOpStr(Node^.BinOp) + ' ' + RHS;
end else
Result := LHS + ' ' + BinOpStr(Node^.BinOp) + ' ' + RHS;
end;
SSA_UNOP: begin
RHS := ExprOf(Node^.OpA, Node^.PC);
{ If the operand is a BINOP, wrap in parens: -(a + b) not -a + b }
if (Node^.OpA.Reg >= 0) and (Node^.OpA.Reg <> SSA_CONST_REG) then begin
RhsNode := nil;
for B := 0 to High(FSF^.AllNodes) do
if RefEqual(FSF^.AllNodes[B]^.Dest, Node^.OpA) then begin
RhsNode := FSF^.AllNodes[B]; Break;
end;
if (RhsNode <> nil) and (RhsNode^.Kind = SSA_BINOP) then
RHS := '(' + RHS + ')';
end;
{ Prevent '--x' which is a Lua comment: -(-x) must become -(-x) }
if (Node^.UnOp = uopNeg) and (Length(RHS) > 0) and (RHS[1] = '-') then
RHS := '(' + RHS + ')';
Result := UnOpStr(Node^.UnOp) + RHS;
end;
SSA_CONCAT: begin
{ CONCAT R(A) := R(B) .. R(B+1) .. ... .. R(C)
ImmA = B (first register), ImmB = C (last register).
Iterate over all registers in the range.
Use ExprOf for the first and last (which have SSA refs in OpA/OpB),
and CallFuncExpr for intermediates (strictly before this PC). }
Result := '';
for I := Node^.ImmA to Node^.ImmB do begin
if Result <> '' then Result := Result + ' .. ';
if I = Node^.ImmA then begin
LHS := ExprOf(Node^.OpA, Node^.PC);
{ .. is right-associative. If the first operand is itself a CONCAT
result (inlined as "a .. b"), the source had explicit left-grouping:
(x .. y) .. z. Wrap in parens to preserve. }
if (Pos(' .. ', LHS) > 0) then begin
LhsNode := nil;
if (Node^.OpA.Reg >= 0) and (Node^.OpA.Reg <> SSA_CONST_REG) then
for B := 0 to High(FSF^.AllNodes) do
if RefEqual(FSF^.AllNodes[B]^.Dest, Node^.OpA) then begin
LhsNode := FSF^.AllNodes[B]; Break;
end;
if (LhsNode <> nil) and (LhsNode^.Kind = SSA_CONCAT) then
LHS := '(' + LHS + ')';
end;
Result := Result + LHS;
end
else if I = Node^.ImmB then
Result := Result + ExprOf(Node^.OpB, Node^.PC)
else
Result := Result + CallFuncExpr(I, Node^.PC);
end;
end;
SSA_CLOSURE: begin
Result := DecompileSubProto(Node^.ConstIdx, Node^.PC);
end;
SSA_VARARG: begin
Result := '...';
end;
SSA_CALL: begin
{ Function is in OpA (SSA-versioned, set before CALL redefines R(A)) }
FuncExpr := ExprOf(Node^.OpA, Node^.PC);
{ Detect if OpA was defined by a SELF instruction - if so, the first
ArgRef is the implicit "self" table which is already bound by the
colon operator in the function expression. Skip it. }
ArgI := 0; { starting index into ArgRefs }
if (Node^.OpA.Reg >= 0) and (Node^.OpA.Reg <> SSA_CONST_REG) then begin
for I := 0 to High(FSF^.AllNodes) do
if RefEqual(FSF^.AllNodes[I]^.Dest, Node^.OpA) and
(FSF^.AllNodes[I]^.Kind = SSA_SELF) then begin
ArgI := 1; { skip first arg (implicit self) }
Break;
end;
end;
Args := '';
if Length(Node^.ArgRefs) > ArgI then begin
while ArgI <= High(Node^.ArgRefs) do begin
if Args <> '' then Args := Args + ', ';
ArgExpr := StripOuterParens(ExprOf(Node^.ArgRefs[ArgI], Node^.PC));
{ Detect "(g())" adjustment: if this is the last argument and it
resolves to a CALL with ImmC=2 (forced single return), wrap in
parens to show the truncation. Without parens, f(g()) passes
all of g()'s returns to f; with parens, f((g())) takes only 1. }
if ArgI = High(Node^.ArgRefs) then begin
ArgNode := nil;
for J := 0 to High(FSF^.AllNodes) do begin
if RefEqual(FSF^.AllNodes[J]^.Dest, Node^.ArgRefs[ArgI]) then begin
ArgNode := FSF^.AllNodes[J]; Break;
end;
end;
if (ArgNode <> nil) and (ArgNode^.Kind = SSA_CALL) and
(ArgNode^.ImmC = 2) then
ArgExpr := '(' + ArgExpr + ')';
{ Similarly, VARARG that is truncated to a single value needs parens.
ImmB=2 means explicit single-value VARARG (Lua 5.1).
ImmB=0 (variable) with a fixed-arg CALL (Node^.ImmB > 0) means
the compiler loaded all vararg but the CALL truncates to 1. }
if (ArgNode <> nil) and (ArgNode^.Kind = SSA_VARARG) and
((ArgNode^.ImmB = 2) or
((ArgNode^.ImmB = 0) and (Node^.ImmB > 0))) then
ArgExpr := '(' + ArgExpr + ')';
end;
Args := Args + ArgExpr;
Inc(ArgI);
end;
end else if (Node^.ImmB = 0) and (Length(Node^.ArgRefs) = 0) then
Args := '...';
{ IIFE: if FuncExpr is a function literal, wrap in parens so that
"function(...)...end(args)" becomes "(function(...)...end)(args)" }
if Copy(FuncExpr, 1, 8) = 'function' then
Result := '(' + FuncExpr + ')(' + Args + ')'
else
Result := FuncExpr + '(' + Args + ')';
end;
SSA_PHI: begin
Result := '';
{ Trivial PHI: all operands are the same SSA ref --> fold directly }
if (Length(Node^.Operands) >= 2) then begin
TrivialPhi := True;
for B := 1 to High(Node^.Operands) do
if not RefEqual(Node^.Operands[B], Node^.Operands[0]) then begin
TrivialPhi := False; Break;
end;
if TrivialPhi then begin
Result := ExprOf(Node^.Operands[0], Node^.PC);
end;
end;
{ Trivial PHI: all operands are GETGLOBAL with the same constant.
This handles passthrough PHIs where the same global (e.g., "print")
flows through multiple boolean expression chain paths with different
SSA versions but the same value. }
if (Result = '') and (Length(Node^.Operands) >= 2) then begin
{ Find defining node for first operand }
FirstDef := nil;
for B := 0 to High(FSF^.AllNodes) do
if RefEqual(FSF^.AllNodes[B]^.Dest, Node^.Operands[0]) then begin
FirstDef := FSF^.AllNodes[B]; Break;
end;
if (FirstDef <> nil) and (FirstDef^.Kind = SSA_GETGLOBAL) then begin
TrivialPhi := True;
for J := 1 to High(Node^.Operands) do begin
DefNode := nil;
for B := 0 to High(FSF^.AllNodes) do
if RefEqual(FSF^.AllNodes[B]^.Dest, Node^.Operands[J]) then begin
DefNode := FSF^.AllNodes[B]; Break;
end;
if (DefNode = nil) or (DefNode^.Kind <> SSA_GETGLOBAL) or
(DefNode^.ConstIdx <> FirstDef^.ConstIdx) then begin
TrivialPhi := False; Break;
end;
end;
if TrivialPhi then
Result := ExprOf(Node^.Operands[0], Node^.PC);
end;
end;
{ Try to detect comparison LOADBOOL patterns (return x < y) }
if (Result = '') and (Length(Node^.Operands) = 2) and (Length(Node^.PhiBlocks) = 2) then
Result := TryBuildComparisonExpr(Node);
{ Try to detect or/and expression patterns at the PHI level. }
if (Result = '') and (Length(Node^.Operands) = 2) and (Length(Node^.PhiBlocks) = 2) then
Result := TryBuildOrAndExpr(Node);
{ Detect "not (a and b)" / "not (a or b)" patterns:
PHI with LOADBOOL constants + UNOP[not], with dead blocks from LOADBOOL pairs }
if (Result = '') and (Length(Node^.Operands) >= 2) then
Result := TryBuildNegatedCompoundExpr(Node);
{ For 3+ operand PHIs (chained or/and like ((sum==2) and val) or ((sum==3) and 1) or 0) }
if (Result = '') and (Length(Node^.Operands) >= 2) then
Result := TryBuildChainedPhiExpr(Node);
if Result = '' then begin
{ Default: use local name for the register at this PC.
This handles loop-carried PHIs correctly (returns ym1, yi, etc.) }
Result := LocalName(Node^.Dest.Reg, Node^.PC);
end;
end;
SSA_SELF: begin
LHS := ExprOf(Node^.OpA, Node^.PC);
RHS := ExprOf(Node^.OpB, Node^.PC);
{ Ensure LHS is a valid prefix expression for method calls.
String/number literals and other non-prefixexp values need parens. }
if (Length(LHS) > 0) and not (
(LHS[Length(LHS)] = ')') or { already parenthesized or call result }
(LHS[Length(LHS)] = ']') or { index result }
((LHS[1] in ['A'..'Z','a'..'z','_']) and { simple identifier/dotted chain }
(Pos('(', LHS) = 0) and (Pos(' ', LHS) = 0)) or
(LHS[1] = '(') { already wrapped in parens }
) then
LHS := '(' + LHS + ')';
if (Length(RHS) >= 2) and (RHS[1] = '"') then
Result := LHS + ':' + Copy(RHS, 2, Length(RHS) - 2)
else
Result := LHS + '[' + RHS + ']';
end;
SSA_BRANCH: begin
{ For TESTSET branches used as value expressions in or/and patterns,
return the value being conditionally assigned (OpA). }
if Node^.RelOp = ropTestSet then
Result := ExprOf(Node^.OpA, Node^.PC)
else
Result := BuildCompare(Node^.OpA, Node^.OpB, Node^.RelOp,
Node^.Invert, Node^.PC);
end;
SSA_FORLOOP: begin
{ The exposed loop variable R(A+3); look up name in the loop body PC range.
LocalName already handles the register-to-LocVar mapping correctly,
so no additional fallback search is needed. }
Result := LocalName(Node^.Dest.Reg, Node^.TargetTrue);
end;
else
if Node^.Dest.Reg >= 0 then
Result := LocalName(Node^.Dest.Reg, Node^.PC)
else
Result := '?';
end;
end;
{ ======================================================================
Constant folding
====================================================================== }
procedure TDecompiler.FoldConstants;
var
I: Integer;
Node: PSSANode;
LA, LB, LR: Double;
HasA, HasB: Boolean;
Idx: Integer;
begin
for I := 0 to High(FSF^.AllNodes) do begin
Node := FSF^.AllNodes[I];
if Node^.Kind <> SSA_BINOP then Continue;
HasA := (Node^.OpA.Reg = SSA_CONST_REG) and
(Node^.OpA.ConstIdx >= 0) and
(Node^.OpA.ConstIdx < Length(FProto^.K)) and
(FProto^.K[Node^.OpA.ConstIdx].Kind = lckNumber);
HasB := (Node^.OpB.Reg = SSA_CONST_REG) and
(Node^.OpB.ConstIdx >= 0) and
(Node^.OpB.ConstIdx < Length(FProto^.K)) and
(FProto^.K[Node^.OpB.ConstIdx].Kind = lckNumber);
if not (HasA and HasB) then Continue;
LA := FProto^.K[Node^.OpA.ConstIdx].NValue;
LB := FProto^.K[Node^.OpB.ConstIdx].NValue;
case Node^.BinOp of
bopAdd: LR := LA + LB;
bopSub: LR := LA - LB;
bopMul: LR := LA * LB;
bopDiv: if LB = 0 then Continue else LR := LA / LB;
bopMod: if LB = 0 then Continue else LR := LA - Trunc(LA/LB)*LB;
bopPow: LR := Power(LA, LB);
else Continue;
end;
{ Fold: change node into LOADK with a synthetic constant }
Node^.Kind := SSA_LOADK;
{ Store folded value in the constant string cache directly }
Idx := NodeIdx(Node^.Dest.Reg, Node^.Dest.Version);
if (Idx >= 0) and (Idx < Length(FExprStr)) then begin
if (Frac(LR) = 0) and (LR >= -1e15) and (LR <= 1e15) then
FExprStr[Idx] := IntToStr(Trunc(LR))
else
FExprStr[Idx] := FloatToStr(LR);
end;
end;
end;
{ ======================================================================
Use counting
====================================================================== }
procedure TDecompiler.CountUses;
var
I: Integer;
Node: PSSANode;
TotalSlots: Integer;
J, K: Integer;
procedure Inc_(const R: TSSARef);
var Idx: Integer;
begin
if R.Reg < 0 then Exit;
Idx := NodeIdx(R.Reg, R.Version);
if (Idx >= 0) and (Idx < TotalSlots) then
Inc(FUseCnt[Idx]);
end;
begin
TotalSlots := FProto^.MaxStack * FMaxVer;
SetLength(FUseCnt, TotalSlots);
SetLength(FExprStr, TotalSlots);
SetLength(FInlined, TotalSlots);
SetLength(FVisited, TotalSlots);
for I := 0 to TotalSlots - 1 do begin
FUseCnt[I] := 0;
FExprStr[I] := '';
FInlined[I] := False;
FVisited[I] := False;
end;
for I := 0 to High(FSF^.AllNodes) do begin
Node := FSF^.AllNodes[I];
Inc_(Node^.OpA);
Inc_(Node^.OpB);
Inc_(Node^.OpC);
for J := 0 to High(Node^.Operands) do
Inc_(Node^.Operands[J]);
for J := 0 to High(Node^.ArgRefs) do
Inc_(Node^.ArgRefs[J]);
{ CONCAT uses all registers in the range ImmA..ImmB implicitly.
OpA and OpB already carry SSA refs for the first and last registers,
but intermediate registers (ImmA+1..ImmB-1) are NOT in any SSA ref.
Find the SSA defs for these intermediates and count them as used. }
if (Node^.Kind = SSA_CONCAT) and (Node^.ImmB - Node^.ImmA > 1) then begin
for J := Node^.ImmA + 1 to Node^.ImmB - 1 do begin
{ Scan backwards from this CONCAT node to find the most recent
definition of register J before this PC. }
for K := I downto 0 do begin
if (FSF^.AllNodes[K]^.Dest.Reg = J) and
(FSF^.AllNodes[K]^.PC <= Node^.PC) and
(FSF^.AllNodes[K]^.Kind <> SSA_PHI) then begin
Inc_(FSF^.AllNodes[K]^.Dest);
Break;
end;
end;
end;
end;
end;
end;
{ ======================================================================
SSA definition lookup helpers
====================================================================== }
{ Find the SSA node that defines a register in a specific block (skip structural) }
function TDecompiler.FindDefNode(BIdx, Reg: Integer): PSSANode;
var
I: Integer;
N: PSSANode;
begin
Result := nil;
for I := 0 to High(FSF^.Blocks[BIdx].Nodes) do begin
N := FSF^.Blocks[BIdx].Nodes[I];
if (N^.Kind in [SSA_PHI, SSA_NOP, SSA_FORPREP, SSA_FORLOOP, SSA_TFORLOOP]) then
Continue;
if (N^.Dest.Reg = Reg) then begin
Result := N;
{ Don't break: take the LAST definition (in case of multiple defs) }
end;
end;
end;
{ Find the SSA node that defines a register anywhere.
If BeforePC >= 0, only consider defs with PC < BeforePC.
Returns the LAST matching definition found. }
function TDecompiler.FindDefNodeAll(Reg: Integer): PSSANode;
var
B, I: Integer;
N: PSSANode;
begin
Result := nil;
for B := 0 to High(FSF^.Blocks) do
for I := 0 to High(FSF^.Blocks[B].Nodes) do begin
N := FSF^.Blocks[B].Nodes[I];
if (N^.Kind <> SSA_PHI) and (N^.Kind <> SSA_NOP) and
(N^.Dest.Reg = Reg) then
Result := N;
end;
end;
{ Get an expression string for a register by finding its defining node.
Finds the last definition of Reg at or before PC. }
function TDecompiler.RegExpr(Reg, PC: Integer): AnsiString;
var
N: PSSANode;
B, I: Integer;
Nd: PSSANode;
begin
N := nil;
for B := 0 to High(FSF^.Blocks) do
for I := 0 to High(FSF^.Blocks[B].Nodes) do begin
Nd := FSF^.Blocks[B].Nodes[I];
if (Nd^.Kind <> SSA_PHI) and (Nd^.Kind <> SSA_NOP) and
(Nd^.Dest.Reg = Reg) and (Nd^.PC <= PC) then
N := Nd;
end;
if N <> nil then
Result := NodeExpr(N)
else
Result := LocalName(Reg, PC);
end;
{ Like RegExpr, but only considers defs strictly before BeforePC.
Used to resolve the function register for a CALL that redefines the
same register as its result. }
function TDecompiler.CallFuncExpr(Reg, BeforePC: Integer): AnsiString;
var
N: PSSANode;
B, I: Integer;
Nd: PSSANode;
begin
N := nil;
for B := 0 to High(FSF^.Blocks) do
for I := 0 to High(FSF^.Blocks[B].Nodes) do begin
Nd := FSF^.Blocks[B].Nodes[I];
if (Nd^.Kind <> SSA_PHI) and (Nd^.Kind <> SSA_NOP) and
(Nd^.Dest.Reg = Reg) and (Nd^.PC < BeforePC) then
N := Nd;
end;
if N <> nil then
Result := NodeExpr(N)
else
Result := LocalName(Reg, BeforePC);
end;