/
AstTranslator.java
4806 lines (3994 loc) · 151 KB
/
AstTranslator.java
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
/******************************************************************************
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*****************************************************************************/
package com.ibm.wala.cast.ir.translator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.ibm.wala.cast.ir.ssa.AssignInstruction;
import com.ibm.wala.cast.ir.ssa.AstAssertInstruction;
import com.ibm.wala.cast.ir.ssa.AstEchoInstruction;
import com.ibm.wala.cast.ir.ssa.AstGlobalRead;
import com.ibm.wala.cast.ir.ssa.AstGlobalWrite;
import com.ibm.wala.cast.ir.ssa.AstIsDefinedInstruction;
import com.ibm.wala.cast.ir.ssa.AstLexicalAccess.Access;
import com.ibm.wala.cast.ir.ssa.AstLexicalRead;
import com.ibm.wala.cast.ir.ssa.AstLexicalWrite;
import com.ibm.wala.cast.ir.ssa.CAstBinaryOp;
import com.ibm.wala.cast.ir.ssa.CAstUnaryOp;
import com.ibm.wala.cast.ir.ssa.EachElementGetInstruction;
import com.ibm.wala.cast.ir.ssa.EachElementHasNextInstruction;
import com.ibm.wala.cast.ir.ssa.SSAConversion;
import com.ibm.wala.cast.loader.AstMethod;
import com.ibm.wala.cast.loader.AstMethod.DebuggingInformation;
import com.ibm.wala.cast.loader.AstMethod.LexicalInformation;
import com.ibm.wala.cast.loader.CAstAbstractLoader;
import com.ibm.wala.cast.tree.CAstControlFlowMap;
import com.ibm.wala.cast.tree.CAstEntity;
import com.ibm.wala.cast.tree.CAstNode;
import com.ibm.wala.cast.tree.CAstSourcePositionMap;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import com.ibm.wala.cast.tree.CAstSymbol;
import com.ibm.wala.cast.tree.CAstType;
import com.ibm.wala.cast.tree.impl.CAstImpl;
import com.ibm.wala.cast.tree.impl.CAstOperator;
import com.ibm.wala.cast.tree.impl.CAstSymbolImpl;
import com.ibm.wala.cast.tree.impl.CAstSymbolImplBase;
import com.ibm.wala.cast.tree.rewrite.CAstCloner;
import com.ibm.wala.cast.tree.rewrite.CAstRewriter;
import com.ibm.wala.cast.tree.visit.CAstVisitor;
import com.ibm.wala.cast.types.AstTypeReference;
import com.ibm.wala.cast.util.CAstPrinter;
import com.ibm.wala.cfg.AbstractCFG;
import com.ibm.wala.cfg.IBasicBlock;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClassLoader;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.ModuleEntry;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.shrikeBT.BinaryOpInstruction;
import com.ibm.wala.shrikeBT.ConditionalBranchInstruction;
import com.ibm.wala.shrikeBT.IBinaryOpInstruction;
import com.ibm.wala.shrikeBT.IConditionalBranchInstruction;
import com.ibm.wala.shrikeBT.IUnaryOpInstruction;
import com.ibm.wala.shrikeBT.ShiftInstruction;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SSAConditionalBranchInstruction;
import com.ibm.wala.ssa.SSAGetCaughtExceptionInstruction;
import com.ibm.wala.ssa.SSAGotoInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.ssa.SSAMonitorInstruction;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.TypeName;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.MapUtil;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.graph.INodeWithNumber;
import com.ibm.wala.util.graph.impl.SparseNumberedGraph;
import com.ibm.wala.util.graph.traverse.DFS;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.IntSetUtil;
import com.ibm.wala.util.intset.MutableIntSet;
import com.ibm.wala.util.strings.Atom;
import com.ibm.wala.util.warnings.Warning;
/**
* Common code to translate CAst to IR. Must be specialized by each language to
* handle semantics appropriately.
*/
public abstract class AstTranslator extends CAstVisitor<AstTranslator.WalkContext> implements ArrayOpHandler, TranslatorToIR {
/**
* does the language care about using type-appropriate default values? For
* Java, the answer is yes (ints should get a default value of 0, null for
* pointers, etc.). For JavaScript, the answer is no, as any variable can hold
* the value 'undefined'.
*/
protected abstract boolean useDefaultInitValues();
/**
* can lexical reads / writes access globals?
*/
protected abstract boolean treatGlobalsAsLexicallyScoped();
protected boolean topLevelFunctionsInGlobalScope() {
return true;
}
/**
* for a block that catches all exceptions, what is the root exception type
* that it can catch? E.g., for Java, java.lang.Throwable
*/
protected abstract TypeReference defaultCatchType();
protected abstract TypeReference makeType(CAstType type);
/**
* define a new (presumably nested) type. return true if type was successfully
* defined, false otherwise
*/
protected abstract boolean defineType(CAstEntity type, WalkContext wc);
/**
* declare a new function, represented by N
*/
protected abstract void declareFunction(CAstEntity N, WalkContext context);
/**
* fully define a function. invoked after all the code of the function has
* been processed
*/
protected abstract void defineFunction(CAstEntity N, WalkContext definingContext, AbstractCFG cfg, SymbolTable symtab,
boolean hasCatchBlock, Map<IBasicBlock, TypeReference[]> catchTypes, boolean hasMonitorOp, AstLexicalInformation lexicalInfo,
DebuggingInformation debugInfo);
/**
* define a new field fieldEntity within topEntity
*/
protected abstract void defineField(CAstEntity topEntity, WalkContext context, CAstEntity fieldEntity);
/**
* create the language-appropriate name for f
*/
protected abstract String composeEntityName(WalkContext parent, CAstEntity f);
/**
* generate IR for a CAst throw expression, updating context.cfg()
*/
protected abstract void doThrow(WalkContext context, int exception);
/**
* generate IR for a CAst array read, updating context.cfg()
*/
@Override
public abstract void doArrayRead(WalkContext context, int result, int arrayValue, CAstNode arrayRef, int[] dimValues);
/**
* generate IR for a CAst array write, updating context.cfg()
*/
@Override
public abstract void doArrayWrite(WalkContext context, int arrayValue, CAstNode arrayRef, int[] dimValues, int rval);
/**
* generate IR for a CAst field read, updating context.cfg()
*/
protected abstract void doFieldRead(WalkContext context, int result, int receiver, CAstNode elt, CAstNode parent);
/**
* generate IR for a CAst field write, updating context.cfg()
*/
protected abstract void doFieldWrite(WalkContext context, int receiver, CAstNode elt, CAstNode parent, int rval);
/**
* generate IR for a CAst function expression, updating context.cfg()
*/
protected abstract void doMaterializeFunction(CAstNode node, WalkContext context, int result, int exception, CAstEntity fn);
/**
* generate IR for a CAst new expression, updating context.cfg()
*/
protected abstract void doNewObject(WalkContext context, CAstNode newNode, int result, Object type, int[] arguments);
/**
* generate IR for a CAst method call expression, updating context.cfg()
*/
protected abstract void doCall(WalkContext context, CAstNode call, int result, int exception, CAstNode name, int receiver,
int[] arguments);
/**
* the most-general type for the language being translated
*/
protected abstract CAstType topType();
/**
* the most-general exception type for the language being translated
*/
protected abstract CAstType exceptionType();
/**
* used to generate instructions for array operations; defaults to this
*/
private ArrayOpHandler arrayOpHandler;
protected boolean isExceptionLabel(Object label) {
if (label == null)
return false;
if (label instanceof Boolean)
return false;
if (label instanceof Number)
return false;
if (label == CAstControlFlowMap.SWITCH_DEFAULT)
return false;
return true;
}
/**
* If this returns true, new global declarations get created for any attempt
* to access a non-existent variable (believe it or not, JavaScript actually
* does this!)
*/
protected boolean hasImplicitGlobals() {
return false;
}
/**
* If this returns true, then attempts to lookup non-existent names return
* `null' rather than tripping an assertion. This can be used when special
* handling is needed for built-in names. (PHP does this)
*/
protected boolean hasSpecialUndeclaredVariables() {
return false;
}
/**
* some languages let you omit initialization of certain fields when writing
* an object literal (e.g., PHP). This method should be overridden to handle
* such cases.
*/
protected void handleUnspecifiedLiteralKey(WalkContext context, CAstNode objectLiteralNode, int unspecifiedLiteralIndex,
CAstVisitor<WalkContext> visitor) {
Assertions.UNREACHABLE();
}
/**
* generate prologue code for each function body
*/
protected void doPrologue(WalkContext context) {
// perform a lexical write to copy the value stored in the local
// associated with each parameter to the lexical name
final CAstEntity entity = context.top();
Set<String> exposedNames = entity2ExposedNames.get(entity);
if (exposedNames != null) {
int i = 0;
for (String arg : entity.getArgumentNames()) {
if (exposedNames.contains(arg)) {
final Scope currentScope = context.currentScope();
Symbol symbol = currentScope.lookup(arg);
assert symbol.getDefiningScope() == currentScope;
int argVN = symbol.valueNumber();
CAstType type = (entity.getType() instanceof CAstType.Method)?
(CAstType)((CAstType.Method)entity.getType()).getArgumentTypes().get(i):
topType();
Access A = new Access(arg, context.getEntityName(entity), makeType(type), argVN);
context.cfg().addInstruction(new AstLexicalWrite(context.cfg().currentInstruction, A));
}
}
}
}
/**
* generate IR for call modeling creation of primitive value, updating
* context.cfg()
*/
protected abstract void doPrimitive(int resultVal, WalkContext context, CAstNode primitiveCall);
/**
* get the value number for a name defined locally (i.e., within the current
* method) by looking up the name in context.currentScope(). Note that the
* caller is responsible for ensuring that name is defined in the local scope.
*/
protected int doLocalRead(WalkContext context, String name, TypeReference type) {
CAstEntity entity = context.top();
Set<String> exposed = entity2ExposedNames.get(entity);
if (exposed != null && exposed.contains(name)) {
return doLexReadHelper(context, name, type);
}
return context.currentScope().lookup(name).valueNumber();
}
/**
* add an {@link AssignInstruction} to context.cfg() that copies rval to the
* value number of local nm. Note that the caller is responsible for ensuring
* that nm is defined in the local scope.
*/
protected void doLocalWrite(WalkContext context, String nm, TypeReference type, int rval) {
CAstEntity entity = context.top();
Set<String> exposed = entity2ExposedNames.get(entity);
if (exposed != null && exposed.contains(nm)) {
// use a lexical write
doLexicallyScopedWrite(context, nm, type, rval);
return;
}
int lval = context.currentScope().lookup(nm).valueNumber();
if (lval != rval) {
context.cfg().addInstruction(new AssignInstruction(context.cfg().currentInstruction, lval, rval));
}
}
/**
* Note that the caller is responsible for ensuring that name is defined in a
* lexical scope.
*
* @param node
* the AST node representing the read
* @param context
* @param name
* @return
*/
protected int doLexicallyScopedRead(CAstNode node, WalkContext context, final String name, TypeReference type) {
return doLexReadHelper(context, name, type);
}
/**
* @param name A variable name
* @return is this name safe to overwrite, i.e. it's synthetic from the translator?
*/
protected boolean ignoreName(String name) {
return false;
}
/**
* we only have this method to avoid having to pass a node parameter at other
* call sites, as would be required for
* {@link #doLexicallyScopedRead(CAstNode, WalkContext, String)}
*/
private int doLexReadHelper(WalkContext context, final String name, TypeReference type) {
Symbol S = context.currentScope().lookup(name);
Scope definingScope = S.getDefiningScope();
CAstEntity E = definingScope.getEntity();
// record in declaring scope that the name is exposed to a nested scope
addExposedName(E, E, name, definingScope.lookup(name).valueNumber(), false, context);
final String entityName = context.getEntityName(E);
int result = context.currentScope().allocateTempValue();
Access A = new Access(name, entityName, type, result);
context.cfg().addInstruction(new AstLexicalRead(context.cfg().currentInstruction, A));
markExposedInEnclosingEntities(context, name, definingScope, type, E, entityName, false);
return result;
}
/**
* record name as exposed for the current entity and for all enclosing
* entities up to that of the defining scope, since if the name is updated via
* a call to a nested function, SSA for these entities may need to be updated
* with the new definition
*
* @param context
* @param name
* @param definingScope
* @param E
* @param entityName
* @param isWrite
*/
private void markExposedInEnclosingEntities(WalkContext context, final String name, Scope definingScope, TypeReference type, CAstEntity E,
final String entityName, boolean isWrite) {
Scope curScope = context.currentScope();
while (!curScope.equals(definingScope)) {
final Symbol curSymbol = curScope.lookup(name);
final int vn = curSymbol.valueNumber();
final Access A = new Access(name, entityName, type, vn);
final CAstEntity entity = curScope.getEntity();
if (entity != definingScope.getEntity()) {
addExposedName(entity, E, name, vn, isWrite, context);
// record the access; later, the Accesses in the instruction
// defining vn will be adjusted based on this information; see
// patchLexicalAccesses()
addAccess(context, entity, A);
}
curScope = curScope.getParent();
}
}
/**
* Note that the caller is responsible for ensuring that name is defined in a
* lexical scope.
*
*/
protected void doLexicallyScopedWrite(WalkContext context, String name, TypeReference type, int rval) {
Symbol S = context.currentScope().lookup(name);
Scope definingScope = S.getDefiningScope();
CAstEntity E = definingScope.getEntity();
// record in declaring scope that the name is exposed to a nested scope
addExposedName(E, E, name, definingScope.lookup(name).valueNumber(), true, context);
// lexically-scoped variables must be written in their scope each time
Access A = new Access(name, context.getEntityName(E), type, rval);
context.cfg().addInstruction(new AstLexicalWrite(context.cfg().currentInstruction, A));
markExposedInEnclosingEntities(context, name, definingScope, type, E, context.getEntityName(E), true);
}
/**
* generate instructions for a read of a global
*/
protected int doGlobalRead(CAstNode node, WalkContext context, String name, TypeReference type) {
// Global variables can be treated as lexicals defined in the CG root, or
if (treatGlobalsAsLexicallyScoped()) {
int result = context.currentScope().allocateTempValue();
Access A = new Access(name, null, type, result);
context.cfg().addInstruction(new AstLexicalRead(context.cfg().currentInstruction, A));
addAccess(context, context.top(), A);
return result;
// globals can be treated as a single static location
} else {
int result = context.currentScope().allocateTempValue();
FieldReference global = makeGlobalRef(name);
context.cfg().addInstruction(new AstGlobalRead(context.cfg().currentInstruction, result, global));
return result;
}
}
/**
* generate instructions for a write of a global
*/
protected void doGlobalWrite(WalkContext context, String name, TypeReference type, int rval) {
// Global variables can be treated as lexicals defined in the CG root, or
if (treatGlobalsAsLexicallyScoped()) {
Access A = new Access(name, null, type, rval);
context.cfg().addInstruction(new AstLexicalWrite(context.cfg().currentInstruction, A));
addAccess(context, context.top(), A);
// globals can be treated as a single static location
} else {
FieldReference global = makeGlobalRef(name);
context.cfg().addInstruction(new AstGlobalWrite(context.cfg().currentInstruction, global, rval));
}
}
/**
* generate instructions to check if ref has field, storing answer in result
*/
protected void doIsFieldDefined(WalkContext context, int result, int ref, CAstNode field) {
Assertions.UNREACHABLE();
}
/**
* creates a reference to a global named globalName. the declaring type and
* type of the global are both the root type.
*/
protected FieldReference makeGlobalRef(String globalName) {
TypeReference rootTypeRef = TypeReference.findOrCreate(loader.getReference(), AstTypeReference.rootTypeName);
return FieldReference.findOrCreate(rootTypeRef, Atom.findOrCreateUnicodeAtom("global " + globalName), rootTypeRef);
}
protected final IClassLoader loader;
/**
* for handling languages that let you include other source files named
* statically (e.g., ABAP)
*/
protected final Map namedEntityResolver;
protected final SSAInstructionFactory insts;
protected AstTranslator(IClassLoader loader, Map namedEntityResolver, ArrayOpHandler arrayOpHandler) {
this.loader = loader;
this.namedEntityResolver = namedEntityResolver;
this.arrayOpHandler = arrayOpHandler!=null? arrayOpHandler: this;
this.insts = loader.getInstructionFactory();
}
protected AstTranslator(IClassLoader loader, Map namedEntityResolver) {
this(loader, namedEntityResolver, null);
}
protected AstTranslator(IClassLoader loader) {
this(loader, null);
}
/**
* for keeping position information for the generated SSAInstructions and SSA
* locals
*/
private static class AstDebuggingInformation implements DebuggingInformation {
private Position codeBodyPosition;
private String[][] valueNumberNames;
private Position[] instructionPositions;
AstDebuggingInformation(Position codeBodyPosition, Position[] instructionPositions, String[] names) {
this.codeBodyPosition = codeBodyPosition;
this.instructionPositions = instructionPositions;
valueNumberNames = new String[names.length][];
for (int i = 0; i < names.length; i++) {
if (names[i] != null) {
valueNumberNames[i] = new String[] { names[i] };
} else {
valueNumberNames[i] = new String[0];
}
}
}
@Override
public Position getCodeBodyPosition() {
return codeBodyPosition;
}
@Override
public Position getInstructionPosition(int instructionOffset) {
return instructionPositions[instructionOffset];
}
@Override
public String[][] getSourceNamesForValues() {
return valueNumberNames;
}
}
public static final boolean DEBUG_ALL = false;
public static final boolean DEBUG_TOP = DEBUG_ALL || false;
public static final boolean DEBUG_CFG = DEBUG_ALL || false;
public static final boolean DEBUG_NAMES = DEBUG_ALL || false;
public static final boolean DEBUG_LEXICAL = DEBUG_ALL || false;
/**
* basic block implementation used in the CFGs constructed during the
* IR-generating AST traversal
*/
protected final static class PreBasicBlock implements INodeWithNumber, IBasicBlock<SSAInstruction> {
private static final int NORMAL = 0;
private static final int HANDLER = 1;
private static final int ENTRY = 2;
private static final int EXIT = 3;
private int kind = NORMAL;
private int number = -1;
private int firstIndex = -1;
private int lastIndex = -2;
private final List<SSAInstruction> instructions = new ArrayList<SSAInstruction>();
@Override
public int getNumber() {
return getGraphNodeId();
}
@Override
public int getGraphNodeId() {
return number;
}
@Override
public void setGraphNodeId(int number) {
this.number = number;
}
@Override
public int getFirstInstructionIndex() {
return firstIndex;
}
void setFirstIndex(int firstIndex) {
this.firstIndex = firstIndex;
}
@Override
public int getLastInstructionIndex() {
return lastIndex;
}
void setLastIndex(int lastIndex) {
this.lastIndex = lastIndex;
}
void makeExitBlock() {
kind = EXIT;
}
void makeEntryBlock() {
kind = ENTRY;
}
void makeHandlerBlock() {
kind = HANDLER;
}
@Override
public boolean isEntryBlock() {
return kind == ENTRY;
}
@Override
public boolean isExitBlock() {
return kind == EXIT;
}
public boolean isHandlerBlock() {
return kind == HANDLER;
}
@Override
public String toString() {
return "PreBB" + number + ":" + firstIndex + ".." + lastIndex;
}
private List<SSAInstruction> instructions() {
return instructions;
}
@Override
public boolean isCatchBlock() {
return (lastIndex > -1) && (instructions.get(0) instanceof SSAGetCaughtExceptionInstruction);
}
@Override
public IMethod getMethod() {
return null;
}
@Override
public Iterator<SSAInstruction> iterator() {
return instructions.iterator();
}
}
protected final class UnwindState {
final CAstNode unwindAst;
final WalkContext astContext;
final CAstVisitor<WalkContext> astVisitor;
UnwindState(CAstNode unwindAst, WalkContext astContext, CAstVisitor<WalkContext> astVisitor) {
this.unwindAst = unwindAst;
this.astContext = astContext;
this.astVisitor = astVisitor;
}
public UnwindState getParent() {
return astContext.getUnwindState();
}
@Override
public int hashCode() {
return astContext.hashCode() * unwindAst.hashCode() * astVisitor.hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof UnwindState) {
if (((UnwindState) o).unwindAst != unwindAst)
return false;
if (((UnwindState) o).astVisitor != astVisitor)
return false;
if (getParent() == null) {
return ((UnwindState) o).getParent() == null;
} else {
return getParent().equals(((UnwindState) o).getParent());
}
}
return false;
}
boolean covers(UnwindState other) {
if (equals(other))
return true;
if (getParent() != null)
return getParent().covers(other);
return false;
}
}
/**
* holds the control-flow graph as it is being constructed. When construction
* is complete, information is stored in an {@link AstCFG}
*/
@SuppressWarnings("javadoc")
public final class IncipientCFG extends SparseNumberedGraph<PreBasicBlock> {
protected class Unwind {
private final Map<PreBasicBlock, UnwindState> unwindData = new LinkedHashMap<PreBasicBlock, UnwindState>();
/**
* a cache of generated blocks
*/
private final Map<Pair<UnwindState, Pair<PreBasicBlock, Boolean>>, PreBasicBlock> code = new LinkedHashMap<Pair<UnwindState, Pair<PreBasicBlock, Boolean>>, PreBasicBlock>();
void setUnwindState(PreBasicBlock block, UnwindState context) {
unwindData.put(block, context);
}
void setUnwindState(CAstNode node, UnwindState context) {
unwindData.put(nodeToBlock.get(node), context);
}
/**
* When adding an edge from source to target, it is possible that certain
* exception-handling code needs to be executed before the control is
* actually transfered to target. This method determines if this is the
* case, and if so, it generates the exception handler blocks and adds an
* appropriate edge to the target. It returns the basic block that should
* be the target of the edge from source (target itself if there is no
* exception-handling code, the initial catch block otherwise)
*/
public PreBasicBlock findOrCreateCode(PreBasicBlock source, PreBasicBlock target, final boolean exception) {
UnwindState sourceContext = unwindData.get(source);
final CAstNode dummy = exception ? (new CAstImpl()).makeNode(CAstNode.EMPTY) : null;
// no unwinding is needed, so jump to target block directly
if (sourceContext == null)
return target;
WalkContext astContext = sourceContext.astContext;
UnwindState targetContext = null;
if (target != null)
targetContext = unwindData.get(target);
// in unwind context, but catch in same (or inner) unwind context
if (targetContext != null && targetContext.covers(sourceContext))
return target;
Pair<UnwindState, Pair<PreBasicBlock, Boolean>> key = Pair.make(sourceContext, Pair.make(target, exception));
if (code.containsKey(key)) {
return code.get(key);
} else {
int e = -1;
PreBasicBlock currentBlock = getCurrentBlock();
if (!isDeadBlock(currentBlock)) {
addInstruction(insts.GotoInstruction(currentInstruction, -1));
newBlock(false);
}
PreBasicBlock startBlock = getCurrentBlock();
if (exception) {
setCurrentBlockAsHandler();
e = sourceContext.astContext.currentScope().allocateTempValue();
addInstruction(insts.GetCaughtExceptionInstruction(currentInstruction, startBlock.getNumber(), e));
sourceContext.astContext.setCatchType(startBlock, defaultCatchType());
}
while (sourceContext != null && (targetContext == null || !targetContext.covers(sourceContext))) {
final CAstRewriter.Rewrite ast = (new CAstCloner(new CAstImpl()) {
@Override
protected CAstNode flowOutTo(Map<Pair<CAstNode, NoKey>, CAstNode> nodeMap, CAstNode oldSource, Object label,
CAstNode oldTarget, CAstControlFlowMap orig, CAstSourcePositionMap src) {
if (exception && !isExceptionLabel(label)) {
return dummy;
} else {
return oldTarget;
}
}
}).copy(sourceContext.unwindAst, sourceContext.astContext.getControlFlow(), sourceContext.astContext.getSourceMap(),
sourceContext.astContext.top().getNodeTypeMap(), sourceContext.astContext.top().getAllScopedEntities());
sourceContext.astVisitor.visit(ast.newRoot(), new DelegatingContext(sourceContext.astContext) {
@Override
public CAstSourcePositionMap getSourceMap() {
return ast.newPos();
}
@Override
public CAstControlFlowMap getControlFlow() {
return ast.newCfg();
}
}, sourceContext.astVisitor);
sourceContext = sourceContext.getParent();
}
PreBasicBlock endBlock = getCurrentBlock();
if (exception) {
addPreNode(dummy);
doThrow(astContext, e);
} else {
addInstruction(insts.GotoInstruction(currentInstruction, -1));
}
newBlock(false);
addEdge(currentBlock, getCurrentBlock());
if (target != null) {
addEdge(endBlock, target);
// `null' target is idiom for branch/throw to exit
} else {
addDelayedEdge(endBlock, exitMarker, exception);
}
code.put(key, startBlock);
return startBlock;
}
}
}
private Unwind unwind = null;
private final List<PreBasicBlock> blocks = new ArrayList<PreBasicBlock>();
private PreBasicBlock entryBlock;
private final Map<CAstNode, PreBasicBlock> nodeToBlock = new LinkedHashMap<CAstNode, PreBasicBlock>();
private final Map<Object, Set<Pair<PreBasicBlock, Boolean>>> delayedEdges = new LinkedHashMap<Object, Set<Pair<PreBasicBlock, Boolean>>>();
private final Object exitMarker = new Object();
private final Set<PreBasicBlock> deadBlocks = new LinkedHashSet<PreBasicBlock>();
private final Set<PreBasicBlock> normalToExit = new LinkedHashSet<PreBasicBlock>();
private final Set<PreBasicBlock> exceptionalToExit = new LinkedHashSet<PreBasicBlock>();
private Position[] linePositions = new Position[10];
private boolean hasCatchBlock = false;
/**
* does the method have any monitor operations?
*/
private boolean hasMonitorOp = false;
private int currentInstruction = 0;
private PreBasicBlock currentBlock;
public int getCurrentInstruction() {
return currentInstruction;
}
public PreBasicBlock getCurrentBlock() {
return currentBlock;
}
boolean hasCatchBlock() {
return hasCatchBlock;
}
boolean hasMonitorOp() {
return hasMonitorOp;
}
void noteCatchBlock() {
hasCatchBlock = true;
}
Position[] getLinePositionMap() {
return linePositions;
}
/**
* create a new basic block, and set it as the current block.
*
* @param fallThruFromPrior
* should a fall-through edge be added from the previous block
* (value of currentBlock at entry)? if false, the newly created
* block is marked as a dead block, as it has no incoming edges.
* @return the new block
*/
public PreBasicBlock newBlock(boolean fallThruFromPrior) {
// optimization: if we have a fall-through from an empty block, just
// return the empty block
if (fallThruFromPrior && !currentBlock.isEntryBlock() && currentBlock.instructions().size() == 0) {
return currentBlock;
}
PreBasicBlock previous = currentBlock;
currentBlock = new PreBasicBlock();
addNode(currentBlock);
blocks.add(currentBlock);
if (DEBUG_CFG)
System.err.println(("adding new block (node) " + currentBlock));
if (fallThruFromPrior) {
if (DEBUG_CFG)
System.err.println(("adding fall-thru edge " + previous + " --> " + currentBlock));
addEdge(previous, currentBlock);
} else {
deadBlocks.add(currentBlock);
}
return currentBlock;
}
/**
* record a delayed edge addition from src to dst. Edge will be added when
* appropriate; see {@link #checkForRealizedEdges(CAstNode)} and
* {@link #checkForRealizedExitEdges(PreBasicBlock)}
*/
private void addDelayedEdge(PreBasicBlock src, Object dst, boolean exception) {
MapUtil.findOrCreateSet(delayedEdges, dst).add(Pair.make(src, exception));
}
void makeEntryBlock(PreBasicBlock bb) {
entryBlock = bb;
bb.makeEntryBlock();
}
void makeExitBlock(PreBasicBlock bb) {
bb.makeExitBlock();
for (Iterator<? extends PreBasicBlock> ps = getPredNodes(bb); ps.hasNext();)
normalToExit.add(ps.next());
// now that we have created the exit block, add the delayed edges to the
// exit
checkForRealizedExitEdges(bb);
}
void setCurrentBlockAsHandler() {
currentBlock.makeHandlerBlock();
}
boolean hasDelayedEdges(CAstNode n) {
return delayedEdges.containsKey(n);
}
/**
* given some n which is now mapped by nodeToBlock, add any delayed edges to
* n's block
*/
private void checkForRealizedEdges(CAstNode n) {
if (delayedEdges.containsKey(n)) {
for (Iterator<Pair<PreBasicBlock, Boolean>> ss = delayedEdges.get(n).iterator(); ss.hasNext();) {
Pair<PreBasicBlock, Boolean> s = ss.next();
PreBasicBlock src = s.fst;
boolean exception = s.snd;
if (unwind == null) {
addEdge(src, nodeToBlock.get(n));
} else {
PreBasicBlock target = nodeToBlock.get(n);
addEdge(src, unwind.findOrCreateCode(src, target, exception));
}
}
delayedEdges.remove(n);
}
}
/**
* add any delayed edges to the exit block
*/
private void checkForRealizedExitEdges(PreBasicBlock exitBlock) {
if (delayedEdges.containsKey(exitMarker)) {
for (Iterator<Pair<PreBasicBlock, Boolean>> ss = delayedEdges.get(exitMarker).iterator(); ss.hasNext();) {
Pair<PreBasicBlock, Boolean> s = ss.next();
PreBasicBlock src = s.fst;
boolean exception = s.snd;
addEdge(src, exitBlock);
if (exception)
exceptionalToExit.add(src);
else
normalToExit.add(src);
}
delayedEdges.remove(exitMarker);
}
}
private void setUnwindState(CAstNode node, UnwindState context) {
if (unwind == null)
unwind = new Unwind();
unwind.setUnwindState(node, context);
}
public void addPreNode(CAstNode n) {
addPreNode(n, null);
}
/**
* associate n with the current block, and update the current unwind state
*/
public void addPreNode(CAstNode n, UnwindState context) {
if (DEBUG_CFG)
System.err.println(("adding pre-node " + n));
nodeToBlock.put(n, currentBlock);