1 package Analysis.Disjoint;
3 import Analysis.CallGraph.*;
4 import Analysis.Liveness;
5 import Analysis.ArrayReferencees;
6 import Analysis.OoOJava.Accessible;
7 import Analysis.OoOJava.RBlockRelationAnalysis;
8 import Analysis.FlatIRGraph.*;
11 import IR.Tree.Modifiers;
16 public class DisjointAnalysis implements HeapAnalysis {
18 ///////////////////////////////////////////
20 // Public interface to discover possible
21 // sharing in the program under analysis
23 ///////////////////////////////////////////
25 // if an object allocated at the target site may be
26 // reachable from both an object from root1 and an
27 // object allocated at root2, return TRUE
28 public boolean mayBothReachTarget(FlatMethod fm,
33 AllocSite asr1 = getAllocationSiteFromFlatNew(fnRoot1);
34 AllocSite asr2 = getAllocationSiteFromFlatNew(fnRoot2);
35 assert asr1.isFlagged();
36 assert asr2.isFlagged();
38 AllocSite ast = getAllocationSiteFromFlatNew(fnTarget);
39 ReachGraph rg = getPartial(fm.getMethod() );
41 return rg.mayBothReachTarget(asr1, asr2, ast);
44 // similar to the method above, return TRUE if ever
45 // more than one object from the root allocation site
46 // may reach an object from the target site
47 public boolean mayManyReachTarget(FlatMethod fm,
51 AllocSite asr = getAllocationSiteFromFlatNew(fnRoot);
52 assert asr.isFlagged();
54 AllocSite ast = getAllocationSiteFromFlatNew(fnTarget);
55 ReachGraph rg = getPartial(fm.getMethod() );
57 return rg.mayManyReachTarget(asr, ast);
63 public HashSet<AllocSite>
64 getFlaggedAllocationSitesReachableFromTask(TaskDescriptor td) {
65 checkAnalysisComplete();
66 return getFlaggedAllocationSitesReachableFromTaskPRIVATE(td);
69 public AllocSite getAllocationSiteFromFlatNew(FlatNew fn) {
70 checkAnalysisComplete();
71 return getAllocSiteFromFlatNewPRIVATE(fn);
74 public AllocSite getAllocationSiteFromHeapRegionNodeID(Integer id) {
75 checkAnalysisComplete();
76 return mapHrnIdToAllocSite.get(id);
79 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
82 checkAnalysisComplete();
83 ReachGraph rg=mapDescriptorToCompleteReachGraph.get(taskOrMethod);
84 FlatMethod fm=state.getMethodFlat(taskOrMethod);
86 return rg.mayReachSharedObjects(fm, paramIndex1, paramIndex2);
89 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
90 int paramIndex, AllocSite alloc) {
91 checkAnalysisComplete();
92 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
93 FlatMethod fm=state.getMethodFlat(taskOrMethod);
95 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
98 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
99 AllocSite alloc, int paramIndex) {
100 checkAnalysisComplete();
101 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
102 FlatMethod fm=state.getMethodFlat(taskOrMethod);
104 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
107 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
108 AllocSite alloc1, AllocSite alloc2) {
109 checkAnalysisComplete();
110 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
112 return rg.mayReachSharedObjects(alloc1, alloc2);
115 public String prettyPrintNodeSet(Set<HeapRegionNode> s) {
116 checkAnalysisComplete();
120 Iterator<HeapRegionNode> i = s.iterator();
121 while (i.hasNext()) {
122 HeapRegionNode n = i.next();
124 AllocSite as = n.getAllocSite();
126 out += " " + n.toString() + ",\n";
128 out += " " + n.toString() + ": " + as.toStringVerbose()
137 // use the methods given above to check every possible sharing class
138 // between task parameters and flagged allocation sites reachable
140 public void writeAllSharing(String outputFile,
143 boolean tabularOutput,
146 throws java.io.IOException {
147 checkAnalysisComplete();
149 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
151 if (!tabularOutput) {
152 bw.write("Conducting ownership analysis with allocation depth = "
153 + allocationDepth + "\n");
154 bw.write(timeReport + "\n");
159 // look through every task for potential sharing
160 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
161 while (taskItr.hasNext()) {
162 TaskDescriptor td = (TaskDescriptor) taskItr.next();
164 if (!tabularOutput) {
165 bw.write("\n---------" + td + "--------\n");
168 HashSet<AllocSite> allocSites = getFlaggedAllocationSitesReachableFromTask(td);
170 Set<HeapRegionNode> common;
172 // for each task parameter, check for sharing classes with
173 // other task parameters and every allocation site
174 // reachable from this task
175 boolean foundSomeSharing = false;
177 FlatMethod fm = state.getMethodFlat(td);
178 for (int i = 0; i < fm.numParameters(); ++i) {
180 // skip parameters with types that cannot reference
182 if( !shouldAnalysisTrack(fm.getParameter(i).getType() ) ) {
186 // for the ith parameter check for sharing classes to all
187 // higher numbered parameters
188 for (int j = i + 1; j < fm.numParameters(); ++j) {
190 // skip parameters with types that cannot reference
192 if( !shouldAnalysisTrack(fm.getParameter(j).getType() ) ) {
197 common = hasPotentialSharing(td, i, j);
198 if (!common.isEmpty()) {
199 foundSomeSharing = true;
201 if (!tabularOutput) {
202 bw.write("Potential sharing between parameters " + i
203 + " and " + j + ".\n");
204 bw.write(prettyPrintNodeSet(common) + "\n");
209 // for the ith parameter, check for sharing classes against
210 // the set of allocation sites reachable from this
212 Iterator allocItr = allocSites.iterator();
213 while (allocItr.hasNext()) {
214 AllocSite as = (AllocSite) allocItr.next();
215 common = hasPotentialSharing(td, i, as);
216 if (!common.isEmpty()) {
217 foundSomeSharing = true;
219 if (!tabularOutput) {
220 bw.write("Potential sharing between parameter " + i
221 + " and " + as.getFlatNew() + ".\n");
222 bw.write(prettyPrintNodeSet(common) + "\n");
228 // for each allocation site check for sharing classes with
229 // other allocation sites in the context of execution
231 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
232 Iterator allocItr1 = allocSites.iterator();
233 while (allocItr1.hasNext()) {
234 AllocSite as1 = (AllocSite) allocItr1.next();
236 Iterator allocItr2 = allocSites.iterator();
237 while (allocItr2.hasNext()) {
238 AllocSite as2 = (AllocSite) allocItr2.next();
240 if (!outerChecked.contains(as2)) {
241 common = hasPotentialSharing(td, as1, as2);
243 if (!common.isEmpty()) {
244 foundSomeSharing = true;
246 if (!tabularOutput) {
247 bw.write("Potential sharing between "
248 + as1.getFlatNew() + " and "
249 + as2.getFlatNew() + ".\n");
250 bw.write(prettyPrintNodeSet(common) + "\n");
256 outerChecked.add(as1);
259 if (!foundSomeSharing) {
260 if (!tabularOutput) {
261 bw.write("No sharing between flagged objects in Task " + td
269 bw.write(" & " + numSharing + " & " + justTime + " & " + numLines
270 + " & " + numMethodsAnalyzed() + " \\\\\n");
272 bw.write("\nNumber sharing classes: "+numSharing);
280 // this version of writeAllSharing is for Java programs that have no tasks
281 // ***********************************
282 // WARNING: THIS DOES NOT DO THE RIGHT THING, REPORTS 0 ALWAYS!
283 // It should use mayBothReachTarget and mayManyReachTarget like
284 // OoOJava does to query analysis results
285 // ***********************************
286 public void writeAllSharingJava(String outputFile,
289 boolean tabularOutput,
292 throws java.io.IOException {
293 checkAnalysisComplete();
299 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
301 bw.write("Conducting disjoint reachability analysis with allocation depth = "
302 + allocationDepth + "\n");
303 bw.write(timeReport + "\n\n");
305 boolean foundSomeSharing = false;
307 Descriptor d = typeUtil.getMain();
308 HashSet<AllocSite> allocSites = getFlaggedAllocationSites(d);
310 // for each allocation site check for sharing classes with
311 // other allocation sites in the context of execution
313 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
314 Iterator allocItr1 = allocSites.iterator();
315 while (allocItr1.hasNext()) {
316 AllocSite as1 = (AllocSite) allocItr1.next();
318 Iterator allocItr2 = allocSites.iterator();
319 while (allocItr2.hasNext()) {
320 AllocSite as2 = (AllocSite) allocItr2.next();
322 if (!outerChecked.contains(as2)) {
323 Set<HeapRegionNode> common = hasPotentialSharing(d,
326 if (!common.isEmpty()) {
327 foundSomeSharing = true;
328 bw.write("Potential sharing between "
329 + as1.getDisjointAnalysisId() + " and "
330 + as2.getDisjointAnalysisId() + ".\n");
331 bw.write(prettyPrintNodeSet(common) + "\n");
337 outerChecked.add(as1);
340 if (!foundSomeSharing) {
341 bw.write("No sharing classes between flagged objects found.\n");
343 bw.write("\nNumber sharing classes: "+numSharing);
346 bw.write("Number of methods analyzed: "+numMethodsAnalyzed()+"\n");
353 public Alloc getCmdLineArgsAlloc() {
354 return getAllocationSiteFromFlatNew( constructedCmdLineArgsNew );
356 public Alloc getCmdLineArgAlloc() {
357 return getAllocationSiteFromFlatNew( constructedCmdLineArgNew );
359 public Alloc getCmdLineArgBytesAlloc() {
360 return getAllocationSiteFromFlatNew( constructedCmdLineArgBytesNew );
362 public Alloc getNewStringLiteralAlloc() {
363 return newStringLiteralAlloc;
365 public Alloc getNewStringLiteralBytesAlloc() {
366 return newStringLiteralBytesAlloc;
369 ///////////////////////////////////////////
371 // end public interface
373 ///////////////////////////////////////////
377 protected void checkAnalysisComplete() {
378 if( !analysisComplete ) {
379 throw new Error("Warning: public interface method called while analysis is running.");
388 // run in faster mode, only when bugs wrung out!
389 public static boolean releaseMode;
391 // use command line option to set this, analysis
392 // should attempt to be deterministic
393 public static boolean determinismDesired;
395 // when we want to enforce determinism in the
396 // analysis we need to sort descriptors rather
397 // than toss them in efficient sets, use this
398 public static DescriptorComparator dComp =
399 new DescriptorComparator();
402 // data from the compiler
404 public CallGraph callGraph;
405 public Liveness liveness;
406 public ArrayReferencees arrayReferencees;
407 public RBlockRelationAnalysis rblockRel;
408 public TypeUtil typeUtil;
409 public int allocationDepth;
411 protected boolean doEffectsAnalysis = false;
412 protected EffectsAnalysis effectsAnalysis;
413 protected BuildStateMachines buildStateMachines;
415 protected boolean doDefiniteReachAnalysis = false;
416 protected DefiniteReachAnalysis definiteReachAnalysis;
419 // data structure for public interface
420 private Hashtable< Descriptor, HashSet<AllocSite> >
421 mapDescriptorToAllocSiteSet;
424 // for public interface methods to warn that they
425 // are grabbing results during analysis
426 private boolean analysisComplete;
429 // used to identify HeapRegionNode objects
430 // A unique ID equates an object in one
431 // ownership graph with an object in another
432 // graph that logically represents the same
434 // start at 10 and increment to reserve some
435 // IDs for special purposes
436 static protected int uniqueIDcount = 10;
439 // An out-of-scope method created by the
440 // analysis that has no parameters, and
441 // appears to allocate the command line
442 // arguments, then invoke the source code's
443 // main method. The purpose of this is to
444 // provide the analysis with an explicit
445 // top-level context with no parameters
446 protected MethodDescriptor mdAnalysisEntry;
447 protected FlatMethod fmAnalysisEntry;
449 // main method defined by source program
450 protected MethodDescriptor mdSourceEntry;
452 // the set of task and/or method descriptors
453 // reachable in call graph
454 protected Set<Descriptor>
455 descriptorsToAnalyze;
457 // current descriptors to visit in fixed-point
458 // interprocedural analysis, prioritized by
459 // dependency in the call graph
460 protected Stack<Descriptor>
461 descriptorsToVisitStack;
462 protected PriorityQueue<DescriptorQWrapper>
465 // a duplication of the above structure, but
466 // for efficient testing of inclusion
467 protected HashSet<Descriptor>
468 descriptorsToVisitSet;
470 // storage for priorities (doesn't make sense)
471 // to add it to the Descriptor class, just in
473 protected Hashtable<Descriptor, Integer>
474 mapDescriptorToPriority;
476 // when analyzing a method and scheduling more:
477 // remember set of callee's enqueued for analysis
478 // so they can be put on top of the callers in
479 // the stack-visit mode
480 protected Set<Descriptor>
483 // maps a descriptor to its current partial result
484 // from the intraprocedural fixed-point analysis--
485 // then the interprocedural analysis settles, this
486 // mapping will have the final results for each
488 protected Hashtable<Descriptor, ReachGraph>
489 mapDescriptorToCompleteReachGraph;
491 // maps a descriptor to its known dependents: namely
492 // methods or tasks that call the descriptor's method
493 // AND are part of this analysis (reachable from main)
494 protected Hashtable< Descriptor, Set<Descriptor> >
495 mapDescriptorToSetDependents;
497 // if the analysis client wants to flag allocation sites
498 // programmatically, it should provide a set of FlatNew
499 // statements--this may be null if unneeded
500 protected Set<FlatNew> sitesToFlag;
502 // maps each flat new to one analysis abstraction
503 // allocate site object, these exist outside reach graphs
504 protected Hashtable<FlatNew, AllocSite>
505 mapFlatNewToAllocSite;
507 // maps intergraph heap region IDs to intergraph
508 // allocation sites that created them, a redundant
509 // structure for efficiency in some operations
510 protected Hashtable<Integer, AllocSite>
513 // maps a method to its initial heap model (IHM) that
514 // is the set of reachability graphs from every caller
515 // site, all merged together. The reason that we keep
516 // them separate is that any one call site's contribution
517 // to the IHM may changed along the path to the fixed point
518 protected Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >
519 mapDescriptorToIHMcontributions;
521 // additionally, keep a mapping from descriptors to the
522 // merged in-coming initial context, because we want this
523 // initial context to be STRICTLY MONOTONIC
524 protected Hashtable<Descriptor, ReachGraph>
525 mapDescriptorToInitialContext;
527 // mapping of current partial results for a given node. Note that
528 // to reanalyze a method we discard all partial results because a
529 // null reach graph indicates the node needs to be visited on the
530 // way to the fixed point.
531 // The reason for a persistent mapping is so after the analysis we
532 // can ask for the graph of any node at the fixed point, but this
533 // option is only enabled with a compiler flag.
534 protected Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraphPersist;
535 protected Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraph;
538 // make the result for back edges analysis-wide STRICTLY
539 // MONOTONIC as well, but notice we use FlatNode as the
540 // key for this map: in case we want to consider other
541 // nodes as back edge's in future implementations
542 protected Hashtable<FlatNode, ReachGraph>
543 mapBackEdgeToMonotone;
546 public static final String arrayElementFieldName = "___element_";
547 static protected Hashtable<TypeDescriptor, FieldDescriptor>
551 protected boolean suppressOutput;
553 // for controlling DOT file output
554 protected boolean writeFinalDOTs;
555 protected boolean writeAllIncrementalDOTs;
557 // supporting DOT output--when we want to write every
558 // partial method result, keep a tally for generating
560 protected Hashtable<Descriptor, Integer>
561 mapDescriptorToNumUpdates;
563 //map task descriptor to initial task parameter
564 protected Hashtable<Descriptor, ReachGraph>
565 mapDescriptorToReachGraph;
567 protected PointerMethod pm;
569 //Keeps track of all the reach graphs at every program point
570 //DO NOT USE UNLESS YOU REALLY NEED IT
571 static protected Hashtable<FlatNode, ReachGraph> fn2rgAtEnter =
572 new Hashtable<FlatNode, ReachGraph>();
574 static protected Hashtable<FlatNode, ReachGraph> fn2rgAtExit =
575 new Hashtable<FlatNode, ReachGraph>();
578 private Hashtable<FlatCall, Descriptor> fc2enclosing;
580 Accessible accessible;
583 // we construct an entry method of flat nodes complete
584 // with a new allocation site to model the command line
585 // args creation just for the analysis, so remember that
586 // allocation site. Later in code gen we might want to
587 // know if something is pointing-to to the cmd line args
588 // and we can verify by checking the allocation site field.
589 protected FlatNew constructedCmdLineArgsNew;
590 protected FlatNew constructedCmdLineArgNew;
591 protected FlatNew constructedCmdLineArgBytesNew;
593 // similar to above, the runtime allocates new strings
594 // for literal nodes, so make up an alloc to model that
595 protected AllocSite newStringLiteralAlloc;
596 protected AllocSite newStringLiteralBytesAlloc;
598 // both of the above need the descriptor of the field
599 // for the String's value field to reference by the
600 // byte array from the string object
601 protected TypeDescriptor stringType;
602 protected TypeDescriptor stringBytesType;
603 protected FieldDescriptor stringBytesField;
606 protected void initImplicitStringsModel() {
608 ClassDescriptor cdString = typeUtil.getClass( typeUtil.StringClass );
609 assert cdString != null;
613 new TypeDescriptor( cdString );
616 new TypeDescriptor(TypeDescriptor.CHAR).makeArray( state );
619 stringBytesField = null;
620 Iterator sFieldsItr = cdString.getFields();
621 while( sFieldsItr.hasNext() ) {
622 FieldDescriptor fd = (FieldDescriptor) sFieldsItr.next();
623 if( fd.getSymbol().equals( typeUtil.StringClassValueField ) ) {
624 stringBytesField = fd;
628 assert stringBytesField != null;
631 TempDescriptor throwAway1 =
632 new TempDescriptor("stringLiteralTemp_dummy1",
635 FlatNew fnStringLiteral =
636 new FlatNew(stringType,
640 newStringLiteralAlloc
641 = getAllocSiteFromFlatNewPRIVATE( fnStringLiteral );
644 TempDescriptor throwAway2 =
645 new TempDescriptor("stringLiteralTemp_dummy2",
648 FlatNew fnStringLiteralBytes =
649 new FlatNew(stringBytesType,
653 newStringLiteralBytesAlloc
654 = getAllocSiteFromFlatNewPRIVATE( fnStringLiteralBytes );
660 // allocate various structures that are not local
661 // to a single class method--should be done once
662 protected void allocateStructures() {
664 if( determinismDesired ) {
665 // use an ordered set
666 descriptorsToAnalyze = new TreeSet<Descriptor>(dComp);
668 // otherwise use a speedy hashset
669 descriptorsToAnalyze = new HashSet<Descriptor>();
672 mapDescriptorToCompleteReachGraph =
673 new Hashtable<Descriptor, ReachGraph>();
675 mapDescriptorToNumUpdates =
676 new Hashtable<Descriptor, Integer>();
678 mapDescriptorToSetDependents =
679 new Hashtable< Descriptor, Set<Descriptor> >();
681 mapFlatNewToAllocSite =
682 new Hashtable<FlatNew, AllocSite>();
684 mapDescriptorToIHMcontributions =
685 new Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >();
687 mapDescriptorToInitialContext =
688 new Hashtable<Descriptor, ReachGraph>();
690 mapFlatNodeToReachGraphPersist =
691 new Hashtable<FlatNode, ReachGraph>();
693 mapBackEdgeToMonotone =
694 new Hashtable<FlatNode, ReachGraph>();
696 mapHrnIdToAllocSite =
697 new Hashtable<Integer, AllocSite>();
699 mapTypeToArrayField =
700 new Hashtable <TypeDescriptor, FieldDescriptor>();
702 if( state.DISJOINTDVISITSTACK ||
703 state.DISJOINTDVISITSTACKEESONTOP
705 descriptorsToVisitStack =
706 new Stack<Descriptor>();
709 if( state.DISJOINTDVISITPQUE ) {
710 descriptorsToVisitQ =
711 new PriorityQueue<DescriptorQWrapper>();
714 descriptorsToVisitSet =
715 new HashSet<Descriptor>();
717 mapDescriptorToPriority =
718 new Hashtable<Descriptor, Integer>();
721 new HashSet<Descriptor>();
723 mapDescriptorToAllocSiteSet =
724 new Hashtable<Descriptor, HashSet<AllocSite> >();
726 mapDescriptorToReachGraph =
727 new Hashtable<Descriptor, ReachGraph>();
729 pm = new PointerMethod();
731 fc2enclosing = new Hashtable<FlatCall, Descriptor>();
736 // this analysis generates a disjoint reachability
737 // graph for every reachable method in the program
738 public DisjointAnalysis(State s,
743 Set<FlatNew> sitesToFlag,
744 RBlockRelationAnalysis rra
746 init(s, tu, cg, l, ar, sitesToFlag, rra, null, false);
749 public DisjointAnalysis(State s,
754 Set<FlatNew> sitesToFlag,
755 RBlockRelationAnalysis rra,
756 boolean suppressOutput
758 init(s, tu, cg, l, ar, sitesToFlag, rra, null, suppressOutput);
761 public DisjointAnalysis(State s,
766 Set<FlatNew> sitesToFlag,
767 RBlockRelationAnalysis rra,
768 BuildStateMachines bsm,
769 boolean suppressOutput
771 init(s, tu, cg, l, ar, sitesToFlag, rra, bsm, suppressOutput);
774 protected void init(State state,
778 ArrayReferencees arrayReferencees,
779 Set<FlatNew> sitesToFlag,
780 RBlockRelationAnalysis rra,
781 BuildStateMachines bsm,
782 boolean suppressOutput
785 analysisComplete = false;
788 this.typeUtil = typeUtil;
789 this.callGraph = callGraph;
790 this.liveness = liveness;
791 this.arrayReferencees = arrayReferencees;
792 this.sitesToFlag = sitesToFlag;
793 this.rblockRel = rra;
794 this.suppressOutput = suppressOutput;
795 this.buildStateMachines = bsm;
797 if( rblockRel != null ) {
798 doEffectsAnalysis = true;
799 effectsAnalysis = new EffectsAnalysis();
801 EffectsAnalysis.state = state;
802 EffectsAnalysis.buildStateMachines = buildStateMachines;
804 //note: instead of reachgraph's isAccessible, using the result of accessible analysis
805 //since accessible gives us more accurate results
806 accessible=new Accessible(state, callGraph, rra, liveness);
807 accessible.doAnalysis();
810 this.allocationDepth = state.DISJOINTALLOCDEPTH;
811 this.releaseMode = state.DISJOINTRELEASEMODE;
812 this.determinismDesired = state.DISJOINTDETERMINISM;
814 this.writeFinalDOTs = state.DISJOINTWRITEDOTS && !state.DISJOINTWRITEALL;
815 this.writeAllIncrementalDOTs = state.DISJOINTWRITEDOTS && state.DISJOINTWRITEALL;
817 this.takeDebugSnapshots = state.DISJOINTSNAPSYMBOL != null;
818 this.descSymbolDebug = state.DISJOINTSNAPSYMBOL;
819 this.visitStartCapture = state.DISJOINTSNAPVISITTOSTART;
820 this.numVisitsToCapture = state.DISJOINTSNAPNUMVISITS;
821 this.stopAfterCapture = state.DISJOINTSNAPSTOPAFTER;
822 this.snapVisitCounter = 1; // count visits from 1 (user will write 1, means 1st visit)
823 this.snapNodeCounter = 0; // count nodes from 0
826 state.DISJOINTDVISITSTACK ||
827 state.DISJOINTDVISITPQUE ||
828 state.DISJOINTDVISITSTACKEESONTOP;
829 assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITPQUE);
830 assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITSTACKEESONTOP);
831 assert !(state.DISJOINTDVISITPQUE && state.DISJOINTDVISITSTACKEESONTOP);
833 // set some static configuration for ReachGraphs
834 ReachGraph.allocationDepth = allocationDepth;
835 ReachGraph.typeUtil = typeUtil;
836 ReachGraph.state = state;
838 ReachGraph.initOutOfScopeTemps();
840 ReachGraph.debugCallSiteVisitStartCapture
841 = state.DISJOINTDEBUGCALLVISITTOSTART;
843 ReachGraph.debugCallSiteNumVisitsToCapture
844 = state.DISJOINTDEBUGCALLNUMVISITS;
846 ReachGraph.debugCallSiteStopAfter
847 = state.DISJOINTDEBUGCALLSTOPAFTER;
849 ReachGraph.debugCallSiteVisitCounter
850 = 0; // count visits from 1, is incremented before first visit
852 if( state.DO_DEFINITE_REACH_ANALYSIS ) {
853 doDefiniteReachAnalysis = true;
854 definiteReachAnalysis = new DefiniteReachAnalysis();
858 if( suppressOutput ) {
859 System.out.println("* Running disjoint reachability analysis with output suppressed! *");
863 allocateStructures();
865 initImplicitStringsModel();
869 double timeStartAnalysis = (double) System.nanoTime();
871 // start interprocedural fixed-point computation
874 } catch( IOException e ) {
875 throw new Error("IO Exception while writing disjointness analysis output.");
878 analysisComplete=true;
880 double timeEndAnalysis = (double) System.nanoTime();
881 double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow(10.0, 9.0) );
884 if( sitesToFlag != null ) {
885 treport = String.format("Disjoint reachability analysis flagged %d sites and took %.3f sec.", sitesToFlag.size(), dt);
886 if(sitesToFlag.size()>0) {
887 treport+="\nFlagged sites:"+"\n"+sitesToFlag.toString();
890 treport = String.format("Disjoint reachability analysis took %.3f sec.", dt);
892 String justtime = String.format("%.2f", dt);
893 System.out.println(treport);
897 if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
901 if( state.DISJOINTWRITEIHMS ) {
905 if( state.DISJOINTWRITEINITCONTEXTS ) {
906 writeInitialContexts();
909 if( state.DISJOINT_WRITE_ALL_NODE_FINAL_GRAPHS ) {
910 writeFinalGraphsForEveryNode();
913 if( state.DISJOINTALIASFILE != null && !suppressOutput ) {
915 writeAllSharing(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines);
917 writeAllSharingJava(state.DISJOINTALIASFILE,
920 state.DISJOINTALIASTAB,
927 buildStateMachines.writeStateMachines();
930 } catch( IOException e ) {
931 throw new Error("IO Exception while writing disjointness analysis output.");
936 protected boolean moreDescriptorsToVisit() {
937 if( state.DISJOINTDVISITSTACK ||
938 state.DISJOINTDVISITSTACKEESONTOP
940 return !descriptorsToVisitStack.isEmpty();
942 } else if( state.DISJOINTDVISITPQUE ) {
943 return !descriptorsToVisitQ.isEmpty();
946 throw new Error("Neither descriptor visiting mode set");
950 // fixed-point computation over the call graph--when a
951 // method's callees are updated, it must be reanalyzed
952 protected void analyzeMethods() throws java.io.IOException {
954 // task or non-task (java) mode determines what the roots
955 // of the call chain are, and establishes the set of methods
956 // reachable from the roots that will be analyzed
959 if( !suppressOutput ) {
960 System.out.println("Bamboo mode...");
963 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
964 while( taskItr.hasNext() ) {
965 TaskDescriptor td = (TaskDescriptor) taskItr.next();
966 if( !descriptorsToAnalyze.contains(td) ) {
967 // add all methods transitively reachable from the
969 descriptorsToAnalyze.add(td);
970 descriptorsToAnalyze.addAll(callGraph.getAllMethods(td) );
975 if( !suppressOutput ) {
976 System.out.println("Java mode...");
979 // add all methods transitively reachable from the
980 // source's main to set for analysis
981 mdSourceEntry = typeUtil.getMain();
982 descriptorsToAnalyze.add(mdSourceEntry);
983 descriptorsToAnalyze.addAll(callGraph.getAllMethods(mdSourceEntry) );
985 // fabricate an empty calling context that will call
986 // the source's main, but call graph doesn't know
987 // about it, so explicitly add it
988 makeAnalysisEntryMethod(mdSourceEntry);
989 descriptorsToAnalyze.add(mdAnalysisEntry);
994 // now, depending on the interprocedural mode for visiting
995 // methods, set up the needed data structures
997 if( state.DISJOINTDVISITPQUE ) {
999 // topologically sort according to the call graph so
1000 // leaf calls are last, helps build contexts up first
1001 LinkedList<Descriptor> sortedDescriptors =
1002 topologicalSort(descriptorsToAnalyze);
1004 // add sorted descriptors to priority queue, and duplicate
1005 // the queue as a set for efficiently testing whether some
1006 // method is marked for analysis
1008 Iterator<Descriptor> dItr;
1010 // for the priority queue, give items at the head
1011 // of the sorted list a low number (highest priority)
1012 while( !sortedDescriptors.isEmpty() ) {
1013 Descriptor d = sortedDescriptors.removeFirst();
1014 mapDescriptorToPriority.put(d, new Integer(p) );
1015 descriptorsToVisitQ.add(new DescriptorQWrapper(p, d) );
1016 descriptorsToVisitSet.add(d);
1020 } else if( state.DISJOINTDVISITSTACK ||
1021 state.DISJOINTDVISITSTACKEESONTOP
1023 // if we're doing the stack scheme, just throw the root
1024 // method or tasks on the stack
1026 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
1027 while( taskItr.hasNext() ) {
1028 TaskDescriptor td = (TaskDescriptor) taskItr.next();
1029 descriptorsToVisitStack.add(td);
1030 descriptorsToVisitSet.add(td);
1034 descriptorsToVisitStack.add(mdAnalysisEntry);
1035 descriptorsToVisitSet.add(mdAnalysisEntry);
1039 throw new Error("Unknown method scheduling mode");
1043 // analyze scheduled methods until there are no more to visit
1044 while( moreDescriptorsToVisit() ) {
1045 Descriptor d = null;
1047 if( state.DISJOINTDVISITSTACK ||
1048 state.DISJOINTDVISITSTACKEESONTOP
1050 d = descriptorsToVisitStack.pop();
1052 } else if( state.DISJOINTDVISITPQUE ) {
1053 d = descriptorsToVisitQ.poll().getDescriptor();
1056 assert descriptorsToVisitSet.contains(d);
1057 descriptorsToVisitSet.remove(d);
1059 // because the task or method descriptor just extracted
1060 // was in the "to visit" set it either hasn't been analyzed
1061 // yet, or some method that it depends on has been
1062 // updated. Recompute a complete reachability graph for
1063 // this task/method and compare it to any previous result.
1064 // If there is a change detected, add any methods/tasks
1065 // that depend on this one to the "to visit" set.
1067 if( !suppressOutput ) {
1068 System.out.println("Analyzing " + d);
1071 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1072 assert calleesToEnqueue.isEmpty();
1075 ReachGraph rg = analyzeMethod(d);
1076 ReachGraph rgPrev = getPartial(d);
1078 if( !rg.equals(rgPrev) ) {
1081 if( state.DISJOINTDEBUGSCHEDULING ) {
1082 System.out.println(" complete graph changed, scheduling callers for analysis:");
1085 // results for d changed, so enqueue dependents
1086 // of d for further analysis
1087 Iterator<Descriptor> depsItr = getDependents(d).iterator();
1088 while( depsItr.hasNext() ) {
1089 Descriptor dNext = depsItr.next();
1092 if( state.DISJOINTDEBUGSCHEDULING ) {
1093 System.out.println(" "+dNext);
1098 // whether or not the method under analysis changed,
1099 // we may have some callees that are scheduled for
1100 // more analysis, and they should go on the top of
1101 // the stack now (in other method-visiting modes they
1102 // are already enqueued at this point
1103 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1104 Iterator<Descriptor> depsItr = calleesToEnqueue.iterator();
1105 while( depsItr.hasNext() ) {
1106 Descriptor dNext = depsItr.next();
1109 calleesToEnqueue.clear();
1115 protected ReachGraph analyzeMethod(Descriptor d)
1116 throws java.io.IOException {
1118 // get the flat code for this descriptor
1120 if( d == mdAnalysisEntry ) {
1121 fm = fmAnalysisEntry;
1123 fm = state.getMethodFlat(d);
1125 pm.analyzeMethod(fm);
1127 // intraprocedural work set
1128 Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
1129 flatNodesToVisit.add(fm);
1131 // if determinism is desired by client, shadow the
1132 // set with a queue to make visit order deterministic
1133 Queue<FlatNode> flatNodesToVisitQ = null;
1134 if( determinismDesired ) {
1135 flatNodesToVisitQ = new LinkedList<FlatNode>();
1136 flatNodesToVisitQ.add(fm);
1139 // start a new mapping of partial results
1140 mapFlatNodeToReachGraph =
1141 new Hashtable<FlatNode, ReachGraph>();
1143 // the set of return nodes partial results that will be combined as
1144 // the final, conservative approximation of the entire method
1145 HashSet<FlatReturnNode> setReturns = new HashSet<FlatReturnNode>();
1149 boolean snapThisMethod = false;
1150 if( takeDebugSnapshots && d instanceof MethodDescriptor ) {
1151 MethodDescriptor mdThisMethod = (MethodDescriptor)d;
1152 ClassDescriptor cdThisMethod = mdThisMethod.getClassDesc();
1153 if( cdThisMethod != null ) {
1155 descSymbolDebug.equals( cdThisMethod.getSymbol()+
1157 mdThisMethod.getSymbol()
1164 while( !flatNodesToVisit.isEmpty() ) {
1167 if( determinismDesired ) {
1168 assert !flatNodesToVisitQ.isEmpty();
1169 fn = flatNodesToVisitQ.remove();
1171 fn = flatNodesToVisit.iterator().next();
1173 flatNodesToVisit.remove(fn);
1175 // effect transfer function defined by this node,
1176 // then compare it to the old graph at this node
1177 // to see if anything was updated.
1179 ReachGraph rg = new ReachGraph();
1180 TaskDescriptor taskDesc;
1181 if(fn instanceof FlatMethod && (taskDesc=((FlatMethod)fn).getTask())!=null) {
1182 if(mapDescriptorToReachGraph.containsKey(taskDesc)) {
1183 // retrieve existing reach graph if it is not first time
1184 rg=mapDescriptorToReachGraph.get(taskDesc);
1186 // create initial reach graph for a task
1187 rg=createInitialTaskReachGraph((FlatMethod)fn);
1189 mapDescriptorToReachGraph.put(taskDesc, rg);
1193 // start by merging all node's parents' graphs
1194 for( int i = 0; i < pm.numPrev(fn); ++i ) {
1195 FlatNode pn = pm.getPrev(fn,i);
1196 if( mapFlatNodeToReachGraph.containsKey(pn) ) {
1197 ReachGraph rgParent = mapFlatNodeToReachGraph.get(pn);
1203 if( snapThisMethod ) {
1204 debugSnapshot(rg, fn, true);
1208 // modify rg with appropriate transfer function
1209 rg = analyzeFlatNode(d, fm, fn, setReturns, rg);
1212 if( snapThisMethod ) {
1213 debugSnapshot(rg, fn, false);
1218 // if the results of the new graph are different from
1219 // the current graph at this node, replace the graph
1220 // with the update and enqueue the children
1221 ReachGraph rgPrev = mapFlatNodeToReachGraph.get(fn);
1222 if( !rg.equals(rgPrev) ) {
1223 mapFlatNodeToReachGraph.put(fn, rg);
1225 // we don't necessarily want to keep the reach graph for every
1226 // node in the program unless a client or the user wants it
1227 if( state.DISJOINT_WRITE_ALL_NODE_FINAL_GRAPHS ) {
1228 mapFlatNodeToReachGraphPersist.put(fn, rg);
1231 for( int i = 0; i < pm.numNext(fn); i++ ) {
1232 FlatNode nn = pm.getNext(fn, i);
1234 flatNodesToVisit.add(nn);
1235 if( determinismDesired ) {
1236 flatNodesToVisitQ.add(nn);
1243 // end by merging all return nodes into a complete
1244 // reach graph that represents all possible heap
1245 // states after the flat method returns
1246 ReachGraph completeGraph = new ReachGraph();
1248 if( setReturns.isEmpty() ) {
1249 System.out.println( "d = "+d );
1252 assert !setReturns.isEmpty();
1253 Iterator retItr = setReturns.iterator();
1254 while( retItr.hasNext() ) {
1255 FlatReturnNode frn = (FlatReturnNode) retItr.next();
1257 assert mapFlatNodeToReachGraph.containsKey(frn);
1258 ReachGraph rgRet = mapFlatNodeToReachGraph.get(frn);
1260 completeGraph.merge(rgRet);
1264 if( snapThisMethod ) {
1265 // increment that we've visited the debug snap
1266 // method, and reset the node counter
1267 System.out.println(" @@@ debug snap at visit "+snapVisitCounter);
1269 snapNodeCounter = 0;
1271 if( snapVisitCounter == visitStartCapture + numVisitsToCapture &&
1274 System.out.println("!!! Stopping analysis after debug snap captures. !!!");
1280 return completeGraph;
1284 protected ReachGraph
1285 analyzeFlatNode(Descriptor d,
1286 FlatMethod fmContaining,
1288 HashSet<FlatReturnNode> setRetNodes,
1290 ) throws java.io.IOException {
1293 // any variables that are no longer live should be
1294 // nullified in the graph to reduce edges
1295 //rg.nullifyDeadVars( liveness.getLiveInTemps( fmContaining, fn ) );
1299 FieldDescriptor fld;
1300 TypeDescriptor tdElement;
1301 FieldDescriptor fdElement;
1302 FlatSESEEnterNode sese;
1303 FlatSESEExitNode fsexn;
1305 Set<EdgeKey> edgeKeysForLoad;
1306 Set<EdgeKey> edgeKeysRemoved;
1307 Set<EdgeKey> edgeKeysAdded;
1309 //Stores the flatnode's reach graph at enter
1310 ReachGraph rgOnEnter = new ReachGraph();
1311 rgOnEnter.merge(rg);
1312 fn2rgAtEnter.put(fn, rgOnEnter);
1316 boolean didDefReachTransfer = false;
1320 // use node type to decide what transfer function
1321 // to apply to the reachability graph
1322 switch( fn.kind() ) {
1324 case FKind.FlatGenReachNode: {
1325 FlatGenReachNode fgrn = (FlatGenReachNode) fn;
1327 System.out.println(" Generating reach graph for program point: "+fgrn.getGraphName() );
1330 rg.writeGraph("genReach"+fgrn.getGraphName(),
1331 true, // write labels (variables)
1332 true, // selectively hide intermediate temp vars
1333 true, // prune unreachable heap regions
1334 false, // hide reachability altogether
1335 true, // hide subset reachability states
1336 true, // hide predicates
1337 true); //false); // hide edge taints
1341 case FKind.FlatGenDefReachNode: {
1342 FlatGenDefReachNode fgdrn = (FlatGenDefReachNode) fn;
1343 if( doDefiniteReachAnalysis ) {
1344 definiteReachAnalysis.writeState( fn, fgdrn.getOutputName() );
1349 case FKind.FlatMethod: {
1350 // construct this method's initial heap model (IHM)
1351 // since we're working on the FlatMethod, we know
1352 // the incoming ReachGraph 'rg' is empty
1354 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1355 getIHMcontributions(d);
1357 Set entrySet = heapsFromCallers.entrySet();
1358 Iterator itr = entrySet.iterator();
1359 while( itr.hasNext() ) {
1360 Map.Entry me = (Map.Entry)itr.next();
1361 FlatCall fc = (FlatCall) me.getKey();
1362 ReachGraph rgContrib = (ReachGraph) me.getValue();
1364 // note that "fc.getMethod()" like (Object.toString)
1365 // might not be equal to "d" like (String.toString)
1366 // because the mapping gets set up when we resolve
1368 rg.merge(rgContrib);
1371 // additionally, we are enforcing STRICT MONOTONICITY for the
1372 // method's initial context, so grow the context by whatever
1373 // the previously computed context was, and put the most
1374 // up-to-date context back in the map
1375 ReachGraph rgPrevContext = mapDescriptorToInitialContext.get(d);
1376 rg.merge(rgPrevContext);
1377 mapDescriptorToInitialContext.put(d, rg);
1379 if( doDefiniteReachAnalysis ) {
1380 FlatMethod fm = (FlatMethod) fn;
1381 Set<TempDescriptor> params = new HashSet<TempDescriptor>();
1382 for( int i = 0; i < fm.numParameters(); ++i ) {
1383 params.add( fm.getParameter( i ) );
1385 definiteReachAnalysis.methodEntry( fn, params );
1386 didDefReachTransfer = true;
1390 case FKind.FlatOpNode:
1391 FlatOpNode fon = (FlatOpNode) fn;
1392 if( fon.getOp().getOp() == Operation.ASSIGN ) {
1393 lhs = fon.getDest();
1394 rhs = fon.getLeft();
1396 // before transfer, do effects analysis support
1397 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1398 if(rblockRel.isPotentialStallSite(fn)) {
1399 // x gets status of y
1400 if(!accessible.isAccessible(fn, rhs)) {
1401 rg.makeInaccessible(lhs);
1407 rg.assignTempXEqualToTempY(lhs, rhs);
1409 if( doDefiniteReachAnalysis ) {
1410 definiteReachAnalysis.copy( fn, lhs, rhs );
1411 didDefReachTransfer = true;
1416 case FKind.FlatCastNode:
1417 FlatCastNode fcn = (FlatCastNode) fn;
1421 TypeDescriptor td = fcn.getType();
1424 // before transfer, do effects analysis support
1425 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1426 if(rblockRel.isPotentialStallSite(fn)) {
1427 // x gets status of y
1428 if(!accessible.isAccessible(fn,rhs)) {
1429 rg.makeInaccessible(lhs);
1435 rg.assignTempXEqualToCastedTempY(lhs, rhs, td);
1437 if( doDefiniteReachAnalysis ) {
1438 definiteReachAnalysis.copy( fn, lhs, rhs );
1439 didDefReachTransfer = true;
1443 case FKind.FlatFieldNode:
1444 FlatFieldNode ffn = (FlatFieldNode) fn;
1448 fld = ffn.getField();
1450 // before graph transform, possible inject
1451 // a stall-site taint
1452 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1454 if(rblockRel.isPotentialStallSite(fn)) {
1455 // x=y.f, stall y if not accessible
1456 // contributes read effects on stall site of y
1457 if(!accessible.isAccessible(fn,rhs)) {
1458 rg.taintStallSite(fn, rhs);
1461 // after this, x and y are accessbile.
1462 rg.makeAccessible(lhs);
1463 rg.makeAccessible(rhs);
1467 edgeKeysForLoad = null;
1468 if( doDefiniteReachAnalysis ) {
1469 edgeKeysForLoad = new HashSet<EdgeKey>();
1472 if( shouldAnalysisTrack(fld.getType() ) ) {
1474 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fld, fn, edgeKeysForLoad );
1476 if( doDefiniteReachAnalysis ) {
1477 definiteReachAnalysis.load( fn, lhs, rhs, fld, edgeKeysForLoad );
1478 didDefReachTransfer = true;
1482 // after transfer, use updated graph to
1483 // do effects analysis
1484 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1485 effectsAnalysis.analyzeFlatFieldNode(rg, rhs, fld, fn);
1489 case FKind.FlatSetFieldNode:
1490 FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
1492 lhs = fsfn.getDst();
1493 fld = fsfn.getField();
1494 rhs = fsfn.getSrc();
1496 boolean strongUpdate = false;
1498 edgeKeysRemoved = null;
1499 edgeKeysAdded = null;
1500 if( doDefiniteReachAnalysis ) {
1501 edgeKeysRemoved = new HashSet<EdgeKey>();
1502 edgeKeysAdded = new HashSet<EdgeKey>();
1505 // before transfer func, possibly inject
1506 // stall-site taints
1507 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1509 if(rblockRel.isPotentialStallSite(fn)) {
1510 // x.y=f , stall x and y if they are not accessible
1511 // also contribute write effects on stall site of x
1512 if(!accessible.isAccessible(fn,lhs)) {
1513 rg.taintStallSite(fn, lhs);
1516 if(!accessible.isAccessible(fn,rhs)) {
1517 rg.taintStallSite(fn, rhs);
1520 // accessible status update
1521 rg.makeAccessible(lhs);
1522 rg.makeAccessible(rhs);
1526 if( shouldAnalysisTrack(fld.getType() ) ) {
1528 strongUpdate = rg.assignTempXFieldFEqualToTempY( lhs,
1534 if( doDefiniteReachAnalysis ) {
1535 definiteReachAnalysis.store( fn,
1541 didDefReachTransfer = true;
1545 // use transformed graph to do effects analysis
1546 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1547 effectsAnalysis.analyzeFlatSetFieldNode(rg, lhs, fld, fn, strongUpdate);
1551 case FKind.FlatElementNode:
1552 FlatElementNode fen = (FlatElementNode) fn;
1557 assert rhs.getType() != null;
1558 assert rhs.getType().isArray();
1560 tdElement = rhs.getType().dereference();
1561 fdElement = getArrayField(tdElement);
1563 // before transfer func, possibly inject
1565 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1566 if(rblockRel.isPotentialStallSite(fn)) {
1567 // x=y.f, stall y if not accessible
1568 // contributes read effects on stall site of y
1569 // after this, x and y are accessbile.
1570 if(!accessible.isAccessible(fn,rhs)) {
1571 rg.taintStallSite(fn, rhs);
1574 rg.makeAccessible(lhs);
1575 rg.makeAccessible(rhs);
1579 edgeKeysForLoad = null;
1580 if( doDefiniteReachAnalysis ) {
1581 edgeKeysForLoad = new HashSet<EdgeKey>();
1584 if( shouldAnalysisTrack(lhs.getType() ) ) {
1586 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fdElement, fn, edgeKeysForLoad );
1588 if( doDefiniteReachAnalysis ) {
1589 definiteReachAnalysis.load( fn, lhs, rhs, fdElement, edgeKeysForLoad );
1590 didDefReachTransfer = true;
1594 // use transformed graph to do effects analysis
1595 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1596 effectsAnalysis.analyzeFlatFieldNode(rg, rhs, fdElement, fn);
1600 case FKind.FlatSetElementNode:
1601 FlatSetElementNode fsen = (FlatSetElementNode) fn;
1603 lhs = fsen.getDst();
1604 rhs = fsen.getSrc();
1606 assert lhs.getType() != null;
1607 assert lhs.getType().isArray();
1609 tdElement = lhs.getType().dereference();
1610 fdElement = getArrayField(tdElement);
1612 edgeKeysRemoved = null;
1613 edgeKeysAdded = null;
1614 if( doDefiniteReachAnalysis ) {
1615 edgeKeysRemoved = new HashSet<EdgeKey>();
1616 edgeKeysAdded = new HashSet<EdgeKey>();
1619 // before transfer func, possibly inject
1620 // stall-site taints
1621 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1623 if(rblockRel.isPotentialStallSite(fn)) {
1624 // x.y=f , stall x and y if they are not accessible
1625 // also contribute write effects on stall site of x
1626 if(!accessible.isAccessible(fn,lhs)) {
1627 rg.taintStallSite(fn, lhs);
1630 if(!accessible.isAccessible(fn,rhs)) {
1631 rg.taintStallSite(fn, rhs);
1634 // accessible status update
1635 rg.makeAccessible(lhs);
1636 rg.makeAccessible(rhs);
1640 if( shouldAnalysisTrack(rhs.getType() ) ) {
1641 // transfer func, BUT
1642 // skip this node if it cannot create new reachability paths
1643 if( !arrayReferencees.doesNotCreateNewReaching(fsen) ) {
1644 rg.assignTempXFieldFEqualToTempY( lhs,
1652 if( doDefiniteReachAnalysis ) {
1653 definiteReachAnalysis.store( fn,
1659 didDefReachTransfer = true;
1663 // use transformed graph to do effects analysis
1664 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1665 effectsAnalysis.analyzeFlatSetFieldNode(rg, lhs, fdElement, fn,
1671 FlatNew fnn = (FlatNew) fn;
1673 if( shouldAnalysisTrack(lhs.getType() ) ) {
1674 AllocSite as = getAllocSiteFromFlatNewPRIVATE(fnn);
1676 // before transform, support effects analysis
1677 if (doEffectsAnalysis && fmContaining != fmAnalysisEntry) {
1678 if (rblockRel.isPotentialStallSite(fn)) {
1679 // after creating new object, lhs is accessible
1680 rg.makeAccessible(lhs);
1685 rg.assignTempEqualToNewAlloc(lhs, as);
1687 if( doDefiniteReachAnalysis ) {
1688 definiteReachAnalysis.newObject( fn, lhs );
1689 didDefReachTransfer = true;
1695 case FKind.FlatLiteralNode:
1696 // BIG NOTE: this transfer function is only here for
1697 // points-to information for String literals. That's it.
1698 // Effects and disjoint reachability and all of that don't
1699 // care about references to literals.
1700 FlatLiteralNode fln = (FlatLiteralNode) fn;
1702 if( fln.getType().equals( stringType ) ) {
1703 rg.assignTempEqualToStringLiteral( fln.getDst(),
1704 newStringLiteralAlloc,
1705 newStringLiteralBytesAlloc,
1711 case FKind.FlatSESEEnterNode:
1712 sese = (FlatSESEEnterNode) fn;
1714 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1716 // always remove ALL stall site taints at enter
1717 rg.removeAllStallSiteTaints();
1719 // inject taints for in-set vars
1720 rg.taintInSetVars(sese);
1725 case FKind.FlatSESEExitNode:
1726 fsexn = (FlatSESEExitNode) fn;
1727 sese = fsexn.getFlatEnter();
1729 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1731 // @ sese exit make all live variables
1732 // inaccessible to later parent statements
1733 rg.makeInaccessible(liveness.getLiveInTemps(fmContaining, fn) );
1735 // always remove ALL stall site taints at exit
1736 rg.removeAllStallSiteTaints();
1738 // remove in-set var taints for the exiting rblock
1739 rg.removeInContextTaints(sese);
1744 case FKind.FlatCall: {
1745 Descriptor mdCaller;
1746 if( fmContaining.getMethod() != null ) {
1747 mdCaller = fmContaining.getMethod();
1749 mdCaller = fmContaining.getTask();
1751 FlatCall fc = (FlatCall) fn;
1752 MethodDescriptor mdCallee = fc.getMethod();
1753 FlatMethod fmCallee = state.getMethodFlat(mdCallee);
1756 if( doDefiniteReachAnalysis ) {
1757 definiteReachAnalysis.methodCall( fn, fc.getReturnTemp() );
1758 didDefReachTransfer = true;
1762 // the transformation for a call site should update the
1763 // current heap abstraction with any effects from the callee,
1764 // or if the method is virtual, the effects from any possible
1765 // callees, so find the set of callees...
1766 Set<MethodDescriptor> setPossibleCallees;
1767 if( determinismDesired ) {
1768 // use an ordered set
1769 setPossibleCallees = new TreeSet<MethodDescriptor>(dComp);
1771 // otherwise use a speedy hashset
1772 setPossibleCallees = new HashSet<MethodDescriptor>();
1775 if( mdCallee.isStatic() ) {
1776 setPossibleCallees.add(mdCallee);
1778 TypeDescriptor typeDesc = fc.getThis().getType();
1779 setPossibleCallees.addAll(callGraph.getMethods(mdCallee,
1785 DebugCallSiteData dcsd = new DebugCallSiteData();
1787 ReachGraph rgMergeOfPossibleCallers = new ReachGraph();
1790 Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
1791 while( mdItr.hasNext() ) {
1792 MethodDescriptor mdPossible = mdItr.next();
1793 FlatMethod fmPossible = state.getMethodFlat(mdPossible);
1795 addDependent(mdPossible, // callee
1799 // decide for each possible resolution of the method whether we
1800 // want to debug this call site
1801 decideDebugCallSite( dcsd, mdCaller, mdPossible );
1805 // calculate the heap this call site can reach--note this is
1806 // not used for the current call site transform, we are
1807 // grabbing this heap model for future analysis of the callees,
1808 // so if different results emerge we will return to this site
1809 ReachGraph heapForThisCall_old =
1810 getIHMcontribution(mdPossible, fc);
1812 // the computation of the callee-reachable heap
1813 // is useful for making the callee starting point
1814 // and for applying the call site transfer function
1815 Set<Integer> callerNodeIDsCopiedToCallee =
1816 new HashSet<Integer>();
1819 ReachGraph heapForThisCall_cur =
1820 rg.makeCalleeView(fc,
1822 callerNodeIDsCopiedToCallee,
1827 // enforce that a call site contribution can only
1828 // monotonically increase
1829 heapForThisCall_cur.merge(heapForThisCall_old);
1831 if( !heapForThisCall_cur.equals(heapForThisCall_old) ) {
1832 // if heap at call site changed, update the contribution,
1833 // and reschedule the callee for analysis
1834 addIHMcontribution(mdPossible, fc, heapForThisCall_cur);
1836 // map a FlatCall to its enclosing method/task descriptor
1837 // so we can write that info out later
1838 fc2enclosing.put(fc, mdCaller);
1840 if( state.DISJOINTDEBUGSCHEDULING ) {
1841 System.out.println(" context changed at callsite: "+fc+", scheduling callee: "+mdPossible);
1844 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1845 calleesToEnqueue.add(mdPossible);
1847 enqueue(mdPossible);
1854 // don't alter the working graph (rg) until we compute a
1855 // result for every possible callee, merge them all together,
1856 // then set rg to that
1857 ReachGraph rgPossibleCaller = new ReachGraph();
1858 rgPossibleCaller.merge(rg);
1860 ReachGraph rgPossibleCallee = getPartial(mdPossible);
1862 if( rgPossibleCallee == null ) {
1863 // if this method has never been analyzed just schedule it
1864 // for analysis and skip over this call site for now
1865 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1866 calleesToEnqueue.add(mdPossible);
1868 enqueue(mdPossible);
1871 if( state.DISJOINTDEBUGSCHEDULING ) {
1872 System.out.println(" callee hasn't been analyzed, scheduling: "+mdPossible);
1878 // calculate the method call transform
1879 rgPossibleCaller.resolveMethodCall(fc,
1882 callerNodeIDsCopiedToCallee,
1887 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1888 if( !accessible.isAccessible(fn, ReachGraph.tdReturn) ) {
1889 rgPossibleCaller.makeInaccessible(fc.getReturnTemp() );
1895 rgMergeOfPossibleCallers.merge(rgPossibleCaller);
1900 statusDebugCallSite( dcsd );
1904 // now that we've taken care of building heap models for
1905 // callee analysis, finish this transformation
1906 rg = rgMergeOfPossibleCallers;
1909 // jjenista: what is this? It breaks compilation
1910 // of programs with no tasks/SESEs/rblocks...
1911 //XXXXXXXXXXXXXXXXXXXXXXXXX
1912 //need to consider more
1913 if( state.OOOJAVA ) {
1914 FlatNode nextFN=fmCallee.getNext(0);
1915 if( nextFN instanceof FlatSESEEnterNode ) {
1916 FlatSESEEnterNode calleeSESE=(FlatSESEEnterNode)nextFN;
1917 if(!calleeSESE.getIsLeafSESE()) {
1918 rg.makeInaccessible(liveness.getLiveInTemps(fmContaining, fn) );
1926 case FKind.FlatReturnNode:
1927 FlatReturnNode frn = (FlatReturnNode) fn;
1928 rhs = frn.getReturnTemp();
1930 // before transfer, do effects analysis support
1931 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1932 if(!accessible.isAccessible(fn,rhs)) {
1933 rg.makeInaccessible(ReachGraph.tdReturn);
1937 if( rhs != null && shouldAnalysisTrack(rhs.getType() ) ) {
1938 rg.assignReturnEqualToTemp(rhs);
1941 setRetNodes.add(frn);
1948 if( doDefiniteReachAnalysis && !didDefReachTransfer ) {
1949 definiteReachAnalysis.otherStatement( fn );
1954 // dead variables were removed before the above transfer function
1955 // was applied, so eliminate heap regions and edges that are no
1956 // longer part of the abstractly-live heap graph, and sweep up
1957 // and reachability effects that are altered by the reduction
1958 //rg.abstractGarbageCollect();
1962 // back edges are strictly monotonic
1963 if( pm.isBackEdge(fn) ) {
1964 ReachGraph rgPrevResult = mapBackEdgeToMonotone.get(fn);
1965 rg.merge(rgPrevResult);
1966 mapBackEdgeToMonotone.put(fn, rg);
1970 ReachGraph rgOnExit = new ReachGraph();
1972 fn2rgAtExit.put(fn, rgOnExit);
1976 // at this point rg should be the correct update
1977 // by an above transfer function, or untouched if
1978 // the flat node type doesn't affect the heap
1984 // this method should generate integers strictly greater than zero!
1985 // special "shadow" regions are made from a heap region by negating
1987 static public Integer generateUniqueHeapRegionNodeID() {
1989 return new Integer(uniqueIDcount);
1994 static public FieldDescriptor getArrayField(TypeDescriptor tdElement) {
1995 FieldDescriptor fdElement = mapTypeToArrayField.get(tdElement);
1996 if( fdElement == null ) {
1997 fdElement = new FieldDescriptor(new Modifiers(Modifiers.PUBLIC),
1999 arrayElementFieldName,
2002 mapTypeToArrayField.put(tdElement, fdElement);
2009 private void writeFinalGraphs() {
2010 Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
2011 Iterator itr = entrySet.iterator();
2012 while( itr.hasNext() ) {
2013 Map.Entry me = (Map.Entry)itr.next();
2014 Descriptor d = (Descriptor) me.getKey();
2015 ReachGraph rg = (ReachGraph) me.getValue();
2018 if( d instanceof TaskDescriptor ) {
2019 graphName = "COMPLETEtask"+d;
2021 graphName = "COMPLETE"+d;
2024 rg.writeGraph(graphName,
2025 true, // write labels (variables)
2026 true, // selectively hide intermediate temp vars
2027 true, // prune unreachable heap regions
2028 true, // hide reachability altogether
2029 true, // hide subset reachability states
2030 true, // hide predicates
2031 false); // hide edge taints
2035 private void writeFinalIHMs() {
2036 Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
2037 while( d2IHMsItr.hasNext() ) {
2038 Map.Entry me1 = (Map.Entry)d2IHMsItr.next();
2039 Descriptor d = (Descriptor) me1.getKey();
2040 Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>)me1.getValue();
2042 Iterator fc2rgItr = IHMs.entrySet().iterator();
2043 while( fc2rgItr.hasNext() ) {
2044 Map.Entry me2 = (Map.Entry)fc2rgItr.next();
2045 FlatCall fc = (FlatCall) me2.getKey();
2046 ReachGraph rg = (ReachGraph) me2.getValue();
2048 rg.writeGraph("IHMPARTFOR"+d+"FROM"+fc2enclosing.get(fc)+fc,
2049 true, // write labels (variables)
2050 true, // selectively hide intermediate temp vars
2051 true, // hide reachability altogether
2052 true, // prune unreachable heap regions
2053 true, // hide subset reachability states
2054 false, // hide predicates
2055 true); // hide edge taints
2060 private void writeInitialContexts() {
2061 Set entrySet = mapDescriptorToInitialContext.entrySet();
2062 Iterator itr = entrySet.iterator();
2063 while( itr.hasNext() ) {
2064 Map.Entry me = (Map.Entry)itr.next();
2065 Descriptor d = (Descriptor) me.getKey();
2066 ReachGraph rg = (ReachGraph) me.getValue();
2068 rg.writeGraph("INITIAL"+d,
2069 true, // write labels (variables)
2070 true, // selectively hide intermediate temp vars
2071 true, // prune unreachable heap regions
2072 false, // hide all reachability
2073 true, // hide subset reachability states
2074 true, // hide predicates
2075 false); // hide edge taints
2079 private void writeFinalGraphsForEveryNode() {
2080 Set entrySet = mapFlatNodeToReachGraphPersist.entrySet();
2081 Iterator itr = entrySet.iterator();
2082 while( itr.hasNext() ) {
2083 Map.Entry me = (Map.Entry) itr.next();
2084 FlatNode fn = (FlatNode) me.getKey();
2085 ReachGraph rg = (ReachGraph) me.getValue();
2087 rg.writeGraph("NODEFINAL"+fn,
2088 true, // write labels (variables)
2089 false, // selectively hide intermediate temp vars
2090 true, // prune unreachable heap regions
2091 true, // hide all reachability
2092 true, // hide subset reachability states
2093 true, // hide predicates
2094 true); // hide edge taints
2099 protected ReachGraph getPartial(Descriptor d) {
2100 return mapDescriptorToCompleteReachGraph.get(d);
2103 protected void setPartial(Descriptor d, ReachGraph rg) {
2104 mapDescriptorToCompleteReachGraph.put(d, rg);
2106 // when the flag for writing out every partial
2107 // result is set, we should spit out the graph,
2108 // but in order to give it a unique name we need
2109 // to track how many partial results for this
2110 // descriptor we've already written out
2111 if( writeAllIncrementalDOTs ) {
2112 if( !mapDescriptorToNumUpdates.containsKey(d) ) {
2113 mapDescriptorToNumUpdates.put(d, new Integer(0) );
2115 Integer n = mapDescriptorToNumUpdates.get(d);
2118 if( d instanceof TaskDescriptor ) {
2119 graphName = d+"COMPLETEtask"+String.format("%05d", n);
2121 graphName = d+"COMPLETE"+String.format("%05d", n);
2124 rg.writeGraph(graphName,
2125 true, // write labels (variables)
2126 true, // selectively hide intermediate temp vars
2127 true, // prune unreachable heap regions
2128 false, // hide all reachability
2129 true, // hide subset reachability states
2130 false, // hide predicates
2131 false); // hide edge taints
2133 mapDescriptorToNumUpdates.put(d, n + 1);
2139 // return just the allocation site associated with one FlatNew node
2140 protected AllocSite getAllocSiteFromFlatNewPRIVATE(FlatNew fnew) {
2142 boolean flagProgrammatically = false;
2143 if( sitesToFlag != null && sitesToFlag.contains(fnew) ) {
2144 flagProgrammatically = true;
2147 if( !mapFlatNewToAllocSite.containsKey(fnew) ) {
2148 AllocSite as = AllocSite.factory(allocationDepth,
2150 fnew.getDisjointId(),
2151 flagProgrammatically
2154 // the newest nodes are single objects
2155 for( int i = 0; i < allocationDepth; ++i ) {
2156 Integer id = generateUniqueHeapRegionNodeID();
2157 as.setIthOldest(i, id);
2158 mapHrnIdToAllocSite.put(id, as);
2161 // the oldest node is a summary node
2162 as.setSummary(generateUniqueHeapRegionNodeID() );
2164 mapFlatNewToAllocSite.put(fnew, as);
2167 return mapFlatNewToAllocSite.get(fnew);
2171 public static boolean shouldAnalysisTrack(TypeDescriptor type) {
2172 // don't track primitive types, but an array
2173 // of primitives is heap memory
2174 if( type.isImmutable() ) {
2175 return type.isArray();
2178 // everything else is an object
2182 protected int numMethodsAnalyzed() {
2183 return descriptorsToAnalyze.size();
2189 // Take in source entry which is the program's compiled entry and
2190 // create a new analysis entry, a method that takes no parameters
2191 // and appears to allocate the command line arguments and call the
2192 // source entry with them. The purpose of this analysis entry is
2193 // to provide a top-level method context with no parameters left.
2194 protected void makeAnalysisEntryMethod(MethodDescriptor mdSourceEntry) {
2196 Modifiers mods = new Modifiers();
2197 mods.addModifier(Modifiers.PUBLIC);
2198 mods.addModifier(Modifiers.STATIC);
2200 TypeDescriptor returnType = new TypeDescriptor(TypeDescriptor.VOID);
2202 this.mdAnalysisEntry =
2203 new MethodDescriptor(mods,
2205 "analysisEntryMethod"
2208 TypeDescriptor argsType = mdSourceEntry.getParamType(0);
2209 TempDescriptor cmdLineArgs =
2210 new TempDescriptor("analysisEntryTemp_args",
2214 new FlatNew(argsType,
2218 this.constructedCmdLineArgsNew = fnArgs;
2220 TypeDescriptor argType = argsType.dereference();
2221 TempDescriptor anArg =
2222 new TempDescriptor("analysisEntryTemp_arg",
2226 new FlatNew(argType,
2230 this.constructedCmdLineArgNew = fnArg;
2232 TypeDescriptor typeIndex = new TypeDescriptor(TypeDescriptor.INT);
2233 TempDescriptor index =
2234 new TempDescriptor("analysisEntryTemp_index",
2237 FlatLiteralNode fli =
2238 new FlatLiteralNode(typeIndex,
2243 FlatSetElementNode fse =
2244 new FlatSetElementNode(cmdLineArgs,
2249 TypeDescriptor typeSize = new TypeDescriptor(TypeDescriptor.INT);
2250 TempDescriptor sizeBytes =
2251 new TempDescriptor("analysisEntryTemp_size",
2254 FlatLiteralNode fls =
2255 new FlatLiteralNode(typeSize,
2260 TempDescriptor strBytes =
2261 new TempDescriptor("analysisEntryTemp_strBytes",
2265 new FlatNew(stringBytesType,
2270 this.constructedCmdLineArgBytesNew = fnBytes;
2272 FlatSetFieldNode fsf =
2273 new FlatSetFieldNode(anArg,
2278 // throw this in so you can always see what the initial heap context
2279 // looks like if you want to, its cheap
2280 FlatGenReachNode fgen = new FlatGenReachNode( "argContext" );
2282 TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
2283 sourceEntryArgs[0] = cmdLineArgs;
2285 new FlatCall(mdSourceEntry,
2291 FlatReturnNode frn = new FlatReturnNode(null);
2293 FlatExit fe = new FlatExit();
2295 this.fmAnalysisEntry =
2296 new FlatMethod(mdAnalysisEntry,
2300 List<FlatNode> nodes = new LinkedList<FlatNode>();
2301 nodes.add( fnArgs );
2306 nodes.add( fnBytes );
2313 FlatNode current = this.fmAnalysisEntry;
2314 for( FlatNode next: nodes ) {
2315 current.addNext( next );
2320 // jjenista - this is useful for looking at the FlatIRGraph of the
2321 // analysis entry method constructed above if you have to modify it.
2322 // The usual method of writing FlatIRGraphs out doesn't work because
2323 // this flat method is private to the model of this analysis only.
2325 // FlatIRGraph flatMethodWriter =
2326 // new FlatIRGraph( state, false, false, false );
2327 // flatMethodWriter.writeFlatIRGraph( fmAnalysisEntry, "analysisEntry" );
2328 //} catch( IOException e ) {}
2332 protected LinkedList<Descriptor> topologicalSort(Set<Descriptor> toSort) {
2334 Set<Descriptor> discovered;
2336 if( determinismDesired ) {
2337 // use an ordered set
2338 discovered = new TreeSet<Descriptor>(dComp);
2340 // otherwise use a speedy hashset
2341 discovered = new HashSet<Descriptor>();
2344 LinkedList<Descriptor> sorted = new LinkedList<Descriptor>();
2346 Iterator<Descriptor> itr = toSort.iterator();
2347 while( itr.hasNext() ) {
2348 Descriptor d = itr.next();
2350 if( !discovered.contains(d) ) {
2351 dfsVisit(d, toSort, sorted, discovered);
2358 // While we're doing DFS on call graph, remember
2359 // dependencies for efficient queuing of methods
2360 // during interprocedural analysis:
2362 // a dependent of a method decriptor d for this analysis is:
2363 // 1) a method or task that invokes d
2364 // 2) in the descriptorsToAnalyze set
2365 protected void dfsVisit(Descriptor d,
2366 Set <Descriptor> toSort,
2367 LinkedList<Descriptor> sorted,
2368 Set <Descriptor> discovered) {
2371 // only methods have callers, tasks never do
2372 if( d instanceof MethodDescriptor ) {
2374 MethodDescriptor md = (MethodDescriptor) d;
2376 // the call graph is not aware that we have a fabricated
2377 // analysis entry that calls the program source's entry
2378 if( md == mdSourceEntry ) {
2379 if( !discovered.contains(mdAnalysisEntry) ) {
2380 addDependent(mdSourceEntry, // callee
2381 mdAnalysisEntry // caller
2383 dfsVisit(mdAnalysisEntry, toSort, sorted, discovered);
2387 // otherwise call graph guides DFS
2388 Iterator itr = callGraph.getCallerSet(md).iterator();
2389 while( itr.hasNext() ) {
2390 Descriptor dCaller = (Descriptor) itr.next();
2392 // only consider callers in the original set to analyze
2393 if( !toSort.contains(dCaller) ) {
2397 if( !discovered.contains(dCaller) ) {
2398 addDependent(md, // callee
2402 dfsVisit(dCaller, toSort, sorted, discovered);
2407 // for leaf-nodes last now!
2412 protected void enqueue(Descriptor d) {
2414 if( !descriptorsToVisitSet.contains(d) ) {
2416 if( state.DISJOINTDVISITSTACK ||
2417 state.DISJOINTDVISITSTACKEESONTOP
2419 descriptorsToVisitStack.add(d);
2421 } else if( state.DISJOINTDVISITPQUE ) {
2422 Integer priority = mapDescriptorToPriority.get(d);
2423 descriptorsToVisitQ.add(new DescriptorQWrapper(priority,
2428 descriptorsToVisitSet.add(d);
2433 // a dependent of a method decriptor d for this analysis is:
2434 // 1) a method or task that invokes d
2435 // 2) in the descriptorsToAnalyze set
2436 protected void addDependent(Descriptor callee, Descriptor caller) {
2437 Set<Descriptor> deps = mapDescriptorToSetDependents.get(callee);
2438 if( deps == null ) {
2439 deps = new HashSet<Descriptor>();
2442 mapDescriptorToSetDependents.put(callee, deps);
2445 protected Set<Descriptor> getDependents(Descriptor callee) {
2446 Set<Descriptor> deps = mapDescriptorToSetDependents.get(callee);
2447 if( deps == null ) {
2448 deps = new HashSet<Descriptor>();
2449 mapDescriptorToSetDependents.put(callee, deps);
2455 public Hashtable<FlatCall, ReachGraph> getIHMcontributions(Descriptor d) {
2457 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2458 mapDescriptorToIHMcontributions.get(d);
2460 if( heapsFromCallers == null ) {
2461 heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
2462 mapDescriptorToIHMcontributions.put(d, heapsFromCallers);
2465 return heapsFromCallers;
2468 public ReachGraph getIHMcontribution(Descriptor d,
2471 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2472 getIHMcontributions(d);
2474 if( !heapsFromCallers.containsKey(fc) ) {
2478 return heapsFromCallers.get(fc);
2482 public void addIHMcontribution(Descriptor d,
2486 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2487 getIHMcontributions(d);
2489 // ensure inputs to initial contexts increase monotonically
2490 ReachGraph merged = new ReachGraph();
2492 merged.merge( heapsFromCallers.get( fc ) );
2494 heapsFromCallers.put( fc, merged );
2499 private AllocSite createParameterAllocSite(ReachGraph rg,
2500 TempDescriptor tempDesc,
2506 flatNew = new FlatNew(tempDesc.getType(), // type
2507 tempDesc, // param temp
2508 false, // global alloc?
2509 "param"+tempDesc // disjoint site ID string
2512 flatNew = new FlatNew(tempDesc.getType(), // type
2513 tempDesc, // param temp
2514 false, // global alloc?
2515 null // disjoint site ID string
2519 // create allocation site
2520 AllocSite as = AllocSite.factory(allocationDepth,
2522 flatNew.getDisjointId(),
2525 for (int i = 0; i < allocationDepth; ++i) {
2526 Integer id = generateUniqueHeapRegionNodeID();
2527 as.setIthOldest(i, id);
2528 mapHrnIdToAllocSite.put(id, as);
2530 // the oldest node is a summary node
2531 as.setSummary(generateUniqueHeapRegionNodeID() );
2539 private Set<FieldDescriptor> getFieldSetTobeAnalyzed(TypeDescriptor typeDesc) {
2541 Set<FieldDescriptor> fieldSet=new HashSet<FieldDescriptor>();
2542 if(!typeDesc.isImmutable()) {
2543 ClassDescriptor classDesc = typeDesc.getClassDesc();
2544 for (Iterator it = classDesc.getFields(); it.hasNext(); ) {
2545 FieldDescriptor field = (FieldDescriptor) it.next();
2546 TypeDescriptor fieldType = field.getType();
2547 if (shouldAnalysisTrack(fieldType)) {
2548 fieldSet.add(field);
2556 private HeapRegionNode createMultiDeimensionalArrayHRN(ReachGraph rg, AllocSite alloc, HeapRegionNode srcHRN, FieldDescriptor fd, Hashtable<HeapRegionNode, HeapRegionNode> map, Hashtable<TypeDescriptor, HeapRegionNode> mapToExistingNode, ReachSet alpha) {
2558 int dimCount=fd.getType().getArrayCount();
2559 HeapRegionNode prevNode=null;
2560 HeapRegionNode arrayEntryNode=null;
2561 for(int i=dimCount; i>0; i--) {
2562 TypeDescriptor typeDesc=fd.getType().dereference(); //hack to get instance of type desc
2563 typeDesc.setArrayCount(i);
2564 TempDescriptor tempDesc=new TempDescriptor(typeDesc.getSymbol(),typeDesc);
2565 HeapRegionNode hrnSummary;
2566 if(!mapToExistingNode.containsKey(typeDesc)) {
2571 as = createParameterAllocSite(rg, tempDesc, false);
2573 // make a new reference to allocated node
2575 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
2576 false, // single object?
2578 false, // out-of-context?
2579 as.getType(), // type
2580 as, // allocation site
2581 alpha, // inherent reach
2582 alpha, // current reach
2583 ExistPredSet.factory(rg.predTrue), // predicates
2584 tempDesc.toString() // description
2586 rg.id2hrn.put(as.getSummary(),hrnSummary);
2588 mapToExistingNode.put(typeDesc, hrnSummary);
2590 hrnSummary=mapToExistingNode.get(typeDesc);
2593 if(prevNode==null) {
2594 // make a new reference between new summary node and source
2595 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2598 fd.getSymbol(), // field name
2600 ExistPredSet.factory(rg.predTrue), // predicates
2604 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
2605 prevNode=hrnSummary;
2606 arrayEntryNode=hrnSummary;
2608 // make a new reference between summary nodes of array
2609 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2612 arrayElementFieldName, // field name
2614 ExistPredSet.factory(rg.predTrue), // predicates
2618 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2619 prevNode=hrnSummary;
2624 // create a new obj node if obj has at least one non-primitive field
2625 TypeDescriptor type=fd.getType();
2626 if(getFieldSetTobeAnalyzed(type).size()>0) {
2627 TypeDescriptor typeDesc=type.dereference();
2628 typeDesc.setArrayCount(0);
2629 if(!mapToExistingNode.containsKey(typeDesc)) {
2630 TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc);
2631 AllocSite as = createParameterAllocSite(rg, tempDesc, false);
2632 // make a new reference to allocated node
2633 HeapRegionNode hrnSummary =
2634 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
2635 false, // single object?
2637 false, // out-of-context?
2639 as, // allocation site
2640 alpha, // inherent reach
2641 alpha, // current reach
2642 ExistPredSet.factory(rg.predTrue), // predicates
2643 tempDesc.toString() // description
2645 rg.id2hrn.put(as.getSummary(),hrnSummary);
2646 mapToExistingNode.put(typeDesc, hrnSummary);
2647 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2650 arrayElementFieldName, // field name
2652 ExistPredSet.factory(rg.predTrue), // predicates
2655 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2656 prevNode=hrnSummary;
2658 HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc);
2659 if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null) {
2660 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2663 arrayElementFieldName, // field name
2665 ExistPredSet.factory(rg.predTrue), // predicates
2668 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2670 prevNode=hrnSummary;
2674 map.put(arrayEntryNode, prevNode);
2675 return arrayEntryNode;
2678 private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
2679 ReachGraph rg = new ReachGraph();
2680 TaskDescriptor taskDesc = fm.getTask();
2682 for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
2683 Descriptor paramDesc = taskDesc.getParameter(idx);
2684 TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
2686 // setup data structure
2687 Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet =
2688 new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
2689 Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode =
2690 new Hashtable<TypeDescriptor, HeapRegionNode>();
2691 Hashtable<HeapRegionNode, HeapRegionNode> mapToFirstDimensionArrayNode =
2692 new Hashtable<HeapRegionNode, HeapRegionNode>();
2693 Set<String> doneSet = new HashSet<String>();
2695 TempDescriptor tempDesc = fm.getParameter(idx);
2697 AllocSite as = createParameterAllocSite(rg, tempDesc, true);
2698 VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
2699 Integer idNewest = as.getIthOldest(0);
2700 HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
2702 // make a new reference to allocated node
2703 RefEdge edgeNew = new RefEdge(lnX, // source
2705 taskDesc.getParamType(idx), // type
2707 hrnNewest.getAlpha(), // beta
2708 ExistPredSet.factory(rg.predTrue), // predicates
2711 rg.addRefEdge(lnX, hrnNewest, edgeNew);
2713 // set-up a work set for class field
2714 ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
2715 for (Iterator it = classDesc.getFields(); it.hasNext(); ) {
2716 FieldDescriptor fd = (FieldDescriptor) it.next();
2717 TypeDescriptor fieldType = fd.getType();
2718 if (shouldAnalysisTrack(fieldType)) {
2719 HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
2720 newMap.put(hrnNewest, fd);
2721 workSet.add(newMap);
2725 int uniqueIdentifier = 0;
2726 while (!workSet.isEmpty()) {
2727 HashMap<HeapRegionNode, FieldDescriptor> map = workSet
2729 workSet.remove(map);
2731 Set<HeapRegionNode> key = map.keySet();
2732 HeapRegionNode srcHRN = key.iterator().next();
2733 FieldDescriptor fd = map.get(srcHRN);
2734 TypeDescriptor type = fd.getType();
2735 String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
2737 if (!doneSet.contains(doneSetIdentifier)) {
2738 doneSet.add(doneSetIdentifier);
2739 if (!mapTypeToExistingSummaryNode.containsKey(type)) {
2740 // create new summary Node
2741 TempDescriptor td = new TempDescriptor("temp"
2742 + uniqueIdentifier, type);
2744 AllocSite allocSite;
2745 if(type.equals(paramTypeDesc)) {
2746 //corresponding allocsite has already been created for a parameter variable.
2749 allocSite = createParameterAllocSite(rg, td, false);
2751 String strDesc = allocSite.toStringForDOT()
2753 TypeDescriptor allocType=allocSite.getType();
2755 HeapRegionNode hrnSummary;
2756 if(allocType.isArray() && allocType.getArrayCount()>0) {
2757 hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha());
2760 rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
2761 false, // single object?
2763 false, // out-of-context?
2764 allocSite.getType(), // type
2765 allocSite, // allocation site
2766 hrnNewest.getAlpha(), // inherent reach
2767 hrnNewest.getAlpha(), // current reach
2768 ExistPredSet.factory(rg.predTrue), // predicates
2769 strDesc // description
2771 rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
2773 // make a new reference to summary node
2774 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2777 fd.getSymbol(), // field name
2778 hrnNewest.getAlpha(), // beta
2779 ExistPredSet.factory(rg.predTrue), // predicates
2783 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
2787 mapTypeToExistingSummaryNode.put(type, hrnSummary);
2789 // set-up a work set for fields of the class
2790 Set<FieldDescriptor> fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type);
2791 for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator
2793 FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator
2795 HeapRegionNode newDstHRN;
2796 if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)) {
2797 //related heap region node is already exsited.
2798 newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary);
2800 newDstHRN=hrnSummary;
2802 doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor;
2803 if(!doneSet.contains(doneSetIdentifier)) {
2804 // add new work item
2805 HashMap<HeapRegionNode, FieldDescriptor> newMap =
2806 new HashMap<HeapRegionNode, FieldDescriptor>();
2807 newMap.put(newDstHRN, fieldDescriptor);
2808 workSet.add(newMap);
2813 // if there exists corresponding summary node
2814 HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
2816 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2818 fd.getType(), // type
2819 fd.getSymbol(), // field name
2820 srcHRN.getAlpha(), // beta
2821 ExistPredSet.factory(rg.predTrue), // predicates
2824 rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
2834 // return all allocation sites in the method (there is one allocation
2835 // site per FlatNew node in a method)
2836 private HashSet<AllocSite> getAllocationSiteSet(Descriptor d) {
2837 if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
2838 buildAllocationSiteSet(d);
2841 return mapDescriptorToAllocSiteSet.get(d);
2845 private void buildAllocationSiteSet(Descriptor d) {
2846 HashSet<AllocSite> s = new HashSet<AllocSite>();
2849 if( d instanceof MethodDescriptor ) {
2850 fm = state.getMethodFlat( (MethodDescriptor) d);
2852 assert d instanceof TaskDescriptor;
2853 fm = state.getMethodFlat( (TaskDescriptor) d);
2855 pm.analyzeMethod(fm);
2857 // visit every node in this FlatMethod's IR graph
2858 // and make a set of the allocation sites from the
2859 // FlatNew node's visited
2860 HashSet<FlatNode> visited = new HashSet<FlatNode>();
2861 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
2864 while( !toVisit.isEmpty() ) {
2865 FlatNode n = toVisit.iterator().next();
2867 if( n instanceof FlatNew ) {
2868 s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
2874 for( int i = 0; i < pm.numNext(n); ++i ) {
2875 FlatNode child = pm.getNext(n, i);
2876 if( !visited.contains(child) ) {
2882 mapDescriptorToAllocSiteSet.put(d, s);
2885 private HashSet<AllocSite> getFlaggedAllocationSites(Descriptor dIn) {
2887 HashSet<AllocSite> out = new HashSet<AllocSite>();
2888 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2889 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2893 while (!toVisit.isEmpty()) {
2894 Descriptor d = toVisit.iterator().next();
2898 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2899 Iterator asItr = asSet.iterator();
2900 while (asItr.hasNext()) {
2901 AllocSite as = (AllocSite) asItr.next();
2902 if (as.getDisjointAnalysisId() != null) {
2907 // enqueue callees of this method to be searched for
2908 // allocation sites also
2909 Set callees = callGraph.getCalleeSet(d);
2910 if (callees != null) {
2911 Iterator methItr = callees.iterator();
2912 while (methItr.hasNext()) {
2913 MethodDescriptor md = (MethodDescriptor) methItr.next();
2915 if (!visited.contains(md)) {
2926 private HashSet<AllocSite>
2927 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
2929 HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
2930 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2931 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2935 // traverse this task and all methods reachable from this task
2936 while( !toVisit.isEmpty() ) {
2937 Descriptor d = toVisit.iterator().next();
2941 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2942 Iterator asItr = asSet.iterator();
2943 while( asItr.hasNext() ) {
2944 AllocSite as = (AllocSite) asItr.next();
2945 TypeDescriptor typed = as.getType();
2946 if( typed != null ) {
2947 ClassDescriptor cd = typed.getClassDesc();
2948 if( cd != null && cd.hasFlags() ) {
2954 // enqueue callees of this method to be searched for
2955 // allocation sites also
2956 Set callees = callGraph.getCalleeSet(d);
2957 if( callees != null ) {
2958 Iterator methItr = callees.iterator();
2959 while( methItr.hasNext() ) {
2960 MethodDescriptor md = (MethodDescriptor) methItr.next();
2962 if( !visited.contains(md) ) {
2972 public Set<Descriptor> getDescriptorsToAnalyze() {
2973 return descriptorsToAnalyze;
2976 public EffectsAnalysis getEffectsAnalysis() {
2977 return effectsAnalysis;
2980 public ReachGraph getReachGraph(Descriptor d) {
2981 return mapDescriptorToCompleteReachGraph.get(d);
2984 public ReachGraph getEnterReachGraph(FlatNode fn) {
2985 return fn2rgAtEnter.get(fn);
2990 protected class DebugCallSiteData {
2991 public boolean debugCallSite;
2992 public boolean didOneDebug;
2993 public boolean writeDebugDOTs;
2994 public boolean stopAfter;
2996 public DebugCallSiteData() {
2997 debugCallSite = false;
2998 didOneDebug = false;
2999 writeDebugDOTs = false;
3004 protected void decideDebugCallSite( DebugCallSiteData dcsd,
3005 Descriptor taskOrMethodCaller,
3006 MethodDescriptor mdCallee ) {
3008 // all this jimma jamma to debug call sites is WELL WORTH the
3009 // effort, so so so many bugs or buggy info appears through call
3012 if( state.DISJOINTDEBUGCALLEE == null ||
3013 state.DISJOINTDEBUGCALLER == null ) {
3018 boolean debugCalleeMatches = false;
3019 boolean debugCallerMatches = false;
3021 ClassDescriptor cdCallee = mdCallee.getClassDesc();
3022 if( cdCallee != null ) {
3023 debugCalleeMatches =
3024 state.DISJOINTDEBUGCALLEE.equals( cdCallee.getSymbol()+
3026 mdCallee.getSymbol()
3031 if( taskOrMethodCaller instanceof MethodDescriptor ) {
3032 ClassDescriptor cdCaller = ((MethodDescriptor)taskOrMethodCaller).getClassDesc();
3033 if( cdCaller != null ) {
3034 debugCallerMatches =
3035 state.DISJOINTDEBUGCALLER.equals( cdCaller.getSymbol()+
3037 taskOrMethodCaller.getSymbol()
3041 // for bristlecone style tasks
3042 debugCallerMatches =
3043 state.DISJOINTDEBUGCALLER.equals( taskOrMethodCaller.getSymbol() );
3047 dcsd.debugCallSite = debugCalleeMatches && debugCallerMatches;
3050 dcsd.writeDebugDOTs =
3052 dcsd.debugCallSite &&
3054 (ReachGraph.debugCallSiteVisitCounter >=
3055 ReachGraph.debugCallSiteVisitStartCapture) &&
3057 (ReachGraph.debugCallSiteVisitCounter <
3058 ReachGraph.debugCallSiteVisitStartCapture +
3059 ReachGraph.debugCallSiteNumVisitsToCapture);
3063 if( dcsd.debugCallSite ) {
3064 dcsd.didOneDebug = true;
3068 protected void statusDebugCallSite( DebugCallSiteData dcsd ) {
3070 dcsd.writeDebugDOTs = false;
3071 dcsd.stopAfter = false;
3073 if( dcsd.didOneDebug ) {
3074 System.out.println(" $$$ Debug call site visit "+
3075 ReachGraph.debugCallSiteVisitCounter+
3079 (ReachGraph.debugCallSiteVisitCounter >=
3080 ReachGraph.debugCallSiteVisitStartCapture) &&
3082 (ReachGraph.debugCallSiteVisitCounter <
3083 ReachGraph.debugCallSiteVisitStartCapture +
3084 ReachGraph.debugCallSiteNumVisitsToCapture)
3086 dcsd.writeDebugDOTs = true;
3087 System.out.println(" $$$ Capturing this call site visit $$$");
3088 if( ReachGraph.debugCallSiteStopAfter &&
3089 (ReachGraph.debugCallSiteVisitCounter ==
3090 ReachGraph.debugCallSiteVisitStartCapture +
3091 ReachGraph.debugCallSiteNumVisitsToCapture - 1)
3093 dcsd.stopAfter = true;
3097 ++ReachGraph.debugCallSiteVisitCounter;
3100 if( dcsd.stopAfter ) {
3101 System.out.println("$$$ Exiting after requested captures of call site. $$$");
3110 // get successive captures of the analysis state, use compiler
3112 boolean takeDebugSnapshots = false;
3113 String descSymbolDebug = null;
3114 boolean stopAfterCapture = false;
3115 int snapVisitCounter = 0;
3116 int snapNodeCounter = 0;
3117 int visitStartCapture = 0;
3118 int numVisitsToCapture = 0;
3121 void debugSnapshot(ReachGraph rg, FlatNode fn, boolean in) {
3122 if( snapVisitCounter > visitStartCapture + numVisitsToCapture ) {
3130 if( snapVisitCounter >= visitStartCapture ) {
3131 System.out.println(" @@@ snapping visit="+snapVisitCounter+
3132 ", node="+snapNodeCounter+
3136 graphName = String.format("snap%03d_%04din",
3140 graphName = String.format("snap%03d_%04dout",
3145 graphName = graphName + fn;
3147 rg.writeGraph(graphName,
3148 true, // write labels (variables)
3149 true, // selectively hide intermediate temp vars
3150 true, // prune unreachable heap regions
3151 false, // hide reachability
3152 true, // hide subset reachability states
3153 true, // hide predicates
3154 true); // hide edge taints
3161 public Set<Alloc> canPointToAt( TempDescriptor x,
3162 FlatNode programPoint ) {
3164 ReachGraph rgAtEnter = fn2rgAtEnter.get( programPoint );
3165 if( rgAtEnter == null ) {
3169 return rgAtEnter.canPointTo( x );
3173 public Hashtable< Alloc, Set<Alloc> > canPointToAt( TempDescriptor x,
3175 FlatNode programPoint ) {
3177 ReachGraph rgAtEnter = fn2rgAtEnter.get( programPoint );
3178 if( rgAtEnter == null ) {
3182 return rgAtEnter.canPointTo( x, f.getSymbol(), f.getType() );
3186 public Hashtable< Alloc, Set<Alloc> > canPointToAtElement( TempDescriptor x,
3187 FlatNode programPoint ) {
3189 ReachGraph rgAtEnter = fn2rgAtEnter.get( programPoint );
3190 if( rgAtEnter == null ) {
3194 assert x.getType() != null;
3195 assert x.getType().isArray();
3197 return rgAtEnter.canPointTo( x, arrayElementFieldName, x.getType().dereference() );
3201 public Set<Alloc> canPointToAfter( TempDescriptor x,
3202 FlatNode programPoint ) {
3204 ReachGraph rgAtExit = fn2rgAtExit.get( programPoint );
3206 if( rgAtExit == null ) {
3210 return rgAtExit.canPointTo( x );
3214 public Hashtable< Alloc, Set<Alloc> > canPointToAfter( TempDescriptor x,
3216 FlatNode programPoint ) {
3218 ReachGraph rgAtExit = fn2rgAtExit.get( programPoint );
3219 if( rgAtExit == null ) {
3223 return rgAtExit.canPointTo( x, f.getSymbol(), f.getType() );
3227 public Hashtable< Alloc, Set<Alloc> > canPointToAfterElement( TempDescriptor x,
3228 FlatNode programPoint ) {
3230 ReachGraph rgAtExit = fn2rgAtExit.get( programPoint );
3231 if( rgAtExit == null ) {
3235 assert x.getType() != null;
3236 assert x.getType().isArray();
3238 return rgAtExit.canPointTo( x, arrayElementFieldName, x.getType().dereference() );