-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLuaDecompBoolean.inc
More file actions
2255 lines (2097 loc) · 94 KB
/
Copy pathLuaDecompBoolean.inc
File metadata and controls
2255 lines (2097 loc) · 94 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
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function TDecompiler.TryEmitOrAnd(BranchBlk, TrueBlk, FalseBlk: Integer): Boolean;
var
BranchNode: PSSANode;
I, J, S: Integer;
JmpBlk, ValBlk, MergeIdx: Integer;
CondExpr, ValExpr, CombinedExpr: AnsiString;
IsOr: Boolean;
PhiNode: PSSANode;
PhiIdx: Integer;
HasOnlyJmp, HasValDef: Boolean;
ValDefNode, EffectiveValDef: PSSANode;
N: PSSANode;
{ Chain continuation variables }
FinalMerge, NextMerge, Safety: Integer;
FinalPhiNode, NextPhiNode, DefaultNode: PSSANode;
LHS, Segment: AnsiString;
HasSideEffect, IsChainIntermediate: Boolean;
UsesTestedReg: Boolean;
ValN: PSSANode;
begin
Result := False;
if FOpts.Debug then
WriteLn(StdErr, 'TryEmitOrAnd: checking BB', BranchBlk,
' TrueBlk=BB', TrueBlk, ' FalseBlk=BB', FalseBlk);
{ Find the BRANCH node in the branch block }
BranchNode := nil;
for I := 0 to High(FSF^.Blocks[BranchBlk].Nodes) do
if FSF^.Blocks[BranchBlk].Nodes[I]^.Kind = SSA_BRANCH then begin
BranchNode := FSF^.Blocks[BranchBlk].Nodes[I]; Break;
end;
if BranchNode = nil then begin
if FOpts.Debug then
WriteLn(StdErr, 'TryEmitOrAnd: failed - no BRANCH node in BB', BranchBlk);
Exit;
end;
{ Accept TEST/TESTSET or comparison operations (EQ/LT/LE) for or/and patterns }
{ Validate both successors exist and are forward }
if (TrueBlk < 0) or (FalseBlk < 0) then begin
if FOpts.Debug then
WriteLn(StdErr, 'TryEmitOrAnd: failed - invalid successor indices');
Exit;
end;
if (TrueBlk >= Length(FSF^.Blocks)) or (FalseBlk >= Length(FSF^.Blocks)) then begin
if FOpts.Debug then
WriteLn(StdErr, 'TryEmitOrAnd: failed - successor out of range');
Exit;
end;
{ Determine which successor is the single-JMP block (pass-through) and
which is the value-definition block (fallback).
For "or" (Invert=true/C=1): TrueBlk is the jump-to-merge (pass condition through),
FalseBlk has the fallback value.
For "and" (Invert=false/C=0): FalseBlk is the jump-to-merge,
TrueBlk has the fallback value. }
{ Check if TrueBlk is a single-JMP block }
HasOnlyJmp := True;
for I := 0 to High(FSF^.Blocks[TrueBlk].Nodes) do
if not (FSF^.Blocks[TrueBlk].Nodes[I]^.Kind in [SSA_JUMP, SSA_PHI, SSA_NOP]) then begin
HasOnlyJmp := False; Break;
end;
if HasOnlyJmp then begin
JmpBlk := TrueBlk;
ValBlk := FalseBlk;
end else begin
{ Check if FalseBlk is a single-JMP block }
HasOnlyJmp := True;
for I := 0 to High(FSF^.Blocks[FalseBlk].Nodes) do
if not (FSF^.Blocks[FalseBlk].Nodes[I]^.Kind in [SSA_JUMP, SSA_PHI, SSA_NOP]) then begin
HasOnlyJmp := False; Break;
end;
if not HasOnlyJmp then begin
if FOpts.Debug then
WriteLn(StdErr, 'TryEmitOrAnd: failed - neither successor is JMP-only');
Exit; { Neither is a JMP-only block; not or/and }
end;
JmpBlk := FalseBlk;
ValBlk := TrueBlk;
end;
{ Reject or/and when the JMP block leads to the current loop exit.
In that case, this is an "if cond then break end" pattern, not a
value expression. Let TryEmitBreakIf handle it instead. }
if IsBreakTarget(JmpBlk) then begin
if FOpts.Debug then
WriteLn(StdErr, 'TryEmitOrAnd: rejected - JmpBlk BB', JmpBlk,
' is break target');
Exit;
end;
{ The value block must have at least one value-defining node.
Multiple real nodes are OK (e.g., GETTABLE chain before BRANCH in chained or/and).
The LAST real node defines the value for the or/and expression.
However, side-effect statements (SETTABLE, SETGLOBAL, SETUPVAL, CALL with
no return value) indicate this is an if/then pattern, not an or/and expression.
A non-TESTSET BRANCH in ValBlk with body statements before it (CALL, GETTABLE, etc.)
indicates this is an if-then body with a nested condition, not a value arm of or/and. }
HasValDef := False;
HasSideEffect := False; { track if ValBlk has body statements }
ValDefNode := nil;
for I := 0 to High(FSF^.Blocks[ValBlk].Nodes) do begin
N := FSF^.Blocks[ValBlk].Nodes[I];
if N^.Kind in [SSA_JUMP, SSA_PHI, SSA_NOP] then Continue;
if N^.Kind = SSA_BRANCH then begin
{ TESTSET branches (RelOp=ropTestSet) define a value - treat as value def.
Other branches (TEST/EQ/LT/LE) indicate nested control flow.
If there are body statements before this branch (CALL, GETTABLE, etc.),
this is an if-then body, not a value arm of an or/and expression.
Example: "if type(x) == 'string' then local name = x; x = tbl[name];
if type(x) ~= 'function' then error(...) end end"
The inner block has MOVE+GETTABLE+CALL+BRANCH - it's a body, not a value. }
if N^.RelOp = ropTestSet then begin
HasValDef := True;
ValDefNode := N;
end else begin
{ Non-TESTSET BRANCH in ValBlk: could be a chain continuation
(e.g., "sum == 2 and self[y][x]" where self[y][x] is TEST'd),
or a nested if-condition (e.g., "if a then if b then ... end end").
Reject if ValBlk has 2+ successors where BOTH lead to blocks
that themselves have bodies (CALL, SETTABLE, etc.), indicating
this is an if-body rather than a value chain.
Accept if the TEST is on a register that feeds a PHI at the merge. }
{ Check if the merge block's PHI has a matching register.
In a true or/and chain, the merge PHI combines values from multiple
short-circuit paths. ValBlk may or may not contribute directly - in
multi-element chains, ValBlk starts a sub-chain whose descendants
contribute to the merge PHI.
Accept if the merge has a PHI on the same register AND either:
(a) ValBlk is directly a PhiBlock, or
(b) the PHI has 3+ operands (multi-element chain). }
UsesTestedReg := False;
if Length(FSF^.Blocks[JmpBlk].Succs) >= 1 then begin
S := FSF^.Blocks[JmpBlk].Succs[0]; { potential merge block }
{ Follow single-successor chain through LOADBOOL intermediates
to find the real merge block (same logic as main merge detection) }
for PhiIdx := 0 to 3 do begin
if (S < 0) or (S >= Length(FSF^.Blocks)) then Break;
if Length(FSF^.Blocks[S].Succs) <> 1 then Break;
HasOnlyJmp := True;
for J := 0 to High(FSF^.Blocks[S].Nodes) do begin
ValN := FSF^.Blocks[S].Nodes[J];
if not (ValN^.Kind in [SSA_JUMP, SSA_PHI, SSA_NOP, SSA_LOADBOOL]) then begin
HasOnlyJmp := False; Break;
end;
end;
if HasOnlyJmp then
S := FSF^.Blocks[S].Succs[0]
else
Break;
end;
if (S >= 0) and (S < Length(FSF^.Blocks)) then begin
for J := 0 to High(FSF^.Blocks[S].Nodes) do begin
ValN := FSF^.Blocks[S].Nodes[J];
if (ValN^.Kind = SSA_PHI) and
(ValN^.Dest.Reg = N^.OpA.Reg) then begin
{ Accept if ValBlk is directly a PhiBlock }
for PhiIdx := 0 to High(ValN^.PhiBlocks) do begin
if ValN^.PhiBlocks[PhiIdx] = ValBlk then begin
UsesTestedReg := True;
Break;
end;
end;
{ Also accept if PHI has 3+ operands (multi-element chain) }
if (not UsesTestedReg) and (Length(ValN^.PhiBlocks) >= 3) then
UsesTestedReg := True;
Break;
end;
end;
end;
end;
if not UsesTestedReg then begin
if FOpts.Debug then
WriteLn(StdErr, 'TryEmitOrAnd: rejected ValBlk BB', ValBlk,
' - non-TESTSET BRANCH, no PHI at merge for tested reg R',
N^.OpA.Reg);
Exit;
end;
{ Accept: the TEST feeds a PHI at the merge --> this is a chained
or/and value expression. However, the TEST BRANCH itself does NOT
produce a value - it only tests R(A). The actual value for the
or/and arm was produced by a preceding node in this block (e.g.
GETTABLE for "self[y][x]"). So we only set HasValDef if ValDefNode
was already assigned by a preceding real node (line 4151-4152).
We do NOT overwrite ValDefNode with the BRANCH. }
if ValDefNode <> nil then
HasValDef := True;
end;
Continue;
end;
if N^.Kind in [SSA_SETTABLE, SSA_SETGLOBAL, SSA_SETUPVAL, SSA_SETLIST] then Exit;
{ CALL with no return (ImmC=1) or as statement (ImmC=0) is a side-effect }
if (N^.Kind = SSA_CALL) and (N^.ImmC <= 1) then Exit;
{ CALL with return value: mark as side-effect for BRANCH rejection
(a CALL in a ValBlk followed by a BRANCH indicates an if-body, not or/and) }
if (N^.Kind = SSA_CALL) and (N^.ImmC > 1) then
HasSideEffect := True;
HasValDef := True;
ValDefNode := N; { take the last real node as the value }
end;
{ Both blocks must converge to the same merge block.
For simple patterns: JmpBlk and ValBlk share one successor.
For chained patterns: JmpBlk leads to a merge block, and ValBlk's
sub-chain eventually reaches the same merge block. We follow the
chain from JmpBlk through single-successor blocks (e.g., LOADBOOL
intermediates) and check if ValBlk also reaches it. }
if Length(FSF^.Blocks[JmpBlk].Succs) < 1 then Exit;
MergeIdx := FSF^.Blocks[JmpBlk].Succs[0];
{ Follow single-successor chain from MergeIdx to find the real merge
(handles LOADBOOL intermediate blocks: JmpBlk-->LOADBOOL-->merge).
IMPORTANT: Only follow through blocks that are truly empty intermediates
(LOADBOOL/JMP/PHI/NOP only, no value-defining content like LOADK or
GETTABLE). If a block has a PHI + value definition (e.g., LOADK for
the "or default" pattern), it IS the merge - don't skip it. }
for Safety := 0 to 3 do begin
if (MergeIdx < 0) or (MergeIdx >= Length(FSF^.Blocks)) then Break;
if Length(FSF^.Blocks[MergeIdx].Succs) = 1 then begin
{ Check if this block has value-defining content (not just LOADBOOL/JMP/PHI/NOP) }
HasOnlyJmp := True;
for I := 0 to High(FSF^.Blocks[MergeIdx].Nodes) do begin
N := FSF^.Blocks[MergeIdx].Nodes[I];
if not (N^.Kind in [SSA_JUMP, SSA_PHI, SSA_NOP, SSA_LOADBOOL]) then begin
HasOnlyJmp := False; Break;
end;
end;
if HasOnlyJmp then
MergeIdx := FSF^.Blocks[MergeIdx].Succs[0]
else
Break; { Block has real content - this is the merge point }
end else
Break;
end;
{ Check if ValBlk directly converges, or if it has a sub-chain }
if (Length(FSF^.Blocks[ValBlk].Succs) >= 1) and
(FSF^.Blocks[ValBlk].Succs[0] = MergeIdx) then begin
{ Direct convergence - simple or/and }
if not HasValDef then Exit;
end else begin
{ ValBlk might have a sub-chain (e.g., TEST-->sub-blocks-->MergeIdx).
Check if the chain eventually reaches MergeIdx.
We allow this only if ValDefNode exists (there's a value). }
if not HasValDef then Exit;
{ Verify the sub-chain converges: follow successors of ValBlk's sub-blocks
up to 8 hops to find MergeIdx. Check both successor paths. }
HasOnlyJmp := False; { reuse as "found merge" flag }
S := ValBlk;
for I := 0 to 7 do begin
if (S < 0) or (S >= Length(FSF^.Blocks)) then Break;
if Length(FSF^.Blocks[S].Succs) = 1 then begin
S := FSF^.Blocks[S].Succs[0];
if S = MergeIdx then begin HasOnlyJmp := True; Break; end;
end else if Length(FSF^.Blocks[S].Succs) >= 2 then begin
{ Check BOTH successors for MergeIdx }
if FSF^.Blocks[S].Succs[0] = MergeIdx then begin HasOnlyJmp := True; Break; end;
if FSF^.Blocks[S].Succs[1] = MergeIdx then begin HasOnlyJmp := True; Break; end;
{ Follow first successor to continue the chain }
S := FSF^.Blocks[S].Succs[0];
if S = MergeIdx then begin HasOnlyJmp := True; Break; end;
end else
Break;
end;
if not HasOnlyJmp then Exit;
end;
{ Find the PHI node at the merge block that combines the two values.
Prefer a PHI whose Dest.Reg matches the branch's value register:
- For TESTSET: prefer Dest.Reg (A = result register), then OpA.Reg (B = test register)
- For TEST: prefer OpA.Reg (test register), then Dest.Reg
- For EQ/LT/LE: prefer OpA.Reg or OpB.Reg
Fall back to first PHI if no register-matching one is found. }
PhiNode := nil;
HasOnlyJmp := False; { reuse as "found LOADBOOL PHI" flag }
for I := 0 to High(FSF^.Blocks[MergeIdx].Nodes) do begin
N := FSF^.Blocks[MergeIdx].Nodes[I];
if (N^.Kind = SSA_PHI) and (Length(N^.PhiBlocks) >= 2) then begin
case BranchNode^.RelOp of
ropTestSet:
if N^.Dest.Reg = BranchNode^.Dest.Reg then begin
PhiNode := N; Break;
end;
ropTest:
if N^.Dest.Reg = BranchNode^.OpA.Reg then begin
PhiNode := N; Break;
end;
ropEQ, ropLT, ropLE: begin
{ For comparison branches, prefer the PHI that has LOADBOOL
operands (the boolean result register), not just any PHI
matching the comparison operand registers. }
if PhiNode = nil then
PhiNode := N; { tentative: first PHI as fallback }
{ Check if this PHI has LOADBOOL source blocks }
if not HasOnlyJmp then
for J := 0 to High(N^.PhiBlocks) do begin
S := N^.PhiBlocks[J];
if (S >= 0) and (S < Length(FSF^.Blocks)) then
for PhiIdx := 0 to High(FSF^.Blocks[S].Nodes) do
if (FSF^.Blocks[S].Nodes[PhiIdx]^.Kind = SSA_LOADBOOL) and
(FSF^.Blocks[S].Nodes[PhiIdx]^.Dest.Reg = N^.Dest.Reg) then begin
PhiNode := N;
HasOnlyJmp := True; { found best match }
Break;
end;
if HasOnlyJmp then Break;
end;
end;
else
begin PhiNode := N; Break; end;
end;
if PhiNode = nil then
PhiNode := N; { fallback: first PHI }
end;
end;
{ A value-expression collapse must have a PHI result to carry the merged
short-circuit value. If no PHI exists at the detected merge, this is
structured control flow (often if/elseif/else inside a loop), not an
or/and expression. Continuing with PhiNode=nil only marks blocks emitted
and silently drops body statements. }
if PhiNode = nil then begin
if FOpts.Debug then
WriteLn(StdErr, 'TryEmitOrAnd: rejected - no PHI result at MergeIdx BB',
MergeIdx);
Exit;
end;
{ Reject if-then-assign patterns: if the ValBlk writes to a register that
has a PHI at the merge block with the same register number, this is a
conditional variable update (e.g., "if cond then count=count+1 end"),
not a genuine or/and value expression. In real or/and, the condition
value flows through the JmpBlk, but in if-then-assign the JmpBlk just
passes through the old value of the variable being modified.
EXCEPTION: For TESTSET branches, the compiler allocates a temp register
(R(A) of TESTSET) specifically for the or/and result. The ValBlk writes
to the SAME register, and the PHI merges both paths - this IS the or/and
pattern, so don't reject it.
NOTE: In Lua 5.4+, the compiler may add a MOVE after a CONCAT/BINOP/UNOP
to copy the result to the target register. When ValDefNode is a MOVE,
look through it to find the underlying value-defining instruction. }
EffectiveValDef := ValDefNode;
if (EffectiveValDef <> nil) and (EffectiveValDef^.Kind = SSA_MOVE) then begin
{ Find the node that defines the source register of this MOVE }
for I := High(FSF^.Blocks[ValBlk].Nodes) downto 0 do begin
N := FSF^.Blocks[ValBlk].Nodes[I];
if (N <> EffectiveValDef) and (N^.Dest.Reg = EffectiveValDef^.OpA.Reg) and
(N^.Kind in [SSA_BINOP, SSA_UNOP, SSA_CONCAT]) then begin
EffectiveValDef := N;
Break;
end;
end;
end;
if (EffectiveValDef <> nil) and
(EffectiveValDef^.Kind in [SSA_BINOP, SSA_UNOP, SSA_CONCAT]) and
((BranchNode^.RelOp <> ropTestSet) or
(ValDefNode^.Dest.Reg <> BranchNode^.Dest.Reg)) then begin
{ Exception: if the merge PHI has a LOADBOOL operand, this is a boolean
expression (e.g., "a < b and not c"), not a conditional assignment.
The LOADBOOL indicates that the false path produces a boolean value,
which is a hallmark of or/and value expressions. }
HasOnlyJmp := False; { reuse: LOADBOOL found flag }
if (MergeIdx >= 0) and (MergeIdx < Length(FSF^.Blocks)) then begin
for I := 0 to High(FSF^.Blocks[MergeIdx].Nodes) do begin
N := FSF^.Blocks[MergeIdx].Nodes[I];
if N^.Kind = SSA_PHI then begin
for J := 0 to High(N^.PhiBlocks) do begin
S := N^.PhiBlocks[J];
if (S >= 0) and (S < Length(FSF^.Blocks)) then begin
for PhiIdx := 0 to High(FSF^.Blocks[S].Nodes) do
if FSF^.Blocks[S].Nodes[PhiIdx]^.Kind = SSA_LOADBOOL then begin
HasOnlyJmp := True; Break;
end;
if HasOnlyJmp then Break;
end;
end;
if HasOnlyJmp then Break;
end;
end;
end;
if not HasOnlyJmp then begin
for I := 0 to High(FSF^.Blocks[MergeIdx].Nodes) do begin
N := FSF^.Blocks[MergeIdx].Nodes[I];
if (N^.Kind = SSA_PHI) and (N^.Dest.Reg = ValDefNode^.Dest.Reg) then begin
{ The ValBlk modifies a register that is merged at the merge block.
This is a conditional assignment, not an or/and expression. }
Exit;
end;
end;
end;
end;
{ Reject if MergeIdx is a loop latch/tail (has a backward successor).
Loop-carried PHIs at such blocks are NOT or/and merge points - they
track variable evolution across loop iterations. Processing them as
or/and would silently swallow the conditional assignment in the body. }
if (MergeIdx >= 0) and (MergeIdx < Length(FSF^.Blocks)) then
for I := 0 to High(FSF^.Blocks[MergeIdx].Succs) do
if FSF^.Blocks[MergeIdx].Succs[I] < MergeIdx then begin
if FOpts.Debug then
WriteLn(StdErr, 'TryEmitOrAnd: rejected - MergeIdx BB', MergeIdx,
' is loop latch (has backward succ BB',
FSF^.Blocks[MergeIdx].Succs[I], ')');
Exit;
end;
{ === Multi-operand PHI: 3+ operands for chained or/and expressions ===
First try negated compound pattern (not (a and b)), then chained handler. }
if (PhiNode <> nil) and (Length(PhiNode^.PhiBlocks) > 2) then begin
CombinedExpr := TryBuildNegatedCompoundExpr(PhiNode);
if CombinedExpr = '' then
CombinedExpr := TryBuildChainedPhiExpr(PhiNode);
if CombinedExpr = '' then begin
{ 3+ operand PHI was rejected as or/and chain (e.g., if/then/else merge).
Do NOT fall through to 2-operand handling - it would incorrectly consume
blocks that belong to structured if/then/else control flow. }
if FOpts.Debug then
WriteLn(StdErr, 'TryEmitOrAnd: 3+ operand PHI rejected by chained handler, aborting');
Exit;
end;
begin
{ Check if the outer branch's contribution is already included in the
chained PHI expression. If JmpBlk (or its chain destination) is a
direct PhiBlock source, then TryBuildChainedPhiExpr already captured
it. If JmpBlk leads to a PhiBlock through a shared intermediate
(e.g., LOADBOOL merge with another path), we need to prepend the
outer condition ourselves.
Example: "print(x == 0 or a.first and a.record.field == value)"
BB0 branches on EQ x 0 --> BB1(JMP-->BB7). BB7 is a PhiBlock but
also receives BB5 (from inner comparison), so the outer "x==0" is
not captured by the chained handler. }
HasOnlyJmp := False; { reuse: "outer already included" flag }
S := JmpBlk;
for Safety := 0 to 4 do begin
for I := 0 to High(PhiNode^.PhiBlocks) do
if PhiNode^.PhiBlocks[I] = S then begin
{ Check that this PhiBlock is exclusively from the outer branch.
If the block has multiple predecessors, the outer condition
merges with other paths and isn't individually represented. }
if Length(FSF^.Blocks[S].Preds) <= 1 then
HasOnlyJmp := True;
Break;
end;
if HasOnlyJmp then Break;
{ Follow single-successor chain }
if (S >= 0) and (S < Length(FSF^.Blocks)) and
(Length(FSF^.Blocks[S].Succs) = 1) then
S := FSF^.Blocks[S].Succs[0]
else
Break;
end;
if (not HasOnlyJmp) and (BranchNode <> nil) then begin
{ Outer condition not included - prepend it.
Determine the raw condition and or/and operator.
For EQ/LT/LE: use non-inverted comparison. The operator depends
on whether JmpBlk = Succs[0] (JMP target) or Succs[1] (skip target)
and the Invert flag (A field of the instruction):
JmpBlk = Succs[0]: IsOr = Invert
JmpBlk = Succs[1]: IsOr = not Invert
For TEST/TESTSET: IsOr = Invert (C=1 --> or, C=0 --> and). }
case BranchNode^.RelOp of
ropEQ, ropLT, ropLE: begin
CondExpr := BuildCompare(BranchNode^.OpA, BranchNode^.OpB,
BranchNode^.RelOp, False, BranchNode^.PC);
if (Length(FSF^.Blocks[BranchBlk].Succs) >= 2) and
(FSF^.Blocks[BranchBlk].Succs[0] = JmpBlk) then
IsOr := BranchNode^.Invert
else
IsOr := not BranchNode^.Invert;
if IsOr then
CombinedExpr := CondExpr + ' or ' + StripOuterParens(CombinedExpr)
else
CombinedExpr := CondExpr + ' and ' + StripOuterParens(CombinedExpr);
if FOpts.Debug then
WriteLn(StdErr, 'TryEmitOrAnd: prepended outer comparison: ', CondExpr,
' op=', BoolToStr(IsOr, 'or', 'and'));
end;
ropTest, ropTestSet: begin
CondExpr := ExprOf(BranchNode^.OpA, BranchNode^.PC);
IsOr := BranchNode^.Invert;
if IsOr then
CombinedExpr := CondExpr + ' or ' + StripOuterParens(CombinedExpr)
else
CombinedExpr := CondExpr + ' and ' + StripOuterParens(CombinedExpr);
if FOpts.Debug then
WriteLn(StdErr, 'TryEmitOrAnd: prepended outer TEST condition: ', CondExpr,
' op=', BoolToStr(IsOr, 'or', 'and'));
end;
end;
end;
{ Cache the result }
PhiIdx := NodeIdx(PhiNode^.Dest.Reg, PhiNode^.Dest.Version);
if (PhiIdx >= 0) and (PhiIdx < Length(FExprStr)) then
FExprStr[PhiIdx] := CombinedExpr;
{ Mark all intermediate blocks as emitted (but NOT MergeIdx itself,
since it may contain important nodes like RETURN, CALL, etc.) }
for I := BranchBlk + 1 to MergeIdx - 1 do
if (I >= 0) and (I < Length(FSF^.Blocks)) then
FEmitted[I] := True;
{ Emit non-branch statements from the branch block (e.g.,
"local value = 'initial'" and "print(value)" before the or/and) }
FEmitted[BranchBlk] := True;
for I := 0 to High(FSF^.Blocks[BranchBlk].Nodes) do begin
N := FSF^.Blocks[BranchBlk].Nodes[I];
if N^.Kind <> SSA_BRANCH then
EmitNode(N, BranchBlk);
end;
{ Emit assignment if the PHI targets a user local or global }
LHS := '';
IsChainIntermediate := False; { reuse as "is global" flag }
{ Check for SETGLOBAL at the merge block }
for I := 0 to High(FSF^.Blocks[MergeIdx].Nodes) do begin
N := FSF^.Blocks[MergeIdx].Nodes[I];
if (N^.Kind = SSA_SETGLOBAL) and (N^.OpA.Reg = PhiNode^.Dest.Reg) then begin
if (N^.ConstIdx >= 0) and (N^.ConstIdx < Length(FProto^.K)) and
(FProto^.K[N^.ConstIdx].Kind = lckString) then
LHS := FProto^.K[N^.ConstIdx].SValue
else
LHS := ConstStr(N^.ConstIdx);
IsChainIntermediate := True; { is global }
Break;
end;
end;
if LHS = '' then begin
if IsUserLocal(PhiNode^.Dest.Reg, PhiNode^.PC) or
IsUserLocal(PhiNode^.Dest.Reg, PhiNode^.PC + 1) or
ShouldEmitAsLocal(PhiNode^.Dest.Reg, PhiNode^.PC) then begin
LHS := LocalNameForEmit(PhiNode^.Dest.Reg, PhiNode^.PC);
end;
end;
if LHS <> '' then begin
if (not IsChainIntermediate) and NeedsLocalDecl(PhiNode^.Dest.Reg, PhiNode^.PC) then
EmitLine('local ' + LHS + ' = ' + StripOuterParens(CombinedExpr))
else
EmitLine(LHS + ' = ' + StripOuterParens(CombinedExpr));
PhiIdx := NodeIdx(PhiNode^.Dest.Reg, PhiNode^.Dest.Version);
if (PhiIdx >= 0) and (PhiIdx < Length(FExprStr)) then
FExprStr[PhiIdx] := LHS;
end;
Result := True;
Exit;
end;
end;
{ Determine or vs and and build condition expression }
case BranchNode^.RelOp of
ropTest, ropTestSet: begin
{ C=1 (Invert=true): truthy values pass through --> "or"
C=0 (Invert=false): falsy values pass through --> "and" }
IsOr := BranchNode^.Invert;
CondExpr := ExprOf(BranchNode^.OpA, BranchNode^.PC);
{ Reject conditional assignment patterns: "if f() then m = j end"
In a genuine or/and, the tested register (or TESTSET dest register)
matches the PHI register. In a conditional assignment, the TEST register
(the call result) differs from the PHI register (old variable value).
For TESTSET: the branch Dest register should match the PHI register.
For TEST: the branch OpA register should match the PHI register.
Only apply this for TEST/TESTSET (not comparison). }
if (PhiNode <> nil) then begin
if BranchNode^.RelOp = ropTestSet then begin
{ TESTSET writes result to Dest register - check Dest vs PHI }
if BranchNode^.Dest.Reg <> PhiNode^.Dest.Reg then begin
if FOpts.Debug then
WriteLn(StdErr, 'TryEmitOrAnd: rejected - TESTSET dest R',
BranchNode^.Dest.Reg, ' <> PHI reg R', PhiNode^.Dest.Reg);
Exit;
end;
end else begin
{ TEST: tested register should match PHI register.
However, in derived-value chains like "opts and opts.width or 80",
the TEST is on R0 (opts) and the PHI is on R1 (width).
The ValBlk uses R0 via GETTABLE to produce R1.
Also, in "status and yes or no", TEST is on R9 (status) and
PHI is on R11 - the ValBlk has a BRANCH (sub-chain).
So: if registers differ, allow if ValBlk reads from the tested
register OR has a TESTSET BRANCH (sub-chain). Otherwise reject.
A plain TEST BRANCH in ValBlk indicates an if-then body with a
nested condition, NOT a value-producing or/and sub-chain. Only
TESTSET branches produce values that flow to the merge PHI. }
if BranchNode^.OpA.Reg <> PhiNode^.Dest.Reg then begin
UsesTestedReg := False;
for I := 0 to High(FSF^.Blocks[ValBlk].Nodes) do begin
ValN := FSF^.Blocks[ValBlk].Nodes[I];
if ValN^.Kind in [SSA_JUMP, SSA_PHI, SSA_NOP] then Continue;
{ Allow if ValBlk has a TESTSET BRANCH (sub-chain --> or/and chain).
A plain TEST BRANCH is just control flow inside an if-body. }
if (ValN^.Kind = SSA_BRANCH) and (ValN^.RelOp = ropTestSet) then begin
UsesTestedReg := True;
Break;
end;
{ Check if any operand reads from the tested register }
if (ValN^.OpA.Reg = BranchNode^.OpA.Reg) or
(ValN^.OpB.Reg = BranchNode^.OpA.Reg) then begin
UsesTestedReg := True;
Break;
end;
end;
if not UsesTestedReg then begin
if FOpts.Debug then
WriteLn(StdErr, 'TryEmitOrAnd: rejected - TEST reg R',
BranchNode^.OpA.Reg, ' <> PHI reg R', PhiNode^.Dest.Reg,
' and ValBlk does not use tested reg or have sub-chain');
Exit;
end;
end;
end;
end;
end;
ropEQ, ropLT, ropLE: begin
{ For comparison branches, reject simple conditional assignments.
A comparison-based or/and has either:
(a) A sub-chain in ValBlk (another BRANCH for chain continuation), or
(b) LOADBOOL somewhere (boolean result of comparison).
Without either, this is "if cond then x = val end" - the or/and
collapse is semantically wrong because when the condition is false,
it assigns false instead of keeping the old value. }
if (PhiNode <> nil) then begin
HasOnlyJmp := False; { reuse: "has sub-chain or LOADBOOL" flag }
{ Check if ValBlk has a BRANCH (sub-chain continuation) }
for I := 0 to High(FSF^.Blocks[ValBlk].Nodes) do
if FSF^.Blocks[ValBlk].Nodes[I]^.Kind = SSA_BRANCH then begin
HasOnlyJmp := True; Break;
end;
{ If no sub-chain, check for LOADBOOL in ValBlk }
if not HasOnlyJmp then
for I := 0 to High(FSF^.Blocks[ValBlk].Nodes) do
if (FSF^.Blocks[ValBlk].Nodes[I]^.Kind = SSA_LOADBOOL) and
(FSF^.Blocks[ValBlk].Nodes[I]^.Dest.Reg = PhiNode^.Dest.Reg) then begin
HasOnlyJmp := True; Break;
end;
{ If no sub-chain and no LOADBOOL in ValBlk, check merge PHI source blocks }
if not HasOnlyJmp then
for I := 0 to High(PhiNode^.PhiBlocks) do begin
S := PhiNode^.PhiBlocks[I];
if (S >= 0) and (S < Length(FSF^.Blocks)) then
for J := 0 to High(FSF^.Blocks[S].Nodes) do
if (FSF^.Blocks[S].Nodes[J]^.Kind = SSA_LOADBOOL) and
(FSF^.Blocks[S].Nodes[J]^.Dest.Reg = PhiNode^.Dest.Reg) then begin
HasOnlyJmp := True; Break;
end;
if HasOnlyJmp then Break;
end;
if not HasOnlyJmp then begin
if FOpts.Debug then
WriteLn(StdErr, 'TryEmitOrAnd: rejected comparison branch - conditional assignment on R',
PhiNode^.Dest.Reg);
Exit;
end;
end;
{ Comparison branch:
Succs[0] = JMP block (condition false path)
Succs[1] = skip target (condition true path)
JmpBlk = Succs[0] --> false passes through --> "and"
JmpBlk = Succs[1] --> true passes through --> "or" }
if (Length(FSF^.Blocks[BranchBlk].Succs) >= 2) and
(FSF^.Blocks[BranchBlk].Succs[0] = JmpBlk) then
IsOr := False
else
IsOr := True;
CondExpr := BuildCompare(BranchNode^.OpA, BranchNode^.OpB,
BranchNode^.RelOp, BranchNode^.Invert,
BranchNode^.PC);
end;
else
Exit;
end;
{ Build value expression }
ValExpr := NodeExpr(ValDefNode);
if FOpts.Debug then
WriteLn(StdErr, 'TryEmitOrAnd: CondExpr="', CondExpr,
'" ValExpr="', ValExpr,
'" ValDefNode.Kind=', Ord(ValDefNode^.Kind),
' ValDefNode.PC=', ValDefNode^.PC);
{ Wrap in parentheses since or/and has lower precedence than .. and other ops.
This ensures correct grouping when the result is embedded in a larger expression. }
if IsOr then
CombinedExpr := '(' + CondExpr + ' or ' + ValExpr + ')'
else
CombinedExpr := '(' + CondExpr + ' and ' + ValExpr + ')';
{ Cache the result in FExprStr for the PHI node at the merge block }
if PhiNode <> nil then begin
PhiIdx := NodeIdx(PhiNode^.Dest.Reg, PhiNode^.Dest.Version);
if (PhiIdx >= 0) and (PhiIdx < Length(FExprStr)) then
FExprStr[PhiIdx] := CombinedExpr;
end;
{ ---- Chain continuation: extend through multi-level or/and chains ----
Check if MergeIdx continues into another merge block with a PHI on
the same register. This handles patterns like:
(x > 5 and "big") or "small"
where the first level builds (x > 5 and "big"), and the merge block
(MergeIdx) defines the "or" default "small", feeding into an outer PHI.
Strict requirements to prevent false extensions:
- FinalMerge must have exactly 1 successor (not a branch block)
- NextMerge's PHI must have exactly 2 operands (not a multi-way chain)
- One operand must come from a JMP-only block, the other from FinalMerge
- No back-edges (all PHI sources must be forward)
- FinalMerge must contain only PHI + a single value definition (no side-effects) }
FinalMerge := MergeIdx;
FinalPhiNode := PhiNode;
Safety := 0;
while (FinalPhiNode <> nil) and (Safety < 10) do begin
Inc(Safety);
{ Check if FinalMerge has exactly 1 successor }
if Length(FSF^.Blocks[FinalMerge].Succs) <> 1 then Break;
NextMerge := FSF^.Blocks[FinalMerge].Succs[0];
if (NextMerge <= FinalMerge) or (NextMerge >= Length(FSF^.Blocks)) then Break;
{ Check if NextMerge has a PHI on the same register with 2+ operands }
NextPhiNode := nil;
for I := 0 to High(FSF^.Blocks[NextMerge].Nodes) do begin
N := FSF^.Blocks[NextMerge].Nodes[I];
if (N^.Kind = SSA_PHI) and (N^.Dest.Reg = FinalPhiNode^.Dest.Reg) and
(Length(N^.Operands) >= 2) and
(Length(N^.PhiBlocks) = Length(N^.Operands)) then begin
NextPhiNode := N; Break;
end;
end;
if NextPhiNode = nil then Break;
{ Verify no back-edges: all PHI sources must be before NextMerge }
HasSideEffect := False;
for I := 0 to High(NextPhiNode^.PhiBlocks) do
if NextPhiNode^.PhiBlocks[I] >= NextMerge then begin
HasSideEffect := True; Break;
end;
if HasSideEffect then Break;
{ Verify that FinalMerge is one of the PHI's source blocks }
HasSideEffect := True; { reuse as "valid chain" flag (inverted) }
for I := 0 to High(NextPhiNode^.PhiBlocks) do begin
if NextPhiNode^.PhiBlocks[I] = FinalMerge then begin
HasSideEffect := False;
Break;
end;
end;
if HasSideEffect then Break;
{ Find the default value defined at FinalMerge (non-PHI, non-JUMP content).
If any side-effect statement is found, this is not a chain - stop extending. }
DefaultNode := nil;
HasSideEffect := False;
for I := 0 to High(FSF^.Blocks[FinalMerge].Nodes) do begin
N := FSF^.Blocks[FinalMerge].Nodes[I];
if N^.Kind in [SSA_PHI, SSA_JUMP, SSA_NOP, SSA_BRANCH] then Continue;
if N^.Kind in [SSA_SETTABLE, SSA_SETGLOBAL, SSA_SETUPVAL] then begin
HasSideEffect := True; Break;
end;
if (N^.Kind = SSA_CALL) and (N^.ImmC <= 1) then begin
HasSideEffect := True; Break;
end;
{ Only accept as chain default if it writes to the SAME register as the chain.
E.g., a CONCAT writing R1 should not be treated as a default for an R11 chain. }
if N^.Dest.Reg = FinalPhiNode^.Dest.Reg then
DefaultNode := N
else begin
HasSideEffect := True; Break; { Different register --> not a chain, stop }
end;
end;
if HasSideEffect or (DefaultNode = nil) then Break;
{ For 3+ operand PHIs at NextMerge, build the FULL chain by incorporating
all operands from JMP-only source blocks (which have cached or/and
expressions from earlier TryEmitOrAnd passes).
The current CombinedExpr represents one arm; other arms come from
JMP-only blocks that resolved to cached intermediate PHI expressions. }
if Length(NextPhiNode^.Operands) > 2 then begin
{ Collect all chain arms: iterate over PHI operands.
Operands from JMP-only blocks represent cached or/and sub-expressions.
The operand from FinalMerge represents the default value. }
ValExpr := '';
for I := 0 to High(NextPhiNode^.PhiBlocks) do begin
S := NextPhiNode^.PhiBlocks[I];
if S = FinalMerge then begin
{ This is the default value from FinalMerge }
Segment := NodeExpr(DefaultNode);
end else begin
{ Check if this source block is JMP-only with a cached expression }
HasOnlyJmp := True;
for PhiIdx := 0 to High(FSF^.Blocks[S].Nodes) do
if not (FSF^.Blocks[S].Nodes[PhiIdx]^.Kind in [SSA_JUMP, SSA_PHI, SSA_NOP]) then begin
HasOnlyJmp := False; Break;
end;
if HasOnlyJmp then begin
{ Trace back: find branch ancestor and any cached intermediate PHI }
Segment := '';
{ Search for cached PHI expression between this block and NextMerge }
for PhiIdx := S + 1 to NextMerge - 1 do begin
for J := 0 to High(FSF^.Blocks[PhiIdx].Nodes) do begin
N := FSF^.Blocks[PhiIdx].Nodes[J];
if (N^.Kind = SSA_PHI) and
(N^.Dest.Reg = NextPhiNode^.Operands[I].Reg) then begin
MergeIdx := NodeIdx(N^.Dest.Reg, N^.Dest.Version);
if (MergeIdx >= 0) and (MergeIdx < Length(FExprStr)) and (FExprStr[MergeIdx] <> '') then
Segment := FExprStr[MergeIdx];
Break;
end;
end;
if Segment <> '' then Break;
end;
if Segment = '' then
Segment := ExprOf(NextPhiNode^.Operands[I], NextPhiNode^.PC);
end else
Segment := ExprOf(NextPhiNode^.Operands[I], NextPhiNode^.PC);
end;
if ValExpr <> '' then
ValExpr := '(' + ValExpr + ' or ' + Segment + ')'
else
ValExpr := Segment;
end;
CombinedExpr := ValExpr;
end else begin
{ Simple 2-operand extension: (CombinedExpr or default)
Wrap in parentheses so the result is safe inside higher-precedence
operators like CONCAT (..), arithmetic, etc. }
ValExpr := NodeExpr(DefaultNode);
CombinedExpr := '(' + StripOuterParens(CombinedExpr) + ' or ' + ValExpr + ')';
end;
if FOpts.Debug then
WriteLn(StdErr, 'TryEmitOrAnd: chain extension BB', FinalMerge,
' --> BB', NextMerge, ' default=', CombinedExpr);
{ Cache at NextMerge's PHI }
PhiIdx := NodeIdx(NextPhiNode^.Dest.Reg, NextPhiNode^.Dest.Version);
if (PhiIdx >= 0) and (PhiIdx < Length(FExprStr)) then
FExprStr[PhiIdx] := CombinedExpr;
{ Mark FinalMerge as emitted (its content is part of the chain) }
FEmitted[FinalMerge] := True;
FinalMerge := NextMerge;
FinalPhiNode := NextPhiNode;
end;
{ Emit non-branch statements from the branch block }
FEmitted[BranchBlk] := True;
for I := 0 to High(FSF^.Blocks[BranchBlk].Nodes) do begin
N := FSF^.Blocks[BranchBlk].Nodes[I];
if N^.Kind <> SSA_BRANCH then
EmitNode(N, BranchBlk);
end;
{ If the final PHI result is a user-local variable or a parameter being
reassigned, emit the assignment. Otherwise the expression is only
cached for inline use (e.g., SETTABLE).
EXCEPTION: If the FinalMerge block is a branch block (has 2+ successors),
this or/and result is likely an intermediate step in a multi-level chain
like ((sum==2) and self[y][x]) or ((sum==3) and 1) or 0.
In that case, do NOT emit as a statement - just keep the cached
expression so the downstream TryEmitOrAnd can build the full chain.
However, only suppress if the branch at FinalMerge actually tests the
SAME register as the PHI (i.e., it IS a chain continuation). If the
branch tests a DIFFERENT register, this is a standalone or/and that
happens to be followed by an unrelated if-condition (e.g.,
valuesTable = (valuesTable or keysTable) followed by if getmetatable(...)). }
if FinalPhiNode <> nil then begin
{ Skip emission if the merge block contains a FORPREP - the PHI is a
for-loop control register (start/limit/step). The expression will be
inlined by EmitForNumericLoop; emitting a standalone assignment here
would produce a spurious "tN = expr" before the for statement. }
for I := 0 to High(FSF^.Blocks[FinalMerge].Nodes) do
if FSF^.Blocks[FinalMerge].Nodes[I]^.Kind = SSA_FORPREP then begin
{ Just mark blocks as emitted and exit - expression is cached in FExprStr }
FEmitted[BranchBlk] := True;
FEmitted[JmpBlk] := True;
FEmitted[ValBlk] := True;
for J := ValBlk + 1 to FinalMerge - 1 do
if (J >= 0) and (J < Length(FSF^.Blocks)) then
FEmitted[J] := True;
{ Emit non-branch statements from the branch block }
for J := 0 to High(FSF^.Blocks[BranchBlk].Nodes) do begin
N := FSF^.Blocks[BranchBlk].Nodes[J];
if N^.Kind <> SSA_BRANCH then
EmitNode(N, BranchBlk);
end;
Result := True;
Exit;
end;
{ Skip emission if this is an intermediate chain result (not user-local
and merge block continues branching on the SAME register) }
IsChainIntermediate := False;
{ Check if FinalMerge has a SETGLOBAL consuming the PHI result.
If so, this is NOT intermediate - the value is consumed by the assignment. }
HasSideEffect := False; { reuse as "has consuming SETGLOBAL" flag }
for I := 0 to High(FSF^.Blocks[FinalMerge].Nodes) do begin
N := FSF^.Blocks[FinalMerge].Nodes[I];
if (N^.Kind = SSA_SETGLOBAL) and (N^.OpA.Reg = FinalPhiNode^.Dest.Reg) then begin
HasSideEffect := True; Break;
end;
end;
if (not HasSideEffect) and
(Length(FSF^.Blocks[FinalMerge].Succs) >= 2) and
(not IsUserLocal(FinalPhiNode^.Dest.Reg, FinalPhiNode^.PC)) and
(not IsUserLocal(FinalPhiNode^.Dest.Reg, FinalPhiNode^.PC + 1)) and
(not ShouldEmitAsLocal(FinalPhiNode^.Dest.Reg, FinalPhiNode^.PC)) then begin
{ Check if any reachable block within a short range has a PHI on the
same register - indicating this is an intermediate in a chain that
a subsequent TryEmitOrAnd call will extend.
E.g., evolve: BB10 has PHI R12_5, BB14 has PHI R12_7, BB15 has PHI R12_9
--> this is a chain. copyTables: merge has PHI R2, but no downstream
PHI on R2 --> this is a standalone or/and that must be emitted. }
for I := FinalMerge + 1 to FinalMerge + 20 do begin
if I >= Length(FSF^.Blocks) then Break;
for J := 0 to High(FSF^.Blocks[I].Nodes) do begin
N := FSF^.Blocks[I].Nodes[J];
if (N^.Kind = SSA_PHI) and (N^.Dest.Reg = FinalPhiNode^.Dest.Reg) then begin
IsChainIntermediate := True;
Break;
end;
end;
if IsChainIntermediate then Break;
end;
end;
if IsChainIntermediate then begin
{ Keep the cached CombinedExpr in FExprStr - don't emit assignment }
end
else if HasSideEffect then begin
{ HasSideEffect = True means SETGLOBAL consumes the PHI result.
Emit the global assignment. }
LHS := '';
for I := 0 to High(FSF^.Blocks[FinalMerge].Nodes) do begin
N := FSF^.Blocks[FinalMerge].Nodes[I];
if (N^.Kind = SSA_SETGLOBAL) and (N^.OpA.Reg = FinalPhiNode^.Dest.Reg) then begin
if (N^.ConstIdx >= 0) and (N^.ConstIdx < Length(FProto^.K)) and
(FProto^.K[N^.ConstIdx].Kind = lckString) then
LHS := FProto^.K[N^.ConstIdx].SValue;
Break;
end;
end;
if LHS <> '' then begin
EmitLine(LHS + ' = ' + StripOuterParens(CombinedExpr));
PhiIdx := NodeIdx(FinalPhiNode^.Dest.Reg, FinalPhiNode^.Dest.Version);
if (PhiIdx >= 0) and (PhiIdx < Length(FExprStr)) then
FExprStr[PhiIdx] := LHS;
end;
end
else if IsUserLocal(FinalPhiNode^.Dest.Reg, FinalPhiNode^.PC) or
IsUserLocal(FinalPhiNode^.Dest.Reg, FinalPhiNode^.PC + 1) or
ShouldEmitAsLocal(FinalPhiNode^.Dest.Reg, FinalPhiNode^.PC) or
ShouldEmitTemp(FinalPhiNode^.Dest.Reg, FinalPhiNode^.Dest.Version,
FinalPhiNode^.PC) then begin
if IsUserLocal(FinalPhiNode^.Dest.Reg, FinalPhiNode^.PC) or
IsUserLocal(FinalPhiNode^.Dest.Reg, FinalPhiNode^.PC + 1) or
ShouldEmitAsLocal(FinalPhiNode^.Dest.Reg, FinalPhiNode^.PC) then
LHS := LocalNameForEmit(FinalPhiNode^.Dest.Reg, FinalPhiNode^.PC)
else
LHS := TempName(FinalPhiNode^.Dest.Reg);
if LHS <> '' then begin
{ Check for parallel assignment: if FinalMerge block also has a MOVE
consuming a previously cached or/and expression (from a temp register),
combine into a multi-assign like "p, a = p or d * 0.3, a or 0".
Pattern: TESTSET R_temp←R_target1 ... PHI R_temp ... TEST R_target2 ...
PHI R_target2 + MOVE R_target1←R_temp at FinalMerge. }
Segment := ''; { reuse: parallel LHS }
ValExpr := ''; { reuse: parallel RHS }
for I := 0 to High(FSF^.Blocks[FinalMerge].Nodes) do begin
N := FSF^.Blocks[FinalMerge].Nodes[I];
if (N^.Kind = SSA_MOVE) and (N <> FinalPhiNode) then begin
J := NodeIdx(N^.OpA.Reg, N^.OpA.Version);
if (J >= 0) and (J < Length(FExprStr)) and (FExprStr[J] <> '') and
((Pos(' or ', FExprStr[J]) > 0) or (Pos(' and ', FExprStr[J]) > 0)) then begin
{ MOVE source has a cached or/and expression - check if MOVE dest
is a user local or parameter }
if IsUserLocal(N^.Dest.Reg, N^.PC) or
IsUserLocal(N^.Dest.Reg, N^.PC + 1) then begin
Segment := LocalNameForEmit(N^.Dest.Reg, N^.PC);
ValExpr := FExprStr[J];
{ Mark the MOVE as inlined to prevent double emission }
S := NodeIdx(N^.Dest.Reg, N^.Dest.Version);
if (S >= 0) and (S < Length(FInlined)) then
FInlined[S] := True;
Break;
end;
end;
end;
end;
if (Segment <> '') and (ValExpr <> '') then begin
{ Emit parallel assignment: target1, target2 = expr1, expr2 }
EmitLine(Segment + ', ' + LHS + ' = ' +
StripOuterParens(ValExpr) + ', ' +
StripOuterParens(CombinedExpr));
end else begin
if NeedsLocalDecl(FinalPhiNode^.Dest.Reg, FinalPhiNode^.PC) then
EmitLine('local ' + LHS + ' = ' + StripOuterParens(CombinedExpr))
else