1 package Analysis.Disjoint;
3 import Analysis.CallGraph.*;
4 import Analysis.Liveness;
5 import Analysis.ArrayReferencees;
6 import Analysis.RBlockRelationAnalysis;
9 import IR.Tree.Modifiers;
14 public class DisjointAnalysis {
16 ///////////////////////////////////////////
18 // Public interface to discover possible
19 // aliases in the program under analysis
21 ///////////////////////////////////////////
23 public HashSet<AllocSite>
24 getFlaggedAllocationSitesReachableFromTask(TaskDescriptor td) {
25 checkAnalysisComplete();
26 return getFlaggedAllocationSitesReachableFromTaskPRIVATE(td);
29 public AllocSite getAllocationSiteFromFlatNew(FlatNew fn) {
30 checkAnalysisComplete();
31 return getAllocSiteFromFlatNewPRIVATE(fn);
34 public AllocSite getAllocationSiteFromHeapRegionNodeID(Integer id) {
35 checkAnalysisComplete();
36 return mapHrnIdToAllocSite.get(id);
39 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
42 checkAnalysisComplete();
43 ReachGraph rg=mapDescriptorToCompleteReachGraph.get(taskOrMethod);
44 FlatMethod fm=state.getMethodFlat(taskOrMethod);
46 return rg.mayReachSharedObjects(fm, paramIndex1, paramIndex2);
49 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
50 int paramIndex, AllocSite alloc) {
51 checkAnalysisComplete();
52 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
53 FlatMethod fm=state.getMethodFlat(taskOrMethod);
55 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
58 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
59 AllocSite alloc, int paramIndex) {
60 checkAnalysisComplete();
61 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
62 FlatMethod fm=state.getMethodFlat(taskOrMethod);
64 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
67 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
68 AllocSite alloc1, AllocSite alloc2) {
69 checkAnalysisComplete();
70 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
72 return rg.mayReachSharedObjects(alloc1, alloc2);
75 public String prettyPrintNodeSet(Set<HeapRegionNode> s) {
76 checkAnalysisComplete();
80 Iterator<HeapRegionNode> i = s.iterator();
82 HeapRegionNode n = i.next();
84 AllocSite as = n.getAllocSite();
86 out += " " + n.toString() + ",\n";
88 out += " " + n.toString() + ": " + as.toStringVerbose()
97 // use the methods given above to check every possible sharing class
98 // between task parameters and flagged allocation sites reachable
100 public void writeAllSharing(String outputFile,
103 boolean tabularOutput,
106 throws java.io.IOException {
107 checkAnalysisComplete();
109 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
111 if (!tabularOutput) {
112 bw.write("Conducting ownership analysis with allocation depth = "
113 + allocationDepth + "\n");
114 bw.write(timeReport + "\n");
119 // look through every task for potential sharing
120 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
121 while (taskItr.hasNext()) {
122 TaskDescriptor td = (TaskDescriptor) taskItr.next();
124 if (!tabularOutput) {
125 bw.write("\n---------" + td + "--------\n");
128 HashSet<AllocSite> allocSites = getFlaggedAllocationSitesReachableFromTask(td);
130 Set<HeapRegionNode> common;
132 // for each task parameter, check for sharing classes with
133 // other task parameters and every allocation site
134 // reachable from this task
135 boolean foundSomeSharing = false;
137 FlatMethod fm = state.getMethodFlat(td);
138 for (int i = 0; i < fm.numParameters(); ++i) {
140 // skip parameters with types that cannot reference
142 if( !shouldAnalysisTrack( fm.getParameter( i ).getType() ) ) {
146 // for the ith parameter check for sharing classes to all
147 // higher numbered parameters
148 for (int j = i + 1; j < fm.numParameters(); ++j) {
150 // skip parameters with types that cannot reference
152 if( !shouldAnalysisTrack( fm.getParameter( j ).getType() ) ) {
157 common = hasPotentialSharing(td, i, j);
158 if (!common.isEmpty()) {
159 foundSomeSharing = true;
161 if (!tabularOutput) {
162 bw.write("Potential sharing between parameters " + i
163 + " and " + j + ".\n");
164 bw.write(prettyPrintNodeSet(common) + "\n");
169 // for the ith parameter, check for sharing classes against
170 // the set of allocation sites reachable from this
172 Iterator allocItr = allocSites.iterator();
173 while (allocItr.hasNext()) {
174 AllocSite as = (AllocSite) allocItr.next();
175 common = hasPotentialSharing(td, i, as);
176 if (!common.isEmpty()) {
177 foundSomeSharing = true;
179 if (!tabularOutput) {
180 bw.write("Potential sharing between parameter " + i
181 + " and " + as.getFlatNew() + ".\n");
182 bw.write(prettyPrintNodeSet(common) + "\n");
188 // for each allocation site check for sharing classes with
189 // other allocation sites in the context of execution
191 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
192 Iterator allocItr1 = allocSites.iterator();
193 while (allocItr1.hasNext()) {
194 AllocSite as1 = (AllocSite) allocItr1.next();
196 Iterator allocItr2 = allocSites.iterator();
197 while (allocItr2.hasNext()) {
198 AllocSite as2 = (AllocSite) allocItr2.next();
200 if (!outerChecked.contains(as2)) {
201 common = hasPotentialSharing(td, as1, as2);
203 if (!common.isEmpty()) {
204 foundSomeSharing = true;
206 if (!tabularOutput) {
207 bw.write("Potential sharing between "
208 + as1.getFlatNew() + " and "
209 + as2.getFlatNew() + ".\n");
210 bw.write(prettyPrintNodeSet(common) + "\n");
216 outerChecked.add(as1);
219 if (!foundSomeSharing) {
220 if (!tabularOutput) {
221 bw.write("No sharing between flagged objects in Task " + td
229 bw.write(" & " + numSharing + " & " + justTime + " & " + numLines
230 + " & " + numMethodsAnalyzed() + " \\\\\n");
232 bw.write("\nNumber sharing classes: "+numSharing);
238 // this version of writeAllSharing is for Java programs that have no tasks
239 public void writeAllSharingJava(String outputFile,
242 boolean tabularOutput,
245 throws java.io.IOException {
246 checkAnalysisComplete();
252 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
254 bw.write("Conducting disjoint reachability analysis with allocation depth = "
255 + allocationDepth + "\n");
256 bw.write(timeReport + "\n\n");
258 boolean foundSomeSharing = false;
260 Descriptor d = typeUtil.getMain();
261 HashSet<AllocSite> allocSites = getFlaggedAllocationSites(d);
263 // for each allocation site check for sharing classes with
264 // other allocation sites in the context of execution
266 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
267 Iterator allocItr1 = allocSites.iterator();
268 while (allocItr1.hasNext()) {
269 AllocSite as1 = (AllocSite) allocItr1.next();
271 Iterator allocItr2 = allocSites.iterator();
272 while (allocItr2.hasNext()) {
273 AllocSite as2 = (AllocSite) allocItr2.next();
275 if (!outerChecked.contains(as2)) {
276 Set<HeapRegionNode> common = hasPotentialSharing(d,
279 if (!common.isEmpty()) {
280 foundSomeSharing = true;
281 bw.write("Potential sharing between "
282 + as1.getDisjointAnalysisId() + " and "
283 + as2.getDisjointAnalysisId() + ".\n");
284 bw.write(prettyPrintNodeSet(common) + "\n");
290 outerChecked.add(as1);
293 if (!foundSomeSharing) {
294 bw.write("No sharing classes between flagged objects found.\n");
296 bw.write("\nNumber sharing classes: "+numSharing);
299 bw.write("Number of methods analyzed: "+numMethodsAnalyzed()+"\n");
304 ///////////////////////////////////////////
306 // end public interface
308 ///////////////////////////////////////////
310 protected void checkAnalysisComplete() {
311 if( !analysisComplete ) {
312 throw new Error("Warning: public interface method called while analysis is running.");
317 // run in faster mode, only when bugs wrung out!
318 public static boolean releaseMode;
320 // use command line option to set this, analysis
321 // should attempt to be deterministic
322 public static boolean determinismDesired;
324 // when we want to enforce determinism in the
325 // analysis we need to sort descriptors rather
326 // than toss them in efficient sets, use this
327 public static DescriptorComparator dComp =
328 new DescriptorComparator();
331 // data from the compiler
333 public CallGraph callGraph;
334 public Liveness liveness;
335 public ArrayReferencees arrayReferencees;
336 public RBlockRelationAnalysis rblockRel;
337 public TypeUtil typeUtil;
338 public int allocationDepth;
340 // data structure for public interface
341 private Hashtable< Descriptor, HashSet<AllocSite> >
342 mapDescriptorToAllocSiteSet;
345 // for public interface methods to warn that they
346 // are grabbing results during analysis
347 private boolean analysisComplete;
350 // used to identify HeapRegionNode objects
351 // A unique ID equates an object in one
352 // ownership graph with an object in another
353 // graph that logically represents the same
355 // start at 10 and increment to reserve some
356 // IDs for special purposes
357 static protected int uniqueIDcount = 10;
360 // An out-of-scope method created by the
361 // analysis that has no parameters, and
362 // appears to allocate the command line
363 // arguments, then invoke the source code's
364 // main method. The purpose of this is to
365 // provide the analysis with an explicit
366 // top-level context with no parameters
367 protected MethodDescriptor mdAnalysisEntry;
368 protected FlatMethod fmAnalysisEntry;
370 // main method defined by source program
371 protected MethodDescriptor mdSourceEntry;
373 // the set of task and/or method descriptors
374 // reachable in call graph
375 protected Set<Descriptor>
376 descriptorsToAnalyze;
378 // current descriptors to visit in fixed-point
379 // interprocedural analysis, prioritized by
380 // dependency in the call graph
381 protected Stack<Descriptor>
382 descriptorsToVisitStack;
383 protected PriorityQueue<DescriptorQWrapper>
386 // a duplication of the above structure, but
387 // for efficient testing of inclusion
388 protected HashSet<Descriptor>
389 descriptorsToVisitSet;
391 // storage for priorities (doesn't make sense)
392 // to add it to the Descriptor class, just in
394 protected Hashtable<Descriptor, Integer>
395 mapDescriptorToPriority;
397 // when analyzing a method and scheduling more:
398 // remember set of callee's enqueued for analysis
399 // so they can be put on top of the callers in
400 // the stack-visit mode
401 protected Set<Descriptor>
404 // maps a descriptor to its current partial result
405 // from the intraprocedural fixed-point analysis--
406 // then the interprocedural analysis settles, this
407 // mapping will have the final results for each
409 protected Hashtable<Descriptor, ReachGraph>
410 mapDescriptorToCompleteReachGraph;
412 // maps a descriptor to its known dependents: namely
413 // methods or tasks that call the descriptor's method
414 // AND are part of this analysis (reachable from main)
415 protected Hashtable< Descriptor, Set<Descriptor> >
416 mapDescriptorToSetDependents;
418 // maps each flat new to one analysis abstraction
419 // allocate site object, these exist outside reach graphs
420 protected Hashtable<FlatNew, AllocSite>
421 mapFlatNewToAllocSite;
423 // maps intergraph heap region IDs to intergraph
424 // allocation sites that created them, a redundant
425 // structure for efficiency in some operations
426 protected Hashtable<Integer, AllocSite>
429 // maps a method to its initial heap model (IHM) that
430 // is the set of reachability graphs from every caller
431 // site, all merged together. The reason that we keep
432 // them separate is that any one call site's contribution
433 // to the IHM may changed along the path to the fixed point
434 protected Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >
435 mapDescriptorToIHMcontributions;
437 // additionally, keep a mapping from descriptors to the
438 // merged in-coming initial context, because we want this
439 // initial context to be STRICTLY MONOTONIC
440 protected Hashtable<Descriptor, ReachGraph>
441 mapDescriptorToInitialContext;
443 // make the result for back edges analysis-wide STRICTLY
444 // MONOTONIC as well, but notice we use FlatNode as the
445 // key for this map: in case we want to consider other
446 // nodes as back edge's in future implementations
447 protected Hashtable<FlatNode, ReachGraph>
448 mapBackEdgeToMonotone;
451 public static final String arrayElementFieldName = "___element_";
452 static protected Hashtable<TypeDescriptor, FieldDescriptor>
455 // for controlling DOT file output
456 protected boolean writeFinalDOTs;
457 protected boolean writeAllIncrementalDOTs;
459 // supporting DOT output--when we want to write every
460 // partial method result, keep a tally for generating
462 protected Hashtable<Descriptor, Integer>
463 mapDescriptorToNumUpdates;
465 //map task descriptor to initial task parameter
466 protected Hashtable<Descriptor, ReachGraph>
467 mapDescriptorToReachGraph;
469 protected PointerMethod pm;
471 static protected Hashtable<FlatNode, ReachGraph> fn2rg =
472 new Hashtable<FlatNode, ReachGraph>();
474 private Hashtable<FlatCall, Descriptor> fc2enclosing;
476 //protected RBlockRelationAnalysis rra;
479 // allocate various structures that are not local
480 // to a single class method--should be done once
481 protected void allocateStructures() {
483 if( determinismDesired ) {
484 // use an ordered set
485 descriptorsToAnalyze = new TreeSet<Descriptor>( dComp );
487 // otherwise use a speedy hashset
488 descriptorsToAnalyze = new HashSet<Descriptor>();
491 mapDescriptorToCompleteReachGraph =
492 new Hashtable<Descriptor, ReachGraph>();
494 mapDescriptorToNumUpdates =
495 new Hashtable<Descriptor, Integer>();
497 mapDescriptorToSetDependents =
498 new Hashtable< Descriptor, Set<Descriptor> >();
500 mapFlatNewToAllocSite =
501 new Hashtable<FlatNew, AllocSite>();
503 mapDescriptorToIHMcontributions =
504 new Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >();
506 mapDescriptorToInitialContext =
507 new Hashtable<Descriptor, ReachGraph>();
509 mapBackEdgeToMonotone =
510 new Hashtable<FlatNode, ReachGraph>();
512 mapHrnIdToAllocSite =
513 new Hashtable<Integer, AllocSite>();
515 mapTypeToArrayField =
516 new Hashtable <TypeDescriptor, FieldDescriptor>();
518 if( state.DISJOINTDVISITSTACK ||
519 state.DISJOINTDVISITSTACKEESONTOP
521 descriptorsToVisitStack =
522 new Stack<Descriptor>();
525 if( state.DISJOINTDVISITPQUE ) {
526 descriptorsToVisitQ =
527 new PriorityQueue<DescriptorQWrapper>();
530 descriptorsToVisitSet =
531 new HashSet<Descriptor>();
533 mapDescriptorToPriority =
534 new Hashtable<Descriptor, Integer>();
537 new HashSet<Descriptor>();
539 mapDescriptorToAllocSiteSet =
540 new Hashtable<Descriptor, HashSet<AllocSite> >();
542 mapDescriptorToReachGraph =
543 new Hashtable<Descriptor, ReachGraph>();
545 pm = new PointerMethod();
547 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 RBlockRelationAnalysis rra
561 init( s, tu, cg, l, ar, rra );
564 protected void init( State state,
568 ArrayReferencees arrayReferencees,
569 RBlockRelationAnalysis rra
572 analysisComplete = false;
575 this.typeUtil = typeUtil;
576 this.callGraph = callGraph;
577 this.liveness = liveness;
578 this.arrayReferencees = arrayReferencees;
579 this.rblockRel = rra;
580 this.allocationDepth = state.DISJOINTALLOCDEPTH;
581 this.releaseMode = state.DISJOINTRELEASEMODE;
582 this.determinismDesired = state.DISJOINTDETERMINISM;
584 this.writeFinalDOTs = state.DISJOINTWRITEDOTS && !state.DISJOINTWRITEALL;
585 this.writeAllIncrementalDOTs = state.DISJOINTWRITEDOTS && state.DISJOINTWRITEALL;
587 this.takeDebugSnapshots = state.DISJOINTSNAPSYMBOL != null;
588 this.descSymbolDebug = state.DISJOINTSNAPSYMBOL;
589 this.visitStartCapture = state.DISJOINTSNAPVISITTOSTART;
590 this.numVisitsToCapture = state.DISJOINTSNAPNUMVISITS;
591 this.stopAfterCapture = state.DISJOINTSNAPSTOPAFTER;
592 this.snapVisitCounter = 1; // count visits from 1 (user will write 1, means 1st visit)
593 this.snapNodeCounter = 0; // count nodes from 0
596 state.DISJOINTDVISITSTACK ||
597 state.DISJOINTDVISITPQUE ||
598 state.DISJOINTDVISITSTACKEESONTOP;
599 assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITPQUE);
600 assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITSTACKEESONTOP);
601 assert !(state.DISJOINTDVISITPQUE && state.DISJOINTDVISITSTACKEESONTOP);
603 // set some static configuration for ReachGraphs
604 ReachGraph.allocationDepth = allocationDepth;
605 ReachGraph.typeUtil = typeUtil;
607 ReachGraph.debugCallSiteVisitStartCapture
608 = state.DISJOINTDEBUGCALLVISITTOSTART;
610 ReachGraph.debugCallSiteNumVisitsToCapture
611 = state.DISJOINTDEBUGCALLNUMVISITS;
613 ReachGraph.debugCallSiteStopAfter
614 = state.DISJOINTDEBUGCALLSTOPAFTER;
616 ReachGraph.debugCallSiteVisitCounter
617 = 0; // count visits from 1, is incremented before first visit
621 allocateStructures();
623 double timeStartAnalysis = (double) System.nanoTime();
625 // start interprocedural fixed-point computation
628 } catch( IOException e ) {
629 throw new Error( "IO Exception while writing disjointness analysis output." );
632 analysisComplete=true;
634 double timeEndAnalysis = (double) System.nanoTime();
635 double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
636 String treport = String.format( "The reachability analysis took %.3f sec.", dt );
637 String justtime = String.format( "%.2f", dt );
638 System.out.println( treport );
641 if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
645 if( state.DISJOINTWRITEIHMS ) {
649 if( state.DISJOINTWRITEINITCONTEXTS ) {
650 writeInitialContexts();
653 if( state.DISJOINTALIASFILE != null ) {
655 writeAllSharing(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines);
657 writeAllSharingJava(state.DISJOINTALIASFILE,
660 state.DISJOINTALIASTAB,
665 } catch( IOException e ) {
666 throw new Error( "IO Exception while writing disjointness analysis output." );
671 protected boolean moreDescriptorsToVisit() {
672 if( state.DISJOINTDVISITSTACK ||
673 state.DISJOINTDVISITSTACKEESONTOP
675 return !descriptorsToVisitStack.isEmpty();
677 } else if( state.DISJOINTDVISITPQUE ) {
678 return !descriptorsToVisitQ.isEmpty();
681 throw new Error( "Neither descriptor visiting mode set" );
685 // fixed-point computation over the call graph--when a
686 // method's callees are updated, it must be reanalyzed
687 protected void analyzeMethods() throws java.io.IOException {
689 // task or non-task (java) mode determines what the roots
690 // of the call chain are, and establishes the set of methods
691 // reachable from the roots that will be analyzed
694 System.out.println( "Bamboo mode..." );
696 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
697 while( taskItr.hasNext() ) {
698 TaskDescriptor td = (TaskDescriptor) taskItr.next();
699 if( !descriptorsToAnalyze.contains( td ) ) {
700 // add all methods transitively reachable from the
702 descriptorsToAnalyze.add( td );
703 descriptorsToAnalyze.addAll( callGraph.getAllMethods( td ) );
708 System.out.println( "Java mode..." );
710 // add all methods transitively reachable from the
711 // source's main to set for analysis
712 mdSourceEntry = typeUtil.getMain();
713 descriptorsToAnalyze.add( mdSourceEntry );
714 descriptorsToAnalyze.addAll( callGraph.getAllMethods( mdSourceEntry ) );
716 // fabricate an empty calling context that will call
717 // the source's main, but call graph doesn't know
718 // about it, so explicitly add it
719 makeAnalysisEntryMethod( mdSourceEntry );
720 descriptorsToAnalyze.add( mdAnalysisEntry );
724 // now, depending on the interprocedural mode for visiting
725 // methods, set up the needed data structures
727 if( state.DISJOINTDVISITPQUE ) {
729 // topologically sort according to the call graph so
730 // leaf calls are last, helps build contexts up first
731 LinkedList<Descriptor> sortedDescriptors =
732 topologicalSort( descriptorsToAnalyze );
734 // add sorted descriptors to priority queue, and duplicate
735 // the queue as a set for efficiently testing whether some
736 // method is marked for analysis
738 Iterator<Descriptor> dItr;
740 // for the priority queue, give items at the head
741 // of the sorted list a low number (highest priority)
742 while( !sortedDescriptors.isEmpty() ) {
743 Descriptor d = sortedDescriptors.removeFirst();
744 mapDescriptorToPriority.put( d, new Integer( p ) );
745 descriptorsToVisitQ.add( new DescriptorQWrapper( p, d ) );
746 descriptorsToVisitSet.add( d );
750 } else if( state.DISJOINTDVISITSTACK ||
751 state.DISJOINTDVISITSTACKEESONTOP
753 // if we're doing the stack scheme, just throw the root
754 // method or tasks on the stack
756 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
757 while( taskItr.hasNext() ) {
758 TaskDescriptor td = (TaskDescriptor) taskItr.next();
759 descriptorsToVisitStack.add( td );
760 descriptorsToVisitSet.add( td );
764 descriptorsToVisitStack.add( mdAnalysisEntry );
765 descriptorsToVisitSet.add( mdAnalysisEntry );
769 throw new Error( "Unknown method scheduling mode" );
773 // analyze scheduled methods until there are no more to visit
774 while( moreDescriptorsToVisit() ) {
777 if( state.DISJOINTDVISITSTACK ||
778 state.DISJOINTDVISITSTACKEESONTOP
780 d = descriptorsToVisitStack.pop();
782 } else if( state.DISJOINTDVISITPQUE ) {
783 d = descriptorsToVisitQ.poll().getDescriptor();
786 assert descriptorsToVisitSet.contains( d );
787 descriptorsToVisitSet.remove( d );
789 // because the task or method descriptor just extracted
790 // was in the "to visit" set it either hasn't been analyzed
791 // yet, or some method that it depends on has been
792 // updated. Recompute a complete reachability graph for
793 // this task/method and compare it to any previous result.
794 // If there is a change detected, add any methods/tasks
795 // that depend on this one to the "to visit" set.
797 System.out.println( "Analyzing " + d );
799 if( state.DISJOINTDVISITSTACKEESONTOP ) {
800 assert calleesToEnqueue.isEmpty();
803 ReachGraph rg = analyzeMethod( d );
804 ReachGraph rgPrev = getPartial( d );
806 if( !rg.equals( rgPrev ) ) {
809 if( state.DISJOINTDEBUGSCHEDULING ) {
810 System.out.println( " complete graph changed, scheduling callers for analysis:" );
813 // results for d changed, so enqueue dependents
814 // of d for further analysis
815 Iterator<Descriptor> depsItr = getDependents( d ).iterator();
816 while( depsItr.hasNext() ) {
817 Descriptor dNext = depsItr.next();
820 if( state.DISJOINTDEBUGSCHEDULING ) {
821 System.out.println( " "+dNext );
826 // whether or not the method under analysis changed,
827 // we may have some callees that are scheduled for
828 // more analysis, and they should go on the top of
829 // the stack now (in other method-visiting modes they
830 // are already enqueued at this point
831 if( state.DISJOINTDVISITSTACKEESONTOP ) {
832 Iterator<Descriptor> depsItr = calleesToEnqueue.iterator();
833 while( depsItr.hasNext() ) {
834 Descriptor dNext = depsItr.next();
837 calleesToEnqueue.clear();
843 protected ReachGraph analyzeMethod( Descriptor d )
844 throws java.io.IOException {
846 // get the flat code for this descriptor
848 if( d == mdAnalysisEntry ) {
849 fm = fmAnalysisEntry;
851 fm = state.getMethodFlat( d );
853 pm.analyzeMethod( fm );
855 // intraprocedural work set
856 Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
857 flatNodesToVisit.add( fm );
859 // if determinism is desired by client, shadow the
860 // set with a queue to make visit order deterministic
861 Queue<FlatNode> flatNodesToVisitQ = null;
862 if( determinismDesired ) {
863 flatNodesToVisitQ = new LinkedList<FlatNode>();
864 flatNodesToVisitQ.add( fm );
867 // mapping of current partial results
868 Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraph =
869 new Hashtable<FlatNode, ReachGraph>();
871 // the set of return nodes partial results that will be combined as
872 // the final, conservative approximation of the entire method
873 HashSet<FlatReturnNode> setReturns = new HashSet<FlatReturnNode>();
875 while( !flatNodesToVisit.isEmpty() ) {
878 if( determinismDesired ) {
879 assert !flatNodesToVisitQ.isEmpty();
880 fn = flatNodesToVisitQ.remove();
882 fn = flatNodesToVisit.iterator().next();
884 flatNodesToVisit.remove( fn );
886 // effect transfer function defined by this node,
887 // then compare it to the old graph at this node
888 // to see if anything was updated.
890 ReachGraph rg = new ReachGraph();
891 TaskDescriptor taskDesc;
892 if(fn instanceof FlatMethod && (taskDesc=((FlatMethod)fn).getTask())!=null){
893 if(mapDescriptorToReachGraph.containsKey(taskDesc)){
894 // retrieve existing reach graph if it is not first time
895 rg=mapDescriptorToReachGraph.get(taskDesc);
897 // create initial reach graph for a task
898 rg=createInitialTaskReachGraph((FlatMethod)fn);
900 mapDescriptorToReachGraph.put(taskDesc, rg);
904 // start by merging all node's parents' graphs
905 for( int i = 0; i < pm.numPrev(fn); ++i ) {
906 FlatNode pn = pm.getPrev(fn,i);
907 if( mapFlatNodeToReachGraph.containsKey( pn ) ) {
908 ReachGraph rgParent = mapFlatNodeToReachGraph.get( pn );
909 rg.merge( rgParent );
913 //if(rra.isEndOfRegion(fn)){
914 // rg.clearAccessibleVarSet();
915 // also need to clear stall mapping
918 if( takeDebugSnapshots &&
919 d.getSymbol().equals( descSymbolDebug )
921 debugSnapshot( rg, fn, true );
925 // modify rg with appropriate transfer function
926 rg = analyzeFlatNode( d, fm, fn, setReturns, rg );
929 if( takeDebugSnapshots &&
930 d.getSymbol().equals( descSymbolDebug )
932 debugSnapshot( rg, fn, false );
937 // if the results of the new graph are different from
938 // the current graph at this node, replace the graph
939 // with the update and enqueue the children
940 ReachGraph rgPrev = mapFlatNodeToReachGraph.get( fn );
941 if( !rg.equals( rgPrev ) ) {
942 mapFlatNodeToReachGraph.put( fn, rg );
944 for( int i = 0; i < pm.numNext( fn ); i++ ) {
945 FlatNode nn = pm.getNext( fn, i );
947 flatNodesToVisit.add( nn );
948 if( determinismDesired ) {
949 flatNodesToVisitQ.add( nn );
956 // end by merging all return nodes into a complete
957 // reach graph that represents all possible heap
958 // states after the flat method returns
959 ReachGraph completeGraph = new ReachGraph();
961 assert !setReturns.isEmpty();
962 Iterator retItr = setReturns.iterator();
963 while( retItr.hasNext() ) {
964 FlatReturnNode frn = (FlatReturnNode) retItr.next();
966 assert mapFlatNodeToReachGraph.containsKey( frn );
967 ReachGraph rgRet = mapFlatNodeToReachGraph.get( frn );
969 completeGraph.merge( rgRet );
973 if( takeDebugSnapshots &&
974 d.getSymbol().equals( descSymbolDebug )
976 // increment that we've visited the debug snap
977 // method, and reset the node counter
978 System.out.println( " @@@ debug snap at visit "+snapVisitCounter );
982 if( snapVisitCounter == visitStartCapture + numVisitsToCapture &&
985 System.out.println( "!!! Stopping analysis after debug snap captures. !!!" );
991 return completeGraph;
996 analyzeFlatNode( Descriptor d,
997 FlatMethod fmContaining,
999 HashSet<FlatReturnNode> setRetNodes,
1001 ) throws java.io.IOException {
1004 // any variables that are no longer live should be
1005 // nullified in the graph to reduce edges
1006 //rg.nullifyDeadVars( liveness.getLiveInTemps( fmContaining, fn ) );
1011 FieldDescriptor fld;
1013 // use node type to decide what transfer function
1014 // to apply to the reachability graph
1015 switch( fn.kind() ) {
1017 case FKind.FlatMethod: {
1018 // construct this method's initial heap model (IHM)
1019 // since we're working on the FlatMethod, we know
1020 // the incoming ReachGraph 'rg' is empty
1022 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1023 getIHMcontributions( d );
1025 Set entrySet = heapsFromCallers.entrySet();
1026 Iterator itr = entrySet.iterator();
1027 while( itr.hasNext() ) {
1028 Map.Entry me = (Map.Entry) itr.next();
1029 FlatCall fc = (FlatCall) me.getKey();
1030 ReachGraph rgContrib = (ReachGraph) me.getValue();
1032 assert fc.getMethod().equals( d );
1034 rg.merge( rgContrib );
1037 // additionally, we are enforcing STRICT MONOTONICITY for the
1038 // method's initial context, so grow the context by whatever
1039 // the previously computed context was, and put the most
1040 // up-to-date context back in the map
1041 ReachGraph rgPrevContext = mapDescriptorToInitialContext.get( d );
1042 rg.merge( rgPrevContext );
1043 mapDescriptorToInitialContext.put( d, rg );
1047 case FKind.FlatOpNode:
1048 FlatOpNode fon = (FlatOpNode) fn;
1049 if( fon.getOp().getOp() == Operation.ASSIGN ) {
1050 lhs = fon.getDest();
1051 rhs = fon.getLeft();
1052 rg.assignTempXEqualToTempY( lhs, rhs );
1056 case FKind.FlatCastNode:
1057 FlatCastNode fcn = (FlatCastNode) fn;
1061 TypeDescriptor td = fcn.getType();
1064 rg.assignTempXEqualToCastedTempY( lhs, rhs, td );
1067 case FKind.FlatFieldNode:
1068 FlatFieldNode ffn = (FlatFieldNode) fn;
1071 fld = ffn.getField();
1072 if( shouldAnalysisTrack( fld.getType() ) ) {
1073 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fld );
1077 case FKind.FlatSetFieldNode:
1078 FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
1079 lhs = fsfn.getDst();
1080 fld = fsfn.getField();
1081 rhs = fsfn.getSrc();
1082 if( shouldAnalysisTrack( fld.getType() ) ) {
1083 rg.assignTempXFieldFEqualToTempY( lhs, fld, rhs );
1087 case FKind.FlatElementNode:
1088 FlatElementNode fen = (FlatElementNode) fn;
1091 if( shouldAnalysisTrack( lhs.getType() ) ) {
1093 assert rhs.getType() != null;
1094 assert rhs.getType().isArray();
1096 TypeDescriptor tdElement = rhs.getType().dereference();
1097 FieldDescriptor fdElement = getArrayField( tdElement );
1099 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fdElement );
1103 case FKind.FlatSetElementNode:
1104 FlatSetElementNode fsen = (FlatSetElementNode) fn;
1106 if( arrayReferencees.doesNotCreateNewReaching( fsen ) ) {
1107 // skip this node if it cannot create new reachability paths
1111 lhs = fsen.getDst();
1112 rhs = fsen.getSrc();
1113 if( shouldAnalysisTrack( rhs.getType() ) ) {
1115 assert lhs.getType() != null;
1116 assert lhs.getType().isArray();
1118 TypeDescriptor tdElement = lhs.getType().dereference();
1119 FieldDescriptor fdElement = getArrayField( tdElement );
1121 rg.assignTempXFieldFEqualToTempY( lhs, fdElement, rhs );
1126 FlatNew fnn = (FlatNew) fn;
1128 if( shouldAnalysisTrack( lhs.getType() ) ) {
1129 AllocSite as = getAllocSiteFromFlatNewPRIVATE( fnn );
1130 rg.assignTempEqualToNewAlloc( lhs, as );
1135 case FKind.FlatSESEEnterNode:
1136 FlatSESEEnterNode sese = (FlatSESEEnterNode) fn;
1137 rg.taintLiveTemps( sese,
1138 liveness.getLiveInTemps( fmContaining, fn )
1142 case FKind.FlatSESEExitNode:
1143 FlatSESEExitNode fsexn = (FlatSESEExitNode) fn;
1144 rg.removeInContextTaints( fsexn.getFlatEnter() );
1148 case FKind.FlatCall: {
1149 Descriptor mdCaller;
1150 if( fmContaining.getMethod() != null ){
1151 mdCaller = fmContaining.getMethod();
1153 mdCaller = fmContaining.getTask();
1155 FlatCall fc = (FlatCall) fn;
1156 MethodDescriptor mdCallee = fc.getMethod();
1157 FlatMethod fmCallee = state.getMethodFlat( mdCallee );
1160 boolean debugCallSite =
1161 mdCaller.getSymbol().equals( state.DISJOINTDEBUGCALLER ) &&
1162 mdCallee.getSymbol().equals( state.DISJOINTDEBUGCALLEE );
1164 boolean writeDebugDOTs = false;
1165 boolean stopAfter = false;
1166 if( debugCallSite ) {
1167 ++ReachGraph.debugCallSiteVisitCounter;
1168 System.out.println( " $$$ Debug call site visit "+
1169 ReachGraph.debugCallSiteVisitCounter+
1173 (ReachGraph.debugCallSiteVisitCounter >=
1174 ReachGraph.debugCallSiteVisitStartCapture) &&
1176 (ReachGraph.debugCallSiteVisitCounter <
1177 ReachGraph.debugCallSiteVisitStartCapture +
1178 ReachGraph.debugCallSiteNumVisitsToCapture)
1180 writeDebugDOTs = true;
1181 System.out.println( " $$$ Capturing this call site visit $$$" );
1182 if( ReachGraph.debugCallSiteStopAfter &&
1183 (ReachGraph.debugCallSiteVisitCounter ==
1184 ReachGraph.debugCallSiteVisitStartCapture +
1185 ReachGraph.debugCallSiteNumVisitsToCapture - 1)
1193 // calculate the heap this call site can reach--note this is
1194 // not used for the current call site transform, we are
1195 // grabbing this heap model for future analysis of the callees,
1196 // so if different results emerge we will return to this site
1197 ReachGraph heapForThisCall_old =
1198 getIHMcontribution( mdCallee, fc );
1200 // the computation of the callee-reachable heap
1201 // is useful for making the callee starting point
1202 // and for applying the call site transfer function
1203 Set<Integer> callerNodeIDsCopiedToCallee =
1204 new HashSet<Integer>();
1206 ReachGraph heapForThisCall_cur =
1207 rg.makeCalleeView( fc,
1209 callerNodeIDsCopiedToCallee,
1213 if( !heapForThisCall_cur.equals( heapForThisCall_old ) ) {
1214 // if heap at call site changed, update the contribution,
1215 // and reschedule the callee for analysis
1216 addIHMcontribution( mdCallee, fc, heapForThisCall_cur );
1218 // map a FlatCall to its enclosing method/task descriptor
1219 // so we can write that info out later
1220 fc2enclosing.put( fc, mdCaller );
1222 if( state.DISJOINTDEBUGSCHEDULING ) {
1223 System.out.println( " context changed, scheduling callee: "+mdCallee );
1226 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1227 calleesToEnqueue.add( mdCallee );
1229 enqueue( mdCallee );
1235 // the transformation for a call site should update the
1236 // current heap abstraction with any effects from the callee,
1237 // or if the method is virtual, the effects from any possible
1238 // callees, so find the set of callees...
1239 Set<MethodDescriptor> setPossibleCallees;
1240 if( determinismDesired ) {
1241 // use an ordered set
1242 setPossibleCallees = new TreeSet<MethodDescriptor>( dComp );
1244 // otherwise use a speedy hashset
1245 setPossibleCallees = new HashSet<MethodDescriptor>();
1248 if( mdCallee.isStatic() ) {
1249 setPossibleCallees.add( mdCallee );
1251 TypeDescriptor typeDesc = fc.getThis().getType();
1252 setPossibleCallees.addAll( callGraph.getMethods( mdCallee,
1257 ReachGraph rgMergeOfEffects = new ReachGraph();
1259 Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
1260 while( mdItr.hasNext() ) {
1261 MethodDescriptor mdPossible = mdItr.next();
1262 FlatMethod fmPossible = state.getMethodFlat( mdPossible );
1264 addDependent( mdPossible, // callee
1267 // don't alter the working graph (rg) until we compute a
1268 // result for every possible callee, merge them all together,
1269 // then set rg to that
1270 ReachGraph rgCopy = new ReachGraph();
1273 ReachGraph rgEffect = getPartial( mdPossible );
1275 if( rgEffect == null ) {
1276 // if this method has never been analyzed just schedule it
1277 // for analysis and skip over this call site for now
1278 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1279 calleesToEnqueue.add( mdPossible );
1281 enqueue( mdPossible );
1284 if( state.DISJOINTDEBUGSCHEDULING ) {
1285 System.out.println( " callee hasn't been analyzed, scheduling: "+mdPossible );
1290 rgCopy.resolveMethodCall( fc,
1293 callerNodeIDsCopiedToCallee,
1298 rgMergeOfEffects.merge( rgCopy );
1303 System.out.println( "$$$ Exiting after requested captures of call site. $$$" );
1308 // now that we've taken care of building heap models for
1309 // callee analysis, finish this transformation
1310 rg = rgMergeOfEffects;
1314 case FKind.FlatReturnNode:
1315 FlatReturnNode frn = (FlatReturnNode) fn;
1316 rhs = frn.getReturnTemp();
1317 if( rhs != null && shouldAnalysisTrack( rhs.getType() ) ) {
1318 rg.assignReturnEqualToTemp( rhs );
1320 setRetNodes.add( frn );
1326 // dead variables were removed before the above transfer function
1327 // was applied, so eliminate heap regions and edges that are no
1328 // longer part of the abstractly-live heap graph, and sweep up
1329 // and reachability effects that are altered by the reduction
1330 //rg.abstractGarbageCollect();
1334 // back edges are strictly monotonic
1335 if( pm.isBackEdge( fn ) ) {
1336 ReachGraph rgPrevResult = mapBackEdgeToMonotone.get( fn );
1337 rg.merge( rgPrevResult );
1338 mapBackEdgeToMonotone.put( fn, rg );
1341 // at this point rg should be the correct update
1342 // by an above transfer function, or untouched if
1343 // the flat node type doesn't affect the heap
1349 // this method should generate integers strictly greater than zero!
1350 // special "shadow" regions are made from a heap region by negating
1352 static public Integer generateUniqueHeapRegionNodeID() {
1354 return new Integer( uniqueIDcount );
1359 static public FieldDescriptor getArrayField( TypeDescriptor tdElement ) {
1360 FieldDescriptor fdElement = mapTypeToArrayField.get( tdElement );
1361 if( fdElement == null ) {
1362 fdElement = new FieldDescriptor( new Modifiers( Modifiers.PUBLIC ),
1364 arrayElementFieldName,
1367 mapTypeToArrayField.put( tdElement, fdElement );
1374 private void writeFinalGraphs() {
1375 Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
1376 Iterator itr = entrySet.iterator();
1377 while( itr.hasNext() ) {
1378 Map.Entry me = (Map.Entry) itr.next();
1379 Descriptor d = (Descriptor) me.getKey();
1380 ReachGraph rg = (ReachGraph) me.getValue();
1382 rg.writeGraph( "COMPLETE"+d,
1383 true, // write labels (variables)
1384 true, // selectively hide intermediate temp vars
1385 true, // prune unreachable heap regions
1386 false, // hide reachability altogether
1387 true, // hide subset reachability states
1388 true, // hide predicates
1389 false ); // hide edge taints
1393 private void writeFinalIHMs() {
1394 Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
1395 while( d2IHMsItr.hasNext() ) {
1396 Map.Entry me1 = (Map.Entry) d2IHMsItr.next();
1397 Descriptor d = (Descriptor) me1.getKey();
1398 Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>) me1.getValue();
1400 Iterator fc2rgItr = IHMs.entrySet().iterator();
1401 while( fc2rgItr.hasNext() ) {
1402 Map.Entry me2 = (Map.Entry) fc2rgItr.next();
1403 FlatCall fc = (FlatCall) me2.getKey();
1404 ReachGraph rg = (ReachGraph) me2.getValue();
1406 rg.writeGraph( "IHMPARTFOR"+d+"FROM"+fc2enclosing.get( fc )+fc,
1407 true, // write labels (variables)
1408 true, // selectively hide intermediate temp vars
1409 true, // hide reachability altogether
1410 true, // prune unreachable heap regions
1411 true, // hide subset reachability states
1412 false, // hide predicates
1413 true ); // hide edge taints
1418 private void writeInitialContexts() {
1419 Set entrySet = mapDescriptorToInitialContext.entrySet();
1420 Iterator itr = entrySet.iterator();
1421 while( itr.hasNext() ) {
1422 Map.Entry me = (Map.Entry) itr.next();
1423 Descriptor d = (Descriptor) me.getKey();
1424 ReachGraph rg = (ReachGraph) me.getValue();
1426 rg.writeGraph( "INITIAL"+d,
1427 true, // write labels (variables)
1428 true, // selectively hide intermediate temp vars
1429 true, // prune unreachable heap regions
1430 false, // hide all reachability
1431 true, // hide subset reachability states
1432 true, // hide predicates
1433 false );// hide edge taints
1438 protected ReachGraph getPartial( Descriptor d ) {
1439 return mapDescriptorToCompleteReachGraph.get( d );
1442 protected void setPartial( Descriptor d, ReachGraph rg ) {
1443 mapDescriptorToCompleteReachGraph.put( d, rg );
1445 // when the flag for writing out every partial
1446 // result is set, we should spit out the graph,
1447 // but in order to give it a unique name we need
1448 // to track how many partial results for this
1449 // descriptor we've already written out
1450 if( writeAllIncrementalDOTs ) {
1451 if( !mapDescriptorToNumUpdates.containsKey( d ) ) {
1452 mapDescriptorToNumUpdates.put( d, new Integer( 0 ) );
1454 Integer n = mapDescriptorToNumUpdates.get( d );
1456 rg.writeGraph( d+"COMPLETE"+String.format( "%05d", n ),
1457 true, // write labels (variables)
1458 true, // selectively hide intermediate temp vars
1459 true, // prune unreachable heap regions
1460 false, // hide all reachability
1461 true, // hide subset reachability states
1462 false, // hide predicates
1463 false); // hide edge taints
1465 mapDescriptorToNumUpdates.put( d, n + 1 );
1471 // return just the allocation site associated with one FlatNew node
1472 protected AllocSite getAllocSiteFromFlatNewPRIVATE( FlatNew fnew ) {
1474 if( !mapFlatNewToAllocSite.containsKey( fnew ) ) {
1475 AllocSite as = AllocSite.factory( allocationDepth,
1477 fnew.getDisjointId(),
1481 // the newest nodes are single objects
1482 for( int i = 0; i < allocationDepth; ++i ) {
1483 Integer id = generateUniqueHeapRegionNodeID();
1484 as.setIthOldest( i, id );
1485 mapHrnIdToAllocSite.put( id, as );
1488 // the oldest node is a summary node
1489 as.setSummary( generateUniqueHeapRegionNodeID() );
1491 mapFlatNewToAllocSite.put( fnew, as );
1494 return mapFlatNewToAllocSite.get( fnew );
1498 public static boolean shouldAnalysisTrack( TypeDescriptor type ) {
1499 // don't track primitive types, but an array
1500 // of primitives is heap memory
1501 if( type.isImmutable() ) {
1502 return type.isArray();
1505 // everything else is an object
1509 protected int numMethodsAnalyzed() {
1510 return descriptorsToAnalyze.size();
1517 // Take in source entry which is the program's compiled entry and
1518 // create a new analysis entry, a method that takes no parameters
1519 // and appears to allocate the command line arguments and call the
1520 // source entry with them. The purpose of this analysis entry is
1521 // to provide a top-level method context with no parameters left.
1522 protected void makeAnalysisEntryMethod( MethodDescriptor mdSourceEntry ) {
1524 Modifiers mods = new Modifiers();
1525 mods.addModifier( Modifiers.PUBLIC );
1526 mods.addModifier( Modifiers.STATIC );
1528 TypeDescriptor returnType =
1529 new TypeDescriptor( TypeDescriptor.VOID );
1531 this.mdAnalysisEntry =
1532 new MethodDescriptor( mods,
1534 "analysisEntryMethod"
1537 TempDescriptor cmdLineArgs =
1538 new TempDescriptor( "args",
1539 mdSourceEntry.getParamType( 0 )
1543 new FlatNew( mdSourceEntry.getParamType( 0 ),
1548 TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
1549 sourceEntryArgs[0] = cmdLineArgs;
1552 new FlatCall( mdSourceEntry,
1558 FlatReturnNode frn = new FlatReturnNode( null );
1560 FlatExit fe = new FlatExit();
1562 this.fmAnalysisEntry =
1563 new FlatMethod( mdAnalysisEntry,
1567 this.fmAnalysisEntry.addNext( fn );
1574 protected LinkedList<Descriptor> topologicalSort( Set<Descriptor> toSort ) {
1576 Set<Descriptor> discovered;
1578 if( determinismDesired ) {
1579 // use an ordered set
1580 discovered = new TreeSet<Descriptor>( dComp );
1582 // otherwise use a speedy hashset
1583 discovered = new HashSet<Descriptor>();
1586 LinkedList<Descriptor> sorted = new LinkedList<Descriptor>();
1588 Iterator<Descriptor> itr = toSort.iterator();
1589 while( itr.hasNext() ) {
1590 Descriptor d = itr.next();
1592 if( !discovered.contains( d ) ) {
1593 dfsVisit( d, toSort, sorted, discovered );
1600 // While we're doing DFS on call graph, remember
1601 // dependencies for efficient queuing of methods
1602 // during interprocedural analysis:
1604 // a dependent of a method decriptor d for this analysis is:
1605 // 1) a method or task that invokes d
1606 // 2) in the descriptorsToAnalyze set
1607 protected void dfsVisit( Descriptor d,
1608 Set <Descriptor> toSort,
1609 LinkedList<Descriptor> sorted,
1610 Set <Descriptor> discovered ) {
1611 discovered.add( d );
1613 // only methods have callers, tasks never do
1614 if( d instanceof MethodDescriptor ) {
1616 MethodDescriptor md = (MethodDescriptor) d;
1618 // the call graph is not aware that we have a fabricated
1619 // analysis entry that calls the program source's entry
1620 if( md == mdSourceEntry ) {
1621 if( !discovered.contains( mdAnalysisEntry ) ) {
1622 addDependent( mdSourceEntry, // callee
1623 mdAnalysisEntry // caller
1625 dfsVisit( mdAnalysisEntry, toSort, sorted, discovered );
1629 // otherwise call graph guides DFS
1630 Iterator itr = callGraph.getCallerSet( md ).iterator();
1631 while( itr.hasNext() ) {
1632 Descriptor dCaller = (Descriptor) itr.next();
1634 // only consider callers in the original set to analyze
1635 if( !toSort.contains( dCaller ) ) {
1639 if( !discovered.contains( dCaller ) ) {
1640 addDependent( md, // callee
1644 dfsVisit( dCaller, toSort, sorted, discovered );
1649 // for leaf-nodes last now!
1650 sorted.addLast( d );
1654 protected void enqueue( Descriptor d ) {
1656 if( !descriptorsToVisitSet.contains( d ) ) {
1658 if( state.DISJOINTDVISITSTACK ||
1659 state.DISJOINTDVISITSTACKEESONTOP
1661 descriptorsToVisitStack.add( d );
1663 } else if( state.DISJOINTDVISITPQUE ) {
1664 Integer priority = mapDescriptorToPriority.get( d );
1665 descriptorsToVisitQ.add( new DescriptorQWrapper( priority,
1670 descriptorsToVisitSet.add( d );
1675 // a dependent of a method decriptor d for this analysis is:
1676 // 1) a method or task that invokes d
1677 // 2) in the descriptorsToAnalyze set
1678 protected void addDependent( Descriptor callee, Descriptor caller ) {
1679 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1680 if( deps == null ) {
1681 deps = new HashSet<Descriptor>();
1684 mapDescriptorToSetDependents.put( callee, deps );
1687 protected Set<Descriptor> getDependents( Descriptor callee ) {
1688 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1689 if( deps == null ) {
1690 deps = new HashSet<Descriptor>();
1691 mapDescriptorToSetDependents.put( callee, deps );
1697 public Hashtable<FlatCall, ReachGraph> getIHMcontributions( Descriptor d ) {
1699 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1700 mapDescriptorToIHMcontributions.get( d );
1702 if( heapsFromCallers == null ) {
1703 heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
1704 mapDescriptorToIHMcontributions.put( d, heapsFromCallers );
1707 return heapsFromCallers;
1710 public ReachGraph getIHMcontribution( Descriptor d,
1713 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1714 getIHMcontributions( d );
1716 if( !heapsFromCallers.containsKey( fc ) ) {
1720 return heapsFromCallers.get( fc );
1724 public void addIHMcontribution( Descriptor d,
1728 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1729 getIHMcontributions( d );
1731 heapsFromCallers.put( fc, rg );
1735 private AllocSite createParameterAllocSite( ReachGraph rg,
1736 TempDescriptor tempDesc,
1742 flatNew = new FlatNew( tempDesc.getType(), // type
1743 tempDesc, // param temp
1744 false, // global alloc?
1745 "param"+tempDesc // disjoint site ID string
1748 flatNew = new FlatNew( tempDesc.getType(), // type
1749 tempDesc, // param temp
1750 false, // global alloc?
1751 null // disjoint site ID string
1755 // create allocation site
1756 AllocSite as = AllocSite.factory( allocationDepth,
1758 flatNew.getDisjointId(),
1761 for (int i = 0; i < allocationDepth; ++i) {
1762 Integer id = generateUniqueHeapRegionNodeID();
1763 as.setIthOldest(i, id);
1764 mapHrnIdToAllocSite.put(id, as);
1766 // the oldest node is a summary node
1767 as.setSummary( generateUniqueHeapRegionNodeID() );
1775 private Set<FieldDescriptor> getFieldSetTobeAnalyzed(TypeDescriptor typeDesc){
1777 Set<FieldDescriptor> fieldSet=new HashSet<FieldDescriptor>();
1778 if(!typeDesc.isImmutable()){
1779 ClassDescriptor classDesc = typeDesc.getClassDesc();
1780 for (Iterator it = classDesc.getFields(); it.hasNext();) {
1781 FieldDescriptor field = (FieldDescriptor) it.next();
1782 TypeDescriptor fieldType = field.getType();
1783 if (shouldAnalysisTrack( fieldType )) {
1784 fieldSet.add(field);
1792 private HeapRegionNode createMultiDeimensionalArrayHRN(ReachGraph rg, AllocSite alloc, HeapRegionNode srcHRN, FieldDescriptor fd, Hashtable<HeapRegionNode, HeapRegionNode> map, Hashtable<TypeDescriptor, HeapRegionNode> mapToExistingNode, ReachSet alpha ){
1794 int dimCount=fd.getType().getArrayCount();
1795 HeapRegionNode prevNode=null;
1796 HeapRegionNode arrayEntryNode=null;
1797 for(int i=dimCount;i>0;i--){
1798 TypeDescriptor typeDesc=fd.getType().dereference();//hack to get instance of type desc
1799 typeDesc.setArrayCount(i);
1800 TempDescriptor tempDesc=new TempDescriptor(typeDesc.getSymbol(),typeDesc);
1801 HeapRegionNode hrnSummary ;
1802 if(!mapToExistingNode.containsKey(typeDesc)){
1807 as = createParameterAllocSite(rg, tempDesc, false);
1809 // make a new reference to allocated node
1811 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1812 false, // single object?
1814 false, // out-of-context?
1815 as.getType(), // type
1816 as, // allocation site
1817 alpha, // inherent reach
1818 alpha, // current reach
1819 ExistPredSet.factory(rg.predTrue), // predicates
1820 tempDesc.toString() // description
1822 rg.id2hrn.put(as.getSummary(),hrnSummary);
1824 mapToExistingNode.put(typeDesc, hrnSummary);
1826 hrnSummary=mapToExistingNode.get(typeDesc);
1830 // make a new reference between new summary node and source
1831 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1834 fd.getSymbol(), // field name
1836 ExistPredSet.factory(rg.predTrue), // predicates
1840 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1841 prevNode=hrnSummary;
1842 arrayEntryNode=hrnSummary;
1844 // make a new reference between summary nodes of array
1845 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1848 arrayElementFieldName, // field name
1850 ExistPredSet.factory(rg.predTrue), // predicates
1854 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1855 prevNode=hrnSummary;
1860 // create a new obj node if obj has at least one non-primitive field
1861 TypeDescriptor type=fd.getType();
1862 if(getFieldSetTobeAnalyzed(type).size()>0){
1863 TypeDescriptor typeDesc=type.dereference();
1864 typeDesc.setArrayCount(0);
1865 if(!mapToExistingNode.containsKey(typeDesc)){
1866 TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc);
1867 AllocSite as = createParameterAllocSite(rg, tempDesc, false);
1868 // make a new reference to allocated node
1869 HeapRegionNode hrnSummary =
1870 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1871 false, // single object?
1873 false, // out-of-context?
1875 as, // allocation site
1876 alpha, // inherent reach
1877 alpha, // current reach
1878 ExistPredSet.factory(rg.predTrue), // predicates
1879 tempDesc.toString() // description
1881 rg.id2hrn.put(as.getSummary(),hrnSummary);
1882 mapToExistingNode.put(typeDesc, hrnSummary);
1883 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1886 arrayElementFieldName, // field name
1888 ExistPredSet.factory(rg.predTrue), // predicates
1891 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1892 prevNode=hrnSummary;
1894 HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc);
1895 if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null){
1896 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1899 arrayElementFieldName, // field name
1901 ExistPredSet.factory(rg.predTrue), // predicates
1904 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1906 prevNode=hrnSummary;
1910 map.put(arrayEntryNode, prevNode);
1911 return arrayEntryNode;
1914 private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
1915 ReachGraph rg = new ReachGraph();
1916 TaskDescriptor taskDesc = fm.getTask();
1918 for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
1919 Descriptor paramDesc = taskDesc.getParameter(idx);
1920 TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
1922 // setup data structure
1923 Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet =
1924 new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
1925 Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode =
1926 new Hashtable<TypeDescriptor, HeapRegionNode>();
1927 Hashtable<HeapRegionNode, HeapRegionNode> mapToFirstDimensionArrayNode =
1928 new Hashtable<HeapRegionNode, HeapRegionNode>();
1929 Set<String> doneSet = new HashSet<String>();
1931 TempDescriptor tempDesc = fm.getParameter(idx);
1933 AllocSite as = createParameterAllocSite(rg, tempDesc, true);
1934 VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
1935 Integer idNewest = as.getIthOldest(0);
1936 HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
1938 // make a new reference to allocated node
1939 RefEdge edgeNew = new RefEdge(lnX, // source
1941 taskDesc.getParamType(idx), // type
1943 hrnNewest.getAlpha(), // beta
1944 ExistPredSet.factory(rg.predTrue), // predicates
1947 rg.addRefEdge(lnX, hrnNewest, edgeNew);
1949 // set-up a work set for class field
1950 ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
1951 for (Iterator it = classDesc.getFields(); it.hasNext();) {
1952 FieldDescriptor fd = (FieldDescriptor) it.next();
1953 TypeDescriptor fieldType = fd.getType();
1954 if (shouldAnalysisTrack( fieldType )) {
1955 HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
1956 newMap.put(hrnNewest, fd);
1957 workSet.add(newMap);
1961 int uniqueIdentifier = 0;
1962 while (!workSet.isEmpty()) {
1963 HashMap<HeapRegionNode, FieldDescriptor> map = workSet
1965 workSet.remove(map);
1967 Set<HeapRegionNode> key = map.keySet();
1968 HeapRegionNode srcHRN = key.iterator().next();
1969 FieldDescriptor fd = map.get(srcHRN);
1970 TypeDescriptor type = fd.getType();
1971 String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
1973 if (!doneSet.contains(doneSetIdentifier)) {
1974 doneSet.add(doneSetIdentifier);
1975 if (!mapTypeToExistingSummaryNode.containsKey(type)) {
1976 // create new summary Node
1977 TempDescriptor td = new TempDescriptor("temp"
1978 + uniqueIdentifier, type);
1980 AllocSite allocSite;
1981 if(type.equals(paramTypeDesc)){
1982 //corresponding allocsite has already been created for a parameter variable.
1985 allocSite = createParameterAllocSite(rg, td, false);
1987 String strDesc = allocSite.toStringForDOT()
1989 TypeDescriptor allocType=allocSite.getType();
1991 HeapRegionNode hrnSummary;
1992 if(allocType.isArray() && allocType.getArrayCount()>0){
1993 hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha());
1996 rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
1997 false, // single object?
1999 false, // out-of-context?
2000 allocSite.getType(), // type
2001 allocSite, // allocation site
2002 hrnNewest.getAlpha(), // inherent reach
2003 hrnNewest.getAlpha(), // current reach
2004 ExistPredSet.factory(rg.predTrue), // predicates
2005 strDesc // description
2007 rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
2009 // make a new reference to summary node
2010 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2013 fd.getSymbol(), // field name
2014 hrnNewest.getAlpha(), // beta
2015 ExistPredSet.factory(rg.predTrue), // predicates
2019 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
2023 mapTypeToExistingSummaryNode.put(type, hrnSummary);
2025 // set-up a work set for fields of the class
2026 Set<FieldDescriptor> fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type);
2027 for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator
2029 FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator
2031 HeapRegionNode newDstHRN;
2032 if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)){
2033 //related heap region node is already exsited.
2034 newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary);
2036 newDstHRN=hrnSummary;
2038 doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor;
2039 if(!doneSet.contains(doneSetIdentifier)){
2040 // add new work item
2041 HashMap<HeapRegionNode, FieldDescriptor> newMap =
2042 new HashMap<HeapRegionNode, FieldDescriptor>();
2043 newMap.put(newDstHRN, fieldDescriptor);
2044 workSet.add(newMap);
2049 // if there exists corresponding summary node
2050 HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
2052 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2054 fd.getType(), // type
2055 fd.getSymbol(), // field name
2056 srcHRN.getAlpha(), // beta
2057 ExistPredSet.factory(rg.predTrue), // predicates
2060 rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
2066 // debugSnapshot(rg, fm, true);
2070 // return all allocation sites in the method (there is one allocation
2071 // site per FlatNew node in a method)
2072 private HashSet<AllocSite> getAllocationSiteSet(Descriptor d) {
2073 if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
2074 buildAllocationSiteSet(d);
2077 return mapDescriptorToAllocSiteSet.get(d);
2081 private void buildAllocationSiteSet(Descriptor d) {
2082 HashSet<AllocSite> s = new HashSet<AllocSite>();
2085 if( d instanceof MethodDescriptor ) {
2086 fm = state.getMethodFlat( (MethodDescriptor) d);
2088 assert d instanceof TaskDescriptor;
2089 fm = state.getMethodFlat( (TaskDescriptor) d);
2091 pm.analyzeMethod(fm);
2093 // visit every node in this FlatMethod's IR graph
2094 // and make a set of the allocation sites from the
2095 // FlatNew node's visited
2096 HashSet<FlatNode> visited = new HashSet<FlatNode>();
2097 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
2100 while( !toVisit.isEmpty() ) {
2101 FlatNode n = toVisit.iterator().next();
2103 if( n instanceof FlatNew ) {
2104 s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
2110 for( int i = 0; i < pm.numNext(n); ++i ) {
2111 FlatNode child = pm.getNext(n, i);
2112 if( !visited.contains(child) ) {
2118 mapDescriptorToAllocSiteSet.put(d, s);
2121 private HashSet<AllocSite> getFlaggedAllocationSites(Descriptor dIn) {
2123 HashSet<AllocSite> out = new HashSet<AllocSite>();
2124 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2125 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2129 while (!toVisit.isEmpty()) {
2130 Descriptor d = toVisit.iterator().next();
2134 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2135 Iterator asItr = asSet.iterator();
2136 while (asItr.hasNext()) {
2137 AllocSite as = (AllocSite) asItr.next();
2138 if (as.getDisjointAnalysisId() != null) {
2143 // enqueue callees of this method to be searched for
2144 // allocation sites also
2145 Set callees = callGraph.getCalleeSet(d);
2146 if (callees != null) {
2147 Iterator methItr = callees.iterator();
2148 while (methItr.hasNext()) {
2149 MethodDescriptor md = (MethodDescriptor) methItr.next();
2151 if (!visited.contains(md)) {
2162 private HashSet<AllocSite>
2163 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
2165 HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
2166 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2167 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2171 // traverse this task and all methods reachable from this task
2172 while( !toVisit.isEmpty() ) {
2173 Descriptor d = toVisit.iterator().next();
2177 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2178 Iterator asItr = asSet.iterator();
2179 while( asItr.hasNext() ) {
2180 AllocSite as = (AllocSite) asItr.next();
2181 TypeDescriptor typed = as.getType();
2182 if( typed != null ) {
2183 ClassDescriptor cd = typed.getClassDesc();
2184 if( cd != null && cd.hasFlags() ) {
2190 // enqueue callees of this method to be searched for
2191 // allocation sites also
2192 Set callees = callGraph.getCalleeSet(d);
2193 if( callees != null ) {
2194 Iterator methItr = callees.iterator();
2195 while( methItr.hasNext() ) {
2196 MethodDescriptor md = (MethodDescriptor) methItr.next();
2198 if( !visited.contains(md) ) {
2208 public Set<Descriptor> getDescriptorsToAnalyze() {
2209 return descriptorsToAnalyze;
2214 // get successive captures of the analysis state, use compiler
2216 boolean takeDebugSnapshots = false;
2217 String descSymbolDebug = null;
2218 boolean stopAfterCapture = false;
2219 int snapVisitCounter = 0;
2220 int snapNodeCounter = 0;
2221 int visitStartCapture = 0;
2222 int numVisitsToCapture = 0;
2225 void debugSnapshot( ReachGraph rg, FlatNode fn, boolean in ) {
2226 if( snapVisitCounter > visitStartCapture + numVisitsToCapture ) {
2234 if( snapVisitCounter >= visitStartCapture ) {
2235 System.out.println( " @@@ snapping visit="+snapVisitCounter+
2236 ", node="+snapNodeCounter+
2240 graphName = String.format( "snap%03d_%04din",
2244 graphName = String.format( "snap%03d_%04dout",
2249 graphName = graphName + fn;
2251 rg.writeGraph( graphName,
2252 true, // write labels (variables)
2253 true, // selectively hide intermediate temp vars
2254 true, // prune unreachable heap regions
2255 false, // hide reachability
2256 true, // hide subset reachability states
2257 true, // hide predicates
2258 false );// hide edge taints