forked from typetools/checker-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CFGBuilder.java
4914 lines (4277 loc) · 208 KB
/
CFGBuilder.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
package org.checkerframework.dataflow.cfg;
import com.sun.source.tree.AnnotatedTypeTree;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ArrayAccessTree;
import com.sun.source.tree.ArrayTypeTree;
import com.sun.source.tree.AssertTree;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.BreakTree;
import com.sun.source.tree.CaseTree;
import com.sun.source.tree.CatchTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.CompoundAssignmentTree;
import com.sun.source.tree.ConditionalExpressionTree;
import com.sun.source.tree.ContinueTree;
import com.sun.source.tree.DoWhileLoopTree;
import com.sun.source.tree.EmptyStatementTree;
import com.sun.source.tree.EnhancedForLoopTree;
import com.sun.source.tree.ErroneousTree;
import com.sun.source.tree.ExpressionStatementTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.ForLoopTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.IfTree;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.InstanceOfTree;
import com.sun.source.tree.LabeledStatementTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.LiteralTree;
import com.sun.source.tree.MemberReferenceTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.ModifiersTree;
import com.sun.source.tree.NewArrayTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.ParameterizedTypeTree;
import com.sun.source.tree.ParenthesizedTree;
import com.sun.source.tree.PrimitiveTypeTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.SwitchTree;
import com.sun.source.tree.SynchronizedTree;
import com.sun.source.tree.ThrowTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.TryTree;
import com.sun.source.tree.TypeCastTree;
import com.sun.source.tree.TypeParameterTree;
import com.sun.source.tree.UnaryTree;
import com.sun.source.tree.UnionTypeTree;
import com.sun.source.tree.VariableTree;
import com.sun.source.tree.WhileLoopTree;
import com.sun.source.tree.WildcardTree;
import com.sun.source.util.TreePath;
import com.sun.source.util.TreePathScanner;
import com.sun.source.util.Trees;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.processing.JavacProcessingEnvironment;
import com.sun.tools.javac.util.Context;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.PrimitiveType;
import javax.lang.model.type.ReferenceType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
import javax.lang.model.type.UnionType;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.dataflow.analysis.Store;
import org.checkerframework.dataflow.cfg.CFGBuilder.ExtendedNode.ExtendedNodeType;
import org.checkerframework.dataflow.cfg.UnderlyingAST.CFGMethod;
import org.checkerframework.dataflow.cfg.block.Block;
import org.checkerframework.dataflow.cfg.block.Block.BlockType;
import org.checkerframework.dataflow.cfg.block.BlockImpl;
import org.checkerframework.dataflow.cfg.block.ConditionalBlockImpl;
import org.checkerframework.dataflow.cfg.block.ExceptionBlockImpl;
import org.checkerframework.dataflow.cfg.block.RegularBlockImpl;
import org.checkerframework.dataflow.cfg.block.SingleSuccessorBlockImpl;
import org.checkerframework.dataflow.cfg.block.SpecialBlock.SpecialBlockType;
import org.checkerframework.dataflow.cfg.block.SpecialBlockImpl;
import org.checkerframework.dataflow.cfg.node.ArrayAccessNode;
import org.checkerframework.dataflow.cfg.node.ArrayCreationNode;
import org.checkerframework.dataflow.cfg.node.ArrayTypeNode;
import org.checkerframework.dataflow.cfg.node.AssertionErrorNode;
import org.checkerframework.dataflow.cfg.node.AssignmentNode;
import org.checkerframework.dataflow.cfg.node.BitwiseAndNode;
import org.checkerframework.dataflow.cfg.node.BitwiseComplementNode;
import org.checkerframework.dataflow.cfg.node.BitwiseOrNode;
import org.checkerframework.dataflow.cfg.node.BitwiseXorNode;
import org.checkerframework.dataflow.cfg.node.BooleanLiteralNode;
import org.checkerframework.dataflow.cfg.node.CaseNode;
import org.checkerframework.dataflow.cfg.node.CharacterLiteralNode;
import org.checkerframework.dataflow.cfg.node.ClassDeclarationNode;
import org.checkerframework.dataflow.cfg.node.ClassNameNode;
import org.checkerframework.dataflow.cfg.node.ConditionalAndNode;
import org.checkerframework.dataflow.cfg.node.ConditionalNotNode;
import org.checkerframework.dataflow.cfg.node.ConditionalOrNode;
import org.checkerframework.dataflow.cfg.node.DoubleLiteralNode;
import org.checkerframework.dataflow.cfg.node.EqualToNode;
import org.checkerframework.dataflow.cfg.node.ExplicitThisLiteralNode;
import org.checkerframework.dataflow.cfg.node.FieldAccessNode;
import org.checkerframework.dataflow.cfg.node.FloatLiteralNode;
import org.checkerframework.dataflow.cfg.node.FloatingDivisionNode;
import org.checkerframework.dataflow.cfg.node.FloatingRemainderNode;
import org.checkerframework.dataflow.cfg.node.FunctionalInterfaceNode;
import org.checkerframework.dataflow.cfg.node.GreaterThanNode;
import org.checkerframework.dataflow.cfg.node.GreaterThanOrEqualNode;
import org.checkerframework.dataflow.cfg.node.ImplicitThisLiteralNode;
import org.checkerframework.dataflow.cfg.node.InstanceOfNode;
import org.checkerframework.dataflow.cfg.node.IntegerDivisionNode;
import org.checkerframework.dataflow.cfg.node.IntegerLiteralNode;
import org.checkerframework.dataflow.cfg.node.IntegerRemainderNode;
import org.checkerframework.dataflow.cfg.node.LambdaResultExpressionNode;
import org.checkerframework.dataflow.cfg.node.LeftShiftNode;
import org.checkerframework.dataflow.cfg.node.LessThanNode;
import org.checkerframework.dataflow.cfg.node.LessThanOrEqualNode;
import org.checkerframework.dataflow.cfg.node.LocalVariableNode;
import org.checkerframework.dataflow.cfg.node.LongLiteralNode;
import org.checkerframework.dataflow.cfg.node.MarkerNode;
import org.checkerframework.dataflow.cfg.node.MethodAccessNode;
import org.checkerframework.dataflow.cfg.node.MethodInvocationNode;
import org.checkerframework.dataflow.cfg.node.NarrowingConversionNode;
import org.checkerframework.dataflow.cfg.node.Node;
import org.checkerframework.dataflow.cfg.node.NotEqualNode;
import org.checkerframework.dataflow.cfg.node.NullChkNode;
import org.checkerframework.dataflow.cfg.node.NullLiteralNode;
import org.checkerframework.dataflow.cfg.node.NumericalAdditionNode;
import org.checkerframework.dataflow.cfg.node.NumericalMinusNode;
import org.checkerframework.dataflow.cfg.node.NumericalMultiplicationNode;
import org.checkerframework.dataflow.cfg.node.NumericalPlusNode;
import org.checkerframework.dataflow.cfg.node.NumericalSubtractionNode;
import org.checkerframework.dataflow.cfg.node.ObjectCreationNode;
import org.checkerframework.dataflow.cfg.node.PackageNameNode;
import org.checkerframework.dataflow.cfg.node.ParameterizedTypeNode;
import org.checkerframework.dataflow.cfg.node.PrimitiveTypeNode;
import org.checkerframework.dataflow.cfg.node.ReturnNode;
import org.checkerframework.dataflow.cfg.node.SignedRightShiftNode;
import org.checkerframework.dataflow.cfg.node.StringConcatenateAssignmentNode;
import org.checkerframework.dataflow.cfg.node.StringConcatenateNode;
import org.checkerframework.dataflow.cfg.node.StringConversionNode;
import org.checkerframework.dataflow.cfg.node.StringLiteralNode;
import org.checkerframework.dataflow.cfg.node.SuperNode;
import org.checkerframework.dataflow.cfg.node.SynchronizedNode;
import org.checkerframework.dataflow.cfg.node.TernaryExpressionNode;
import org.checkerframework.dataflow.cfg.node.ThisLiteralNode;
import org.checkerframework.dataflow.cfg.node.ThrowNode;
import org.checkerframework.dataflow.cfg.node.TypeCastNode;
import org.checkerframework.dataflow.cfg.node.UnsignedRightShiftNode;
import org.checkerframework.dataflow.cfg.node.ValueLiteralNode;
import org.checkerframework.dataflow.cfg.node.VariableDeclarationNode;
import org.checkerframework.dataflow.cfg.node.WideningConversionNode;
import org.checkerframework.dataflow.qual.TerminatesExecution;
import org.checkerframework.dataflow.util.IdentityMostlySingleton;
import org.checkerframework.dataflow.util.MostlySingleton;
import org.checkerframework.javacutil.AnnotationProvider;
import org.checkerframework.javacutil.BasicAnnotationProvider;
import org.checkerframework.javacutil.BugInCF;
import org.checkerframework.javacutil.ElementUtils;
import org.checkerframework.javacutil.Pair;
import org.checkerframework.javacutil.TreeUtils;
import org.checkerframework.javacutil.TypesUtils;
import org.checkerframework.javacutil.trees.TreeBuilder;
/**
* Builds the control flow graph of some Java code (either a method, or an arbitrary statement).
*
* <p>The translation of the AST to the CFG is split into three phases:
*
* <ol>
* <li><em>Phase one.</em> In the first phase, the AST is translated into a sequence of {@link
* org.checkerframework.dataflow.cfg.CFGBuilder.ExtendedNode}s. An extended node can either be
* a {@link Node}, or one of several meta elements such as a conditional or unconditional jump
* or a node with additional information about exceptions. Some of the extended nodes contain
* labels (e.g., for the jump target), and phase one additionally creates a mapping from
* labels to extended nodes. Finally, the list of leaders is computed: A leader is an extended
* node which will give rise to a basic block in phase two.
* <li><em>Phase two.</em> In this phase, the sequence of extended nodes is translated to a graph
* of control flow blocks that contain nodes. The meta elements from phase one are translated
* into the correct edges.
* <li><em>Phase three.</em> The control flow graph generated in phase two can contain degenerate
* basic blocks such as empty regular basic blocks or conditional basic blocks that have the
* same block as both 'then' and 'else' successor. This phase removes these cases while
* preserving the control flow structure.
* </ol>
*/
public class CFGBuilder {
protected CFGBuilder() {}
/** Build the control flow graph of some code. */
public static ControlFlowGraph build(
CompilationUnitTree root,
UnderlyingAST underlyingAST,
boolean assumeAssertionsEnabled,
boolean assumeAssertionsDisabled,
ProcessingEnvironment env) {
TreeBuilder builder = new TreeBuilder(env);
AnnotationProvider annotationProvider = new BasicAnnotationProvider();
PhaseOneResult phase1result =
new CFGTranslationPhaseOne(
builder,
annotationProvider,
assumeAssertionsEnabled,
assumeAssertionsDisabled,
env)
.process(root, underlyingAST);
ControlFlowGraph phase2result = CFGTranslationPhaseTwo.process(phase1result);
ControlFlowGraph phase3result = CFGTranslationPhaseThree.process(phase2result);
return phase3result;
}
/**
* Build the control flow graph of some code (method, initializer block, ...). bodyPath is the
* TreePath to the body of that code.
*/
public static ControlFlowGraph build(
TreePath bodyPath,
UnderlyingAST underlyingAST,
boolean assumeAssertionsEnabled,
boolean assumeAssertionsDisabled,
ProcessingEnvironment env) {
TreeBuilder builder = new TreeBuilder(env);
AnnotationProvider annotationProvider = new BasicAnnotationProvider();
PhaseOneResult phase1result =
new CFGTranslationPhaseOne(
builder,
annotationProvider,
assumeAssertionsEnabled,
assumeAssertionsDisabled,
env)
.process(bodyPath, underlyingAST);
ControlFlowGraph phase2result = CFGTranslationPhaseTwo.process(phase1result);
ControlFlowGraph phase3result = CFGTranslationPhaseThree.process(phase2result);
return phase3result;
}
/** Build the control flow graph of some code. */
public static ControlFlowGraph build(
CompilationUnitTree root, UnderlyingAST underlyingAST, ProcessingEnvironment env) {
return build(root, underlyingAST, false, false, env);
}
/** Build the control flow graph of a method. */
public static ControlFlowGraph build(
CompilationUnitTree root,
MethodTree tree,
@Nullable ClassTree classTree,
@Nullable ProcessingEnvironment env) {
UnderlyingAST underlyingAST = new CFGMethod(tree, classTree);
return build(root, underlyingAST, false, false, env);
}
/**
* An extended node can be one of several things (depending on its {@code type}):
*
* <ul>
* <li><em>NODE</em>. An extended node of this type is just a wrapper for a {@link Node} (that
* cannot throw exceptions).
* <li><em>EXCEPTION_NODE</em>. A wrapper for a {@link Node} which can throw exceptions. It
* contains a label for every possible exception type the node might throw.
* <li><em>UNCONDITIONAL_JUMP</em>. An unconditional jump to a label.
* <li><em>TWO_TARGET_CONDITIONAL_JUMP</em>. A conditional jump with two targets for both the
* 'then' and 'else' branch.
* </ul>
*/
protected abstract static class ExtendedNode {
/** The basic block this extended node belongs to (as determined in phase two). */
protected BlockImpl block;
/** Type of this node. */
protected ExtendedNodeType type;
/** Does this node terminate the execution? (e.g., "System.exit()") */
protected boolean terminatesExecution = false;
public ExtendedNode(ExtendedNodeType type) {
this.type = type;
}
/** Extended node types (description see above). */
public enum ExtendedNodeType {
NODE,
EXCEPTION_NODE,
UNCONDITIONAL_JUMP,
CONDITIONAL_JUMP
}
public ExtendedNodeType getType() {
return type;
}
public boolean getTerminatesExecution() {
return terminatesExecution;
}
public void setTerminatesExecution(boolean terminatesExecution) {
this.terminatesExecution = terminatesExecution;
}
/**
* @return the node contained in this extended node (only applicable if the type is {@code
* NODE} or {@code EXCEPTION_NODE}).
*/
public Node getNode() {
assert false;
return null;
}
/**
* @return the label associated with this extended node (only applicable if type is {@link
* ExtendedNodeType#CONDITIONAL_JUMP} or {@link ExtendedNodeType#UNCONDITIONAL_JUMP}).
*/
public Label getLabel() {
assert false;
return null;
}
public BlockImpl getBlock() {
return block;
}
public void setBlock(BlockImpl b) {
this.block = b;
}
@Override
public String toString() {
throw new BugInCF("DO NOT CALL ExtendedNode.toString(). Write your own.");
}
}
/** An extended node of type {@code NODE}. */
protected static class NodeHolder extends ExtendedNode {
protected Node node;
public NodeHolder(Node node) {
super(ExtendedNodeType.NODE);
this.node = node;
}
@Override
public Node getNode() {
return node;
}
@Override
public String toString() {
return "NodeHolder(" + node + ")";
}
}
/** An extended node of type {@code EXCEPTION_NODE}. */
protected static class NodeWithExceptionsHolder extends ExtendedNode {
protected Node node;
/**
* Map from exception type to labels of successors that may be reached as a result of that
* exception.
*/
protected Map<TypeMirror, Set<Label>> exceptions;
public NodeWithExceptionsHolder(Node node, Map<TypeMirror, Set<Label>> exceptions) {
super(ExtendedNodeType.EXCEPTION_NODE);
this.node = node;
this.exceptions = exceptions;
}
public Map<TypeMirror, Set<Label>> getExceptions() {
return exceptions;
}
@Override
public Node getNode() {
return node;
}
@Override
public String toString() {
return "NodeWithExceptionsHolder(" + node + ")";
}
}
/**
* An extended node of type {@link ExtendedNodeType#CONDITIONAL_JUMP}.
*
* <p><em>Important:</em> In the list of extended nodes, there should not be any labels that
* point to a conditional jump. Furthermore, the node directly ahead of any conditional jump has
* to be a {@link NodeWithExceptionsHolder} or {@link NodeHolder}, and the node held by that
* extended node is required to be of boolean type.
*/
protected static class ConditionalJump extends ExtendedNode {
protected Label trueSucc;
protected Label falseSucc;
protected Store.FlowRule trueFlowRule;
protected Store.FlowRule falseFlowRule;
public ConditionalJump(Label trueSucc, Label falseSucc) {
super(ExtendedNodeType.CONDITIONAL_JUMP);
assert trueSucc != null;
this.trueSucc = trueSucc;
assert falseSucc != null;
this.falseSucc = falseSucc;
}
public Label getThenLabel() {
return trueSucc;
}
public Label getElseLabel() {
return falseSucc;
}
public Store.FlowRule getTrueFlowRule() {
return trueFlowRule;
}
public Store.FlowRule getFalseFlowRule() {
return falseFlowRule;
}
public void setTrueFlowRule(Store.FlowRule rule) {
trueFlowRule = rule;
}
public void setFalseFlowRule(Store.FlowRule rule) {
falseFlowRule = rule;
}
@Override
public String toString() {
return "TwoTargetConditionalJump(" + getThenLabel() + "," + getElseLabel() + ")";
}
}
/** An extended node of type {@link ExtendedNodeType#UNCONDITIONAL_JUMP}. */
protected static class UnconditionalJump extends ExtendedNode {
protected Label jumpTarget;
public UnconditionalJump(Label jumpTarget) {
super(ExtendedNodeType.UNCONDITIONAL_JUMP);
assert jumpTarget != null;
this.jumpTarget = jumpTarget;
}
@Override
public Label getLabel() {
return jumpTarget;
}
@Override
public String toString() {
return "JumpMarker(" + getLabel() + ")";
}
}
/**
* A label is used to refer to other extended nodes using a mapping from labels to extended
* nodes. Labels get their names either from labeled statements in the source code or from
* internally generated unique names.
*/
protected static class Label {
private static int uid = 0;
protected final String name;
public Label(String name) {
this.name = name;
}
public Label() {
this.name = uniqueName();
}
@Override
public String toString() {
return name;
}
/**
* Return a new unique label name that cannot be confused with a Java source code label.
*
* @return a new unique label name
*/
private static String uniqueName() {
return "%L" + uid++;
}
}
/**
* A TryFrame takes a thrown exception type and maps it to a set of possible control-flow
* successors.
*/
protected static interface TryFrame {
/**
* Given a type of thrown exception, add the set of possible control flow successor {@link
* Label}s to the argument set. Return true if the exception is known to be caught by one of
* those labels and false if it may propagate still further.
*/
public boolean possibleLabels(TypeMirror thrown, Set<Label> labels);
}
/**
* A TryCatchFrame contains an ordered list of catch labels that apply to exceptions with
* specific types.
*/
protected static class TryCatchFrame implements TryFrame {
protected Types types;
/** An ordered list of pairs because catch blocks are ordered. */
protected List<Pair<TypeMirror, Label>> catchLabels;
public TryCatchFrame(Types types, List<Pair<TypeMirror, Label>> catchLabels) {
this.types = types;
this.catchLabels = catchLabels;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (this.catchLabels.isEmpty()) {
sb.append("TryCatchFrame: no catch labels.\n");
} else {
sb.append("TryCatchFrame: ");
}
for (Pair<TypeMirror, Label> ptml : this.catchLabels) {
sb.append(ptml.first.toString());
sb.append(" -> ");
sb.append(ptml.second.toString());
sb.append('\n');
}
return sb.toString();
}
/**
* Given a type of thrown exception, add the set of possible control flow successor {@link
* Label}s to the argument set. Return true if the exception is known to be caught by one of
* those labels and false if it may propagate still further.
*/
@Override
public boolean possibleLabels(TypeMirror thrown, Set<Label> labels) {
// A conservative approach would be to say that every catch block
// might execute for any thrown exception, but we try to do better.
//
// We rely on several assumptions that seem to hold as of Java 7.
// 1) An exception parameter in a catch block must be either
// a declared type or a union composed of declared types,
// all of which are subtypes of Throwable.
// 2) A thrown type must either be a declared type or a variable
// that extends a declared type, which is a subtype of Throwable.
//
// Under those assumptions, if the thrown type (or its bound) is
// a subtype of the caught type (or one of its alternatives), then
// the catch block must apply and none of the later ones can apply.
// Otherwise, if the thrown type (or its bound) is a supertype
// of the caught type (or one of its alternatives), then the catch
// block may apply, but so may later ones.
// Otherwise, the thrown type and the caught type are unrelated
// declared types, so they do not overlap on any non-null value.
while (!(thrown instanceof DeclaredType)) {
assert thrown instanceof TypeVariable
: "thrown type must be a variable or a declared type";
thrown = ((TypeVariable) thrown).getUpperBound();
}
DeclaredType declaredThrown = (DeclaredType) thrown;
assert thrown != null : "thrown type must be bounded by a declared type";
for (Pair<TypeMirror, Label> pair : catchLabels) {
TypeMirror caught = pair.first;
boolean canApply = false;
if (caught instanceof DeclaredType) {
DeclaredType declaredCaught = (DeclaredType) caught;
if (types.isSubtype(declaredThrown, declaredCaught)) {
// No later catch blocks can apply.
labels.add(pair.second);
return true;
} else if (types.isSubtype(declaredCaught, declaredThrown)) {
canApply = true;
}
} else {
assert caught instanceof UnionType
: "caught type must be a union or a declared type";
UnionType caughtUnion = (UnionType) caught;
for (TypeMirror alternative : caughtUnion.getAlternatives()) {
assert alternative instanceof DeclaredType
: "alternatives of an caught union type must be declared types";
DeclaredType declaredAlt = (DeclaredType) alternative;
if (types.isSubtype(declaredThrown, declaredAlt)) {
// No later catch blocks can apply.
labels.add(pair.second);
return true;
} else if (types.isSubtype(declaredAlt, declaredThrown)) {
canApply = true;
}
}
}
if (canApply) {
labels.add(pair.second);
}
}
return false;
}
}
/** A TryFinallyFrame applies to exceptions of any type. */
protected static class TryFinallyFrame implements TryFrame {
protected Label finallyLabel;
public TryFinallyFrame(Label finallyLabel) {
this.finallyLabel = finallyLabel;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("TryFinallyFrame: finallyLabel: " + finallyLabel + '\n');
return sb.toString();
}
@Override
public boolean possibleLabels(TypeMirror thrown, Set<Label> labels) {
labels.add(finallyLabel);
return true;
}
}
/**
* An exception stack represents the set of all try-catch blocks in effect at a given point in a
* program. It maps an exception type to a set of Labels and it maps a block exit (via return or
* fall-through) to a single Label.
*/
protected static class TryStack {
protected Label exitLabel;
protected ArrayDeque<TryFrame> frames;
public TryStack(Label exitLabel) {
this.exitLabel = exitLabel;
this.frames = new ArrayDeque<>();
}
public void pushFrame(TryFrame frame) {
frames.addFirst(frame);
}
public void popFrame() {
frames.removeFirst();
}
/**
* Returns the set of possible {@link Label}s where control may transfer when an exception
* of the given type is thrown.
*/
public Set<Label> possibleLabels(TypeMirror thrown) {
// Work up from the innermost frame until the exception is known to
// be caught.
Set<Label> labels = new MostlySingleton<>();
for (TryFrame frame : frames) {
if (frame.possibleLabels(thrown, labels)) {
return labels;
}
}
labels.add(exitLabel);
return labels;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("TryStack: exitLabel: " + this.exitLabel + '\n');
if (this.frames.isEmpty()) {
sb.append("No TryFrames.\n");
}
for (TryFrame tf : this.frames) {
sb.append(tf.toString());
}
return sb.toString();
}
}
/**
* A map that keeps track of new labels added within a try block. For names that are outside of
* the try block, the finally label is returned. This ensures that a finally block is executed
* when control flows outside of the try block.
*/
@SuppressWarnings("serial")
protected static class TryFinallyScopeMap extends HashMap<Name, Label> {
private final Map<Name, Label> accessedNames;
protected TryFinallyScopeMap() {
this.accessedNames = new HashMap<>();
}
@Override
public Label get(Object key) {
if (super.containsKey(key)) {
return super.get(key);
} else {
if (accessedNames.containsKey(key)) {
return accessedNames.get(key);
}
Label l = new Label();
accessedNames.put((Name) key, l);
return l;
}
}
@Override
@SuppressWarnings(
"keyfor:contracts.conditional.postcondition.not.satisfied") // get adds everything
public boolean containsKey(Object key) {
return true;
}
public Map<Name, Label> getAccessedNames() {
return accessedNames;
}
}
/** Storage cell for a single Label, with tracking whether it was accessed. */
protected static class TryFinallyScopeCell {
private Label label;
private boolean accessed;
protected TryFinallyScopeCell() {
this.label = null;
this.accessed = false;
}
protected TryFinallyScopeCell(Label label) {
assert label != null;
this.label = label;
this.accessed = false;
}
public Label accessLabel() {
if (label == null) {
label = new Label();
}
accessed = true;
return label;
}
public Label peekLabel() {
assert label != null;
return label;
}
public boolean wasAccessed() {
return accessed;
}
}
/* --------------------------------------------------------- */
/* Phase Three */
/* --------------------------------------------------------- */
/**
* Class that performs phase three of the translation process. In particular, the following
* degenerate cases of basic blocks are removed:
*
* <ol>
* <li>Empty regular basic blocks: These blocks will be removed and their predecessors linked
* directly to the successor.
* <li>Conditional basic blocks that have the same basic block as the 'then' and 'else'
* successor: The conditional basic block will be removed in this case.
* <li>Two consecutive, non-empty, regular basic blocks where the second block has exactly one
* predecessor (namely the other of the two blocks): In this case, the two blocks are
* merged.
* <li>Some basic blocks might not be reachable from the entryBlock. These basic blocks are
* removed, and the list of predecessors (in the doubly-linked structure of basic blocks)
* are adapted correctly.
* </ol>
*
* Eliminating the second type of degenerate cases might introduce cases of the third problem.
* These are also removed.
*/
protected static class CFGTranslationPhaseThree {
/**
* A simple wrapper object that holds a basic block and allows to set one of its successors.
*/
protected interface PredecessorHolder {
void setSuccessor(BlockImpl b);
BlockImpl getBlock();
}
/**
* Perform phase three on the control flow graph {@code cfg}.
*
* @param cfg the control flow graph. Ownership is transfered to this method and the caller
* is not allowed to read or modify {@code cfg} after the call to {@code process} any
* more.
* @return the resulting control flow graph
*/
public static ControlFlowGraph process(ControlFlowGraph cfg) {
Set<Block> worklist = cfg.getAllBlocks();
Set<Block> dontVisit = new HashSet<>();
// note: this method has to be careful when relinking basic blocks
// to not forget to adjust the predecessors, too
// fix predecessor lists by removing any unreachable predecessors
for (Block c : worklist) {
BlockImpl cur = (BlockImpl) c;
for (BlockImpl pred : new HashSet<>(cur.getPredecessors())) {
if (!worklist.contains(pred)) {
cur.removePredecessor(pred);
}
}
}
// remove empty blocks
for (Block cur : worklist) {
if (dontVisit.contains(cur)) {
continue;
}
if (cur.getType() == BlockType.REGULAR_BLOCK) {
RegularBlockImpl b = (RegularBlockImpl) cur;
if (b.isEmpty()) {
Set<RegularBlockImpl> empty = new HashSet<>();
Set<PredecessorHolder> predecessors = new HashSet<>();
BlockImpl succ = computeNeighborhoodOfEmptyBlock(b, empty, predecessors);
for (RegularBlockImpl e : empty) {
succ.removePredecessor(e);
dontVisit.add(e);
}
for (PredecessorHolder p : predecessors) {
BlockImpl block = p.getBlock();
dontVisit.add(block);
succ.removePredecessor(block);
p.setSuccessor(succ);
}
}
}
}
// remove useless conditional blocks
worklist = cfg.getAllBlocks();
for (Block c : worklist) {
BlockImpl cur = (BlockImpl) c;
if (cur.getType() == BlockType.CONDITIONAL_BLOCK) {
ConditionalBlockImpl cb = (ConditionalBlockImpl) cur;
assert cb.getPredecessors().size() == 1;
if (cb.getThenSuccessor() == cb.getElseSuccessor()) {
BlockImpl pred = cb.getPredecessors().iterator().next();
PredecessorHolder predecessorHolder = getPredecessorHolder(pred, cb);
BlockImpl succ = (BlockImpl) cb.getThenSuccessor();
succ.removePredecessor(cb);
predecessorHolder.setSuccessor(succ);
}
}
}
// merge consecutive basic blocks if possible
worklist = cfg.getAllBlocks();
for (Block cur : worklist) {
if (cur.getType() == BlockType.REGULAR_BLOCK) {
RegularBlockImpl b = (RegularBlockImpl) cur;
Block succ = b.getRegularSuccessor();
if (succ.getType() == BlockType.REGULAR_BLOCK) {
RegularBlockImpl rs = (RegularBlockImpl) succ;
if (rs.getPredecessors().size() == 1) {
b.setSuccessor(rs.getRegularSuccessor());
b.addNodes(rs.getContents());
rs.getRegularSuccessor().removePredecessor(rs);
}
}
}
}
return cfg;
}
/**
* Compute the set of empty regular basic blocks {@code empty}, starting at {@code start}
* and going both forward and backwards. Furthermore, compute the predecessors of these
* empty blocks ({@code predecessors} ), and their single successor (return value).
*
* @param start the starting point of the search (an empty, regular basic block)
* @param empty an empty set to be filled by this method with all empty basic blocks found
* (including {@code start}).
* @param predecessors an empty set to be filled by this method with all predecessors
* @return the single successor of the set of the empty basic blocks
*/
protected static BlockImpl computeNeighborhoodOfEmptyBlock(
RegularBlockImpl start,
Set<RegularBlockImpl> empty,
Set<PredecessorHolder> predecessors) {
// get empty neighborhood that come before 'start'
computeNeighborhoodOfEmptyBlockBackwards(start, empty, predecessors);
// go forward
BlockImpl succ = (BlockImpl) start.getSuccessor();
while (succ.getType() == BlockType.REGULAR_BLOCK) {
RegularBlockImpl cur = (RegularBlockImpl) succ;
if (cur.isEmpty()) {
computeNeighborhoodOfEmptyBlockBackwards(cur, empty, predecessors);
assert empty.contains(cur) : "cur ought to be in empty";
succ = (BlockImpl) cur.getSuccessor();
if (succ == cur) {
// An infinite loop, making exit block unreachable
break;
}
} else {
break;
}
}
return succ;
}
/**
* Compute the set of empty regular basic blocks {@code empty}, starting at {@code start}
* and looking only backwards in the control flow graph. Furthermore, compute the
* predecessors of these empty blocks ( {@code predecessors}).
*
* @param start the starting point of the search (an empty, regular basic block)
* @param empty a set to be filled by this method with all empty basic blocks found
* (including {@code start}).
* @param predecessors a set to be filled by this method with all predecessors
*/
protected static void computeNeighborhoodOfEmptyBlockBackwards(
RegularBlockImpl start,
Set<RegularBlockImpl> empty,
Set<PredecessorHolder> predecessors) {
RegularBlockImpl cur = start;
empty.add(cur);
for (final BlockImpl pred : cur.getPredecessors()) {
switch (pred.getType()) {
case SPECIAL_BLOCK:
// add pred correctly to predecessor list
predecessors.add(getPredecessorHolder(pred, cur));
break;
case CONDITIONAL_BLOCK:
// add pred correctly to predecessor list
predecessors.add(getPredecessorHolder(pred, cur));
break;
case EXCEPTION_BLOCK:
// add pred correctly to predecessor list
predecessors.add(getPredecessorHolder(pred, cur));
break;
case REGULAR_BLOCK:
RegularBlockImpl r = (RegularBlockImpl) pred;
if (r.isEmpty()) {
// recursively look backwards
if (!empty.contains(r)) {
computeNeighborhoodOfEmptyBlockBackwards(r, empty, predecessors);
}
} else {
// add pred correctly to predecessor list
predecessors.add(getPredecessorHolder(pred, cur));
}
break;
}
}
}
/**
* Return a predecessor holder that can be used to set the successor of {@code pred} in the
* place where previously the edge pointed to {@code cur}. Additionally, the predecessor
* holder also takes care of unlinking (i.e., removing the {@code pred} from {@code cur's}
* predecessors).
*/