-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCodeGen.pas
1928 lines (1777 loc) · 85.7 KB
/
CodeGen.pas
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
// Based on XD Pascal (2020) original code by Vasiliy Tereshkov
// Refactoring and extensions by Wanderlan
{$I-,H-}
unit CodeGen;
interface
uses
Common;
const
MAXCODESIZE = 1024 * 1024;
var
Code: array [0..MAXCODESIZE - 1] of Byte;
procedure InitializeCodeGen;
function GetCodeSize: Longint;
procedure PushConst(Value: Longint);
procedure PushRealConst(Value: Double);
procedure PushRelocConst(Value: Longint; RelocType: TRelocType);
procedure Relocate(CodeDeltaAddr, InitDataDeltaAddr, UninitDataDeltaAddr, ImportDeltaAddr: Integer);
procedure PushFunctionResult(ResultType: Integer);
procedure MoveFunctionResultFromFPUToEDXEAX(DataType: Integer);
procedure MoveFunctionResultFromEDXEAXToFPU(DataType: Integer);
procedure PushVarPtr(Addr: Integer; Scope: TScope; DeltaNesting: Byte; RelocType: TRelocType);
procedure DerefPtr(DataType: Integer);
procedure GetArrayElementPtr(ArrType: Integer);
procedure GetFieldPtr(Offset: Integer);
procedure GetCharAsTempString(Depth: Integer);
procedure SaveStackTopToEAX;
procedure RestoreStackTopFromEAX;
procedure SaveStackTopToEDX;
procedure RestoreStackTopFromEDX;
procedure RaiseStackTop(NumItems: Byte);
procedure DiscardStackTop(NumItems: Byte);
procedure DuplicateStackTop;
procedure SaveCodePos;
procedure GenerateIncDec(proc: TPredefProc; Size: Byte; BaseTypeSize: Integer = 0);
procedure GenerateRound(TruncMode: Boolean);
procedure GenerateDoubleFromInteger(Depth: Byte);
procedure GenerateDoubleFromSingle;
procedure GenerateSingleFromDouble;
procedure GenerateMathFunction(func: TPredefProc; ResultType: Integer);
procedure GenerateUnaryOperator(op: TTokenKind; ResultType: Integer);
procedure GenerateBinaryOperator(op: TTokenKind; ResultType: Integer);
procedure GenerateRelation(rel: TTokenKind; ValType: Integer);
procedure GenerateAssignment(DesignatorType: Integer);
procedure GenerateForAssignmentAndNumberOfIterations(CounterType: Integer; Down: Boolean);
procedure GenerateStructuredAssignment(DesignatorType: Integer);
procedure GenerateInterfaceFieldAssignment(Offset: Integer; PopValueFromStack: Boolean; Value: Longint; RelocType: TRelocType);
procedure InitializeCStack;
procedure PushToCStack(SourceStackDepth: Integer; DataType: Integer; PushByValue: Boolean);
procedure ConvertSmallStructureToPointer(Addr: Longint; Size: Longint);
procedure ConvertPointerToSmallStructure(Size: Longint);
procedure GenerateImportFuncStub(EntryPoint: Longint);
procedure GenerateCall(EntryPoint: Longint; CallerNesting, CalleeNesting: Integer);
procedure GenerateIndirectCall(CallAddressDepth: Integer);
procedure GenerateReturn(TotalParamsSize, Nesting: Integer);
procedure GenerateForwardReference;
procedure GenerateForwardResolution(CodePos: Integer);
procedure GenerateIfCondition;
procedure GenerateIfProlog;
procedure GenerateElseProlog;
procedure GenerateIfElseEpilog;
procedure GenerateCaseProlog;
procedure GenerateCaseEpilog(NumCaseStatements: Integer);
procedure GenerateCaseEqualityCheck(Value: Longint);
procedure GenerateCaseRangeCheck(Value1, Value2: Longint);
procedure GenerateCaseStatementProlog;
procedure GenerateCaseStatementEpilog;
procedure GenerateWhileCondition;
procedure GenerateWhileProlog;
procedure GenerateWhileEpilog;
procedure GenerateRepeatCondition;
procedure GenerateRepeatProlog;
procedure GenerateRepeatEpilog;
procedure GenerateForCondition;
procedure GenerateForProlog;
procedure GenerateForEpilog(CounterType: Integer; Down: Boolean);
procedure GenerateGotoProlog;
procedure GenerateGoto(LabelIndex: Integer);
procedure GenerateGotoEpilog;
procedure GenerateShortCircuitProlog(op: TTokenKind);
procedure GenerateShortCircuitEpilog;
procedure GenerateNestedProcsProlog;
procedure GenerateNestedProcsEpilog;
procedure GenerateFPUInit;
procedure GenerateStackFrameProlog(PreserveRegs: Boolean);
procedure GenerateStackFrameEpilog(TotalStackStorageSize: Longint; PreserveRegs: Boolean);
procedure GenerateBreakProlog(LoopNesting: Integer);
procedure GenerateBreakCall(LoopNesting: Integer);
procedure GenerateBreakEpilog(LoopNesting: Integer);
procedure GenerateContinueProlog(LoopNesting: Integer);
procedure GenerateContinueCall(LoopNesting: Integer);
procedure GenerateContinueEpilog(LoopNesting: Integer);
procedure GenerateExitProlog;
procedure GenerateExitCall;
procedure GenerateExitEpilog;
implementation
const
MAXINSTRSIZE = 15;
MAXPREVCODESIZES = 10;
MAXRELOCS = 20000;
MAXGOTOS = 100;
MAXLOOPNESTING = 20;
MAXBREAKCALLS = 100;
type
TRelocatable = record
RelocType: TRelocType;
Pos: Longint;
Value: Longint;
end;
TGoto = record
Pos: Longint;
LabelIndex: Integer;
ForLoopNesting: Integer;
end;
TBreakContinueExitCallList = record
NumCalls: Integer;
Pos: array [1..MAXBREAKCALLS] of Longint;
end;
TRegister = (EAX, ECX, EDX, ESI, EDI, EBP);
var
CodePosStack: array [0..1023] of Integer;
CodeSize, CodePosStackTop: Integer;
PrevCodeSizes: array [1..MAXPREVCODESIZES] of Integer;
NumPrevCodeSizes: Integer;
Reloc: array [1..MAXRELOCS] of TRelocatable;
NumRelocs: Integer;
Gotos: array [1..MAXGOTOS] of TGoto;
NumGotos: Integer;
BreakCall, ContinueCall: array [1..MAXLOOPNESTING] of TBreakContinueExitCallList;
ExitCall: TBreakContinueExitCallList;
procedure InitializeCodeGen;
begin
CodeSize := 0;
CodePosStackTop := 0;
NumPrevCodeSizes := 0;
NumRelocs := 0;
NumGotos := 0;
end;
function GetCodeSize: Longint;
begin
Result := CodeSize;
NumPrevCodeSizes := 0;
end;
procedure Gen(b: Byte);
begin
Code[CodeSize] := b;
Inc(CodeSize);
end;
procedure GenNew(b: Byte);
var
i: Integer;
begin
if CodeSize + MAXINSTRSIZE >= MAXCODESIZE then
Error('Maximum code size exceeded');
if NumPrevCodeSizes < MAXPREVCODESIZES then
Inc(NumPrevCodeSizes)
else
for i := 1 to MAXPREVCODESIZES - 1 do
PrevCodeSizes[i] := PrevCodeSizes[i + 1];
PrevCodeSizes[NumPrevCodeSizes] := CodeSize;
Gen(b);
end;
procedure GenAt(Pos: Longint; b: Byte);
begin
Code[Pos] := b;
end;
procedure GenWord(w: Integer);
var
i: Integer;
begin
for i := 1 to 2 do begin
Gen(Byte(w and $FF));
w := w shr 8;
end;
end;
procedure GenWordAt(Pos: Longint; w: Integer);
var
i: Integer;
begin
for i := 0 to 1 do begin
GenAt(Pos + i, Byte(w and $FF));
w := w shr 8;
end;
end;
procedure GenDWord(dw: Longint);
var
i: Integer;
begin
for i := 1 to 4 do begin
Gen(Byte(dw and $FF));
dw := dw shr 8;
end;
end;
procedure GenDWordAt(Pos: Longint; dw: Longint);
var
i: Integer;
begin
for i := 0 to 3 do begin
GenAt(Pos + i, Byte(dw and $FF));
dw := dw shr 8;
end;
end;
procedure GenRelocDWord(dw: Longint; RelocType: TRelocType);
begin
Inc(NumRelocs);
if NumRelocs > MAXRELOCS then
Error('Maximum number of relocations exceeded');
Reloc[NumRelocs].RelocType := RelocType;
Reloc[NumRelocs].Pos := CodeSize;
Reloc[NumRelocs].Value := dw;
GenDWord(dw);
end;
function PrevInstrByte(Depth, Offset: Integer): Byte;
begin
Result := 0;
// The last generated instruction starts at Depth = 0, Offset = 0
if Depth < NumPrevCodeSizes then
Result := Code[PrevCodeSizes[NumPrevCodeSizes - Depth] + Offset];
end;
function PrevInstrDWord(Depth, Offset: Integer): Longint;
begin
Result := 0;
// The last generated instruction starts at Depth = 0, Offset = 0
if Depth < NumPrevCodeSizes then
Result := PLongInt(@Code[PrevCodeSizes[NumPrevCodeSizes - Depth] + Offset])^;
end;
function PrevInstrRelocDWordIndex(Depth, Offset: Integer): Integer;
var
i: Integer;
Pos: Longint;
begin
Result := 0;
// The last generated instruction starts at Depth = 0, Offset = 0
if Depth < NumPrevCodeSizes then begin
Pos := PrevCodeSizes[NumPrevCodeSizes - Depth] + Offset;
for i := NumRelocs downto 1 do
if Reloc[i].Pos = Pos then begin
Result := i;
Exit;
end;
end;
end;
procedure RemovePrevInstr(Depth: Integer);
begin
if Depth >= NumPrevCodeSizes then
Error('Internal fault: previous instruction not found');
CodeSize := PrevCodeSizes[NumPrevCodeSizes - Depth];
NumPrevCodeSizes := NumPrevCodeSizes - Depth - 1;
end;
procedure PushConst(Value: Longint);
begin
GenNew($68); GenDWord(Value); // push Value
end;
procedure PushRealConst(Value: Double);
type
TIntegerArray = array [0..1] of Longint;
PIntegerArray = ^TIntegerArray;
var
IntegerArray: PIntegerArray;
begin
IntegerArray := PIntegerArray(@Value);
PushConst(IntegerArray^[1]);
PushConst(IntegerArray^[0]);
end;
procedure PushRelocConst(Value: Longint; RelocType: TRelocType);
begin
GenNew($68); GenRelocDWord(Value, RelocType); // push Value ; relocatable
end;
procedure Relocate(CodeDeltaAddr, InitDataDeltaAddr, UninitDataDeltaAddr, ImportDeltaAddr: Integer);
var
i, DeltaAddr: Integer;
begin
DeltaAddr := 0;
for i := 1 to NumRelocs do begin
case Reloc[i].RelocType of
CODERELOC: DeltaAddr := CodeDeltaAddr;
INITDATARELOC: DeltaAddr := InitDataDeltaAddr;
UNINITDATARELOC: DeltaAddr := UninitDataDeltaAddr;
IMPORTRELOC: DeltaAddr := ImportDeltaAddr
else Error('Internal fault: Illegal relocation type');
end;
GenDWordAt(Reloc[i].Pos, Reloc[i].Value + DeltaAddr);
end;
end;
procedure GenPushReg(Reg: TRegister);
begin
case Reg of
EAX: GenNew($50); // push eax
ECX: GenNew($51); // push ecx
EDX: GenNew($52); // push edx
ESI: GenNew($56); // push esi
EDI: GenNew($57); // push edi
EBP: GenNew($55) // push ebp
else Error('Internal fault: Illegal register');
end;
end;
procedure GenPopReg(Reg: TRegister);
function OptimizePopReg: Boolean;
var
HasPushRegPrefix: Boolean;
Value, Addr: Longint;
ValueRelocIndex: Integer;
PrevOpCode: Byte;
begin
Result := False;
PrevOpCode := PrevInstrByte(0, 0);
// Optimization: (push Reg) + (pop Reg) -> 0
if ((Reg = EAX) and (PrevOpCode = $50)) or // Previous: push eax
((Reg = ECX) and (PrevOpCode = $51)) or // Previous: push ecx
((Reg = EDX) and (PrevOpCode = $52)) or // Previous: push edx
((Reg = ESI) and (PrevOpCode = $56)) or // Previous: push esi
((Reg = EDI) and (PrevOpCode = $57)) or // Previous: push edi
((Reg = EBP) and (PrevOpCode = $55)) // Previous: push ebp
then begin
RemovePrevInstr(0); // Remove: push Reg
Result := True;
Exit;
end
// Optimization: (push eax) + (pop ecx) -> (mov ecx, eax)
else
if (Reg = ECX) and (PrevOpCode = $50) then begin // Previous: push eax
RemovePrevInstr(0); // Remove: push eax
GenNew($89); Gen($C1); // mov ecx, eax
Result := True;
Exit;
end
// Optimization: (push eax) + (pop esi) -> (mov esi, eax)
else
if (Reg = ESI) and (PrevOpCode = $50) then begin // Previous: push esi
RemovePrevInstr(0); // Remove: push eax
// Special case: (mov eax, [epb + Addr]) + (push eax) + (pop esi) -> (mov esi, [epb + Addr])
if (PrevInstrByte(0, 0) = $8B) and (PrevInstrByte(0, 1) = $85) then begin // Previous: mov eax, [epb + Addr]
Addr := PrevInstrDWord(0, 2);
RemovePrevInstr(0); // Remove: mov eax, [epb + Addr]
GenNew($8B); Gen($B5); GenDWord(Addr); // mov esi, [epb + Addr]
end
else begin
GenNew($89); Gen($C6); // mov esi, eax
end;
Result := True;
Exit;
end
// Optimization: (push esi) + (pop eax) -> (mov eax, esi)
else
if (Reg = EAX) and (PrevOpCode = $56) then begin // Previous: push esi
RemovePrevInstr(0); // Remove: push esi
GenNew($89); Gen($F0); // mov eax, esi
Result := True;
Exit;
end
// Optimization: (push Value) + (pop eax) -> (mov eax, Value)
else
if (Reg = EAX) and (PrevOpCode = $68) then begin // Previous: push Value
Value := PrevInstrDWord(0, 1);
ValueRelocIndex := PrevInstrRelocDWordIndex(0, 1);
// Special case: (push esi) + (push Value) + (pop eax) -> (mov eax, Value) + (push esi)
HasPushRegPrefix := PrevInstrByte(1, 0) = $56; // Previous: push esi
RemovePrevInstr(0); // Remove: push Value
if HasPushRegPrefix then
RemovePrevInstr(0); // Remove: push esi
GenNew($B8); GenDWord(Value); // mov eax, Value
if HasPushRegPrefix then begin
if ValueRelocIndex <> 0 then
Dec(Reloc[ValueRelocIndex].Pos); // Relocate Value if necessary
GenPushReg(ESI); // push esi
end;
Result := True;
Exit;
end
// Optimization: (push [esi]) + (pop eax) -> (mov eax, [esi])
else
if (Reg = EAX) and (PrevInstrByte(0, 0) = $FF) and (PrevInstrByte(0, 1) = $36) then begin // Previous: push [esi]
RemovePrevInstr(0); // Remove: push [esi]
GenNew($8B); Gen($06); // mov eax, [esi]
Result := True;
Exit;
end
// Optimization: (push [esi + 4]) + (mov eax, [esi]) + (pop edx) -> (mov eax, [esi]) + (mov edx, [esi + 4])
else
if (Reg = EDX) and (PrevInstrByte(1, 0) = $FF) and (PrevInstrByte(1, 1) = $76) and (PrevInstrByte(1, 2) = $04) // Previous: push [esi + 4]
and (PrevInstrByte(0, 0) = $8B) and (PrevInstrByte(0, 1) = $06) // Previous: mov eax, [esi]
then begin
RemovePrevInstr(1); // Remove: push [esi + 4], mov eax, [esi]
GenNew($8B); Gen($06); // mov eax, [esi]
GenNew($8B); Gen($56); Gen($04); // mov edx, [esi + 4]
Result := True;
Exit;
end
// Optimization: (push Value) + (pop ecx) -> (mov ecx, Value)
else
if (Reg = ECX) and (PrevOpCode = $68) then begin // Previous: push Value
Value := PrevInstrDWord(0, 1);
ValueRelocIndex := PrevInstrRelocDWordIndex(0, 1);
// Special case: (push eax) + (push Value) + (pop ecx) -> (mov ecx, Value) + (push eax)
HasPushRegPrefix := PrevInstrByte(1, 0) = $50; // Previous: push eax
RemovePrevInstr(0); // Remove: push Value
if HasPushRegPrefix then
RemovePrevInstr(0); // Remove: push eax / push [ebp + Addr]
GenNew($B9); GenDWord(Value); // mov ecx, Value
if HasPushRegPrefix then begin
if ValueRelocIndex <> 0 then
Dec(Reloc[ValueRelocIndex].Pos); // Relocate Value if necessary
GenPushReg(EAX); // push eax
end;
Result := True;
Exit;
end
// Optimization: (push Value) + (pop esi) -> (mov esi, Value)
else
if (Reg = ESI) and (PrevOpCode = $68) then begin // Previous: push Value
Value := PrevInstrDWord(0, 1);
RemovePrevInstr(0); // Remove: push Value
GenNew($BE); GenDWord(Value); // mov esi, Value
Result := True;
Exit;
end
// Optimization: (push Value) + (mov eax, [Addr]) + (pop esi) -> (mov esi, Value) + (mov eax, [Addr])
else
if (Reg = ESI) and (PrevInstrByte(1, 0) = $68) and (PrevInstrByte(0, 0) = $A1) then begin // Previous: push Value, mov eax, [Addr]
Value := PrevInstrDWord(1, 1);
Addr := PrevInstrDWord(0, 1);
RemovePrevInstr(1); // Remove: push Value, mov eax, [Addr]
GenNew($BE); GenDWord(Value); // mov esi, Value
GenNew($A1); GenDWord(Addr); // mov eax, [Addr]
Result := True;
Exit;
end
// Optimization: (push esi) + (mov eax, [ebp + Value]) + (pop esi) -> (mov eax, [ebp + Value])
else
if (Reg = ESI) and (PrevInstrByte(1, 0) = $56) // Previous: push esi
and (PrevInstrByte(0, 0) = $8B) and (PrevInstrByte(0, 1) = $85) then begin // Previous: mov eax, [ebp + Value]
Value := PrevInstrDWord(0, 2);
RemovePrevInstr(1); // Remove: push esi, mov eax, [ebp + Value]
GenNew($8B); Gen($85); GenDWord(Value); // mov eax, [ebp + Value]
Result := True;
Exit;
end
// Optimization: (push dword ptr [esp]) + (pop esi) -> (mov esi, [esp])
else
if (Reg = ESI) and (PrevInstrByte(0, 0) = $FF) and (PrevInstrByte(0, 1) = $34) and (PrevInstrByte(0, 2) = $24) then
begin // Previous: push dword ptr [esp]
RemovePrevInstr(0); // Remove: push dword ptr [esp]
GenNew($8B); Gen($34); Gen($24); // mov esi, [esp]
Result := True;
Exit;
end;
end;
begin // GenPopReg
if not OptimizePopReg then
case Reg of
EAX: GenNew($58); // pop eax
ECX: GenNew($59); // pop ecx
EDX: GenNew($5A); // pop edx
ESI: GenNew($5E); // pop esi
EDI: GenNew($5F); // pop edi
EBP: GenNew($5D) // pop ebp
else Error('Internal fault: Illegal register');
end;
end;
procedure GenPushToFPU;
function OptimizeGenPushToFPU: Boolean;
begin
Result := False;
// Optimization: (fstp qword ptr [esp]) + (fld qword ptr [esp]) -> (fst qword ptr [esp])
if (PrevInstrByte(0, 0) = $DD) and (PrevInstrByte(0, 1) = $1C) and (PrevInstrByte(0, 2) = $24) then // Previous: fstp dword ptr [esp]
begin
RemovePrevInstr(0); // Remove: fstp dword ptr [esp]
GenNew($DD); Gen($14); Gen($24); // fst qword ptr [esp]
Result := True;
end
// Optimization: (push [esi + 4]) + (push [esi]) + (fld qword ptr [esp]) -> (fld qword ptr [esi]) + (sub esp, 8)
else
if (PrevInstrByte(1, 0) = $FF) and (PrevInstrByte(1, 1) = $76) and (PrevInstrByte(1, 2) = $04) and // Previous: push [esi + 4]
(PrevInstrByte(0, 0) = $FF) and (PrevInstrByte(0, 1) = $36) // Previous: push [esi]
then begin
RemovePrevInstr(1); // Remove: push [esi + 4], push [esi]
GenNew($DD); Gen($06); // fld qword ptr [esi]
RaiseStackTop(2); // sub esp, 8
Result := True;
end;
end;
begin
if not OptimizeGenPushToFPU then begin
GenNew($DD); Gen($04); Gen($24); // fld qword ptr [esp]
end;
end;
procedure GenPopFromFPU;
begin
GenNew($DD); Gen($1C); Gen($24); // fstp qword ptr [esp]
end;
procedure PushFunctionResult(ResultType: Integer);
begin
if Types[ResultType].Kind = REALTYPE then
GenPushReg(EDX) // push edx
else
if Types[ResultType].Kind = BOOLEANTYPE then begin
GenNew($83); Gen($E0); Gen($01); // and eax, 1
end
else
case TypeSize(ResultType) of
1: if Types[ResultType].Kind in UnsignedTypes then begin
GenNew($0F); Gen($B6); Gen($C0); // movzx eax, al
end
else begin
GenNew($0F); Gen($BE); Gen($C0); // movsx eax, al
end;
2: if Types[ResultType].Kind in UnsignedTypes then begin
GenNew($0F); Gen($B7); Gen($C0); // movzx eax, ax
end
else begin
GenNew($0F); Gen($BF); Gen($C0); // movsx eax, ax
end;
end; // case
GenPushReg(EAX); // push eax
end;
procedure MoveFunctionResultFromFPUToEDXEAX(DataType: Integer);
begin
if Types[DataType].Kind = REALTYPE then begin
RaiseStackTop(2); // sub esp, 8 ; expand stack
GenPopFromFPU; // fstp qword ptr [esp] ; [esp] := st; pop
GenNew($8B); Gen($04); Gen($24); // mov eax, [esp]
GenNew($8B); Gen($54); Gen($24); Gen($04); // mov edx, [esp + 4]
DiscardStackTop(2); // add esp, 8 ; shrink stack
end
else
if Types[DataType].Kind = SINGLETYPE then begin
RaiseStackTop(1); // sub esp, 4 ; expand stack
GenNew($D9); Gen($1C); Gen($24); // fstp dword ptr [esp] ; [esp] := single(st); pop
GenNew($8B); Gen($04); Gen($24); // mov eax, [esp]
DiscardStackTop(1); // add esp, 4 ; shrink stack
end
else
Error('Internal fault: Illegal type');
end;
procedure MoveFunctionResultFromEDXEAXToFPU(DataType: Integer);
begin
if Types[DataType].Kind = REALTYPE then begin
GenPushReg(EDX); // push edx
GenPushReg(EAX); // push eax
GenPushToFPU; // fld qword ptr [esp]
DiscardStackTop(2); // add esp, 8 ; shrink stack
end
else
if Types[DataType].Kind = SINGLETYPE then begin
GenPushReg(EAX); // push eax
GenNew($D9); Gen($04); Gen($24); // fld dword ptr [esp]
DiscardStackTop(1); // add esp, 4 ; shrink stack
end
else
Error('Internal fault: Illegal type');
end;
procedure PushVarPtr(Addr: Integer; Scope: TScope; DeltaNesting: Byte; RelocType: TRelocType);
const
StaticLinkAddr = 2 * 4;
var
i: Integer;
begin
// EAX must be preserved
case Scope of
GLOBAL: // Global variable
PushRelocConst(Addr, RelocType);
LOCAL: begin
if DeltaNesting = 0 then // Strictly local variable
begin
GenNew($8D); Gen($B5); GenDWord(Addr); // lea esi, [ebp + Addr]
end
else // Intermediate level variable
begin
GenNew($8B); Gen($75); Gen(StaticLinkAddr); // mov esi, [ebp + StaticLinkAddr]
for i := 1 to DeltaNesting - 1 do begin
GenNew($8B); Gen($76); Gen(StaticLinkAddr); // mov esi, [esi + StaticLinkAddr]
end;
GenNew($8D); Gen($B6); GenDWord(Addr); // lea esi, [esi + Addr]
end;
GenPushReg(ESI); // push esi
end;
end; // case
end;
procedure DerefPtr(DataType: Integer);
function OptimizeDerefPtr: Boolean;
var
Addr, Offset: Longint;
AddrRelocIndex: Integer;
begin
Result := False;
// Global variable loading
// Optimization: (mov esi, Addr) + (mov... eax, ... ptr [esi]) -> (mov... eax, ... ptr [Addr]) ; relocatable
if PrevInstrByte(0, 0) = $BE then begin // Previous: mov esi, Addr
Addr := PrevInstrDWord(0, 1);
AddrRelocIndex := PrevInstrRelocDWordIndex(0, 1);
RemovePrevInstr(0); // Remove: mov esi, Addr
case TypeSize(DataType) of
1: if Types[DataType].Kind in UnsignedTypes then begin
GenNew($0F); Gen($B6); Gen($05); // movzx eax, byte ptr ...
end
else begin
GenNew($0F); Gen($BE); Gen($05); // movsx eax, byte ptr ...
end;
2: if Types[DataType].Kind in UnsignedTypes then begin
GenNew($0F); Gen($B7); Gen($05); // movzx eax, word ptr ...
end
else begin
GenNew($0F); Gen($BF); Gen($05); // movsx eax, word ptr ...
end;
4: GenNew($A1)// mov eax, dword ptr ...
else Error('Internal fault: Illegal designator size');
end;
GenDWord(Addr); // ... [Addr]
// Relocate Addr if necessary
if (AddrRelocIndex <> 0) and (TypeSize(DataType) <> 4) then
with Reloc[AddrRelocIndex] do
Pos := Pos + 2;
Result := True;
Exit;
end
// Local variable loading
// Optimization: (lea esi, [ebp + Addr]) + (mov... eax, ... ptr [esi]) -> (mov... eax, ... ptr [ebp + Addr])
else
if (PrevInstrByte(0, 0) = $8D) and (PrevInstrByte(0, 1) = $B5) then // Previous: lea esi, [ebp + Addr]
begin
Addr := PrevInstrDWord(0, 2);
RemovePrevInstr(0); // Remove: lea esi, [ebp + Addr]
case TypeSize(DataType) of
1: if Types[DataType].Kind in UnsignedTypes then begin
GenNew($0F); Gen($B6); Gen($85); // movzx eax, byte ptr [ebp + ...
end
else begin
GenNew($0F); Gen($BE); Gen($85); // movsx eax, byte ptr [ebp + ...
end;
2: if Types[DataType].Kind in UnsignedTypes then begin
GenNew($0F); Gen($B7); Gen($85); // movzx eax, word ptr [ebp + ...
end
else begin
GenNew($0F); Gen($BF); Gen($85); // movsx eax, word ptr [ebp + ...
end;
4: begin
GenNew($8B); Gen($85); // mov eax, dword ptr [ebp + ...
end
else Error('Internal fault: Illegal designator size');
end;
GenDWord(Addr); // ... + Addr]
Result := True;
Exit;
end
// Record field loading
// Optimization: (add esi, Offset) + (mov... eax, ... ptr [esi]) -> (mov... eax, ... ptr [esi + Offset])
else
if (PrevInstrByte(0, 0) = $81) and (PrevInstrByte(0, 1) = $C6) then // Previous: add esi, Offset
begin
Offset := PrevInstrDWord(0, 2);
RemovePrevInstr(0); // Remove: add esi, Offset
case TypeSize(DataType) of
1: if Types[DataType].Kind in UnsignedTypes then begin
GenNew($0F); Gen($B6); Gen($86); // movzx eax, byte ptr [esi + ...
end
else begin
GenNew($0F); Gen($BE); Gen($86); // movsx eax, byte ptr [esi + ...
end;
2: if Types[DataType].Kind in UnsignedTypes then begin
GenNew($0F); Gen($B7); Gen($86); // movzx eax, word ptr [esi + ...
end
else begin
GenNew($0F); Gen($BF); Gen($86); // movsx eax, word ptr [esi + ...
end;
4: begin
GenNew($8B); Gen($86); // mov eax, dword ptr [esi + ...
end
else Error('Internal fault: Illegal designator size');
end;
GenDWord(Offset); // ... + Offset]
Result := True;
Exit;
end;
end;
begin // DerefPtr
GenPopReg(ESI); // pop esi
if Types[DataType].Kind = REALTYPE then // Special case: Double
begin
GenNew($FF); Gen($76); Gen($04); // push [esi + 4]
GenNew($FF); Gen($36); // push [esi]
end
else // General rule
begin
if not OptimizeDerefPtr then
case TypeSize(DataType) of
1: if Types[DataType].Kind in UnsignedTypes then begin
GenNew($0F); Gen($B6); Gen($06); // movzx eax, byte ptr [esi]
end
else begin
GenNew($0F); Gen($BE); Gen($06); // movsx eax, byte ptr [esi]
end;
2: if Types[DataType].Kind in UnsignedTypes then begin
GenNew($0F); Gen($B7); Gen($06); // movzx eax, word ptr [esi]
end
else begin
GenNew($0F); Gen($BF); Gen($06); // movsx eax, word ptr [esi]
end;
4: begin
GenNew($8B); Gen($06); // mov eax, dword ptr [esi]
end
else Error('Internal fault: Illegal designator size');
end;
GenPushReg(EAX); // push eax
end;
end;
procedure GetArrayElementPtr(ArrType: Integer);
function OptimizeGetArrayElementPtr: Boolean;
var
BaseAddr, IndexAddr: Longint;
Index: Integer;
begin
Result := False;
// Global arrays
// Optimization: (push BaseAddr) + (mov eax, [ebp + IndexAddr]) + (pop esi) -> (mov esi, BaseAddr) + (mov eax, [ebp + IndexAddr])
if (PrevInstrByte(1, 0) = $68) and (PrevInstrByte(0, 0) = $8B) and (PrevInstrByte(0, 1) = $85) then // Previous: push BaseAddr, mov eax, [ebp + IndexAddr]
begin
BaseAddr := PrevInstrDWord(1, 1);
IndexAddr := PrevInstrDWord(0, 2);
RemovePrevInstr(1); // Remove: push BaseAddr, mov eax, [ebp + IndexAddr]
GenNew($BE); GenDWord(BaseAddr); // mov esi, BaseAddr ; suilable for relocatable addresses (instruction length is the same as for push BaseAddr)
GenNew($8B); Gen($85); GenDWord(IndexAddr); // mov eax, [ebp + IndexAddr]
Result := True;
end
// Optimization: (push BaseAddr) + (mov eax, Index) + (pop esi) -> (mov esi, BaseAddr) + (mov eax, Index)
else
if (PrevInstrByte(1, 0) = $68) and (PrevInstrByte(0, 0) = $B8) then // Previous: push BaseAddr, mov eax, Index
begin
BaseAddr := PrevInstrDWord(1, 1);
Index := PrevInstrDWord(0, 1);
RemovePrevInstr(1); // Remove: push BaseAddr, mov eax, Index
GenNew($BE); GenDWord(BaseAddr); // mov esi, BaseAddr ; suitable for relocatable addresses (instruction length is the same as for push BaseAddr)
GenNew($B8); GenDWord(Index); // mov eax, Index
Result := True;
end
// Local arrays
// Optimization: (mov eax, [ebp + BaseAddr]) + (push eax) + (mov eax, [ebp + IndexAddr]) + (pop esi) -> (mov esi, [ebp + BaseAddr]) + (mov eax, [ebp + IndexAddr])
else
if (PrevInstrByte(2, 0) = $8B) and (PrevInstrByte(2, 1) = $85) and // Previous: mov eax, [ebp + BaseAddr]
(PrevInstrByte(1, 0) = $50) and // Previous: push eax
(PrevInstrByte(0, 0) = $8B) and (PrevInstrByte(0, 1) = $85) // Previous: mov eax, [ebp + IndexAddr]
then begin
BaseAddr := PrevInstrDWord(2, 2);
IndexAddr := PrevInstrDWord(0, 2);
RemovePrevInstr(2); // Remove: mov eax, [ebp + BaseAddr], push eax, mov eax, [ebp + IndexAddr]
GenNew($8B); Gen($B5); GenDWord(BaseAddr); // mov esi, [ebp + BaseAddr]
GenNew($8B); Gen($85); GenDWord(IndexAddr); // mov eax, [ebp + IndexAddr]
Result := True;
end
// Optimization: (mov eax, [ebp + BaseAddr]) + (push eax) + (mov eax, Index) + (pop esi) -> (mov esi, [ebp + BaseAddr]) + (mov eax, Index)
else
if (PrevInstrByte(2, 0) = $8B) and (PrevInstrByte(2, 1) = $85) and // Previous: mov eax, [ebp + BaseAddr]
(PrevInstrByte(1, 0) = $50) and // Previous: push eax
(PrevInstrByte(0, 0) = $B8) // Previous: mov eax, Index
then begin
BaseAddr := PrevInstrDWord(2, 2);
Index := PrevInstrDWord(0, 1);
RemovePrevInstr(2); // Remove: mov eax, [ebp + BaseAddr], push eax, mov eax, Index
GenNew($8B); Gen($B5); GenDWord(BaseAddr); // mov esi, [ebp + BaseAddr]
GenNew($B8); GenDWord(Index); // mov eax, Index
Result := True;
end;
end;
function Log2(x: Longint): Shortint;
var
i: Integer;
begin
for i := 0 to 31 do
if x = 1 shl i then begin
Result := i;
Exit;
end;
Result := -1;
end;
var
BaseTypeSize, IndexLowBound: Integer;
Log2BaseTypeSize: Shortint;
begin
GenPopReg(EAX); // pop eax ; Array index
if not OptimizeGetArrayElementPtr then
GenPopReg(ESI); // pop esi ; Array base offset
BaseTypeSize := TypeSize(Types[ArrType].BaseType);
IndexLowBound := LowBound(Types[ArrType].IndexType);
if IndexLowBound = 1 then
GenNew($48) // dec eax
else
if IndexLowBound <> 0 then begin
GenNew($2D); GenDWord(IndexLowBound); // sub eax, IndexLowBound
end;
if (BaseTypeSize <> 1) and (BaseTypeSize <> 2) and (BaseTypeSize <> 4) and (BaseTypeSize <> 8) then begin
Log2BaseTypeSize := Log2(BaseTypeSize);
if Log2BaseTypeSize > 0 then begin
GenNew($C1); Gen($E0); Gen(Log2BaseTypeSize); // shl eax, Log2BaseTypeSize
end
else begin
GenNew($69); Gen($C0); GenDWord(BaseTypeSize); // imul eax, BaseTypeSize
end;
end; // if
GenNew($8D); Gen($34); // lea esi, [esi + eax * ...
case BaseTypeSize of
1: Gen($06); // ... * 1]
2: Gen($46); // ... * 2]
4: Gen($86); // ... * 4]
8: Gen($C6) // ... * 8]
else Gen($06) // ... * 1] ; already multiplied above
end;
GenPushReg(ESI); // push esi
end;
procedure GetFieldPtr(Offset: Integer);
function OptimizeGetFieldPtr: Boolean;
var
Addr: Longint;
BaseTypeSizeCode: Byte;
begin
Result := False;
// Optimization: (lea esi, [ebp + Addr]) + (add esi, Offset) -> (lea esi, [ebp + Addr + Offset])
if (PrevInstrByte(0, 0) = $8D) and (PrevInstrByte(0, 1) = $B5) then // Previous: lea esi, [ebp + Addr]
begin
Addr := PrevInstrDWord(0, 2);
RemovePrevInstr(0); // Remove: lea esi, [ebp + Addr]
GenNew($8D); Gen($B5); GenDWord(Addr + Offset); // lea esi, [ebp + Addr + Offset]
Result := True;
end
// Optimization: (lea esi, [esi + eax * BaseTypeSize]) + (add esi, Offset) -> (lea esi, [esi + eax * BaseTypeSize + Offset])
else
if (PrevInstrByte(0, 0) = $8D) and (PrevInstrByte(0, 1) = $34) then // Previous: lea esi, [esi + eax * BaseTypeSize]
begin
BaseTypeSizeCode := PrevInstrDWord(0, 2);
RemovePrevInstr(0); // Remove: lea esi, [esi + eax * BaseTypeSize]
GenNew($8D); Gen($B4); Gen(BaseTypeSizeCode); GenDWord(Offset); // lea esi, [esi + eax * BaseTypeSize + Offset]
Result := True;
end;
end;
begin // GetFieldPtr
if Offset <> 0 then begin
GenPopReg(ESI); // pop esi
if not OptimizeGetFieldPtr then begin
GenNew($81); Gen($C6); GenDWord(Offset); // add esi, Offset
end;
GenPushReg(ESI); // push esi
end;
end;
procedure GetCharAsTempString(Depth: Integer);
begin
if (Depth <> 0) and (Depth <> SizeOf(Longint)) then
Error('Internal fault: Illegal depth');
GenPopReg(ESI); // pop esi ; Temporary string address
if Depth = SizeOf(Longint) then
GenPopReg(ECX); // pop ecx ; Some other string address
GenPopReg(EAX); // pop eax ; Character
GenNew($88); Gen($06); // mov byte ptr [esi], al
GenNew($C6); Gen($46); Gen($01); Gen($00); // mov byte ptr [esi + 1], 0
GenPushReg(ESI); // push esi
if Depth = SizeOf(Longint) then
GenPushReg(ECX); // push ecx ; Some other string address
end;
procedure SaveStackTopToEAX;
begin
GenPopReg(EAX); // pop eax
end;
procedure RestoreStackTopFromEAX;
begin
GenPushReg(EAX); // push eax
end;
procedure SaveStackTopToEDX;
begin
GenPopReg(EDX); // pop edx
end;
procedure RestoreStackTopFromEDX;
begin
GenPushReg(EDX); // push edx
end;
procedure RaiseStackTop(NumItems: Byte);
begin
GenNew($81); Gen($EC); GenDWord(SizeOf(Longint) * NumItems); // sub esp, 4 * NumItems
end;
procedure DiscardStackTop(NumItems: Byte);
function OptimizeDiscardStackTop: Boolean;
var
Value: Longint;
begin
Result := False;
// Optimization: (push Reg) + (add esp, 4 * NumItems) -> (add esp, 4 * (NumItems - 1))
if PrevInstrByte(0, 0) in [$50, $51, $52, $56, $57, $55] then begin // Previous: push Reg
RemovePrevInstr(0); // Remove: push Reg
if NumItems > 1 then begin
GenNew($81); Gen($C4); GenDWord(SizeOf(Longint) * (NumItems - 1)); // add esp, 4 * (NumItems - 1)
end;
Result := True;
end
// Optimization: (sub esp, Value) + (add esp, 4 * NumItems) -> (add esp, 4 * NumItems - Value)
else
if (PrevInstrByte(0, 0) = $81) and (PrevInstrByte(0, 1) = $EC) then // Previous: sub esp, Value
begin
Value := PrevInstrDWord(0, 2);
RemovePrevInstr(0); // Remove: sub esp, Value
if SizeOf(Longint) * NumItems <> Value then begin
GenNew($81); Gen($C4); GenDWord(SizeOf(Longint) * NumItems - Value); // add esp, 4 * NumItems - Value
end;
Result := True;
end;
end;
begin // DiscardStackTop
if not OptimizeDiscardStackTop then begin
GenNew($81); Gen($C4); GenDWord(SizeOf(Longint) * NumItems); // add esp, 4 * NumItems
end;
end;
procedure DiscardStackTopAt(Pos: Longint; NumItems: Byte);
begin
GenAt(Pos, $81); GenAt(Pos + 1, $C4); GenDWordAt(Pos + 2, SizeOf(Longint) * NumItems); // add esp, 4 * NumItems
end;
procedure DuplicateStackTop;
begin
GenNew($FF); Gen($34); Gen($24); // push dword ptr [esp]
end;
procedure SaveCodePos;
begin
Inc(CodePosStackTop);
CodePosStack[CodePosStackTop] := GetCodeSize;
end;
function RestoreCodePos: Longint;
begin
Result := CodePosStack[CodePosStackTop];
Dec(CodePosStackTop);
end;
procedure GenerateIncDec(proc: TPredefProc; Size: Byte; BaseTypeSize: Integer = 0);
begin
GenPopReg(ESI); // pop esi
if BaseTypeSize <> 0 then // Special case: typed pointer
begin
GenNew($81); // ... dword ptr ...