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 // data from the compiler
325 public CallGraph callGraph;
326 public Liveness liveness;
327 public ArrayReferencees arrayReferencees;
328 public TypeUtil typeUtil;
329 public int allocationDepth;
331 // data structure for public interface
332 private Hashtable<Descriptor, HashSet<AllocSite> > mapDescriptorToAllocSiteSet;
335 // for public interface methods to warn that they
336 // are grabbing results during analysis
337 private boolean analysisComplete;
340 // used to identify HeapRegionNode objects
341 // A unique ID equates an object in one
342 // ownership graph with an object in another
343 // graph that logically represents the same
345 // start at 10 and increment to reserve some
346 // IDs for special purposes
347 static protected int uniqueIDcount = 10;
350 // An out-of-scope method created by the
351 // analysis that has no parameters, and
352 // appears to allocate the command line
353 // arguments, then invoke the source code's
354 // main method. The purpose of this is to
355 // provide the analysis with an explicit
356 // top-level context with no parameters
357 protected MethodDescriptor mdAnalysisEntry;
358 protected FlatMethod fmAnalysisEntry;
360 // main method defined by source program
361 protected MethodDescriptor mdSourceEntry;
363 // the set of task and/or method descriptors
364 // reachable in call graph
365 protected Set<Descriptor>
366 descriptorsToAnalyze;
368 // current descriptors to visit in fixed-point
369 // interprocedural analysis, prioritized by
370 // dependency in the call graph
371 protected Stack<Descriptor>
372 descriptorsToVisitStack;
373 protected PriorityQueue<DescriptorQWrapper>
376 // a duplication of the above structure, but
377 // for efficient testing of inclusion
378 protected HashSet<Descriptor>
379 descriptorsToVisitSet;
381 // storage for priorities (doesn't make sense)
382 // to add it to the Descriptor class, just in
384 protected Hashtable<Descriptor, Integer>
385 mapDescriptorToPriority;
387 // when analyzing a method and scheduling more:
388 // remember set of callee's enqueued for analysis
389 // so they can be put on top of the callers in
390 // the stack-visit mode
391 protected Set<Descriptor>
394 // maps a descriptor to its current partial result
395 // from the intraprocedural fixed-point analysis--
396 // then the interprocedural analysis settles, this
397 // mapping will have the final results for each
399 protected Hashtable<Descriptor, ReachGraph>
400 mapDescriptorToCompleteReachGraph;
402 // maps a descriptor to its known dependents: namely
403 // methods or tasks that call the descriptor's method
404 // AND are part of this analysis (reachable from main)
405 protected Hashtable< Descriptor, Set<Descriptor> >
406 mapDescriptorToSetDependents;
408 // maps each flat new to one analysis abstraction
409 // allocate site object, these exist outside reach graphs
410 protected Hashtable<FlatNew, AllocSite>
411 mapFlatNewToAllocSite;
413 // maps intergraph heap region IDs to intergraph
414 // allocation sites that created them, a redundant
415 // structure for efficiency in some operations
416 protected Hashtable<Integer, AllocSite>
419 // maps a method to its initial heap model (IHM) that
420 // is the set of reachability graphs from every caller
421 // site, all merged together. The reason that we keep
422 // them separate is that any one call site's contribution
423 // to the IHM may changed along the path to the fixed point
424 protected Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >
425 mapDescriptorToIHMcontributions;
427 // additionally, keep a mapping from descriptors to the
428 // merged in-coming initial context, because we want this
429 // initial context to be STRICTLY MONOTONIC
430 protected Hashtable<Descriptor, ReachGraph>
431 mapDescriptorToInitialContext;
433 // make the result for back edges analysis-wide STRICTLY
434 // MONOTONIC as well, but notice we use FlatNode as the
435 // key for this map: in case we want to consider other
436 // nodes as back edge's in future implementations
437 protected Hashtable<FlatNode, ReachGraph>
438 mapBackEdgeToMonotone;
441 public static final String arrayElementFieldName = "___element_";
442 static protected Hashtable<TypeDescriptor, FieldDescriptor>
445 // for controlling DOT file output
446 protected boolean writeFinalDOTs;
447 protected boolean writeAllIncrementalDOTs;
449 // supporting DOT output--when we want to write every
450 // partial method result, keep a tally for generating
452 protected Hashtable<Descriptor, Integer>
453 mapDescriptorToNumUpdates;
455 //map task descriptor to initial task parameter
456 protected Hashtable<Descriptor, ReachGraph>
457 mapDescriptorToReachGraph;
459 protected PointerMethod pm;
461 static protected Hashtable<FlatNode, ReachGraph> fn2rg =
462 new Hashtable<FlatNode, ReachGraph>();
465 // allocate various structures that are not local
466 // to a single class method--should be done once
467 protected void allocateStructures() {
469 if( determinismDesired ) {
470 // use an ordered set
472 = new TreeSet<Descriptor>( new DescriptorComparator() );
475 // otherwise use a speedy hashset
476 descriptorsToAnalyze = new HashSet<Descriptor>();
479 mapDescriptorToCompleteReachGraph =
480 new Hashtable<Descriptor, ReachGraph>();
482 mapDescriptorToNumUpdates =
483 new Hashtable<Descriptor, Integer>();
485 mapDescriptorToSetDependents =
486 new Hashtable< Descriptor, Set<Descriptor> >();
488 mapFlatNewToAllocSite =
489 new Hashtable<FlatNew, AllocSite>();
491 mapDescriptorToIHMcontributions =
492 new Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >();
494 mapDescriptorToInitialContext =
495 new Hashtable<Descriptor, ReachGraph>();
497 mapBackEdgeToMonotone =
498 new Hashtable<FlatNode, ReachGraph>();
500 mapHrnIdToAllocSite =
501 new Hashtable<Integer, AllocSite>();
503 mapTypeToArrayField =
504 new Hashtable <TypeDescriptor, FieldDescriptor>();
506 if( state.DISJOINTDVISITSTACK ||
507 state.DISJOINTDVISITSTACKEESONTOP
509 descriptorsToVisitStack =
510 new Stack<Descriptor>();
513 if( state.DISJOINTDVISITPQUE ) {
514 descriptorsToVisitQ =
515 new PriorityQueue<DescriptorQWrapper>();
518 descriptorsToVisitSet =
519 new HashSet<Descriptor>();
521 mapDescriptorToPriority =
522 new Hashtable<Descriptor, Integer>();
525 new HashSet<Descriptor>();
527 mapDescriptorToAllocSiteSet =
528 new Hashtable<Descriptor, HashSet<AllocSite> >();
530 mapDescriptorToReachGraph =
531 new Hashtable<Descriptor, ReachGraph>();
533 pm = new PointerMethod();
538 // this analysis generates a disjoint reachability
539 // graph for every reachable method in the program
540 public DisjointAnalysis( State s,
545 ) throws java.io.IOException {
546 init( s, tu, cg, l, ar );
549 protected void init( State state,
553 ArrayReferencees arrayReferencees
554 ) throws java.io.IOException {
556 analysisComplete = false;
559 this.typeUtil = typeUtil;
560 this.callGraph = callGraph;
561 this.liveness = liveness;
562 this.arrayReferencees = arrayReferencees;
563 this.allocationDepth = state.DISJOINTALLOCDEPTH;
564 this.releaseMode = state.DISJOINTRELEASEMODE;
565 this.determinismDesired = state.DISJOINTDETERMINISM;
567 this.writeFinalDOTs = state.DISJOINTWRITEDOTS && !state.DISJOINTWRITEALL;
568 this.writeAllIncrementalDOTs = state.DISJOINTWRITEDOTS && state.DISJOINTWRITEALL;
570 this.takeDebugSnapshots = state.DISJOINTSNAPSYMBOL != null;
571 this.descSymbolDebug = state.DISJOINTSNAPSYMBOL;
572 this.visitStartCapture = state.DISJOINTSNAPVISITTOSTART;
573 this.numVisitsToCapture = state.DISJOINTSNAPNUMVISITS;
574 this.stopAfterCapture = state.DISJOINTSNAPSTOPAFTER;
575 this.snapVisitCounter = 1; // count visits from 1 (user will write 1, means 1st visit)
576 this.snapNodeCounter = 0; // count nodes from 0
579 state.DISJOINTDVISITSTACK ||
580 state.DISJOINTDVISITPQUE ||
581 state.DISJOINTDVISITSTACKEESONTOP;
582 assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITPQUE);
583 assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITSTACKEESONTOP);
584 assert !(state.DISJOINTDVISITPQUE && state.DISJOINTDVISITSTACKEESONTOP);
586 // set some static configuration for ReachGraphs
587 ReachGraph.allocationDepth = allocationDepth;
588 ReachGraph.typeUtil = typeUtil;
590 ReachGraph.debugCallSiteVisitStartCapture
591 = state.DISJOINTDEBUGCALLVISITTOSTART;
593 ReachGraph.debugCallSiteNumVisitsToCapture
594 = state.DISJOINTDEBUGCALLNUMVISITS;
596 ReachGraph.debugCallSiteStopAfter
597 = state.DISJOINTDEBUGCALLSTOPAFTER;
599 ReachGraph.debugCallSiteVisitCounter
600 = 0; // count visits from 1, is incremented before first visit
604 allocateStructures();
606 double timeStartAnalysis = (double) System.nanoTime();
608 // start interprocedural fixed-point computation
610 analysisComplete=true;
612 double timeEndAnalysis = (double) System.nanoTime();
613 double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
614 String treport = String.format( "The reachability analysis took %.3f sec.", dt );
615 String justtime = String.format( "%.2f", dt );
616 System.out.println( treport );
618 if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
622 if( state.DISJOINTWRITEIHMS ) {
626 if( state.DISJOINTALIASFILE != null ) {
628 writeAllSharing(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines);
630 writeAllSharingJava(state.DISJOINTALIASFILE,
633 state.DISJOINTALIASTAB,
641 protected boolean moreDescriptorsToVisit() {
642 if( state.DISJOINTDVISITSTACK ||
643 state.DISJOINTDVISITSTACKEESONTOP
645 return !descriptorsToVisitStack.isEmpty();
647 } else if( state.DISJOINTDVISITPQUE ) {
648 return !descriptorsToVisitQ.isEmpty();
651 throw new Error( "Neither descriptor visiting mode set" );
655 // fixed-point computation over the call graph--when a
656 // method's callees are updated, it must be reanalyzed
657 protected void analyzeMethods() throws java.io.IOException {
659 // task or non-task (java) mode determines what the roots
660 // of the call chain are, and establishes the set of methods
661 // reachable from the roots that will be analyzed
664 System.out.println( "Bamboo mode..." );
666 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
667 while( taskItr.hasNext() ) {
668 TaskDescriptor td = (TaskDescriptor) taskItr.next();
669 if( !descriptorsToAnalyze.contains( td ) ) {
670 // add all methods transitively reachable from the
672 descriptorsToAnalyze.add( td );
673 descriptorsToAnalyze.addAll( callGraph.getAllMethods( td ) );
678 System.out.println( "Java mode..." );
680 // add all methods transitively reachable from the
681 // source's main to set for analysis
682 mdSourceEntry = typeUtil.getMain();
683 descriptorsToAnalyze.add( mdSourceEntry );
684 descriptorsToAnalyze.addAll( callGraph.getAllMethods( mdSourceEntry ) );
686 // fabricate an empty calling context that will call
687 // the source's main, but call graph doesn't know
688 // about it, so explicitly add it
689 makeAnalysisEntryMethod( mdSourceEntry );
690 descriptorsToAnalyze.add( mdAnalysisEntry );
694 // now, depending on the interprocedural mode for visiting
695 // methods, set up the needed data structures
697 if( state.DISJOINTDVISITPQUE ) {
699 // topologically sort according to the call graph so
700 // leaf calls are last, helps build contexts up first
701 LinkedList<Descriptor> sortedDescriptors =
702 topologicalSort( descriptorsToAnalyze );
704 // add sorted descriptors to priority queue, and duplicate
705 // the queue as a set for efficiently testing whether some
706 // method is marked for analysis
708 Iterator<Descriptor> dItr;
710 // for the priority queue, give items at the head
711 // of the sorted list a low number (highest priority)
712 while( !sortedDescriptors.isEmpty() ) {
713 Descriptor d = sortedDescriptors.removeFirst();
714 mapDescriptorToPriority.put( d, new Integer( p ) );
715 descriptorsToVisitQ.add( new DescriptorQWrapper( p, d ) );
716 descriptorsToVisitSet.add( d );
720 } else if( state.DISJOINTDVISITSTACK ||
721 state.DISJOINTDVISITSTACKEESONTOP
723 // if we're doing the stack scheme, just throw the root
724 // method or tasks on the stack
726 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
727 while( taskItr.hasNext() ) {
728 TaskDescriptor td = (TaskDescriptor) taskItr.next();
729 descriptorsToVisitStack.add( td );
730 descriptorsToVisitSet.add( td );
734 descriptorsToVisitStack.add( mdAnalysisEntry );
735 descriptorsToVisitSet.add( mdAnalysisEntry );
739 throw new Error( "Unknown method scheduling mode" );
743 // analyze scheduled methods until there are no more to visit
744 while( moreDescriptorsToVisit() ) {
747 if( state.DISJOINTDVISITSTACK ||
748 state.DISJOINTDVISITSTACKEESONTOP
750 d = descriptorsToVisitStack.pop();
752 } else if( state.DISJOINTDVISITPQUE ) {
753 d = descriptorsToVisitQ.poll().getDescriptor();
756 assert descriptorsToVisitSet.contains( d );
757 descriptorsToVisitSet.remove( d );
759 // because the task or method descriptor just extracted
760 // was in the "to visit" set it either hasn't been analyzed
761 // yet, or some method that it depends on has been
762 // updated. Recompute a complete reachability graph for
763 // this task/method and compare it to any previous result.
764 // If there is a change detected, add any methods/tasks
765 // that depend on this one to the "to visit" set.
767 System.out.println( "Analyzing " + d );
769 if( state.DISJOINTDVISITSTACKEESONTOP ) {
770 assert calleesToEnqueue.isEmpty();
773 ReachGraph rg = analyzeMethod( d );
774 ReachGraph rgPrev = getPartial( d );
776 if( !rg.equals( rgPrev ) ) {
779 if( state.DISJOINTDEBUGSCHEDULING ) {
780 System.out.println( " complete graph changed, scheduling callers for analysis:" );
783 // results for d changed, so enqueue dependents
784 // of d for further analysis
785 Iterator<Descriptor> depsItr = getDependents( d ).iterator();
786 while( depsItr.hasNext() ) {
787 Descriptor dNext = depsItr.next();
790 if( state.DISJOINTDEBUGSCHEDULING ) {
791 System.out.println( " "+dNext );
795 if( state.DISJOINTDVISITSTACKEESONTOP ) {
797 if( state.DISJOINTDEBUGSCHEDULING ) {
798 System.out.println( " contexts changed, scheduling callees for analysis:" );
801 depsItr = calleesToEnqueue.iterator();
802 while( depsItr.hasNext() ) {
803 Descriptor dNext = depsItr.next();
806 if( state.DISJOINTDEBUGSCHEDULING ) {
807 System.out.println( " "+dNext );
810 calleesToEnqueue.clear();
814 // we got the result result as the last visit
815 // to this method, but we might need to clean
817 if( state.DISJOINTDVISITSTACKEESONTOP ) {
818 calleesToEnqueue.clear();
825 protected ReachGraph analyzeMethod( Descriptor d )
826 throws java.io.IOException {
828 // get the flat code for this descriptor
830 if( d == mdAnalysisEntry ) {
831 fm = fmAnalysisEntry;
833 fm = state.getMethodFlat( d );
835 pm.analyzeMethod( fm );
837 // intraprocedural work set
838 Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
839 flatNodesToVisit.add( fm );
841 // if determinism is desired by client, shadow the
842 // set with a queue to make visit order deterministic
843 Queue<FlatNode> flatNodesToVisitQ = null;
844 if( determinismDesired ) {
845 flatNodesToVisitQ = new LinkedList<FlatNode>();
846 flatNodesToVisitQ.add( fm );
849 // mapping of current partial results
850 Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraph =
851 new Hashtable<FlatNode, ReachGraph>();
853 // the set of return nodes partial results that will be combined as
854 // the final, conservative approximation of the entire method
855 HashSet<FlatReturnNode> setReturns = new HashSet<FlatReturnNode>();
857 while( !flatNodesToVisit.isEmpty() ) {
860 if( determinismDesired ) {
861 assert !flatNodesToVisitQ.isEmpty();
862 fn = flatNodesToVisitQ.remove();
864 fn = flatNodesToVisit.iterator().next();
866 flatNodesToVisit.remove( fn );
868 // effect transfer function defined by this node,
869 // then compare it to the old graph at this node
870 // to see if anything was updated.
872 ReachGraph rg = new ReachGraph();
873 TaskDescriptor taskDesc;
874 if(fn instanceof FlatMethod && (taskDesc=((FlatMethod)fn).getTask())!=null){
875 if(mapDescriptorToReachGraph.containsKey(taskDesc)){
876 // retrieve existing reach graph if it is not first time
877 rg=mapDescriptorToReachGraph.get(taskDesc);
879 // create initial reach graph for a task
880 rg=createInitialTaskReachGraph((FlatMethod)fn);
882 mapDescriptorToReachGraph.put(taskDesc, rg);
886 // start by merging all node's parents' graphs
887 for( int i = 0; i < pm.numPrev(fn); ++i ) {
888 FlatNode pn = pm.getPrev(fn,i);
889 if( mapFlatNodeToReachGraph.containsKey( pn ) ) {
890 ReachGraph rgParent = mapFlatNodeToReachGraph.get( pn );
891 rg.merge( rgParent );
896 if( takeDebugSnapshots &&
897 d.getSymbol().equals( descSymbolDebug )
899 debugSnapshot( rg, fn, true );
903 // modify rg with appropriate transfer function
904 rg = analyzeFlatNode( d, fm, fn, setReturns, rg );
907 if( takeDebugSnapshots &&
908 d.getSymbol().equals( descSymbolDebug )
910 debugSnapshot( rg, fn, false );
915 // if the results of the new graph are different from
916 // the current graph at this node, replace the graph
917 // with the update and enqueue the children
918 ReachGraph rgPrev = mapFlatNodeToReachGraph.get( fn );
919 if( !rg.equals( rgPrev ) ) {
920 mapFlatNodeToReachGraph.put( fn, rg );
922 for( int i = 0; i < pm.numNext( fn ); i++ ) {
923 FlatNode nn = pm.getNext( fn, i );
925 flatNodesToVisit.add( nn );
926 if( determinismDesired ) {
927 flatNodesToVisitQ.add( nn );
934 // end by merging all return nodes into a complete
935 // reach graph that represents all possible heap
936 // states after the flat method returns
937 ReachGraph completeGraph = new ReachGraph();
939 assert !setReturns.isEmpty();
940 Iterator retItr = setReturns.iterator();
941 while( retItr.hasNext() ) {
942 FlatReturnNode frn = (FlatReturnNode) retItr.next();
944 assert mapFlatNodeToReachGraph.containsKey( frn );
945 ReachGraph rgRet = mapFlatNodeToReachGraph.get( frn );
947 completeGraph.merge( rgRet );
951 if( takeDebugSnapshots &&
952 d.getSymbol().equals( descSymbolDebug )
954 // increment that we've visited the debug snap
955 // method, and reset the node counter
956 System.out.println( " @@@ debug snap at visit "+snapVisitCounter );
960 if( snapVisitCounter == visitStartCapture + numVisitsToCapture &&
963 System.out.println( "!!! Stopping analysis after debug snap captures. !!!" );
969 return completeGraph;
974 analyzeFlatNode( Descriptor d,
975 FlatMethod fmContaining,
977 HashSet<FlatReturnNode> setRetNodes,
979 ) throws java.io.IOException {
982 // any variables that are no longer live should be
983 // nullified in the graph to reduce edges
984 //rg.nullifyDeadVars( liveness.getLiveInTemps( fmContaining, fn ) );
991 // use node type to decide what transfer function
992 // to apply to the reachability graph
993 switch( fn.kind() ) {
995 case FKind.FlatMethod: {
996 // construct this method's initial heap model (IHM)
997 // since we're working on the FlatMethod, we know
998 // the incoming ReachGraph 'rg' is empty
1000 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1001 getIHMcontributions( d );
1003 Set entrySet = heapsFromCallers.entrySet();
1004 Iterator itr = entrySet.iterator();
1005 while( itr.hasNext() ) {
1006 Map.Entry me = (Map.Entry) itr.next();
1007 FlatCall fc = (FlatCall) me.getKey();
1008 ReachGraph rgContrib = (ReachGraph) me.getValue();
1010 assert fc.getMethod().equals( d );
1012 rg.merge( rgContrib );
1015 // additionally, we are enforcing STRICT MONOTONICITY for the
1016 // method's initial context, so grow the context by whatever
1017 // the previously computed context was, and put the most
1018 // up-to-date context back in the map
1019 ReachGraph rgPrevContext = mapDescriptorToInitialContext.get( d );
1020 rg.merge( rgPrevContext );
1021 mapDescriptorToInitialContext.put( d, rg );
1025 case FKind.FlatOpNode:
1026 FlatOpNode fon = (FlatOpNode) fn;
1027 if( fon.getOp().getOp() == Operation.ASSIGN ) {
1028 lhs = fon.getDest();
1029 rhs = fon.getLeft();
1030 rg.assignTempXEqualToTempY( lhs, rhs );
1034 case FKind.FlatCastNode:
1035 FlatCastNode fcn = (FlatCastNode) fn;
1039 TypeDescriptor td = fcn.getType();
1042 rg.assignTempXEqualToCastedTempY( lhs, rhs, td );
1045 case FKind.FlatFieldNode:
1046 FlatFieldNode ffn = (FlatFieldNode) fn;
1049 fld = ffn.getField();
1050 if( shouldAnalysisTrack( fld.getType() ) ) {
1051 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fld );
1055 case FKind.FlatSetFieldNode:
1056 FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
1057 lhs = fsfn.getDst();
1058 fld = fsfn.getField();
1059 rhs = fsfn.getSrc();
1060 if( shouldAnalysisTrack( fld.getType() ) ) {
1061 rg.assignTempXFieldFEqualToTempY( lhs, fld, rhs );
1065 case FKind.FlatElementNode:
1066 FlatElementNode fen = (FlatElementNode) fn;
1069 if( shouldAnalysisTrack( lhs.getType() ) ) {
1071 assert rhs.getType() != null;
1072 assert rhs.getType().isArray();
1074 TypeDescriptor tdElement = rhs.getType().dereference();
1075 FieldDescriptor fdElement = getArrayField( tdElement );
1077 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fdElement );
1081 case FKind.FlatSetElementNode:
1082 FlatSetElementNode fsen = (FlatSetElementNode) fn;
1084 if( arrayReferencees.doesNotCreateNewReaching( fsen ) ) {
1085 // skip this node if it cannot create new reachability paths
1089 lhs = fsen.getDst();
1090 rhs = fsen.getSrc();
1091 if( shouldAnalysisTrack( rhs.getType() ) ) {
1093 assert lhs.getType() != null;
1094 assert lhs.getType().isArray();
1096 TypeDescriptor tdElement = lhs.getType().dereference();
1097 FieldDescriptor fdElement = getArrayField( tdElement );
1099 rg.assignTempXFieldFEqualToTempY( lhs, fdElement, rhs );
1104 FlatNew fnn = (FlatNew) fn;
1106 if( shouldAnalysisTrack( lhs.getType() ) ) {
1107 AllocSite as = getAllocSiteFromFlatNewPRIVATE( fnn );
1108 rg.assignTempEqualToNewAlloc( lhs, as );
1112 case FKind.FlatCall: {
1113 Descriptor mdCaller;
1114 if( fmContaining.getMethod() != null ){
1115 mdCaller = fmContaining.getMethod();
1117 mdCaller = fmContaining.getTask();
1119 FlatCall fc = (FlatCall) fn;
1120 MethodDescriptor mdCallee = fc.getMethod();
1121 FlatMethod fmCallee = state.getMethodFlat( mdCallee );
1124 boolean debugCallSite =
1125 mdCaller.getSymbol().equals( state.DISJOINTDEBUGCALLER ) &&
1126 mdCallee.getSymbol().equals( state.DISJOINTDEBUGCALLEE );
1128 boolean writeDebugDOTs = false;
1129 boolean stopAfter = false;
1130 if( debugCallSite ) {
1131 ++ReachGraph.debugCallSiteVisitCounter;
1132 System.out.println( " $$$ Debug call site visit "+
1133 ReachGraph.debugCallSiteVisitCounter+
1137 (ReachGraph.debugCallSiteVisitCounter >=
1138 ReachGraph.debugCallSiteVisitStartCapture) &&
1140 (ReachGraph.debugCallSiteVisitCounter <
1141 ReachGraph.debugCallSiteVisitStartCapture +
1142 ReachGraph.debugCallSiteNumVisitsToCapture)
1144 writeDebugDOTs = true;
1145 System.out.println( " $$$ Capturing this call site visit $$$" );
1146 if( ReachGraph.debugCallSiteStopAfter &&
1147 (ReachGraph.debugCallSiteVisitCounter ==
1148 ReachGraph.debugCallSiteVisitStartCapture +
1149 ReachGraph.debugCallSiteNumVisitsToCapture - 1)
1157 // calculate the heap this call site can reach--note this is
1158 // not used for the current call site transform, we are
1159 // grabbing this heap model for future analysis of the callees,
1160 // so if different results emerge we will return to this site
1161 ReachGraph heapForThisCall_old =
1162 getIHMcontribution( mdCallee, fc );
1164 // the computation of the callee-reachable heap
1165 // is useful for making the callee starting point
1166 // and for applying the call site transfer function
1167 Set<Integer> callerNodeIDsCopiedToCallee =
1168 new HashSet<Integer>();
1170 ReachGraph heapForThisCall_cur =
1171 rg.makeCalleeView( fc,
1173 callerNodeIDsCopiedToCallee,
1177 if( !heapForThisCall_cur.equals( heapForThisCall_old ) ) {
1178 // if heap at call site changed, update the contribution,
1179 // and reschedule the callee for analysis
1180 addIHMcontribution( mdCallee, fc, heapForThisCall_cur );
1182 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1183 calleesToEnqueue.add( mdCallee );
1185 enqueue( mdCallee );
1187 if( state.DISJOINTDEBUGSCHEDULING ) {
1188 System.out.println( " context changed, scheduling callee: "+mdCallee );
1196 // the transformation for a call site should update the
1197 // current heap abstraction with any effects from the callee,
1198 // or if the method is virtual, the effects from any possible
1199 // callees, so find the set of callees...
1200 Set<MethodDescriptor> setPossibleCallees =
1201 new HashSet<MethodDescriptor>();
1203 if( mdCallee.isStatic() ) {
1204 setPossibleCallees.add( mdCallee );
1206 TypeDescriptor typeDesc = fc.getThis().getType();
1207 setPossibleCallees.addAll( callGraph.getMethods( mdCallee,
1212 ReachGraph rgMergeOfEffects = new ReachGraph();
1214 Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
1215 while( mdItr.hasNext() ) {
1216 MethodDescriptor mdPossible = mdItr.next();
1217 FlatMethod fmPossible = state.getMethodFlat( mdPossible );
1219 addDependent( mdPossible, // callee
1222 // don't alter the working graph (rg) until we compute a
1223 // result for every possible callee, merge them all together,
1224 // then set rg to that
1225 ReachGraph rgCopy = new ReachGraph();
1228 ReachGraph rgEffect = getPartial( mdPossible );
1230 if( rgEffect == null ) {
1231 // if this method has never been analyzed just schedule it
1232 // for analysis and skip over this call site for now
1233 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1234 calleesToEnqueue.add( mdPossible );
1236 enqueue( mdPossible );
1238 if( state.DISJOINTDEBUGSCHEDULING ) {
1239 System.out.println( " callee hasn't been analyzed, scheduling: "+mdPossible );
1244 rgCopy.resolveMethodCall( fc,
1247 callerNodeIDsCopiedToCallee,
1252 rgMergeOfEffects.merge( rgCopy );
1257 System.out.println( "$$$ Exiting after requested captures of call site. $$$" );
1262 // now that we've taken care of building heap models for
1263 // callee analysis, finish this transformation
1264 rg = rgMergeOfEffects;
1268 case FKind.FlatReturnNode:
1269 FlatReturnNode frn = (FlatReturnNode) fn;
1270 rhs = frn.getReturnTemp();
1271 if( rhs != null && shouldAnalysisTrack( rhs.getType() ) ) {
1272 rg.assignReturnEqualToTemp( rhs );
1274 setRetNodes.add( frn );
1280 // dead variables were removed before the above transfer function
1281 // was applied, so eliminate heap regions and edges that are no
1282 // longer part of the abstractly-live heap graph, and sweep up
1283 // and reachability effects that are altered by the reduction
1284 //rg.abstractGarbageCollect();
1288 // back edges are strictly monotonic
1289 if( pm.isBackEdge( fn ) ) {
1290 ReachGraph rgPrevResult = mapBackEdgeToMonotone.get( fn );
1291 rg.merge( rgPrevResult );
1292 mapBackEdgeToMonotone.put( fn, rg );
1295 // at this point rg should be the correct update
1296 // by an above transfer function, or untouched if
1297 // the flat node type doesn't affect the heap
1303 // this method should generate integers strictly greater than zero!
1304 // special "shadow" regions are made from a heap region by negating
1306 static public Integer generateUniqueHeapRegionNodeID() {
1308 return new Integer( uniqueIDcount );
1313 static public FieldDescriptor getArrayField( TypeDescriptor tdElement ) {
1314 FieldDescriptor fdElement = mapTypeToArrayField.get( tdElement );
1315 if( fdElement == null ) {
1316 fdElement = new FieldDescriptor( new Modifiers( Modifiers.PUBLIC ),
1318 arrayElementFieldName,
1321 mapTypeToArrayField.put( tdElement, fdElement );
1328 private void writeFinalGraphs() {
1329 Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
1330 Iterator itr = entrySet.iterator();
1331 while( itr.hasNext() ) {
1332 Map.Entry me = (Map.Entry) itr.next();
1333 Descriptor d = (Descriptor) me.getKey();
1334 ReachGraph rg = (ReachGraph) me.getValue();
1336 rg.writeGraph( "COMPLETE"+d,
1337 true, // write labels (variables)
1338 true, // selectively hide intermediate temp vars
1339 true, // prune unreachable heap regions
1340 false, // hide subset reachability states
1341 true ); // hide edge taints
1345 private void writeFinalIHMs() {
1346 Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
1347 while( d2IHMsItr.hasNext() ) {
1348 Map.Entry me1 = (Map.Entry) d2IHMsItr.next();
1349 Descriptor d = (Descriptor) me1.getKey();
1350 Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>) me1.getValue();
1352 Iterator fc2rgItr = IHMs.entrySet().iterator();
1353 while( fc2rgItr.hasNext() ) {
1354 Map.Entry me2 = (Map.Entry) fc2rgItr.next();
1355 FlatCall fc = (FlatCall) me2.getKey();
1356 ReachGraph rg = (ReachGraph) me2.getValue();
1358 rg.writeGraph( "IHMPARTFOR"+d+"FROM"+fc,
1359 true, // write labels (variables)
1360 true, // selectively hide intermediate temp vars
1361 true, // prune unreachable heap regions
1362 false, // hide subset reachability states
1363 true ); // hide edge taints
1369 protected ReachGraph getPartial( Descriptor d ) {
1370 return mapDescriptorToCompleteReachGraph.get( d );
1373 protected void setPartial( Descriptor d, ReachGraph rg ) {
1374 mapDescriptorToCompleteReachGraph.put( d, rg );
1376 // when the flag for writing out every partial
1377 // result is set, we should spit out the graph,
1378 // but in order to give it a unique name we need
1379 // to track how many partial results for this
1380 // descriptor we've already written out
1381 if( writeAllIncrementalDOTs ) {
1382 if( !mapDescriptorToNumUpdates.containsKey( d ) ) {
1383 mapDescriptorToNumUpdates.put( d, new Integer( 0 ) );
1385 Integer n = mapDescriptorToNumUpdates.get( d );
1387 rg.writeGraph( d+"COMPLETE"+String.format( "%05d", n ),
1388 true, // write labels (variables)
1389 true, // selectively hide intermediate temp vars
1390 true, // prune unreachable heap regions
1391 false, // hide subset reachability states
1392 true ); // hide edge taints
1394 mapDescriptorToNumUpdates.put( d, n + 1 );
1400 // return just the allocation site associated with one FlatNew node
1401 protected AllocSite getAllocSiteFromFlatNewPRIVATE( FlatNew fnew ) {
1403 if( !mapFlatNewToAllocSite.containsKey( fnew ) ) {
1404 AllocSite as = AllocSite.factory( allocationDepth,
1406 fnew.getDisjointId()
1409 // the newest nodes are single objects
1410 for( int i = 0; i < allocationDepth; ++i ) {
1411 Integer id = generateUniqueHeapRegionNodeID();
1412 as.setIthOldest( i, id );
1413 mapHrnIdToAllocSite.put( id, as );
1416 // the oldest node is a summary node
1417 as.setSummary( generateUniqueHeapRegionNodeID() );
1419 mapFlatNewToAllocSite.put( fnew, as );
1422 return mapFlatNewToAllocSite.get( fnew );
1426 public static boolean shouldAnalysisTrack( TypeDescriptor type ) {
1427 // don't track primitive types, but an array
1428 // of primitives is heap memory
1429 if( type.isImmutable() ) {
1430 return type.isArray();
1433 // everything else is an object
1437 protected int numMethodsAnalyzed() {
1438 return descriptorsToAnalyze.size();
1445 // Take in source entry which is the program's compiled entry and
1446 // create a new analysis entry, a method that takes no parameters
1447 // and appears to allocate the command line arguments and call the
1448 // source entry with them. The purpose of this analysis entry is
1449 // to provide a top-level method context with no parameters left.
1450 protected void makeAnalysisEntryMethod( MethodDescriptor mdSourceEntry ) {
1452 Modifiers mods = new Modifiers();
1453 mods.addModifier( Modifiers.PUBLIC );
1454 mods.addModifier( Modifiers.STATIC );
1456 TypeDescriptor returnType =
1457 new TypeDescriptor( TypeDescriptor.VOID );
1459 this.mdAnalysisEntry =
1460 new MethodDescriptor( mods,
1462 "analysisEntryMethod"
1465 TempDescriptor cmdLineArgs =
1466 new TempDescriptor( "args",
1467 mdSourceEntry.getParamType( 0 )
1471 new FlatNew( mdSourceEntry.getParamType( 0 ),
1476 TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
1477 sourceEntryArgs[0] = cmdLineArgs;
1480 new FlatCall( mdSourceEntry,
1486 FlatReturnNode frn = new FlatReturnNode( null );
1488 FlatExit fe = new FlatExit();
1490 this.fmAnalysisEntry =
1491 new FlatMethod( mdAnalysisEntry,
1495 this.fmAnalysisEntry.addNext( fn );
1502 protected LinkedList<Descriptor> topologicalSort( Set<Descriptor> toSort ) {
1504 Set<Descriptor> discovered;
1506 if( determinismDesired ) {
1507 // use an ordered set
1509 = new TreeSet<Descriptor>( new DescriptorComparator() );
1512 // otherwise use a speedy hashset
1513 discovered = new HashSet<Descriptor>();
1516 LinkedList<Descriptor> sorted = new LinkedList<Descriptor>();
1518 Iterator<Descriptor> itr = toSort.iterator();
1519 while( itr.hasNext() ) {
1520 Descriptor d = itr.next();
1522 if( !discovered.contains( d ) ) {
1523 dfsVisit( d, toSort, sorted, discovered );
1530 // While we're doing DFS on call graph, remember
1531 // dependencies for efficient queuing of methods
1532 // during interprocedural analysis:
1534 // a dependent of a method decriptor d for this analysis is:
1535 // 1) a method or task that invokes d
1536 // 2) in the descriptorsToAnalyze set
1537 protected void dfsVisit( Descriptor d,
1538 Set <Descriptor> toSort,
1539 LinkedList<Descriptor> sorted,
1540 Set <Descriptor> discovered ) {
1541 discovered.add( d );
1543 // only methods have callers, tasks never do
1544 if( d instanceof MethodDescriptor ) {
1546 MethodDescriptor md = (MethodDescriptor) d;
1548 // the call graph is not aware that we have a fabricated
1549 // analysis entry that calls the program source's entry
1550 if( md == mdSourceEntry ) {
1551 if( !discovered.contains( mdAnalysisEntry ) ) {
1552 addDependent( mdSourceEntry, // callee
1553 mdAnalysisEntry // caller
1555 dfsVisit( mdAnalysisEntry, toSort, sorted, discovered );
1559 // otherwise call graph guides DFS
1560 Iterator itr = callGraph.getCallerSet( md ).iterator();
1561 while( itr.hasNext() ) {
1562 Descriptor dCaller = (Descriptor) itr.next();
1564 // only consider callers in the original set to analyze
1565 if( !toSort.contains( dCaller ) ) {
1569 if( !discovered.contains( dCaller ) ) {
1570 addDependent( md, // callee
1574 dfsVisit( dCaller, toSort, sorted, discovered );
1579 // for leaf-nodes last now!
1580 sorted.addLast( d );
1584 protected void enqueue( Descriptor d ) {
1586 if( !descriptorsToVisitSet.contains( d ) ) {
1588 if( state.DISJOINTDVISITSTACK ||
1589 state.DISJOINTDVISITSTACKEESONTOP
1591 descriptorsToVisitStack.add( d );
1593 } else if( state.DISJOINTDVISITPQUE ) {
1594 Integer priority = mapDescriptorToPriority.get( d );
1595 descriptorsToVisitQ.add( new DescriptorQWrapper( priority,
1600 descriptorsToVisitSet.add( d );
1605 // a dependent of a method decriptor d for this analysis is:
1606 // 1) a method or task that invokes d
1607 // 2) in the descriptorsToAnalyze set
1608 protected void addDependent( Descriptor callee, Descriptor caller ) {
1609 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1610 if( deps == null ) {
1611 deps = new HashSet<Descriptor>();
1614 mapDescriptorToSetDependents.put( callee, deps );
1617 protected Set<Descriptor> getDependents( Descriptor callee ) {
1618 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1619 if( deps == null ) {
1620 deps = new HashSet<Descriptor>();
1621 mapDescriptorToSetDependents.put( callee, deps );
1627 public Hashtable<FlatCall, ReachGraph> getIHMcontributions( Descriptor d ) {
1629 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1630 mapDescriptorToIHMcontributions.get( d );
1632 if( heapsFromCallers == null ) {
1633 heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
1634 mapDescriptorToIHMcontributions.put( d, heapsFromCallers );
1637 return heapsFromCallers;
1640 public ReachGraph getIHMcontribution( Descriptor d,
1643 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1644 getIHMcontributions( d );
1646 if( !heapsFromCallers.containsKey( fc ) ) {
1647 heapsFromCallers.put( fc, new ReachGraph() );
1650 return heapsFromCallers.get( fc );
1653 public void addIHMcontribution( Descriptor d,
1657 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1658 getIHMcontributions( d );
1660 heapsFromCallers.put( fc, rg );
1663 private AllocSite createParameterAllocSite( ReachGraph rg,
1664 TempDescriptor tempDesc,
1670 flatNew = new FlatNew( tempDesc.getType(), // type
1671 tempDesc, // param temp
1672 false, // global alloc?
1673 "param"+tempDesc // disjoint site ID string
1676 flatNew = new FlatNew( tempDesc.getType(), // type
1677 tempDesc, // param temp
1678 false, // global alloc?
1679 null // disjoint site ID string
1683 // create allocation site
1684 AllocSite as = AllocSite.factory( allocationDepth,
1686 flatNew.getDisjointId()
1688 for (int i = 0; i < allocationDepth; ++i) {
1689 Integer id = generateUniqueHeapRegionNodeID();
1690 as.setIthOldest(i, id);
1691 mapHrnIdToAllocSite.put(id, as);
1693 // the oldest node is a summary node
1694 as.setSummary( generateUniqueHeapRegionNodeID() );
1702 private Set<FieldDescriptor> getFieldSetTobeAnalyzed(TypeDescriptor typeDesc){
1704 Set<FieldDescriptor> fieldSet=new HashSet<FieldDescriptor>();
1705 if(!typeDesc.isImmutable()){
1706 ClassDescriptor classDesc = typeDesc.getClassDesc();
1707 for (Iterator it = classDesc.getFields(); it.hasNext();) {
1708 FieldDescriptor field = (FieldDescriptor) it.next();
1709 TypeDescriptor fieldType = field.getType();
1710 if (shouldAnalysisTrack( fieldType )) {
1711 fieldSet.add(field);
1719 private HeapRegionNode createMultiDeimensionalArrayHRN(ReachGraph rg, AllocSite alloc, HeapRegionNode srcHRN, FieldDescriptor fd, Hashtable<HeapRegionNode, HeapRegionNode> map, Hashtable<TypeDescriptor, HeapRegionNode> mapToExistingNode, ReachSet alpha ){
1721 int dimCount=fd.getType().getArrayCount();
1722 HeapRegionNode prevNode=null;
1723 HeapRegionNode arrayEntryNode=null;
1724 for(int i=dimCount;i>0;i--){
1725 TypeDescriptor typeDesc=fd.getType().dereference();//hack to get instance of type desc
1726 typeDesc.setArrayCount(i);
1727 TempDescriptor tempDesc=new TempDescriptor(typeDesc.getSymbol(),typeDesc);
1728 HeapRegionNode hrnSummary ;
1729 if(!mapToExistingNode.containsKey(typeDesc)){
1734 as = createParameterAllocSite(rg, tempDesc, false);
1736 // make a new reference to allocated node
1738 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1739 false, // single object?
1741 false, // out-of-context?
1742 as.getType(), // type
1743 as, // allocation site
1744 alpha, // inherent reach
1745 alpha, // current reach
1746 ExistPredSet.factory(rg.predTrue), // predicates
1747 tempDesc.toString() // description
1749 rg.id2hrn.put(as.getSummary(),hrnSummary);
1751 mapToExistingNode.put(typeDesc, hrnSummary);
1753 hrnSummary=mapToExistingNode.get(typeDesc);
1757 // make a new reference between new summary node and source
1758 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1761 fd.getSymbol(), // field name
1763 ExistPredSet.factory(rg.predTrue) // predicates
1766 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1767 prevNode=hrnSummary;
1768 arrayEntryNode=hrnSummary;
1770 // make a new reference between summary nodes of array
1771 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1774 arrayElementFieldName, // field name
1776 ExistPredSet.factory(rg.predTrue) // predicates
1779 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1780 prevNode=hrnSummary;
1785 // create a new obj node if obj has at least one non-primitive field
1786 TypeDescriptor type=fd.getType();
1787 if(getFieldSetTobeAnalyzed(type).size()>0){
1788 TypeDescriptor typeDesc=type.dereference();
1789 typeDesc.setArrayCount(0);
1790 if(!mapToExistingNode.containsKey(typeDesc)){
1791 TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc);
1792 AllocSite as = createParameterAllocSite(rg, tempDesc, false);
1793 // make a new reference to allocated node
1794 HeapRegionNode hrnSummary =
1795 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1796 false, // single object?
1798 false, // out-of-context?
1800 as, // allocation site
1801 alpha, // inherent reach
1802 alpha, // current reach
1803 ExistPredSet.factory(rg.predTrue), // predicates
1804 tempDesc.toString() // description
1806 rg.id2hrn.put(as.getSummary(),hrnSummary);
1807 mapToExistingNode.put(typeDesc, hrnSummary);
1808 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1811 arrayElementFieldName, // field name
1813 ExistPredSet.factory(rg.predTrue) // predicates
1815 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1816 prevNode=hrnSummary;
1818 HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc);
1819 if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null){
1820 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1823 arrayElementFieldName, // field name
1825 ExistPredSet.factory(rg.predTrue) // predicates
1827 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1829 prevNode=hrnSummary;
1833 map.put(arrayEntryNode, prevNode);
1834 return arrayEntryNode;
1837 private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
1838 ReachGraph rg = new ReachGraph();
1839 TaskDescriptor taskDesc = fm.getTask();
1841 for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
1842 Descriptor paramDesc = taskDesc.getParameter(idx);
1843 TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
1845 // setup data structure
1846 Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet =
1847 new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
1848 Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode =
1849 new Hashtable<TypeDescriptor, HeapRegionNode>();
1850 Hashtable<HeapRegionNode, HeapRegionNode> mapToFirstDimensionArrayNode =
1851 new Hashtable<HeapRegionNode, HeapRegionNode>();
1852 Set<String> doneSet = new HashSet<String>();
1854 TempDescriptor tempDesc = fm.getParameter(idx);
1856 AllocSite as = createParameterAllocSite(rg, tempDesc, true);
1857 VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
1858 Integer idNewest = as.getIthOldest(0);
1859 HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
1861 // make a new reference to allocated node
1862 RefEdge edgeNew = new RefEdge(lnX, // source
1864 taskDesc.getParamType(idx), // type
1866 hrnNewest.getAlpha(), // beta
1867 ExistPredSet.factory(rg.predTrue) // predicates
1869 rg.addRefEdge(lnX, hrnNewest, edgeNew);
1871 // set-up a work set for class field
1872 ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
1873 for (Iterator it = classDesc.getFields(); it.hasNext();) {
1874 FieldDescriptor fd = (FieldDescriptor) it.next();
1875 TypeDescriptor fieldType = fd.getType();
1876 if (shouldAnalysisTrack( fieldType )) {
1877 HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
1878 newMap.put(hrnNewest, fd);
1879 workSet.add(newMap);
1883 int uniqueIdentifier = 0;
1884 while (!workSet.isEmpty()) {
1885 HashMap<HeapRegionNode, FieldDescriptor> map = workSet
1887 workSet.remove(map);
1889 Set<HeapRegionNode> key = map.keySet();
1890 HeapRegionNode srcHRN = key.iterator().next();
1891 FieldDescriptor fd = map.get(srcHRN);
1892 TypeDescriptor type = fd.getType();
1893 String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
1895 if (!doneSet.contains(doneSetIdentifier)) {
1896 doneSet.add(doneSetIdentifier);
1897 if (!mapTypeToExistingSummaryNode.containsKey(type)) {
1898 // create new summary Node
1899 TempDescriptor td = new TempDescriptor("temp"
1900 + uniqueIdentifier, type);
1902 AllocSite allocSite;
1903 if(type.equals(paramTypeDesc)){
1904 //corresponding allocsite has already been created for a parameter variable.
1907 allocSite = createParameterAllocSite(rg, td, false);
1909 String strDesc = allocSite.toStringForDOT()
1911 TypeDescriptor allocType=allocSite.getType();
1913 HeapRegionNode hrnSummary;
1914 if(allocType.isArray() && allocType.getArrayCount()>0){
1915 hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha());
1918 rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
1919 false, // single object?
1921 false, // out-of-context?
1922 allocSite.getType(), // type
1923 allocSite, // allocation site
1924 hrnNewest.getAlpha(), // inherent reach
1925 hrnNewest.getAlpha(), // current reach
1926 ExistPredSet.factory(rg.predTrue), // predicates
1927 strDesc // description
1929 rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
1931 // make a new reference to summary node
1932 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1935 fd.getSymbol(), // field name
1936 hrnNewest.getAlpha(), // beta
1937 ExistPredSet.factory(rg.predTrue) // predicates
1940 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1944 mapTypeToExistingSummaryNode.put(type, hrnSummary);
1946 // set-up a work set for fields of the class
1947 Set<FieldDescriptor> fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type);
1948 for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator
1950 FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator
1952 HeapRegionNode newDstHRN;
1953 if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)){
1954 //related heap region node is already exsited.
1955 newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary);
1957 newDstHRN=hrnSummary;
1959 doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor;
1960 if(!doneSet.contains(doneSetIdentifier)){
1961 // add new work item
1962 HashMap<HeapRegionNode, FieldDescriptor> newMap =
1963 new HashMap<HeapRegionNode, FieldDescriptor>();
1964 newMap.put(newDstHRN, fieldDescriptor);
1965 workSet.add(newMap);
1970 // if there exists corresponding summary node
1971 HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
1973 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1975 fd.getType(), // type
1976 fd.getSymbol(), // field name
1977 srcHRN.getAlpha(), // beta
1978 ExistPredSet.factory(rg.predTrue) // predicates
1980 rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
1986 // debugSnapshot(rg, fm, true);
1990 // return all allocation sites in the method (there is one allocation
1991 // site per FlatNew node in a method)
1992 private HashSet<AllocSite> getAllocationSiteSet(Descriptor d) {
1993 if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
1994 buildAllocationSiteSet(d);
1997 return mapDescriptorToAllocSiteSet.get(d);
2001 private void buildAllocationSiteSet(Descriptor d) {
2002 HashSet<AllocSite> s = new HashSet<AllocSite>();
2005 if( d instanceof MethodDescriptor ) {
2006 fm = state.getMethodFlat( (MethodDescriptor) d);
2008 assert d instanceof TaskDescriptor;
2009 fm = state.getMethodFlat( (TaskDescriptor) d);
2011 pm.analyzeMethod(fm);
2013 // visit every node in this FlatMethod's IR graph
2014 // and make a set of the allocation sites from the
2015 // FlatNew node's visited
2016 HashSet<FlatNode> visited = new HashSet<FlatNode>();
2017 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
2020 while( !toVisit.isEmpty() ) {
2021 FlatNode n = toVisit.iterator().next();
2023 if( n instanceof FlatNew ) {
2024 s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
2030 for( int i = 0; i < pm.numNext(n); ++i ) {
2031 FlatNode child = pm.getNext(n, i);
2032 if( !visited.contains(child) ) {
2038 mapDescriptorToAllocSiteSet.put(d, s);
2041 private HashSet<AllocSite> getFlaggedAllocationSites(Descriptor dIn) {
2043 HashSet<AllocSite> out = new HashSet<AllocSite>();
2044 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2045 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2049 while (!toVisit.isEmpty()) {
2050 Descriptor d = toVisit.iterator().next();
2054 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2055 Iterator asItr = asSet.iterator();
2056 while (asItr.hasNext()) {
2057 AllocSite as = (AllocSite) asItr.next();
2058 if (as.getDisjointAnalysisId() != null) {
2063 // enqueue callees of this method to be searched for
2064 // allocation sites also
2065 Set callees = callGraph.getCalleeSet(d);
2066 if (callees != null) {
2067 Iterator methItr = callees.iterator();
2068 while (methItr.hasNext()) {
2069 MethodDescriptor md = (MethodDescriptor) methItr.next();
2071 if (!visited.contains(md)) {
2082 private HashSet<AllocSite>
2083 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
2085 HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
2086 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2087 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2091 // traverse this task and all methods reachable from this task
2092 while( !toVisit.isEmpty() ) {
2093 Descriptor d = toVisit.iterator().next();
2097 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2098 Iterator asItr = asSet.iterator();
2099 while( asItr.hasNext() ) {
2100 AllocSite as = (AllocSite) asItr.next();
2101 TypeDescriptor typed = as.getType();
2102 if( typed != null ) {
2103 ClassDescriptor cd = typed.getClassDesc();
2104 if( cd != null && cd.hasFlags() ) {
2110 // enqueue callees of this method to be searched for
2111 // allocation sites also
2112 Set callees = callGraph.getCalleeSet(d);
2113 if( callees != null ) {
2114 Iterator methItr = callees.iterator();
2115 while( methItr.hasNext() ) {
2116 MethodDescriptor md = (MethodDescriptor) methItr.next();
2118 if( !visited.contains(md) ) {
2131 // get successive captures of the analysis state, use compiler
2133 boolean takeDebugSnapshots = false;
2134 String descSymbolDebug = null;
2135 boolean stopAfterCapture = false;
2136 int snapVisitCounter = 0;
2137 int snapNodeCounter = 0;
2138 int visitStartCapture = 0;
2139 int numVisitsToCapture = 0;
2142 void debugSnapshot( ReachGraph rg, FlatNode fn, boolean in ) {
2143 if( snapVisitCounter > visitStartCapture + numVisitsToCapture ) {
2151 if( snapVisitCounter >= visitStartCapture ) {
2152 System.out.println( " @@@ snapping visit="+snapVisitCounter+
2153 ", node="+snapNodeCounter+
2157 graphName = String.format( "snap%02d_%04din",
2161 graphName = String.format( "snap%02d_%04dout",
2166 graphName = graphName + fn;
2168 rg.writeGraph( graphName,
2169 true, // write labels (variables)
2170 true, // selectively hide intermediate temp vars
2171 true, // prune unreachable heap regions
2172 false, // hide subset reachability states
2173 true );// hide edge taints