1 package Analysis.Disjoint;
3 import Analysis.CallGraph.*;
4 import Analysis.Liveness;
5 import Analysis.ArrayReferencees;
8 import IR.Tree.Modifiers;
13 public class DisjointAnalysis {
15 ///////////////////////////////////////////
17 // Public interface to discover possible
18 // aliases in the program under analysis
20 ///////////////////////////////////////////
22 public HashSet<AllocSite>
23 getFlaggedAllocationSitesReachableFromTask(TaskDescriptor td) {
24 checkAnalysisComplete();
25 return getFlaggedAllocationSitesReachableFromTaskPRIVATE(td);
28 public AllocSite getAllocationSiteFromFlatNew(FlatNew fn) {
29 checkAnalysisComplete();
30 return getAllocSiteFromFlatNewPRIVATE(fn);
33 public AllocSite getAllocationSiteFromHeapRegionNodeID(Integer id) {
34 checkAnalysisComplete();
35 return mapHrnIdToAllocSite.get(id);
38 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
41 checkAnalysisComplete();
42 ReachGraph rg=mapDescriptorToCompleteReachGraph.get(taskOrMethod);
43 FlatMethod fm=state.getMethodFlat(taskOrMethod);
45 return rg.mayReachSharedObjects(fm, paramIndex1, paramIndex2);
48 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
49 int paramIndex, AllocSite alloc) {
50 checkAnalysisComplete();
51 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
52 FlatMethod fm=state.getMethodFlat(taskOrMethod);
54 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
57 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
58 AllocSite alloc, int paramIndex) {
59 checkAnalysisComplete();
60 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
61 FlatMethod fm=state.getMethodFlat(taskOrMethod);
63 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
66 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
67 AllocSite alloc1, AllocSite alloc2) {
68 checkAnalysisComplete();
69 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
71 return rg.mayReachSharedObjects(alloc1, alloc2);
74 public String prettyPrintNodeSet(Set<HeapRegionNode> s) {
75 checkAnalysisComplete();
79 Iterator<HeapRegionNode> i = s.iterator();
81 HeapRegionNode n = i.next();
83 AllocSite as = n.getAllocSite();
85 out += " " + n.toString() + ",\n";
87 out += " " + n.toString() + ": " + as.toStringVerbose()
96 // use the methods given above to check every possible sharing class
97 // between task parameters and flagged allocation sites reachable
99 public void writeAllSharing(String outputFile,
102 boolean tabularOutput,
105 throws java.io.IOException {
106 checkAnalysisComplete();
108 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
110 if (!tabularOutput) {
111 bw.write("Conducting ownership analysis with allocation depth = "
112 + allocationDepth + "\n");
113 bw.write(timeReport + "\n");
118 // look through every task for potential sharing
119 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
120 while (taskItr.hasNext()) {
121 TaskDescriptor td = (TaskDescriptor) taskItr.next();
123 if (!tabularOutput) {
124 bw.write("\n---------" + td + "--------\n");
127 HashSet<AllocSite> allocSites = getFlaggedAllocationSitesReachableFromTask(td);
129 Set<HeapRegionNode> common;
131 // for each task parameter, check for sharing classes with
132 // other task parameters and every allocation site
133 // reachable from this task
134 boolean foundSomeSharing = false;
136 FlatMethod fm = state.getMethodFlat(td);
137 for (int i = 0; i < fm.numParameters(); ++i) {
139 // skip parameters with types that cannot reference
141 if( !shouldAnalysisTrack( fm.getParameter( i ).getType() ) ) {
145 // for the ith parameter check for sharing classes to all
146 // higher numbered parameters
147 for (int j = i + 1; j < fm.numParameters(); ++j) {
149 // skip parameters with types that cannot reference
151 if( !shouldAnalysisTrack( fm.getParameter( j ).getType() ) ) {
156 common = hasPotentialSharing(td, i, j);
157 if (!common.isEmpty()) {
158 foundSomeSharing = true;
160 if (!tabularOutput) {
161 bw.write("Potential sharing between parameters " + i
162 + " and " + j + ".\n");
163 bw.write(prettyPrintNodeSet(common) + "\n");
168 // for the ith parameter, check for sharing classes against
169 // the set of allocation sites reachable from this
171 Iterator allocItr = allocSites.iterator();
172 while (allocItr.hasNext()) {
173 AllocSite as = (AllocSite) allocItr.next();
174 common = hasPotentialSharing(td, i, as);
175 if (!common.isEmpty()) {
176 foundSomeSharing = true;
178 if (!tabularOutput) {
179 bw.write("Potential sharing between parameter " + i
180 + " and " + as.getFlatNew() + ".\n");
181 bw.write(prettyPrintNodeSet(common) + "\n");
187 // for each allocation site check for sharing classes with
188 // other allocation sites in the context of execution
190 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
191 Iterator allocItr1 = allocSites.iterator();
192 while (allocItr1.hasNext()) {
193 AllocSite as1 = (AllocSite) allocItr1.next();
195 Iterator allocItr2 = allocSites.iterator();
196 while (allocItr2.hasNext()) {
197 AllocSite as2 = (AllocSite) allocItr2.next();
199 if (!outerChecked.contains(as2)) {
200 common = hasPotentialSharing(td, as1, as2);
202 if (!common.isEmpty()) {
203 foundSomeSharing = true;
205 if (!tabularOutput) {
206 bw.write("Potential sharing between "
207 + as1.getFlatNew() + " and "
208 + as2.getFlatNew() + ".\n");
209 bw.write(prettyPrintNodeSet(common) + "\n");
215 outerChecked.add(as1);
218 if (!foundSomeSharing) {
219 if (!tabularOutput) {
220 bw.write("No sharing between flagged objects in Task " + td
228 bw.write(" & " + numSharing + " & " + justTime + " & " + numLines
229 + " & " + numMethodsAnalyzed() + " \\\\\n");
231 bw.write("\nNumber sharing classes: "+numSharing);
237 // this version of writeAllSharing is for Java programs that have no tasks
238 public void writeAllSharingJava(String outputFile,
241 boolean tabularOutput,
244 throws java.io.IOException {
245 checkAnalysisComplete();
251 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
253 bw.write("Conducting disjoint reachability analysis with allocation depth = "
254 + allocationDepth + "\n");
255 bw.write(timeReport + "\n\n");
257 boolean foundSomeSharing = false;
259 Descriptor d = typeUtil.getMain();
260 HashSet<AllocSite> allocSites = getFlaggedAllocationSites(d);
262 // for each allocation site check for sharing classes with
263 // other allocation sites in the context of execution
265 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
266 Iterator allocItr1 = allocSites.iterator();
267 while (allocItr1.hasNext()) {
268 AllocSite as1 = (AllocSite) allocItr1.next();
270 Iterator allocItr2 = allocSites.iterator();
271 while (allocItr2.hasNext()) {
272 AllocSite as2 = (AllocSite) allocItr2.next();
274 if (!outerChecked.contains(as2)) {
275 Set<HeapRegionNode> common = hasPotentialSharing(d,
278 if (!common.isEmpty()) {
279 foundSomeSharing = true;
280 bw.write("Potential sharing between "
281 + as1.getDisjointAnalysisId() + " and "
282 + as2.getDisjointAnalysisId() + ".\n");
283 bw.write(prettyPrintNodeSet(common) + "\n");
289 outerChecked.add(as1);
292 if (!foundSomeSharing) {
293 bw.write("No sharing classes between flagged objects found.\n");
295 bw.write("\nNumber sharing classes: "+numSharing);
298 bw.write("Number of methods analyzed: "+numMethodsAnalyzed()+"\n");
303 ///////////////////////////////////////////
305 // end public interface
307 ///////////////////////////////////////////
309 protected void checkAnalysisComplete() {
310 if( !analysisComplete ) {
311 throw new Error("Warning: public interface method called while analysis is running.");
316 // run in faster mode, only when bugs wrung out!
317 public static boolean releaseMode;
319 // use command line option to set this, analysis
320 // should attempt to be deterministic
321 public static boolean determinismDesired;
323 // when we want to enforce determinism in the
324 // analysis we need to sort descriptors rather
325 // than toss them in efficient sets, use this
326 public static DescriptorComparator dComp =
327 new DescriptorComparator();
330 // data from the compiler
332 public CallGraph callGraph;
333 public Liveness liveness;
334 public ArrayReferencees arrayReferencees;
335 public TypeUtil typeUtil;
336 public int allocationDepth;
338 // data structure for public interface
339 private Hashtable< Descriptor, HashSet<AllocSite> >
340 mapDescriptorToAllocSiteSet;
343 // for public interface methods to warn that they
344 // are grabbing results during analysis
345 private boolean analysisComplete;
348 // used to identify HeapRegionNode objects
349 // A unique ID equates an object in one
350 // ownership graph with an object in another
351 // graph that logically represents the same
353 // start at 10 and increment to reserve some
354 // IDs for special purposes
355 static protected int uniqueIDcount = 10;
358 // An out-of-scope method created by the
359 // analysis that has no parameters, and
360 // appears to allocate the command line
361 // arguments, then invoke the source code's
362 // main method. The purpose of this is to
363 // provide the analysis with an explicit
364 // top-level context with no parameters
365 protected MethodDescriptor mdAnalysisEntry;
366 protected FlatMethod fmAnalysisEntry;
368 // main method defined by source program
369 protected MethodDescriptor mdSourceEntry;
371 // the set of task and/or method descriptors
372 // reachable in call graph
373 protected Set<Descriptor>
374 descriptorsToAnalyze;
376 // current descriptors to visit in fixed-point
377 // interprocedural analysis, prioritized by
378 // dependency in the call graph
379 protected Stack<Descriptor>
380 descriptorsToVisitStack;
381 protected PriorityQueue<DescriptorQWrapper>
384 // a duplication of the above structure, but
385 // for efficient testing of inclusion
386 protected HashSet<Descriptor>
387 descriptorsToVisitSet;
389 // storage for priorities (doesn't make sense)
390 // to add it to the Descriptor class, just in
392 protected Hashtable<Descriptor, Integer>
393 mapDescriptorToPriority;
395 // when analyzing a method and scheduling more:
396 // remember set of callee's enqueued for analysis
397 // so they can be put on top of the callers in
398 // the stack-visit mode
399 protected Set<Descriptor>
402 // maps a descriptor to its current partial result
403 // from the intraprocedural fixed-point analysis--
404 // then the interprocedural analysis settles, this
405 // mapping will have the final results for each
407 protected Hashtable<Descriptor, ReachGraph>
408 mapDescriptorToCompleteReachGraph;
410 // maps a descriptor to its known dependents: namely
411 // methods or tasks that call the descriptor's method
412 // AND are part of this analysis (reachable from main)
413 protected Hashtable< Descriptor, Set<Descriptor> >
414 mapDescriptorToSetDependents;
416 // maps each flat new to one analysis abstraction
417 // allocate site object, these exist outside reach graphs
418 protected Hashtable<FlatNew, AllocSite>
419 mapFlatNewToAllocSite;
421 // maps intergraph heap region IDs to intergraph
422 // allocation sites that created them, a redundant
423 // structure for efficiency in some operations
424 protected Hashtable<Integer, AllocSite>
427 // maps a method to its initial heap model (IHM) that
428 // is the set of reachability graphs from every caller
429 // site, all merged together. The reason that we keep
430 // them separate is that any one call site's contribution
431 // to the IHM may changed along the path to the fixed point
432 protected Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >
433 mapDescriptorToIHMcontributions;
435 // additionally, keep a mapping from descriptors to the
436 // merged in-coming initial context, because we want this
437 // initial context to be STRICTLY MONOTONIC
438 protected Hashtable<Descriptor, ReachGraph>
439 mapDescriptorToInitialContext;
441 // make the result for back edges analysis-wide STRICTLY
442 // MONOTONIC as well, but notice we use FlatNode as the
443 // key for this map: in case we want to consider other
444 // nodes as back edge's in future implementations
445 protected Hashtable<FlatNode, ReachGraph>
446 mapBackEdgeToMonotone;
449 public static final String arrayElementFieldName = "___element_";
450 static protected Hashtable<TypeDescriptor, FieldDescriptor>
453 // for controlling DOT file output
454 protected boolean writeFinalDOTs;
455 protected boolean writeAllIncrementalDOTs;
457 // supporting DOT output--when we want to write every
458 // partial method result, keep a tally for generating
460 protected Hashtable<Descriptor, Integer>
461 mapDescriptorToNumUpdates;
463 //map task descriptor to initial task parameter
464 protected Hashtable<Descriptor, ReachGraph>
465 mapDescriptorToReachGraph;
467 protected PointerMethod pm;
469 static protected Hashtable<FlatNode, ReachGraph> fn2rg =
470 new Hashtable<FlatNode, ReachGraph>();
472 private Hashtable<FlatCall, Descriptor> fc2enclosing;
476 // allocate various structures that are not local
477 // to a single class method--should be done once
478 protected void allocateStructures() {
480 if( determinismDesired ) {
481 // use an ordered set
482 descriptorsToAnalyze = new TreeSet<Descriptor>( dComp );
484 // otherwise use a speedy hashset
485 descriptorsToAnalyze = new HashSet<Descriptor>();
488 mapDescriptorToCompleteReachGraph =
489 new Hashtable<Descriptor, ReachGraph>();
491 mapDescriptorToNumUpdates =
492 new Hashtable<Descriptor, Integer>();
494 mapDescriptorToSetDependents =
495 new Hashtable< Descriptor, Set<Descriptor> >();
497 mapFlatNewToAllocSite =
498 new Hashtable<FlatNew, AllocSite>();
500 mapDescriptorToIHMcontributions =
501 new Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >();
503 mapDescriptorToInitialContext =
504 new Hashtable<Descriptor, ReachGraph>();
506 mapBackEdgeToMonotone =
507 new Hashtable<FlatNode, ReachGraph>();
509 mapHrnIdToAllocSite =
510 new Hashtable<Integer, AllocSite>();
512 mapTypeToArrayField =
513 new Hashtable <TypeDescriptor, FieldDescriptor>();
515 if( state.DISJOINTDVISITSTACK ||
516 state.DISJOINTDVISITSTACKEESONTOP
518 descriptorsToVisitStack =
519 new Stack<Descriptor>();
522 if( state.DISJOINTDVISITPQUE ) {
523 descriptorsToVisitQ =
524 new PriorityQueue<DescriptorQWrapper>();
527 descriptorsToVisitSet =
528 new HashSet<Descriptor>();
530 mapDescriptorToPriority =
531 new Hashtable<Descriptor, Integer>();
534 new HashSet<Descriptor>();
536 mapDescriptorToAllocSiteSet =
537 new Hashtable<Descriptor, HashSet<AllocSite> >();
539 mapDescriptorToReachGraph =
540 new Hashtable<Descriptor, ReachGraph>();
542 pm = new PointerMethod();
544 if( state.DISJOINTDEBUGSCHEDULING ) {
545 fc2enclosing = new Hashtable<FlatCall, Descriptor>();
552 // this analysis generates a disjoint reachability
553 // graph for every reachable method in the program
554 public DisjointAnalysis( State s,
559 ) throws java.io.IOException {
560 init( s, tu, cg, l, ar );
563 protected void init( State state,
567 ArrayReferencees arrayReferencees
568 ) throws java.io.IOException {
570 analysisComplete = false;
573 this.typeUtil = typeUtil;
574 this.callGraph = callGraph;
575 this.liveness = liveness;
576 this.arrayReferencees = arrayReferencees;
577 this.allocationDepth = state.DISJOINTALLOCDEPTH;
578 this.releaseMode = state.DISJOINTRELEASEMODE;
579 this.determinismDesired = state.DISJOINTDETERMINISM;
581 this.writeFinalDOTs = state.DISJOINTWRITEDOTS && !state.DISJOINTWRITEALL;
582 this.writeAllIncrementalDOTs = state.DISJOINTWRITEDOTS && state.DISJOINTWRITEALL;
584 this.takeDebugSnapshots = state.DISJOINTSNAPSYMBOL != null;
585 this.descSymbolDebug = state.DISJOINTSNAPSYMBOL;
586 this.visitStartCapture = state.DISJOINTSNAPVISITTOSTART;
587 this.numVisitsToCapture = state.DISJOINTSNAPNUMVISITS;
588 this.stopAfterCapture = state.DISJOINTSNAPSTOPAFTER;
589 this.snapVisitCounter = 1; // count visits from 1 (user will write 1, means 1st visit)
590 this.snapNodeCounter = 0; // count nodes from 0
593 state.DISJOINTDVISITSTACK ||
594 state.DISJOINTDVISITPQUE ||
595 state.DISJOINTDVISITSTACKEESONTOP;
596 assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITPQUE);
597 assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITSTACKEESONTOP);
598 assert !(state.DISJOINTDVISITPQUE && state.DISJOINTDVISITSTACKEESONTOP);
600 // set some static configuration for ReachGraphs
601 ReachGraph.allocationDepth = allocationDepth;
602 ReachGraph.typeUtil = typeUtil;
604 ReachGraph.debugCallSiteVisitStartCapture
605 = state.DISJOINTDEBUGCALLVISITTOSTART;
607 ReachGraph.debugCallSiteNumVisitsToCapture
608 = state.DISJOINTDEBUGCALLNUMVISITS;
610 ReachGraph.debugCallSiteStopAfter
611 = state.DISJOINTDEBUGCALLSTOPAFTER;
613 ReachGraph.debugCallSiteVisitCounter
614 = 0; // count visits from 1, is incremented before first visit
618 allocateStructures();
620 double timeStartAnalysis = (double) System.nanoTime();
622 // start interprocedural fixed-point computation
624 analysisComplete=true;
626 double timeEndAnalysis = (double) System.nanoTime();
627 double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
628 String treport = String.format( "The reachability analysis took %.3f sec.", dt );
629 String justtime = String.format( "%.2f", dt );
630 System.out.println( treport );
632 if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
636 if( state.DISJOINTWRITEIHMS ) {
640 if( state.DISJOINTWRITEINITCONTEXTS ) {
641 writeInitialContexts();
644 if( state.DISJOINTALIASFILE != null ) {
646 writeAllSharing(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines);
648 writeAllSharingJava(state.DISJOINTALIASFILE,
651 state.DISJOINTALIASTAB,
659 protected boolean moreDescriptorsToVisit() {
660 if( state.DISJOINTDVISITSTACK ||
661 state.DISJOINTDVISITSTACKEESONTOP
663 return !descriptorsToVisitStack.isEmpty();
665 } else if( state.DISJOINTDVISITPQUE ) {
666 return !descriptorsToVisitQ.isEmpty();
669 throw new Error( "Neither descriptor visiting mode set" );
673 // fixed-point computation over the call graph--when a
674 // method's callees are updated, it must be reanalyzed
675 protected void analyzeMethods() throws java.io.IOException {
677 // task or non-task (java) mode determines what the roots
678 // of the call chain are, and establishes the set of methods
679 // reachable from the roots that will be analyzed
682 System.out.println( "Bamboo mode..." );
684 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
685 while( taskItr.hasNext() ) {
686 TaskDescriptor td = (TaskDescriptor) taskItr.next();
687 if( !descriptorsToAnalyze.contains( td ) ) {
688 // add all methods transitively reachable from the
690 descriptorsToAnalyze.add( td );
691 descriptorsToAnalyze.addAll( callGraph.getAllMethods( td ) );
696 System.out.println( "Java mode..." );
698 // add all methods transitively reachable from the
699 // source's main to set for analysis
700 mdSourceEntry = typeUtil.getMain();
701 descriptorsToAnalyze.add( mdSourceEntry );
702 descriptorsToAnalyze.addAll( callGraph.getAllMethods( mdSourceEntry ) );
704 // fabricate an empty calling context that will call
705 // the source's main, but call graph doesn't know
706 // about it, so explicitly add it
707 makeAnalysisEntryMethod( mdSourceEntry );
708 descriptorsToAnalyze.add( mdAnalysisEntry );
712 // now, depending on the interprocedural mode for visiting
713 // methods, set up the needed data structures
715 if( state.DISJOINTDVISITPQUE ) {
717 // topologically sort according to the call graph so
718 // leaf calls are last, helps build contexts up first
719 LinkedList<Descriptor> sortedDescriptors =
720 topologicalSort( descriptorsToAnalyze );
722 // add sorted descriptors to priority queue, and duplicate
723 // the queue as a set for efficiently testing whether some
724 // method is marked for analysis
726 Iterator<Descriptor> dItr;
728 // for the priority queue, give items at the head
729 // of the sorted list a low number (highest priority)
730 while( !sortedDescriptors.isEmpty() ) {
731 Descriptor d = sortedDescriptors.removeFirst();
732 mapDescriptorToPriority.put( d, new Integer( p ) );
733 descriptorsToVisitQ.add( new DescriptorQWrapper( p, d ) );
734 descriptorsToVisitSet.add( d );
738 } else if( state.DISJOINTDVISITSTACK ||
739 state.DISJOINTDVISITSTACKEESONTOP
741 // if we're doing the stack scheme, just throw the root
742 // method or tasks on the stack
744 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
745 while( taskItr.hasNext() ) {
746 TaskDescriptor td = (TaskDescriptor) taskItr.next();
747 descriptorsToVisitStack.add( td );
748 descriptorsToVisitSet.add( td );
752 descriptorsToVisitStack.add( mdAnalysisEntry );
753 descriptorsToVisitSet.add( mdAnalysisEntry );
757 throw new Error( "Unknown method scheduling mode" );
761 // analyze scheduled methods until there are no more to visit
762 while( moreDescriptorsToVisit() ) {
765 if( state.DISJOINTDVISITSTACK ||
766 state.DISJOINTDVISITSTACKEESONTOP
768 d = descriptorsToVisitStack.pop();
770 } else if( state.DISJOINTDVISITPQUE ) {
771 d = descriptorsToVisitQ.poll().getDescriptor();
774 assert descriptorsToVisitSet.contains( d );
775 descriptorsToVisitSet.remove( d );
777 // because the task or method descriptor just extracted
778 // was in the "to visit" set it either hasn't been analyzed
779 // yet, or some method that it depends on has been
780 // updated. Recompute a complete reachability graph for
781 // this task/method and compare it to any previous result.
782 // If there is a change detected, add any methods/tasks
783 // that depend on this one to the "to visit" set.
785 System.out.println( "Analyzing " + d );
787 if( state.DISJOINTDVISITSTACKEESONTOP ) {
788 assert calleesToEnqueue.isEmpty();
791 ReachGraph rg = analyzeMethod( d );
792 ReachGraph rgPrev = getPartial( d );
794 if( !rg.equals( rgPrev ) ) {
797 if( state.DISJOINTDEBUGSCHEDULING ) {
798 System.out.println( " complete graph changed, scheduling callers for analysis:" );
801 // results for d changed, so enqueue dependents
802 // of d for further analysis
803 Iterator<Descriptor> depsItr = getDependents( d ).iterator();
804 while( depsItr.hasNext() ) {
805 Descriptor dNext = depsItr.next();
808 if( state.DISJOINTDEBUGSCHEDULING ) {
809 System.out.println( " "+dNext );
814 // whether or not the method under analysis changed,
815 // we may have some callees that are scheduled for
816 // more analysis, and they should go on the top of
817 // the stack now (in other method-visiting modes they
818 // are already enqueued at this point
819 if( state.DISJOINTDVISITSTACKEESONTOP ) {
820 Iterator<Descriptor> depsItr = calleesToEnqueue.iterator();
821 while( depsItr.hasNext() ) {
822 Descriptor dNext = depsItr.next();
825 calleesToEnqueue.clear();
831 protected ReachGraph analyzeMethod( Descriptor d )
832 throws java.io.IOException {
834 // get the flat code for this descriptor
836 if( d == mdAnalysisEntry ) {
837 fm = fmAnalysisEntry;
839 fm = state.getMethodFlat( d );
841 pm.analyzeMethod( fm );
843 // intraprocedural work set
844 Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
845 flatNodesToVisit.add( fm );
847 // if determinism is desired by client, shadow the
848 // set with a queue to make visit order deterministic
849 Queue<FlatNode> flatNodesToVisitQ = null;
850 if( determinismDesired ) {
851 flatNodesToVisitQ = new LinkedList<FlatNode>();
852 flatNodesToVisitQ.add( fm );
855 // mapping of current partial results
856 Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraph =
857 new Hashtable<FlatNode, ReachGraph>();
859 // the set of return nodes partial results that will be combined as
860 // the final, conservative approximation of the entire method
861 HashSet<FlatReturnNode> setReturns = new HashSet<FlatReturnNode>();
863 while( !flatNodesToVisit.isEmpty() ) {
866 if( determinismDesired ) {
867 assert !flatNodesToVisitQ.isEmpty();
868 fn = flatNodesToVisitQ.remove();
870 fn = flatNodesToVisit.iterator().next();
872 flatNodesToVisit.remove( fn );
874 // effect transfer function defined by this node,
875 // then compare it to the old graph at this node
876 // to see if anything was updated.
878 ReachGraph rg = new ReachGraph();
879 TaskDescriptor taskDesc;
880 if(fn instanceof FlatMethod && (taskDesc=((FlatMethod)fn).getTask())!=null){
881 if(mapDescriptorToReachGraph.containsKey(taskDesc)){
882 // retrieve existing reach graph if it is not first time
883 rg=mapDescriptorToReachGraph.get(taskDesc);
885 // create initial reach graph for a task
886 rg=createInitialTaskReachGraph((FlatMethod)fn);
888 mapDescriptorToReachGraph.put(taskDesc, rg);
892 // start by merging all node's parents' graphs
893 for( int i = 0; i < pm.numPrev(fn); ++i ) {
894 FlatNode pn = pm.getPrev(fn,i);
895 if( mapFlatNodeToReachGraph.containsKey( pn ) ) {
896 ReachGraph rgParent = mapFlatNodeToReachGraph.get( pn );
897 rg.merge( rgParent );
902 if( takeDebugSnapshots &&
903 d.getSymbol().equals( descSymbolDebug )
905 debugSnapshot( rg, fn, true );
909 // modify rg with appropriate transfer function
910 rg = analyzeFlatNode( d, fm, fn, setReturns, rg );
913 if( takeDebugSnapshots &&
914 d.getSymbol().equals( descSymbolDebug )
916 debugSnapshot( rg, fn, false );
921 // if the results of the new graph are different from
922 // the current graph at this node, replace the graph
923 // with the update and enqueue the children
924 ReachGraph rgPrev = mapFlatNodeToReachGraph.get( fn );
925 if( !rg.equals( rgPrev ) ) {
926 mapFlatNodeToReachGraph.put( fn, rg );
928 for( int i = 0; i < pm.numNext( fn ); i++ ) {
929 FlatNode nn = pm.getNext( fn, i );
931 flatNodesToVisit.add( nn );
932 if( determinismDesired ) {
933 flatNodesToVisitQ.add( nn );
940 // end by merging all return nodes into a complete
941 // reach graph that represents all possible heap
942 // states after the flat method returns
943 ReachGraph completeGraph = new ReachGraph();
945 assert !setReturns.isEmpty();
946 Iterator retItr = setReturns.iterator();
947 while( retItr.hasNext() ) {
948 FlatReturnNode frn = (FlatReturnNode) retItr.next();
950 assert mapFlatNodeToReachGraph.containsKey( frn );
951 ReachGraph rgRet = mapFlatNodeToReachGraph.get( frn );
953 completeGraph.merge( rgRet );
957 if( takeDebugSnapshots &&
958 d.getSymbol().equals( descSymbolDebug )
960 // increment that we've visited the debug snap
961 // method, and reset the node counter
962 System.out.println( " @@@ debug snap at visit "+snapVisitCounter );
966 if( snapVisitCounter == visitStartCapture + numVisitsToCapture &&
969 System.out.println( "!!! Stopping analysis after debug snap captures. !!!" );
975 return completeGraph;
980 analyzeFlatNode( Descriptor d,
981 FlatMethod fmContaining,
983 HashSet<FlatReturnNode> setRetNodes,
985 ) throws java.io.IOException {
988 // any variables that are no longer live should be
989 // nullified in the graph to reduce edges
990 //rg.nullifyDeadVars( liveness.getLiveInTemps( fmContaining, fn ) );
997 // use node type to decide what transfer function
998 // to apply to the reachability graph
999 switch( fn.kind() ) {
1001 case FKind.FlatMethod: {
1002 // construct this method's initial heap model (IHM)
1003 // since we're working on the FlatMethod, we know
1004 // the incoming ReachGraph 'rg' is empty
1006 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1007 getIHMcontributions( d );
1009 Set entrySet = heapsFromCallers.entrySet();
1010 Iterator itr = entrySet.iterator();
1011 while( itr.hasNext() ) {
1012 Map.Entry me = (Map.Entry) itr.next();
1013 FlatCall fc = (FlatCall) me.getKey();
1014 ReachGraph rgContrib = (ReachGraph) me.getValue();
1016 assert fc.getMethod().equals( d );
1018 rg.merge( rgContrib );
1021 // additionally, we are enforcing STRICT MONOTONICITY for the
1022 // method's initial context, so grow the context by whatever
1023 // the previously computed context was, and put the most
1024 // up-to-date context back in the map
1025 ReachGraph rgPrevContext = mapDescriptorToInitialContext.get( d );
1026 rg.merge( rgPrevContext );
1027 mapDescriptorToInitialContext.put( d, rg );
1031 case FKind.FlatOpNode:
1032 FlatOpNode fon = (FlatOpNode) fn;
1033 if( fon.getOp().getOp() == Operation.ASSIGN ) {
1034 lhs = fon.getDest();
1035 rhs = fon.getLeft();
1036 rg.assignTempXEqualToTempY( lhs, rhs );
1040 case FKind.FlatCastNode:
1041 FlatCastNode fcn = (FlatCastNode) fn;
1045 TypeDescriptor td = fcn.getType();
1048 rg.assignTempXEqualToCastedTempY( lhs, rhs, td );
1051 case FKind.FlatFieldNode:
1052 FlatFieldNode ffn = (FlatFieldNode) fn;
1055 fld = ffn.getField();
1056 if( shouldAnalysisTrack( fld.getType() ) ) {
1057 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fld );
1061 case FKind.FlatSetFieldNode:
1062 FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
1063 lhs = fsfn.getDst();
1064 fld = fsfn.getField();
1065 rhs = fsfn.getSrc();
1066 if( shouldAnalysisTrack( fld.getType() ) ) {
1067 rg.assignTempXFieldFEqualToTempY( lhs, fld, rhs );
1071 case FKind.FlatElementNode:
1072 FlatElementNode fen = (FlatElementNode) fn;
1075 if( shouldAnalysisTrack( lhs.getType() ) ) {
1077 assert rhs.getType() != null;
1078 assert rhs.getType().isArray();
1080 TypeDescriptor tdElement = rhs.getType().dereference();
1081 FieldDescriptor fdElement = getArrayField( tdElement );
1083 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fdElement );
1087 case FKind.FlatSetElementNode:
1088 FlatSetElementNode fsen = (FlatSetElementNode) fn;
1090 if( arrayReferencees.doesNotCreateNewReaching( fsen ) ) {
1091 // skip this node if it cannot create new reachability paths
1095 lhs = fsen.getDst();
1096 rhs = fsen.getSrc();
1097 if( shouldAnalysisTrack( rhs.getType() ) ) {
1099 assert lhs.getType() != null;
1100 assert lhs.getType().isArray();
1102 TypeDescriptor tdElement = lhs.getType().dereference();
1103 FieldDescriptor fdElement = getArrayField( tdElement );
1105 rg.assignTempXFieldFEqualToTempY( lhs, fdElement, rhs );
1110 FlatNew fnn = (FlatNew) fn;
1112 if( shouldAnalysisTrack( lhs.getType() ) ) {
1113 AllocSite as = getAllocSiteFromFlatNewPRIVATE( fnn );
1114 rg.assignTempEqualToNewAlloc( lhs, as );
1118 case FKind.FlatCall: {
1119 Descriptor mdCaller;
1120 if( fmContaining.getMethod() != null ){
1121 mdCaller = fmContaining.getMethod();
1123 mdCaller = fmContaining.getTask();
1125 FlatCall fc = (FlatCall) fn;
1126 MethodDescriptor mdCallee = fc.getMethod();
1127 FlatMethod fmCallee = state.getMethodFlat( mdCallee );
1130 boolean debugCallSite =
1131 mdCaller.getSymbol().equals( state.DISJOINTDEBUGCALLER ) &&
1132 mdCallee.getSymbol().equals( state.DISJOINTDEBUGCALLEE );
1134 boolean writeDebugDOTs = false;
1135 boolean stopAfter = false;
1136 if( debugCallSite ) {
1137 ++ReachGraph.debugCallSiteVisitCounter;
1138 System.out.println( " $$$ Debug call site visit "+
1139 ReachGraph.debugCallSiteVisitCounter+
1143 (ReachGraph.debugCallSiteVisitCounter >=
1144 ReachGraph.debugCallSiteVisitStartCapture) &&
1146 (ReachGraph.debugCallSiteVisitCounter <
1147 ReachGraph.debugCallSiteVisitStartCapture +
1148 ReachGraph.debugCallSiteNumVisitsToCapture)
1150 writeDebugDOTs = true;
1151 System.out.println( " $$$ Capturing this call site visit $$$" );
1152 if( ReachGraph.debugCallSiteStopAfter &&
1153 (ReachGraph.debugCallSiteVisitCounter ==
1154 ReachGraph.debugCallSiteVisitStartCapture +
1155 ReachGraph.debugCallSiteNumVisitsToCapture - 1)
1163 // calculate the heap this call site can reach--note this is
1164 // not used for the current call site transform, we are
1165 // grabbing this heap model for future analysis of the callees,
1166 // so if different results emerge we will return to this site
1167 ReachGraph heapForThisCall_old =
1168 getIHMcontribution( mdCallee, fc );
1170 // the computation of the callee-reachable heap
1171 // is useful for making the callee starting point
1172 // and for applying the call site transfer function
1173 Set<Integer> callerNodeIDsCopiedToCallee =
1174 new HashSet<Integer>();
1176 ReachGraph heapForThisCall_cur =
1177 rg.makeCalleeView( fc,
1179 callerNodeIDsCopiedToCallee,
1183 if( !heapForThisCall_cur.equals( heapForThisCall_old ) ) {
1184 // if heap at call site changed, update the contribution,
1185 // and reschedule the callee for analysis
1186 addIHMcontribution( mdCallee, fc, heapForThisCall_cur );
1188 if( state.DISJOINTDEBUGSCHEDULING ) {
1189 System.out.println( " context changed, scheduling callee: "+mdCallee );
1191 // if we're debugging the scheduling system, map a FlatCall
1192 // to its enclosing method/task descriptor so we can write
1193 // that info out later
1194 fc2enclosing.put( fc, mdCaller );
1197 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1198 calleesToEnqueue.add( mdCallee );
1200 enqueue( mdCallee );
1206 // the transformation for a call site should update the
1207 // current heap abstraction with any effects from the callee,
1208 // or if the method is virtual, the effects from any possible
1209 // callees, so find the set of callees...
1210 Set<MethodDescriptor> setPossibleCallees;
1211 if( determinismDesired ) {
1212 // use an ordered set
1213 setPossibleCallees = new TreeSet<MethodDescriptor>( dComp );
1215 // otherwise use a speedy hashset
1216 setPossibleCallees = new HashSet<MethodDescriptor>();
1219 if( mdCallee.isStatic() ) {
1220 setPossibleCallees.add( mdCallee );
1222 TypeDescriptor typeDesc = fc.getThis().getType();
1223 setPossibleCallees.addAll( callGraph.getMethods( mdCallee,
1228 ReachGraph rgMergeOfEffects = new ReachGraph();
1230 Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
1231 while( mdItr.hasNext() ) {
1232 MethodDescriptor mdPossible = mdItr.next();
1233 FlatMethod fmPossible = state.getMethodFlat( mdPossible );
1235 addDependent( mdPossible, // callee
1238 // don't alter the working graph (rg) until we compute a
1239 // result for every possible callee, merge them all together,
1240 // then set rg to that
1241 ReachGraph rgCopy = new ReachGraph();
1244 ReachGraph rgEffect = getPartial( mdPossible );
1246 if( rgEffect == null ) {
1247 // if this method has never been analyzed just schedule it
1248 // for analysis and skip over this call site for now
1249 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1250 calleesToEnqueue.add( mdPossible );
1252 enqueue( mdPossible );
1255 if( state.DISJOINTDEBUGSCHEDULING ) {
1256 System.out.println( " callee hasn't been analyzed, scheduling: "+mdPossible );
1261 rgCopy.resolveMethodCall( fc,
1264 callerNodeIDsCopiedToCallee,
1269 rgMergeOfEffects.merge( rgCopy );
1274 System.out.println( "$$$ Exiting after requested captures of call site. $$$" );
1279 // now that we've taken care of building heap models for
1280 // callee analysis, finish this transformation
1281 rg = rgMergeOfEffects;
1285 case FKind.FlatReturnNode:
1286 FlatReturnNode frn = (FlatReturnNode) fn;
1287 rhs = frn.getReturnTemp();
1288 if( rhs != null && shouldAnalysisTrack( rhs.getType() ) ) {
1289 rg.assignReturnEqualToTemp( rhs );
1291 setRetNodes.add( frn );
1297 // dead variables were removed before the above transfer function
1298 // was applied, so eliminate heap regions and edges that are no
1299 // longer part of the abstractly-live heap graph, and sweep up
1300 // and reachability effects that are altered by the reduction
1301 //rg.abstractGarbageCollect();
1305 // back edges are strictly monotonic
1306 if( pm.isBackEdge( fn ) ) {
1307 ReachGraph rgPrevResult = mapBackEdgeToMonotone.get( fn );
1308 rg.merge( rgPrevResult );
1309 mapBackEdgeToMonotone.put( fn, rg );
1312 // at this point rg should be the correct update
1313 // by an above transfer function, or untouched if
1314 // the flat node type doesn't affect the heap
1320 // this method should generate integers strictly greater than zero!
1321 // special "shadow" regions are made from a heap region by negating
1323 static public Integer generateUniqueHeapRegionNodeID() {
1325 return new Integer( uniqueIDcount );
1330 static public FieldDescriptor getArrayField( TypeDescriptor tdElement ) {
1331 FieldDescriptor fdElement = mapTypeToArrayField.get( tdElement );
1332 if( fdElement == null ) {
1333 fdElement = new FieldDescriptor( new Modifiers( Modifiers.PUBLIC ),
1335 arrayElementFieldName,
1338 mapTypeToArrayField.put( tdElement, fdElement );
1345 private void writeFinalGraphs() {
1346 Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
1347 Iterator itr = entrySet.iterator();
1348 while( itr.hasNext() ) {
1349 Map.Entry me = (Map.Entry) itr.next();
1350 Descriptor d = (Descriptor) me.getKey();
1351 ReachGraph rg = (ReachGraph) me.getValue();
1353 rg.writeGraph( "COMPLETE"+d,
1354 true, // write labels (variables)
1355 true, // selectively hide intermediate temp vars
1356 true, // prune unreachable heap regions
1357 false, // hide subset reachability states
1358 true ); // hide edge taints
1362 private void writeFinalIHMs() {
1363 Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
1364 while( d2IHMsItr.hasNext() ) {
1365 Map.Entry me1 = (Map.Entry) d2IHMsItr.next();
1366 Descriptor d = (Descriptor) me1.getKey();
1367 Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>) me1.getValue();
1369 Iterator fc2rgItr = IHMs.entrySet().iterator();
1370 while( fc2rgItr.hasNext() ) {
1371 Map.Entry me2 = (Map.Entry) fc2rgItr.next();
1372 FlatCall fc = (FlatCall) me2.getKey();
1373 ReachGraph rg = (ReachGraph) me2.getValue();
1375 rg.writeGraph( "IHMPARTFOR"+d+"FROM"+fc,
1376 true, // write labels (variables)
1377 true, // selectively hide intermediate temp vars
1378 true, // prune unreachable heap regions
1379 false, // hide subset reachability states
1380 true ); // hide edge taints
1385 private void writeInitialContexts() {
1386 Set entrySet = mapDescriptorToInitialContext.entrySet();
1387 Iterator itr = entrySet.iterator();
1388 while( itr.hasNext() ) {
1389 Map.Entry me = (Map.Entry) itr.next();
1390 Descriptor d = (Descriptor) me.getKey();
1391 ReachGraph rg = (ReachGraph) me.getValue();
1393 rg.writeGraph( "INITIAL"+d,
1394 true, // write labels (variables)
1395 true, // selectively hide intermediate temp vars
1396 true, // prune unreachable heap regions
1397 false, // hide subset reachability states
1398 true ); // hide edge taints
1403 protected ReachGraph getPartial( Descriptor d ) {
1404 return mapDescriptorToCompleteReachGraph.get( d );
1407 protected void setPartial( Descriptor d, ReachGraph rg ) {
1408 mapDescriptorToCompleteReachGraph.put( d, rg );
1410 // when the flag for writing out every partial
1411 // result is set, we should spit out the graph,
1412 // but in order to give it a unique name we need
1413 // to track how many partial results for this
1414 // descriptor we've already written out
1415 if( writeAllIncrementalDOTs ) {
1416 if( !mapDescriptorToNumUpdates.containsKey( d ) ) {
1417 mapDescriptorToNumUpdates.put( d, new Integer( 0 ) );
1419 Integer n = mapDescriptorToNumUpdates.get( d );
1421 rg.writeGraph( d+"COMPLETE"+String.format( "%05d", n ),
1422 true, // write labels (variables)
1423 true, // selectively hide intermediate temp vars
1424 true, // prune unreachable heap regions
1425 false, // hide subset reachability states
1426 true ); // hide edge taints
1428 mapDescriptorToNumUpdates.put( d, n + 1 );
1434 // return just the allocation site associated with one FlatNew node
1435 protected AllocSite getAllocSiteFromFlatNewPRIVATE( FlatNew fnew ) {
1437 if( !mapFlatNewToAllocSite.containsKey( fnew ) ) {
1438 AllocSite as = AllocSite.factory( allocationDepth,
1440 fnew.getDisjointId()
1443 // the newest nodes are single objects
1444 for( int i = 0; i < allocationDepth; ++i ) {
1445 Integer id = generateUniqueHeapRegionNodeID();
1446 as.setIthOldest( i, id );
1447 mapHrnIdToAllocSite.put( id, as );
1450 // the oldest node is a summary node
1451 as.setSummary( generateUniqueHeapRegionNodeID() );
1453 mapFlatNewToAllocSite.put( fnew, as );
1456 return mapFlatNewToAllocSite.get( fnew );
1460 public static boolean shouldAnalysisTrack( TypeDescriptor type ) {
1461 // don't track primitive types, but an array
1462 // of primitives is heap memory
1463 if( type.isImmutable() ) {
1464 return type.isArray();
1467 // everything else is an object
1471 protected int numMethodsAnalyzed() {
1472 return descriptorsToAnalyze.size();
1479 // Take in source entry which is the program's compiled entry and
1480 // create a new analysis entry, a method that takes no parameters
1481 // and appears to allocate the command line arguments and call the
1482 // source entry with them. The purpose of this analysis entry is
1483 // to provide a top-level method context with no parameters left.
1484 protected void makeAnalysisEntryMethod( MethodDescriptor mdSourceEntry ) {
1486 Modifiers mods = new Modifiers();
1487 mods.addModifier( Modifiers.PUBLIC );
1488 mods.addModifier( Modifiers.STATIC );
1490 TypeDescriptor returnType =
1491 new TypeDescriptor( TypeDescriptor.VOID );
1493 this.mdAnalysisEntry =
1494 new MethodDescriptor( mods,
1496 "analysisEntryMethod"
1499 TempDescriptor cmdLineArgs =
1500 new TempDescriptor( "args",
1501 mdSourceEntry.getParamType( 0 )
1505 new FlatNew( mdSourceEntry.getParamType( 0 ),
1510 TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
1511 sourceEntryArgs[0] = cmdLineArgs;
1514 new FlatCall( mdSourceEntry,
1520 FlatReturnNode frn = new FlatReturnNode( null );
1522 FlatExit fe = new FlatExit();
1524 this.fmAnalysisEntry =
1525 new FlatMethod( mdAnalysisEntry,
1529 this.fmAnalysisEntry.addNext( fn );
1536 protected LinkedList<Descriptor> topologicalSort( Set<Descriptor> toSort ) {
1538 Set<Descriptor> discovered;
1540 if( determinismDesired ) {
1541 // use an ordered set
1542 discovered = new TreeSet<Descriptor>( dComp );
1544 // otherwise use a speedy hashset
1545 discovered = new HashSet<Descriptor>();
1548 LinkedList<Descriptor> sorted = new LinkedList<Descriptor>();
1550 Iterator<Descriptor> itr = toSort.iterator();
1551 while( itr.hasNext() ) {
1552 Descriptor d = itr.next();
1554 if( !discovered.contains( d ) ) {
1555 dfsVisit( d, toSort, sorted, discovered );
1562 // While we're doing DFS on call graph, remember
1563 // dependencies for efficient queuing of methods
1564 // during interprocedural analysis:
1566 // a dependent of a method decriptor d for this analysis is:
1567 // 1) a method or task that invokes d
1568 // 2) in the descriptorsToAnalyze set
1569 protected void dfsVisit( Descriptor d,
1570 Set <Descriptor> toSort,
1571 LinkedList<Descriptor> sorted,
1572 Set <Descriptor> discovered ) {
1573 discovered.add( d );
1575 // only methods have callers, tasks never do
1576 if( d instanceof MethodDescriptor ) {
1578 MethodDescriptor md = (MethodDescriptor) d;
1580 // the call graph is not aware that we have a fabricated
1581 // analysis entry that calls the program source's entry
1582 if( md == mdSourceEntry ) {
1583 if( !discovered.contains( mdAnalysisEntry ) ) {
1584 addDependent( mdSourceEntry, // callee
1585 mdAnalysisEntry // caller
1587 dfsVisit( mdAnalysisEntry, toSort, sorted, discovered );
1591 // otherwise call graph guides DFS
1592 Iterator itr = callGraph.getCallerSet( md ).iterator();
1593 while( itr.hasNext() ) {
1594 Descriptor dCaller = (Descriptor) itr.next();
1596 // only consider callers in the original set to analyze
1597 if( !toSort.contains( dCaller ) ) {
1601 if( !discovered.contains( dCaller ) ) {
1602 addDependent( md, // callee
1606 dfsVisit( dCaller, toSort, sorted, discovered );
1611 // for leaf-nodes last now!
1612 sorted.addLast( d );
1616 protected void enqueue( Descriptor d ) {
1618 if( !descriptorsToVisitSet.contains( d ) ) {
1620 if( state.DISJOINTDVISITSTACK ||
1621 state.DISJOINTDVISITSTACKEESONTOP
1623 descriptorsToVisitStack.add( d );
1625 } else if( state.DISJOINTDVISITPQUE ) {
1626 Integer priority = mapDescriptorToPriority.get( d );
1627 descriptorsToVisitQ.add( new DescriptorQWrapper( priority,
1632 descriptorsToVisitSet.add( d );
1637 // a dependent of a method decriptor d for this analysis is:
1638 // 1) a method or task that invokes d
1639 // 2) in the descriptorsToAnalyze set
1640 protected void addDependent( Descriptor callee, Descriptor caller ) {
1641 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1642 if( deps == null ) {
1643 deps = new HashSet<Descriptor>();
1646 mapDescriptorToSetDependents.put( callee, deps );
1649 protected Set<Descriptor> getDependents( Descriptor callee ) {
1650 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1651 if( deps == null ) {
1652 deps = new HashSet<Descriptor>();
1653 mapDescriptorToSetDependents.put( callee, deps );
1659 public Hashtable<FlatCall, ReachGraph> getIHMcontributions( Descriptor d ) {
1661 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1662 mapDescriptorToIHMcontributions.get( d );
1664 if( heapsFromCallers == null ) {
1665 heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
1666 mapDescriptorToIHMcontributions.put( d, heapsFromCallers );
1669 return heapsFromCallers;
1672 public ReachGraph getIHMcontribution( Descriptor d,
1675 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1676 getIHMcontributions( d );
1678 if( !heapsFromCallers.containsKey( fc ) ) {
1682 return heapsFromCallers.get( fc );
1686 public void addIHMcontribution( Descriptor d,
1690 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1691 getIHMcontributions( d );
1693 heapsFromCallers.put( fc, rg );
1697 private AllocSite createParameterAllocSite( ReachGraph rg,
1698 TempDescriptor tempDesc,
1704 flatNew = new FlatNew( tempDesc.getType(), // type
1705 tempDesc, // param temp
1706 false, // global alloc?
1707 "param"+tempDesc // disjoint site ID string
1710 flatNew = new FlatNew( tempDesc.getType(), // type
1711 tempDesc, // param temp
1712 false, // global alloc?
1713 null // disjoint site ID string
1717 // create allocation site
1718 AllocSite as = AllocSite.factory( allocationDepth,
1720 flatNew.getDisjointId()
1722 for (int i = 0; i < allocationDepth; ++i) {
1723 Integer id = generateUniqueHeapRegionNodeID();
1724 as.setIthOldest(i, id);
1725 mapHrnIdToAllocSite.put(id, as);
1727 // the oldest node is a summary node
1728 as.setSummary( generateUniqueHeapRegionNodeID() );
1736 private Set<FieldDescriptor> getFieldSetTobeAnalyzed(TypeDescriptor typeDesc){
1738 Set<FieldDescriptor> fieldSet=new HashSet<FieldDescriptor>();
1739 if(!typeDesc.isImmutable()){
1740 ClassDescriptor classDesc = typeDesc.getClassDesc();
1741 for (Iterator it = classDesc.getFields(); it.hasNext();) {
1742 FieldDescriptor field = (FieldDescriptor) it.next();
1743 TypeDescriptor fieldType = field.getType();
1744 if (shouldAnalysisTrack( fieldType )) {
1745 fieldSet.add(field);
1753 private HeapRegionNode createMultiDeimensionalArrayHRN(ReachGraph rg, AllocSite alloc, HeapRegionNode srcHRN, FieldDescriptor fd, Hashtable<HeapRegionNode, HeapRegionNode> map, Hashtable<TypeDescriptor, HeapRegionNode> mapToExistingNode, ReachSet alpha ){
1755 int dimCount=fd.getType().getArrayCount();
1756 HeapRegionNode prevNode=null;
1757 HeapRegionNode arrayEntryNode=null;
1758 for(int i=dimCount;i>0;i--){
1759 TypeDescriptor typeDesc=fd.getType().dereference();//hack to get instance of type desc
1760 typeDesc.setArrayCount(i);
1761 TempDescriptor tempDesc=new TempDescriptor(typeDesc.getSymbol(),typeDesc);
1762 HeapRegionNode hrnSummary ;
1763 if(!mapToExistingNode.containsKey(typeDesc)){
1768 as = createParameterAllocSite(rg, tempDesc, false);
1770 // make a new reference to allocated node
1772 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1773 false, // single object?
1775 false, // out-of-context?
1776 as.getType(), // type
1777 as, // allocation site
1778 alpha, // inherent reach
1779 alpha, // current reach
1780 ExistPredSet.factory(rg.predTrue), // predicates
1781 tempDesc.toString() // description
1783 rg.id2hrn.put(as.getSummary(),hrnSummary);
1785 mapToExistingNode.put(typeDesc, hrnSummary);
1787 hrnSummary=mapToExistingNode.get(typeDesc);
1791 // make a new reference between new summary node and source
1792 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1795 fd.getSymbol(), // field name
1797 ExistPredSet.factory(rg.predTrue) // predicates
1800 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1801 prevNode=hrnSummary;
1802 arrayEntryNode=hrnSummary;
1804 // make a new reference between summary nodes of array
1805 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1808 arrayElementFieldName, // field name
1810 ExistPredSet.factory(rg.predTrue) // predicates
1813 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1814 prevNode=hrnSummary;
1819 // create a new obj node if obj has at least one non-primitive field
1820 TypeDescriptor type=fd.getType();
1821 if(getFieldSetTobeAnalyzed(type).size()>0){
1822 TypeDescriptor typeDesc=type.dereference();
1823 typeDesc.setArrayCount(0);
1824 if(!mapToExistingNode.containsKey(typeDesc)){
1825 TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc);
1826 AllocSite as = createParameterAllocSite(rg, tempDesc, false);
1827 // make a new reference to allocated node
1828 HeapRegionNode hrnSummary =
1829 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1830 false, // single object?
1832 false, // out-of-context?
1834 as, // allocation site
1835 alpha, // inherent reach
1836 alpha, // current reach
1837 ExistPredSet.factory(rg.predTrue), // predicates
1838 tempDesc.toString() // description
1840 rg.id2hrn.put(as.getSummary(),hrnSummary);
1841 mapToExistingNode.put(typeDesc, hrnSummary);
1842 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1845 arrayElementFieldName, // field name
1847 ExistPredSet.factory(rg.predTrue) // predicates
1849 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1850 prevNode=hrnSummary;
1852 HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc);
1853 if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null){
1854 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1857 arrayElementFieldName, // field name
1859 ExistPredSet.factory(rg.predTrue) // predicates
1861 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1863 prevNode=hrnSummary;
1867 map.put(arrayEntryNode, prevNode);
1868 return arrayEntryNode;
1871 private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
1872 ReachGraph rg = new ReachGraph();
1873 TaskDescriptor taskDesc = fm.getTask();
1875 for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
1876 Descriptor paramDesc = taskDesc.getParameter(idx);
1877 TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
1879 // setup data structure
1880 Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet =
1881 new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
1882 Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode =
1883 new Hashtable<TypeDescriptor, HeapRegionNode>();
1884 Hashtable<HeapRegionNode, HeapRegionNode> mapToFirstDimensionArrayNode =
1885 new Hashtable<HeapRegionNode, HeapRegionNode>();
1886 Set<String> doneSet = new HashSet<String>();
1888 TempDescriptor tempDesc = fm.getParameter(idx);
1890 AllocSite as = createParameterAllocSite(rg, tempDesc, true);
1891 VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
1892 Integer idNewest = as.getIthOldest(0);
1893 HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
1895 // make a new reference to allocated node
1896 RefEdge edgeNew = new RefEdge(lnX, // source
1898 taskDesc.getParamType(idx), // type
1900 hrnNewest.getAlpha(), // beta
1901 ExistPredSet.factory(rg.predTrue) // predicates
1903 rg.addRefEdge(lnX, hrnNewest, edgeNew);
1905 // set-up a work set for class field
1906 ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
1907 for (Iterator it = classDesc.getFields(); it.hasNext();) {
1908 FieldDescriptor fd = (FieldDescriptor) it.next();
1909 TypeDescriptor fieldType = fd.getType();
1910 if (shouldAnalysisTrack( fieldType )) {
1911 HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
1912 newMap.put(hrnNewest, fd);
1913 workSet.add(newMap);
1917 int uniqueIdentifier = 0;
1918 while (!workSet.isEmpty()) {
1919 HashMap<HeapRegionNode, FieldDescriptor> map = workSet
1921 workSet.remove(map);
1923 Set<HeapRegionNode> key = map.keySet();
1924 HeapRegionNode srcHRN = key.iterator().next();
1925 FieldDescriptor fd = map.get(srcHRN);
1926 TypeDescriptor type = fd.getType();
1927 String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
1929 if (!doneSet.contains(doneSetIdentifier)) {
1930 doneSet.add(doneSetIdentifier);
1931 if (!mapTypeToExistingSummaryNode.containsKey(type)) {
1932 // create new summary Node
1933 TempDescriptor td = new TempDescriptor("temp"
1934 + uniqueIdentifier, type);
1936 AllocSite allocSite;
1937 if(type.equals(paramTypeDesc)){
1938 //corresponding allocsite has already been created for a parameter variable.
1941 allocSite = createParameterAllocSite(rg, td, false);
1943 String strDesc = allocSite.toStringForDOT()
1945 TypeDescriptor allocType=allocSite.getType();
1947 HeapRegionNode hrnSummary;
1948 if(allocType.isArray() && allocType.getArrayCount()>0){
1949 hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha());
1952 rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
1953 false, // single object?
1955 false, // out-of-context?
1956 allocSite.getType(), // type
1957 allocSite, // allocation site
1958 hrnNewest.getAlpha(), // inherent reach
1959 hrnNewest.getAlpha(), // current reach
1960 ExistPredSet.factory(rg.predTrue), // predicates
1961 strDesc // description
1963 rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
1965 // make a new reference to summary node
1966 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1969 fd.getSymbol(), // field name
1970 hrnNewest.getAlpha(), // beta
1971 ExistPredSet.factory(rg.predTrue) // predicates
1974 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1978 mapTypeToExistingSummaryNode.put(type, hrnSummary);
1980 // set-up a work set for fields of the class
1981 Set<FieldDescriptor> fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type);
1982 for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator
1984 FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator
1986 HeapRegionNode newDstHRN;
1987 if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)){
1988 //related heap region node is already exsited.
1989 newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary);
1991 newDstHRN=hrnSummary;
1993 doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor;
1994 if(!doneSet.contains(doneSetIdentifier)){
1995 // add new work item
1996 HashMap<HeapRegionNode, FieldDescriptor> newMap =
1997 new HashMap<HeapRegionNode, FieldDescriptor>();
1998 newMap.put(newDstHRN, fieldDescriptor);
1999 workSet.add(newMap);
2004 // if there exists corresponding summary node
2005 HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
2007 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2009 fd.getType(), // type
2010 fd.getSymbol(), // field name
2011 srcHRN.getAlpha(), // beta
2012 ExistPredSet.factory(rg.predTrue) // predicates
2014 rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
2020 // debugSnapshot(rg, fm, true);
2024 // return all allocation sites in the method (there is one allocation
2025 // site per FlatNew node in a method)
2026 private HashSet<AllocSite> getAllocationSiteSet(Descriptor d) {
2027 if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
2028 buildAllocationSiteSet(d);
2031 return mapDescriptorToAllocSiteSet.get(d);
2035 private void buildAllocationSiteSet(Descriptor d) {
2036 HashSet<AllocSite> s = new HashSet<AllocSite>();
2039 if( d instanceof MethodDescriptor ) {
2040 fm = state.getMethodFlat( (MethodDescriptor) d);
2042 assert d instanceof TaskDescriptor;
2043 fm = state.getMethodFlat( (TaskDescriptor) d);
2045 pm.analyzeMethod(fm);
2047 // visit every node in this FlatMethod's IR graph
2048 // and make a set of the allocation sites from the
2049 // FlatNew node's visited
2050 HashSet<FlatNode> visited = new HashSet<FlatNode>();
2051 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
2054 while( !toVisit.isEmpty() ) {
2055 FlatNode n = toVisit.iterator().next();
2057 if( n instanceof FlatNew ) {
2058 s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
2064 for( int i = 0; i < pm.numNext(n); ++i ) {
2065 FlatNode child = pm.getNext(n, i);
2066 if( !visited.contains(child) ) {
2072 mapDescriptorToAllocSiteSet.put(d, s);
2075 private HashSet<AllocSite> getFlaggedAllocationSites(Descriptor dIn) {
2077 HashSet<AllocSite> out = new HashSet<AllocSite>();
2078 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2079 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2083 while (!toVisit.isEmpty()) {
2084 Descriptor d = toVisit.iterator().next();
2088 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2089 Iterator asItr = asSet.iterator();
2090 while (asItr.hasNext()) {
2091 AllocSite as = (AllocSite) asItr.next();
2092 if (as.getDisjointAnalysisId() != null) {
2097 // enqueue callees of this method to be searched for
2098 // allocation sites also
2099 Set callees = callGraph.getCalleeSet(d);
2100 if (callees != null) {
2101 Iterator methItr = callees.iterator();
2102 while (methItr.hasNext()) {
2103 MethodDescriptor md = (MethodDescriptor) methItr.next();
2105 if (!visited.contains(md)) {
2116 private HashSet<AllocSite>
2117 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
2119 HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
2120 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2121 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2125 // traverse this task and all methods reachable from this task
2126 while( !toVisit.isEmpty() ) {
2127 Descriptor d = toVisit.iterator().next();
2131 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2132 Iterator asItr = asSet.iterator();
2133 while( asItr.hasNext() ) {
2134 AllocSite as = (AllocSite) asItr.next();
2135 TypeDescriptor typed = as.getType();
2136 if( typed != null ) {
2137 ClassDescriptor cd = typed.getClassDesc();
2138 if( cd != null && cd.hasFlags() ) {
2144 // enqueue callees of this method to be searched for
2145 // allocation sites also
2146 Set callees = callGraph.getCalleeSet(d);
2147 if( callees != null ) {
2148 Iterator methItr = callees.iterator();
2149 while( methItr.hasNext() ) {
2150 MethodDescriptor md = (MethodDescriptor) methItr.next();
2152 if( !visited.contains(md) ) {
2165 // get successive captures of the analysis state, use compiler
2167 boolean takeDebugSnapshots = false;
2168 String descSymbolDebug = null;
2169 boolean stopAfterCapture = false;
2170 int snapVisitCounter = 0;
2171 int snapNodeCounter = 0;
2172 int visitStartCapture = 0;
2173 int numVisitsToCapture = 0;
2176 void debugSnapshot( ReachGraph rg, FlatNode fn, boolean in ) {
2177 if( snapVisitCounter > visitStartCapture + numVisitsToCapture ) {
2185 if( snapVisitCounter >= visitStartCapture ) {
2186 System.out.println( " @@@ snapping visit="+snapVisitCounter+
2187 ", node="+snapNodeCounter+
2191 graphName = String.format( "snap%02d_%04din",
2195 graphName = String.format( "snap%02d_%04dout",
2200 graphName = graphName + fn;
2202 rg.writeGraph( graphName,
2203 true, // write labels (variables)
2204 true, // selectively hide intermediate temp vars
2205 true, // prune unreachable heap regions
2206 false, // hide subset reachability states
2207 true );// hide edge taints