File: STDecompiler.st

package info (click to toggle)
gnu-smalltalk 2.1.8-2.1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 17,484 kB
  • ctags: 8,274
  • sloc: ansic: 53,661; sh: 17,366; perl: 4,319; awk: 1,319; yacc: 1,023; makefile: 1,010; sed: 258; lex: 249
file content (1324 lines) | stat: -rw-r--r-- 33,459 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
"======================================================================
|
|   Smalltalk bytecode decompiler
|
|
 ======================================================================"


"======================================================================
|
| Copyright 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
| Written by Paolo Bonzini.
|
| This file is part of GNU Smalltalk.
|
| GNU Smalltalk is free software; you can redistribute it and/or modify it
| under the terms of the GNU General Public License as published by the Free
| Software Foundation; either version 2, or (at your option) any later version.
| 
| GNU Smalltalk is distributed in the hope that it will be useful, but WITHOUT
| ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
| FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
| details.
| 
| You should have received a copy of the GNU General Public License along with
| GNU Smalltalk; see the file COPYING.  If not, write to the Free Software
| Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  
|
 ======================================================================"


RBValueToken subclass: #STDecompiledValueToken
       instanceVariableNames: ''
       classVariableNames: ''
       poolDictionaries: ''
       category: 'System-Compiler'
! 

Object subclass: #STDecompilationContext
       instanceVariableNames: 'mclass outer method numTemps numArgs tmpNames current jumps instVarNames instVarNamesSet cfg basicBlocks '
       classVariableNames: ''
       poolDictionaries: ''
       category: 'System-Compiler'
! 

STDecompilationContext comment:
'This class holds the information about the current decompilation,
including the CFG and the synthetic variable names.

Most of this information is interesting to the decompilers for
the blocks, which is why the sub-contexts hold a pointer to
the outer context.'!

Magnitude subclass: #STControlFlowGraphNode
       instanceVariableNames: 'id dfnum pred succ fallThrough statements stack '
       classVariableNames: ''
       poolDictionaries: ''
       category: 'System-Compiler'
!

STControlFlowGraphNode comment:
'This class is a node in the CFG of a method.  It knows how
to simplify itself to a single node that uses Smalltalk''s
control-structures-as-messages.'!

Object subclass: #STDecompiler
       instanceVariableNames: 'context stack statements isBlock current bbList bb '
       classVariableNames: ''
       poolDictionaries: ''
       category: 'System-Compiler'
! 

STDecompiler comment:
'This class converts bytecodes back to parse trees.'!

!STDecompiledValueToken methodsFor: 'overrides'!

length
    "Always answer 1 (the size of a bytecode)."
    ^1! !

!STDecompilationContext class methodsFor: 'instance creation'!

on: aCompiledCodeObject class: aClass outer: outerContext
    ^self new initialize: aCompiledCodeObject class: aClass outer: outerContext!

!STDecompilationContext methodsFor: 'initialization'!

initialize: aCompiledCodeObject class: aClass outer: outerContext
    "Initialize the receiver's instance variables with information
     about decompiling the block or method aCompiledCodeObject, found in
     the aClass class.  If we are to decompile a block, the context
     for the outer method is found in outerContext."

    mclass := aClass.
    outer := outerContext.
    method := aCompiledCodeObject.
    numTemps := outer isNil ifTrue: [ 0 ] ifFalse: [ outer numTemps ].
    numArgs := outer isNil ifTrue: [ 0 ] ifFalse: [ outer numArgs ].
    instVarNames := aClass allInstVarNames.
    instVarNamesSet := instVarNames asSet.
    tmpNames := IdentityDictionary new.
    jumps := IdentityDictionary new.

    0 to: self methodNumArgs - 1
	do: [ :index | tmpNames at: index put: self newArgName ].

    aCompiledCodeObject dispatchTo: self with: nil.
    self buildCFG.
!

buildCFG
    "Build the control-flow graph of the object to be decompiled."

    | basicBlockBoundaries n |
    basicBlockBoundaries := jumps keys collect: [ :each |
	method nextByteCodeIndex: each ].
    basicBlockBoundaries addAll: (jumps values collect: [ :each |
	each value ]).
    basicBlockBoundaries add: method size + 2.

    "Build a map from bytecode numbers to basic block ids"
    basicBlocks := OrderedCollection new.
    cfg := OrderedCollection new.
    n := 1.
    basicBlockBoundaries asSortedCollection inject: 1 into: [ :old :boundary |
	boundary > old ifTrue: [
	    boundary - old timesRepeat: [ basicBlocks add: n ].
	    cfg addLast: (STControlFlowGraphNode id: n).
	    n := n + 1.
	].
	boundary
    ].

    "Now use it to build the CFG"
    jumps keysAndValuesDo: [ :key :each |
	(self cfgNodeAt: key)
	    addSuccessor: each key -> (self cfgNodeAt: each value).
    ].

    "Add arcs for falling off the basic block."
    cfg from: 1 to: cfg size - 1 do: [ :each |
	each succ isNil ifTrue: [
	    each addSuccessor: #jump -> (cfg at: each id + 1) ].

	(each succ at: 1) key = #jumpTrue ifTrue: [
	    each addSuccessor: #jumpFalse -> (cfg at: each id + 1) ].

	(each succ at: 1) key = #jumpFalse ifTrue: [
	    each addSuccessor: #jumpTrue -> (cfg at: each id + 1) ].
    ].

    "Sort in depth-first order"
    (cfg at: 1) computeDfnums: 1
! !

!STDecompilationContext methodsFor: 'accessing'!

outer
    "Answer the outer decompilation context"
    ^outer!

mclass
    "Answer the class in which the method we are decompiling lives"
    ^mclass!

method
    "Answer the method we are decompiling"
    ^method!

cfg
    "Answer an Array with all the nodes in the method's control-flow
     graph."
    ^cfg!

cfgNodeAt: bytecode
    "Answer the node of the control-flow graph that contains information
     for the basic block of which the given bytecode index is part"

    ^cfg at: (basicBlocks at: bytecode)!

outerTemporaryAt: anIndex scopes: scopes
    "Answer the name of the anIndex-th temporary in the scopes-th outer
     scope"

    ^scopes > 0
	ifTrue: [ self outer outerTemporaryAt: anIndex scopes: scopes - 1 ]
	ifFalse: [ self temporaryAt: anIndex ]!

instVarNameAt: anIndex
    "Answer the name of the anIndex-th instance variable of the class
     in which the decompiled method lives."

    ^instVarNames at: anIndex + 1!

temporaryAt: anIndex
    "Answer the name of the anIndex-th temporary of the decompiled method."

    ^tmpNames at: anIndex!

temporaryNames
    "Answer the name of all the temporaries of the decompiled method."

    ^tmpNames values!

methodNumArgs
    "Answer the number of arguments that the decompiled method receives."

    ^method numArgs!

numArgs
    "Answer the number of argXXX variables that have been defined so far."

    ^numArgs!

numTemps
    "Answer the number of tXXX variables that have been defined so far."

    ^numTemps!

newArgName
    "Answer a new argXXX variable"

    | candidate |
    [
	candidate := 'arg', (numArgs := numArgs + 1) printString.
	instVarNamesSet includes: candidate
    ] whileTrue.
    ^candidate!

newTemporaryName
    "Answer a new tXXX variable"

    | candidate |
    [
	candidate := 't', (numTemps := numTemps + 1) printString.
	instVarNamesSet includes: candidate
    ] whileTrue.
    ^candidate!

!STDecompilationContext methodsFor: 'analyzing'!

invalidOpcode: unused
    "Signal an error"

    self error: 'invalid opcode'!

pushInstVar: anIndex with: unused
!

storeInstVar: anIndex with: unused
!

popStoreInstVar: anIndex with: unused
!

setTopInstVar: anIndex with: unused
!

pushTemporary: anIndex outer: scopes with: unused
    "Create the name of the given temporary"

    scopes > 0
	ifTrue: [ self pushTemporary: anIndex with: unused ]
	ifFalse: [ outer pushTemporary: anIndex outer: scopes - 1 with: unused ]
!

storeTemporary: anIndex outer: scopes with: unused
    "Create the name of the given temporary"

    scopes > 0
	ifTrue: [ self storeTemporary: anIndex with: unused ]
	ifFalse: [ outer storeTemporary: anIndex outer: scopes - 1 with: unused ]
!

popStoreTemporary: anIndex outer: scopes with: unused
    "Create the name of the given temporary"

    scopes > 0
	ifTrue: [ self popStoreTemporary: anIndex with: unused ]
	ifFalse: [ outer popStoreTemporary: anIndex outer: scopes - 1 with: unused ]
!

pushTemporary: anIndex with: unused
    "Create the name of the given temporary"

    tmpNames at: anIndex ifAbsentPut: [ self newTemporaryName ]!

storeTemporary: anIndex with: unused
    "Create the name of the given temporary"

    tmpNames at: anIndex ifAbsentPut: [ self newTemporaryName ]!

popStoreTemporary: anIndex with: unused
    "Create the name of the given temporary"

    tmpNames at: anIndex ifAbsentPut: [ self newTemporaryName ]!

setTopTemporary: anIndex with: unused
    "Create the name of the given temporary"

    tmpNames at: anIndex ifAbsentPut: [ self newTemporaryName ]!

popIntoArray: anIndex with: unused
!

pushLiteral: anObject with: unused
!

setTopLiteral: anObject with: unused
!

pushGlobal: anObject with: unused
!

storeGlobal: anObject with: unused
!

popStoreGlobal: anObject with: unused
!

setTopGlobal: anObject with: unused
!

pushSelf: unused
!

returnSelf: unused
    "Returns are treated as jumps to past the final bytecode"

    self returnFromContext: unused
!

setTopSelf: unused
!

pushThisContext: unused
!

popStackTop: unused
!

dupStackTop: unused
!

exitInterpreter: unused
!

noOperation: unused
!

returnLiteral: anObject with: unused
    "Returns are treated as jumps to past the final bytecode"

    self returnFromContext: unused
!

returnFromContext: unused
    "Returns are treated as jumps to past the final bytecode"

    self jumpTo: method size + 1 with: unused
!

returnFromMethod: unused
    "Returns are treated as jumps to past the final bytecode"

    self jumpTo: method size + 1 with: unused
!

popJumpIfFalseTo: destination with: unused
    "Record the jump"

    jumps at: current put: #jumpFalse->destination!

popJumpIfTrueTo: destination with: unused
    "Record the jump"

    jumps at: current put: #jumpTrue->destination!

jumpTo: destination with: unused
    "Record the jump"

    jumps at: current put: #jump->destination!

superSend: aSymbol numArgs: anInteger with: unused
!

send: aSymbol numArgs: anInteger with: unused
!

bytecodeIndex: byte with: unused
    current := byte.
! !

!STControlFlowGraphNode class methodsFor: 'instance creation'!

id: id
    "Create a new instance of the receiver"

    ^self new id: id!

!STControlFlowGraphNode methodsFor: 'printing'!

printOn: aStream 
    "Print a textual representation of the receiver on aStream"

    aStream
	print: self id;
	nextPutAll: ' df=';
	print: self dfnum.

    self succ isNil ifFalse: [
	aStream print: (self succ
    	    collect: [ :each | each key -> each value id ]) asArray
    ].
    statements isNil ifFalse: [
        statements do: [ :each |
	    aStream nl; space: 4; print: each
        ]
    ].
    aStream nl!

printTreeOn: aStream 
    "Print a textual representation of the receiver and all of its
     successors on aStream"

    (self withAllSuccessors asSortedCollection: [ :a :b | a id < b id ])
	do: [ :node | aStream print: node; nl ]!

!STControlFlowGraphNode methodsFor: 'private'!

addPredecessor: node
    "Private - Add `node' to the set of predecessors of the receiver."

    pred := pred isNil
	ifTrue: [ {node} ]
	ifFalse: [ pred copyWith: node ]!

removeSuccessor: node
    "Private - Remove `node' from the set of successors of the receiver."

    succ isNil
	ifFalse: [ succ := succ reject: [ :each | each value = node ].
	    succ isEmpty ifTrue: [ succ := nil ]
	]!

removePredecessor: node
    "Private - Remove `node' from the set of predecessors of the receiver."

    pred isNil
	ifFalse: [ pred := pred copyWithout: node.
	    pred isEmpty ifTrue: [ pred := nil ]
	]!

addAllSuccessorsTo: aSet
    "Private - Add all the direct and indirect successors of the receiver
     to aSet."

    succ isNil ifTrue: [ ^aSet ].
    succ do: [ :each |
	(aSet includes: each value) ifFalse: [
	    aSet add: each value.
	    each value addAllSuccessorsTo: aSet ]
    ].
    ^aSet!

computeDfnums: n
    "Private - Number the receiver and all of its direct and
     indirect successors in depth-first order, starting from n."

    | num |
    self dfnum isNil ifFalse: [ ^n ].
    self dfnum: n.
    num := n + 1.
    self succ isNil ifFalse: [
	succ do: [ :each |
	    num := each value computeDfnums: num
	]
    ].
    ^num! !
 
!STControlFlowGraphNode methodsFor: 'comparison'!

< anObject
    "Sort in depth-first order"

    ^self dfnum < anObject dfnum!

= anObject
    "Sort in depth-first order"

    ^self class == anObject class and: [
	self dfnum = anObject dfnum ]!

hash
    "Sort in depth-first order"

    ^self dfnum! !

!STControlFlowGraphNode methodsFor: 'accessing'!

allSuccessors
    "Answer the set of all direct and indirect successors of
     the receiver"
    ^self addAllSuccessorsTo: Set new!

withAllSuccessors
    "Answer the set of all the nodes in the receiver's CFG, that
     is the node and all of its direct and indirect successors."
    ^(self addAllSuccessorsTo: Set new) add: self; yourself!

dfnum
    "Answer the progressive number of the receiver in a depth-first
     visit of the graph."
    ^dfnum!

dfnum: n
    "Set the progressive number of the receiver in a depth-first
     visit of the graph."
    dfnum := n!

id
    "Answer a numeric identifier for the receiver.  Consecutive indexes
     represent basic blocks that are adjacent in memory."

    ^id!

id: n
    "Set the numeric identifier for the receiver.  Consecutive indexes
     represent basic blocks that are adjacent in memory."

    id := n!

pred
    "Answer the set of predecessors of the receiver."
    ^pred!

succ
    "Answer the set of successors of the receiver."
    ^succ!

succ: newSucc
    "Set the set of successors of the receiver to be newSucc.
     newSucc should hold associations that represent the kind
     of jump (#jump, #jumpTrue, #jumpFalse) in the key, and
     the destination basic block in the value."

    succ isNil ifFalse: [
	succ do: [ :each |
	    each value removePredecessor: self
	].
	succ := nil.
    ].
    succ := newSucc.
    succ isNil ifTrue: [ ^self ].
    succ do: [ :assoc |
	assoc value addPredecessor: self ]!

statements
    "Answer the set of statements executed by the receiver"

    ^statements!

statements: aCollection
    "Set the set of statements executed by the receiver"

    statements := aCollection!

stack
    "Answer the state of the stack after the receiver completes
     its execution"

    stack isNil ifTrue: [ stack := OrderedCollection new ].
    ^stack!

stack: aCollection
    "Set the state of the stack after the receiver completes
     its execution"

    stack := aCollection!

fallThroughIfFalse
    "Answer whether the receiver ends with a `jump if true'
     bytecode"
    ^fallThrough = #jumpFalse!

fallThroughIfTrue
    "Answer whether the receiver ends with a `jump if false'
     bytecode"
    ^fallThrough = #jumpTrue!

addSuccessor: kindBlockAssociation
    "Add the successor represented by kindBlockAssociation,
     which should be an association that represents the kind
     of jump (#jump, #jumpTrue, #jumpFalse) in the key, and
     the destination basic block in the value."

    kindBlockAssociation value id = (self id + 1)
	ifTrue: [ fallThrough := kindBlockAssociation key ].

    succ := succ isNil
	ifTrue: [ {kindBlockAssociation} ]
	ifFalse: [ succ copyWith: kindBlockAssociation ].

    kindBlockAssociation value
	addPredecessor: self!

!STControlFlowGraphNode methodsFor: 'simplification'!

blkNode: statements arguments: args
    "Private - Answer an RBBlockNode with the given statements
     and arguments."

    ^RBBlockNode new
	body: (self seqNode: statements);
	arguments: args!

blkNode: statements
    "Private - Answer an RBBlockNode with the given statements."

    ^RBBlockNode new
	body: (self seqNode: statements);
	arguments: #()!

msgNode: arguments receiver: receiver selector: aSymbol
    "Private - Answer an RBMessageNode with the given arguments,
     receiver and selector."

    | selParts |
    selParts := aSymbol keywords
	collect: [ :each | RBValueToken new value: each ].
    
    ^RBMessageNode new
	arguments: arguments;
	receiver: receiver;
	selectorParts: selParts!

seqNode: statements
    "Private - Answer an RBSequenceNode with the given statements."

    ^RBSequenceNode new
	temporaries: #();
	statements: statements;
	periods: #()!

disconnect
    "Disconnect the receiver from the graph (removing
     all arcs that point to it or depart from it)."

    pred isNil ifFalse: [
	pred do: [ :each |
	    each removeSuccessor: self
	].
	pred := nil
    ].
    self succ: nil
!

disconnectSuccessorsAndMerge: newSucc
    "Disconnect the receiver's successors from the graph (removing
     all arcs that point to them or depart from them),
     then try to merge the receiver with its predecessor
     (if there is only one after the disconnection) and
     possibly with the new successors, newSucc (if there
     is only one and it has no other predecessors than the
     receiver)."

    succ do: [ :each | each value disconnect ].
    self merge: newSucc
!

merge: newSucc
     "Try to merge the receiver with its predecessor
     (if there is only one after the disconnection) and
     possibly with the new successors, newSucc (if there
     is only one and it has no other predecessors than the
     receiver)."

    | newSelf |

    self succ: newSucc.
    newSelf := pred size = 1
	ifFalse: [ newSelf := self ]
	ifTrue: [
	    (newSelf := pred at: 1) statements
	        addAllLast: self statements.
	    self disconnect.
	    newSelf succ: newSucc.
	].

    newSucc size = 1 ifFalse: [ ^self ].
    (newSucc at: 1) value pred size = 1
	ifTrue: [ newSelf merge: (newSucc at: 1) value succ ]!

simplify
    "Recognize simple control structures in the receiver and
     reduce them to a single basic block that sends the appropriate
     Smalltalk messages."

    self
	simplifyRepeat;
	simplifyIf;
	simplifyLoop!

simplifyIf: cond then: arm2 else: arm1 ifTrueIfFalse: ifTrueIfFalse
    "Simplify a two-way conditional.  cond used to be the
     last statement of the receiver, arm1 and arm2 are the
     receiver's successor basic blocks."

    | block1 block2 |
    "'resolving if/then/else' displayNl."

    block2 := self blkNode: arm2 statements.
    block1 := self blkNode: arm1 statements.

    self statements addLast: (self
	msgNode: { block1. block2 }
	receiver: cond
	selector: (ifTrueIfFalse
	    ifTrue: [ #ifTrue:ifFalse: ]
	    ifFalse: [ #ifFalse:ifTrue: ]))
!

simplifyIf: cond then: arm ifTrue: ifTrue
    "Simplify a one-way conditional.  cond used to be the
     last statement of the receiver, arm is one of the
     receiver's successor basic blocks."

    | seq block |
    "'resolving if/then' displayNl."

    block := self blkNode: arm statements.

    self statements addLast: (self
	msgNode: { block }
	receiver: cond
	selector: (ifTrue
	    ifTrue: [ #ifTrue: ]
	    ifFalse: [ #ifFalse: ]))
!

simplifyIf
    "Recognize conditional control structures where the
     receiver is the header, and simplify them."

    | cond arm1 arm2 |
    succ size < 2 ifTrue: [ ^false ].

    arm1 := (self succ at: 1) value.
    arm2 := (self succ at: 2) value.

    ((arm1 succ at: 1) value = (arm2 succ at: 1) value
	and: [ (arm1 succ at: 1) value ~= self
	and: [ (arm2 succ at: 1) value ~= self ]])
	    ifTrue: [ self simplifyIf: self statements removeLast
				then: arm1
				else: arm2
				ifTrueIfFalse: self fallThroughIfFalse;
			    disconnectSuccessorsAndMerge: arm1 succ. ^true ].

    ((arm2 succ at: 1) value = arm1
	and: [ (arm2 succ at: 1) value ~= self ])
	    ifTrue: [ self simplifyIf: self statements removeLast
				then: arm2
				ifTrue: self fallThroughIfTrue;
			    disconnectSuccessorsAndMerge: arm1 succ. ^true ].

    ^false
!

simplifyWhile: body whileTrue: whileTrue
    "Simplify a #whileTrue: or #whileFalse: control structure
     where the receiver will be the receiver block, and body
     the argument block."

    | cond block |
    "'resolving while' displayNl."

    cond := self blkNode: self statements.
    block := self blkNode: body statements.

    self statements: (OrderedCollection
	with: (self
	    msgNode: { block }
	    receiver: cond 
	    selector: (whileTrue
	        ifTrue: [ #whileTrue: ]
	        ifFalse: [ #whileFalse: ])))
!

simplifyToByDo: body
    "Simplify a #to:do: or #to:by:do: control structure."

    | variable from to by block |

    "'resolving to/by/do' displayNl."

    self statements removeLast.
    to := self statements removeLast.
    from := self statements last value.
    variable := self statements removeLast variable.
    by := body statements removeLast value arguments at: 1.

    body statements removeLast; removeLast; removeLast.
    (self pred at: 2) statements removeLast; removeLast; removeLast; removeLast.
    block := self blkNode: body statements arguments: { variable }.

    self statements addLast: (self
	msgNode: (by=1
	    ifTrue: [ { to. block } ]
	    ifFalse: [ { to. by. block } ])
	receiver: from
	selector: (by=1
	    ifFalse: [ #to:by:do: ]
	    ifTrue: [ #to:do: ]))
!

simplifyLoop
    "Recognize looping control structures where the
     receiver is the dominator, and simplify them."

    | middle bottom |
    succ size < 2 ifTrue: [ ^false ].
    pred isNil ifTrue: [ ^false ].

    bottom := succ detect: [ :each |
	pred includes: each value ] ifNone: [ ^false ].

    middle := succ detect: [ :each | each ~= bottom ].

    middle value statements size = 0
	ifFalse: [ self simplifyToByDo: bottom value ]
	ifTrue: [ self simplifyWhile: bottom value
			whileTrue: self fallThroughIfFalse ].

    self disconnectSuccessorsAndMerge: middle value succ.
    ^true
!

simplifyRepeat
    "Recognize and simplify infinite loops (#repeat)."

    | block |
    self succ isNil ifTrue: [ ^false ].
    (self succ at: 1) value = self ifFalse: [ ^false ].

    "'resolving repeat' displayNl."

    block := self blkNode: self statements.

    self statements: {self
	msgNode: #()
	receiver: block
	selector: #repeat}.

    self merge: nil.
    ^true
! !

!STDecompiler class methodsFor: 'instance creation'!

decompile: aSelector in: aClass
    "Answer the source code for the selector aSelector of the
     given class"

    | node |
    node := self parseTreeForMethod: aClass >> aSelector in: aClass.

    ^RBFormatter new format: node!

parseTreeForMethod: aMethod in: aClass
    "Answer the parse tree for the method aMethod of the
     given class"

    ^self new decompileMethod:
	(STDecompilationContext on: aMethod class: aClass outer: nil)!

parseTreeForBlock: aBlock from: aDecompilerObject
    "Answer the parse tree for the block aBlock, considering
     the information already dug by aDecompilerObject"

    ^self new
	decompileBlock: (STDecompilationContext
			on: aBlock
			class: aDecompilerObject context mclass
			outer: aDecompilerObject context)! !

!STDecompiler methodsFor: 'auxiliary'!

context
    ^context!

source
    "Answer a dummy source code object to be used to insert
     primitive names in the decompiled code."

    ^context method primitive > 0
	ifTrue: [ '<primitive: %1>' bindWith:
	    (VMPrimitives keyAtValue: context method primitive) asString ]
	ifFalse: [ '' ]!

tags: source
    ^source isEmpty
	ifTrue: [ #() ]
	ifFalse: [ { 1 to: source size } ]!

argumentNames
    ^(0 to: context methodNumArgs - 1)
	collect: [ :each | context temporaryAt: each ]!

arguments
    ^self argumentNames collect: [ :each | self varNode: each ]!

selectorParts: aSymbol
    ^aSymbol keywords
	collect: [ :each | RBValueToken value: each start: current ]!

temporaries
    ^self temporaryNames collect: [ :each | self varNode: each ]!

temporaryNames
    ^context temporaryNames asOrderedCollection
	removeAll: self argumentNames;
	yourself!

litNode: anObject
    | tok |
    anObject class == BlockClosure
	ifTrue: [ ^self class parseTreeForBlock: anObject block from: self ].

    tok := anObject class == Association
	ifFalse: [ RBLiteralToken value: anObject start: current ]
	ifTrue: [ RBBindingToken value: anObject path start: current ].

    ^RBLiteralNode new literalToken: tok!

varNode: name
    ^RBVariableNode new identifierToken:
        (STDecompiledValueToken value: name start: current)!

assignment: name
    ^RBAssignmentNode new
	value: stack removeLast;
	variable: (self varNode: name)! !

!STDecompiler methodsFor: 'decompilation'!

decompileBlock: stDecompilationContext

    isBlock := true.
    ^RBBlockNode new
	body: (self decompileBody: stDecompilationContext);
	arguments: self arguments;
	yourself!

decompileMethod: stDecompilationContext
    | parseNode |

    isBlock := false.
    ^(parseNode := RBMethodNode new)
	body: (self decompileBody: stDecompilationContext);
	selectorParts: (self selectorParts: context method selector);
	source: self source;
	tags: (self tags: parseNode source);
	arguments: self arguments;
	yourself!

decompileBody: stDecompilationContext
    | seq |
    context := stDecompilationContext.
    stack := OrderedCollection new.
    bbList := SortedCollection new.
    context method dispatchTo: self with: nil.

    self bytecodeIndex: context method size + 1 with: nil.
    self simplify.

    seq := RBSequenceNode new
	temporaries: self temporaries;
	statements: (context cfg at: 1) statements;
	periods: #().

    ^seq

!

doCascade: send
    (stack notEmpty and: [ stack last isCascade ])
	ifFalse: [
	    stack addLast: (RBCascadeNode new
		messages: (OrderedCollection with: send)).
	]
	ifTrue: [
	    send parent: stack last.
	    stack last messages addLast: send.
	].
!

endStatement
    statements addLast: stack removeLast
! !

!STDecompiler methodsFor: 'analyzing'!

invalidOpcode: unused
    self error: 'invalid opcode'!

pushInstVar: anIndex with: unused
    stack addLast: (self varNode: (context instVarNameAt: anIndex))!

storeInstVar: anIndex with: unused
    stack addLast: (self assignment: (context instVarNameAt: anIndex))!

popStoreInstVar: anIndex with: unused
    self
	storeInstVar: anIndex with: unused;
	popStackTop: unused!

setTopInstVar: anIndex with: unused
    self
	popStackTop: unused;
	pushInstVar: anIndex with: unused!

pushTemporary: anIndex outer: scopes with: unused
    stack addLast: (self varNode: (context outerTemporaryAt: anIndex scopes: scopes))!

storeTemporary: anIndex outer: scopes with: unused
    stack addLast: (self assignment: (context outerTemporaryAt: anIndex scopes: scopes))!

popStoreTemporary: anIndex outer: scopes with: unused
    self
	storeTemporary: anIndex outer: scopes with: unused;
	popStackTop: unused!

pushTemporary: anIndex with: unused
    stack addLast: (self varNode: (context temporaryAt: anIndex))!

storeTemporary: anIndex with: unused
    stack addLast: (self assignment: (context temporaryAt: anIndex))!

popStoreTemporary: anIndex with: unused
    self
	storeTemporary: anIndex with: unused;
	popStackTop: unused!

setTopTemporary: anIndex with: unused
    self
	popStackTop: unused;
	pushTemporary: anIndex with: unused!

popIntoArray: anIndex with: unused
    | value |
    value := stack removeLast.
    anIndex = 0 ifTrue: [
	stack removeLast.
	stack addLast: (RBArrayConstructorNode new
	    body: (RBSequenceNode new
		temporaries: #();
		statements: OrderedCollection new;
		periods: #()))
    ].

    stack last body addNode: value!

pushLiteral: anObject with: unused
    stack addLast: (self litNode: anObject)!

setTopLiteral: anObject with: unused
    self
	popStackTop: unused;
	pushLiteral: anObject with: unused!

pushGlobal: anObject with: unused
    stack addLast: (self varNode: anObject path)!

storeGlobal: anObject with: unused
    stack addLast: (self assignment: anObject path)!

popStoreGlobal: anObject with: unused
    self
	storeGlobal: anObject with: unused;
	popStackTop: unused!

setTopGlobal: anObject with: unused
    self
	popStackTop: unused;
	pushGlobal: anObject with: unused!

pushSelf: unused
    stack addLast: (self varNode: 'self')!

returnSelf: unused
    stack isEmpty ifFalse: [ self popStackTop: unused ].

    self
	pushSelf: unused;
	returnFromContext: unused!

setTopSelf: unused
    self
	popStackTop: unused;
	pushSelf: unused!

pushThisContext: unused
    stack addLast: (self varNode: 'thisContext')!

isCascadeLast
    ^stack size >= 2 and: [
	(stack at: stack size - 1) isCascade ]!

isCascade
    (stack size >= 3 and: [
	(stack at: stack size - 2) isCascade ]) ifTrue: [ ^true ].

    ^stack size >= 2 and: [
	stack last isMessage and: [
	(stack at: stack size - 1) == stack last receiver ]]!

popStackTop: unused
    | send receiver |
    self isCascade ifFalse: [ ^self endStatement ].

    "There are two possible cases:

	 the receiver		-->	an RBCascadeNode
	 the new message send		the receiver

	 the RBCascadeNode		augmented RBCascadeNode
	 the receiver		-->	the receiver
	 the new message send"

    send := stack removeLast.
    receiver := stack removeLast.
    self doCascade: send.
    stack addLast: receiver!

dupStackTop: unused
    stack addLast: (stack at: stack size)!

exitInterpreter: unused
!

noOperation: unused
!

returnLiteral: anObject with: unused
    stack isEmpty ifFalse: [ self popStackTop: unused ].

    self
	pushLiteral: anObject with: unused;
	returnFromContext: unused!

returnFromContext: unused
    isBlock
	ifTrue: [ self endStatement ]
	ifFalse: [ self returnFromMethod: unused ]!

returnFromMethod: unused
    stack addLast: (RBReturnNode value: stack removeLast).
    self endStatement!

popJumpIfFalseTo: destination with: unused
!

popJumpIfTrueTo: destination with: unused
!

jumpTo: destination with: unused
!

superSend: aSymbol numArgs: anInteger with: unused
    stack at: stack size - anInteger put: (self varNode: 'super').
    ^self send: aSymbol numArgs: anInteger with: unused!

send: aSymbol numArgs: anInteger with: unused
    | args collection msg |
    aSymbol == #blockCopy: ifTrue: [
	^stack removeLast ].

    args := Array new: anInteger.
    anInteger to: 1 by: -1 do: [ :each |
	args at: each put: stack removeLast
    ].

    stack addLast: (RBMessageNode new
	arguments: args;
	receiver: stack removeLast;
	selectorParts: (self selectorParts: aSymbol)).

    "If the receiver was over an RBCascadeNode, merge the send
     with the cascade."
    self isCascadeLast
	ifTrue: [ self doCascade: stack removeLast ]!

bytecodeIndex: byte with: unused
    | newBB |
    current := byte.
    newBB := context cfgNodeAt: byte.
    newBB == bb ifFalse: [
	self newBasicBlock: newBB.
	statements := OrderedCollection new.
	bb := newBB
    ]!

newBasicBlock: newBB
    bb isNil ifTrue: [ ^self ].
    bb dfnum isNil ifTrue: [ ^self ].

    statements addAllLast: stack.
    bb statements: statements.

    bbList add: bb.

    bb succ do: [ :each |
	each value stack: stack copy.
	each key = #jump ifFalse: [
	    each value stack removeLast
	]
    ].

    stack := newBB stack!

simplify
    | oldSize goOn |
    bbList := bbList asArray.

    [
	bbList := bbList select: [ :each |
	    each succ size >= 2 or: [
		each succ notNil and: [
		    (each succ at: 1) value id <= each id ] ]
	].

	bbList isEmpty
    ] whileFalse: [
	bbList do: [ :each | each simplify ].
    ]!

!STDecompiler class methodsFor: 'test'!

testRepeat
    "A meaningless method to test #repeat simplification"
    | c |
    c := 'c'.
    [ c * 2.
      true ifTrue: [ c * c ].
      2 * c ] repeat!

testIfTrue
    "A meaningless method to test #ifTrue: simplification"
    | a b c |
    a := 'a'.
    b := 'b'.
    c := 'c'.
    a = b ifTrue: [ c * c ]!

testWhile
    "A meaningless method to test #whileTrue: simplification"
    | a b c |
    a := 'a'.
    b := 'b'.
    c := 'c'.
    [ b = 1. 1 = b ] whileFalse: [ c * 1. 1 * c ].
    [ b = 2. 2 = b ] whileTrue: [ c * 2. 2 * c ]!

testToByDo
    "A meaningless method to test #to:by:do: simplification"
    | a b c |
    a := 'a'.
    b := 'b'.
    c := 'c'.
    a to: b by: 3 do: [ :i | a = b. c = i ]!

test
    "Do some tests"

    (self decompile: #testToByDo in: STDecompiler class) displayNl.
    '' displayNl.

    (self decompile: #testWhile in: STDecompiler class) displayNl.
    '' displayNl.

    (self decompile: #testIfTrue in: STDecompiler class) displayNl.
    '' displayNl.

    (self decompile: #testRepeat in: STDecompiler class) displayNl.
    '' displayNl.

    (self decompile: #path in: VariableBinding) displayNl.
    '' displayNl.

    (self decompile: #bindWith: in: CharacterArray) displayNl.
    '' displayNl.

    (self decompile: #detect: in: Collection) displayNl.
    '' displayNl.

    (self decompile: #key:value:environment: in: VariableBinding class) displayNl.
    '' displayNl.

    (self decompile: #storeOn: in: VariableBinding) displayNl.
    '' displayNl.

    (self decompile: #contents in: MappedCollection) displayNl.
    '' displayNl.

    (self decompile: #collect: in: MappedCollection) displayNl.
    '' displayNl.

    (self decompile: #repeat in: BlockClosure) displayNl.
    '' displayNl.

    (self decompile: #binaryRepresentationObject in: Object) displayNl.
    '' displayNl.

    (self decompile: #whileTrue: in: BlockClosure) displayNl.
    '' displayNl.

    (self decompile: #become: in: Object) displayNl.
    '' displayNl.

    (self decompile: #timesRepeat: in: Integer) displayNl! !