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 {
16 // data from the compiler
18 public CallGraph callGraph;
19 public Liveness liveness;
20 public ArrayReferencees arrayReferencees;
21 public TypeUtil typeUtil;
22 public int allocationDepth;
25 // used to identify HeapRegionNode objects
26 // A unique ID equates an object in one
27 // ownership graph with an object in another
28 // graph that logically represents the same
30 // start at 10 and increment to reserve some
31 // IDs for special purposes
32 static protected int uniqueIDcount = 10;
35 // An out-of-scope method created by the
36 // analysis that has no parameters, and
37 // appears to allocate the command line
38 // arguments, then invoke the source code's
39 // main method. The purpose of this is to
40 // provide the analysis with an explicit
41 // top-level context with no parameters
42 protected MethodDescriptor mdAnalysisEntry;
43 protected FlatMethod fmAnalysisEntry;
45 // main method defined by source program
46 protected MethodDescriptor mdSourceEntry;
48 // the set of task and/or method descriptors
49 // reachable in call graph
50 protected Set<Descriptor>
53 // current descriptors to visit in fixed-point
54 // interprocedural analysis, prioritized by
55 // dependency in the call graph
56 protected PriorityQueue<DescriptorQWrapper>
59 // a duplication of the above structure, but
60 // for efficient testing of inclusion
61 protected HashSet<Descriptor>
62 descriptorsToVisitSet;
64 // storage for priorities (doesn't make sense)
65 // to add it to the Descriptor class, just in
67 protected Hashtable<Descriptor, Integer>
68 mapDescriptorToPriority;
71 // maps a descriptor to its current partial result
72 // from the intraprocedural fixed-point analysis--
73 // then the interprocedural analysis settles, this
74 // mapping will have the final results for each
76 protected Hashtable<Descriptor, ReachGraph>
77 mapDescriptorToCompleteReachGraph;
79 // maps a descriptor to its known dependents: namely
80 // methods or tasks that call the descriptor's method
81 // AND are part of this analysis (reachable from main)
82 protected Hashtable< Descriptor, Set<Descriptor> >
83 mapDescriptorToSetDependents;
85 // maps each flat new to one analysis abstraction
86 // allocate site object, these exist outside reach graphs
87 protected Hashtable<FlatNew, AllocSite>
88 mapFlatNewToAllocSite;
90 // maps intergraph heap region IDs to intergraph
91 // allocation sites that created them, a redundant
92 // structure for efficiency in some operations
93 protected Hashtable<Integer, AllocSite>
96 // maps a method to its initial heap model (IHM) that
97 // is the set of reachability graphs from every caller
98 // site, all merged together. The reason that we keep
99 // them separate is that any one call site's contribution
100 // to the IHM may changed along the path to the fixed point
101 protected Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >
102 mapDescriptorToIHMcontributions;
104 // TODO -- CHANGE EDGE/TYPE/FIELD storage!
105 public static final String arrayElementFieldName = "___element_";
106 static protected Hashtable<TypeDescriptor, FieldDescriptor>
109 // for controlling DOT file output
110 protected boolean writeFinalDOTs;
111 protected boolean writeAllIncrementalDOTs;
113 // supporting DOT output--when we want to write every
114 // partial method result, keep a tally for generating
116 protected Hashtable<Descriptor, Integer>
117 mapDescriptorToNumUpdates;
120 // allocate various structures that are not local
121 // to a single class method--should be done once
122 protected void allocateStructures() {
123 descriptorsToAnalyze = new HashSet<Descriptor>();
125 mapDescriptorToCompleteReachGraph =
126 new Hashtable<Descriptor, ReachGraph>();
128 mapDescriptorToNumUpdates =
129 new Hashtable<Descriptor, Integer>();
131 mapDescriptorToSetDependents =
132 new Hashtable< Descriptor, Set<Descriptor> >();
134 mapFlatNewToAllocSite =
135 new Hashtable<FlatNew, AllocSite>();
137 mapDescriptorToIHMcontributions =
138 new Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >();
140 mapHrnIdToAllocSite =
141 new Hashtable<Integer, AllocSite>();
143 mapTypeToArrayField =
144 new Hashtable <TypeDescriptor, FieldDescriptor>();
146 descriptorsToVisitQ =
147 new PriorityQueue<DescriptorQWrapper>();
149 descriptorsToVisitSet =
150 new HashSet<Descriptor>();
152 mapDescriptorToPriority =
153 new Hashtable<Descriptor, Integer>();
158 // this analysis generates a disjoint reachability
159 // graph for every reachable method in the program
160 public DisjointAnalysis( State s,
165 ) throws java.io.IOException {
166 init( s, tu, cg, l, ar );
169 protected void init( State state,
173 ArrayReferencees arrayReferencees
174 ) throws java.io.IOException {
177 this.typeUtil = typeUtil;
178 this.callGraph = callGraph;
179 this.liveness = liveness;
180 this.arrayReferencees = arrayReferencees;
181 this.allocationDepth = state.DISJOINTALLOCDEPTH;
182 this.writeFinalDOTs = state.DISJOINTWRITEDOTS && !state.DISJOINTWRITEALL;
183 this.writeAllIncrementalDOTs = state.DISJOINTWRITEDOTS && state.DISJOINTWRITEALL;
185 // set some static configuration for ReachGraphs
186 ReachGraph.allocationDepth = allocationDepth;
187 ReachGraph.typeUtil = typeUtil;
189 allocateStructures();
191 double timeStartAnalysis = (double) System.nanoTime();
193 // start interprocedural fixed-point computation
196 double timeEndAnalysis = (double) System.nanoTime();
197 double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
198 String treport = String.format( "The reachability analysis took %.3f sec.", dt );
199 String justtime = String.format( "%.2f", dt );
200 System.out.println( treport );
202 if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
206 if( state.DISJOINTALIASFILE != null ) {
208 // not supporting tasks yet...
211 writeAllAliasesJava( aliasFile,
214 state.DISJOINTALIASTAB,
222 // fixed-point computation over the call graph--when a
223 // method's callees are updated, it must be reanalyzed
224 protected void analyzeMethods() throws java.io.IOException {
227 // This analysis does not support Bamboo at the moment,
228 // but if it does in the future we would initialize the
229 // set of descriptors to analyze as the program-reachable
230 // tasks and the methods callable by them. For Java,
231 // just methods reachable from the main method.
232 System.out.println( "No Bamboo support yet..." );
236 // add all methods transitively reachable from the
237 // source's main to set for analysis
238 mdSourceEntry = typeUtil.getMain();
239 descriptorsToAnalyze.add( mdSourceEntry );
240 descriptorsToAnalyze.addAll(
241 callGraph.getAllMethods( mdSourceEntry )
244 // fabricate an empty calling context that will call
245 // the source's main, but call graph doesn't know
246 // about it, so explicitly add it
247 makeAnalysisEntryMethod( mdSourceEntry );
248 descriptorsToAnalyze.add( mdAnalysisEntry );
251 // topologically sort according to the call graph so
252 // leaf calls are ordered first, smarter analysis order
253 LinkedList<Descriptor> sortedDescriptors =
254 topologicalSort( descriptorsToAnalyze );
256 // add sorted descriptors to priority queue, and duplicate
257 // the queue as a set for efficiently testing whether some
258 // method is marked for analysis
260 Iterator<Descriptor> dItr = sortedDescriptors.iterator();
261 while( dItr.hasNext() ) {
262 Descriptor d = dItr.next();
263 mapDescriptorToPriority.put( d, new Integer( p ) );
264 descriptorsToVisitQ.add( new DescriptorQWrapper( p, d ) );
265 descriptorsToVisitSet.add( d );
269 // analyze methods from the priority queue until it is empty
270 while( !descriptorsToVisitQ.isEmpty() ) {
271 Descriptor d = descriptorsToVisitQ.poll().getDescriptor();
272 assert descriptorsToVisitSet.contains( d );
273 descriptorsToVisitSet.remove( d );
275 // because the task or method descriptor just extracted
276 // was in the "to visit" set it either hasn't been analyzed
277 // yet, or some method that it depends on has been
278 // updated. Recompute a complete reachability graph for
279 // this task/method and compare it to any previous result.
280 // If there is a change detected, add any methods/tasks
281 // that depend on this one to the "to visit" set.
283 System.out.println( "Analyzing " + d );
285 ReachGraph rg = analyzeMethod( d );
286 ReachGraph rgPrev = getPartial( d );
288 if( !rg.equals( rgPrev ) ) {
291 // results for d changed, so enqueue dependents
292 // of d for further analysis
293 Iterator<Descriptor> depsItr = getDependents( d ).iterator();
294 while( depsItr.hasNext() ) {
295 Descriptor dNext = depsItr.next();
303 protected ReachGraph analyzeMethod( Descriptor d )
304 throws java.io.IOException {
306 // get the flat code for this descriptor
308 if( d == mdAnalysisEntry ) {
309 fm = fmAnalysisEntry;
311 fm = state.getMethodFlat( d );
314 // intraprocedural work set
315 Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
316 flatNodesToVisit.add( fm );
318 // mapping of current partial results
319 Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraph =
320 new Hashtable<FlatNode, ReachGraph>();
322 // the set of return nodes partial results that will be combined as
323 // the final, conservative approximation of the entire method
324 HashSet<FlatReturnNode> setReturns = new HashSet<FlatReturnNode>();
326 while( !flatNodesToVisit.isEmpty() ) {
327 FlatNode fn = (FlatNode) flatNodesToVisit.iterator().next();
328 flatNodesToVisit.remove( fn );
330 //System.out.println( " "+fn );
332 // effect transfer function defined by this node,
333 // then compare it to the old graph at this node
334 // to see if anything was updated.
336 ReachGraph rg = new ReachGraph();
338 // start by merging all node's parents' graphs
339 for( int i = 0; i < fn.numPrev(); ++i ) {
340 FlatNode pn = fn.getPrev( i );
341 if( mapFlatNodeToReachGraph.containsKey( pn ) ) {
342 ReachGraph rgParent = mapFlatNodeToReachGraph.get( pn );
343 rg.merge( rgParent );
347 // modify rg with appropriate transfer function
348 analyzeFlatNode( d, fm, fn, setReturns, rg );
351 if( takeDebugSnapshots &&
352 d.getSymbol().equals( descSymbolDebug ) ) {
353 debugSnapshot(og,fn);
357 // if the results of the new graph are different from
358 // the current graph at this node, replace the graph
359 // with the update and enqueue the children
360 ReachGraph rgPrev = mapFlatNodeToReachGraph.get( fn );
361 if( !rg.equals( rgPrev ) ) {
362 mapFlatNodeToReachGraph.put( fn, rg );
364 for( int i = 0; i < fn.numNext(); i++ ) {
365 FlatNode nn = fn.getNext( i );
366 flatNodesToVisit.add( nn );
371 // end by merging all return nodes into a complete
372 // ownership graph that represents all possible heap
373 // states after the flat method returns
374 ReachGraph completeGraph = new ReachGraph();
376 assert !setReturns.isEmpty();
377 Iterator retItr = setReturns.iterator();
378 while( retItr.hasNext() ) {
379 FlatReturnNode frn = (FlatReturnNode) retItr.next();
381 assert mapFlatNodeToReachGraph.containsKey( frn );
382 ReachGraph rgRet = mapFlatNodeToReachGraph.get( frn );
384 completeGraph.merge( rgRet );
387 return completeGraph;
392 analyzeFlatNode( Descriptor d,
393 FlatMethod fmContaining,
395 HashSet<FlatReturnNode> setRetNodes,
397 ) throws java.io.IOException {
400 // any variables that are no longer live should be
401 // nullified in the graph to reduce edges
402 // NOTE: it is not clear we need this. It costs a
403 // liveness calculation for every method, so only
404 // turn it on if we find we actually need it.
405 // rg.nullifyDeadVars( liveness.getLiveInTemps( fmContaining, fn ) );
412 // use node type to decide what transfer function
413 // to apply to the reachability graph
414 switch( fn.kind() ) {
416 case FKind.FlatMethod: {
417 // construct this method's initial heap model (IHM)
418 // since we're working on the FlatMethod, we know
419 // the incoming ReachGraph 'rg' is empty
421 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
422 getIHMcontributions( d );
424 Set entrySet = heapsFromCallers.entrySet();
425 Iterator itr = entrySet.iterator();
426 while( itr.hasNext() ) {
427 Map.Entry me = (Map.Entry) itr.next();
428 FlatCall fc = (FlatCall) me.getKey();
429 ReachGraph rgContrib = (ReachGraph) me.getValue();
431 assert fc.getMethod().equals( d );
433 // some call sites are in same method context though,
434 // and all of them should be merged together first,
435 // then heaps from different contexts should be merged
436 // THIS ASSUMES DIFFERENT CONTEXTS NEED SPECIAL CONSIDERATION!
437 // such as, do allocation sites need to be aged?
439 rg.merge_diffMethodContext( rgContrib );
442 FlatMethod fm = (FlatMethod) fn;
443 for( int i = 0; i < fm.numParameters(); ++i ) {
444 TempDescriptor tdParam = fm.getParameter( i );
445 //assert rg.hasVariable( tdParam );
449 case FKind.FlatOpNode:
450 FlatOpNode fon = (FlatOpNode) fn;
451 if( fon.getOp().getOp() == Operation.ASSIGN ) {
454 rg.assignTempXEqualToTempY( lhs, rhs );
458 case FKind.FlatCastNode:
459 FlatCastNode fcn = (FlatCastNode) fn;
463 TypeDescriptor td = fcn.getType();
466 rg.assignTempXEqualToCastedTempY( lhs, rhs, td );
469 case FKind.FlatFieldNode:
470 FlatFieldNode ffn = (FlatFieldNode) fn;
473 fld = ffn.getField();
474 if( !fld.getType().isImmutable() || fld.getType().isArray() ) {
475 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fld );
479 case FKind.FlatSetFieldNode:
480 FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
482 fld = fsfn.getField();
484 if( !fld.getType().isImmutable() || fld.getType().isArray() ) {
485 rg.assignTempXFieldFEqualToTempY( lhs, fld, rhs );
489 case FKind.FlatElementNode:
490 FlatElementNode fen = (FlatElementNode) fn;
493 if( !lhs.getType().isImmutable() || lhs.getType().isArray() ) {
495 assert rhs.getType() != null;
496 assert rhs.getType().isArray();
498 TypeDescriptor tdElement = rhs.getType().dereference();
499 FieldDescriptor fdElement = getArrayField( tdElement );
501 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fdElement );
505 case FKind.FlatSetElementNode:
506 FlatSetElementNode fsen = (FlatSetElementNode) fn;
508 if( arrayReferencees.doesNotCreateNewReaching( fsen ) ) {
509 // skip this node if it cannot create new reachability paths
515 if( !rhs.getType().isImmutable() || rhs.getType().isArray() ) {
517 assert lhs.getType() != null;
518 assert lhs.getType().isArray();
520 TypeDescriptor tdElement = lhs.getType().dereference();
521 FieldDescriptor fdElement = getArrayField( tdElement );
523 rg.assignTempXFieldFEqualToTempY( lhs, fdElement, rhs );
528 FlatNew fnn = (FlatNew) fn;
530 if( !lhs.getType().isImmutable() || lhs.getType().isArray() ) {
531 AllocSite as = getAllocSiteFromFlatNewPRIVATE( fnn );
532 rg.assignTempEqualToNewAlloc( lhs, as );
536 case FKind.FlatCall: {
537 FlatCall fc = (FlatCall) fn;
538 MethodDescriptor mdCallee = fc.getMethod();
539 FlatMethod fmCallee = state.getMethodFlat( mdCallee );
541 // the transformation for a call site should update the
542 // current heap abstraction with any effects from the callee,
543 // or if the method is virtual, the effects from any possible
544 // callees, so find the set of callees...
545 Set<MethodDescriptor> setPossibleCallees =
546 new HashSet<MethodDescriptor>();
548 if( mdCallee.isStatic() ) {
549 setPossibleCallees.add( mdCallee );
551 TypeDescriptor typeDesc = fc.getThis().getType();
552 setPossibleCallees.addAll( callGraph.getMethods( mdCallee, typeDesc ) );
555 ReachGraph rgMergeOfEffects = new ReachGraph();
557 Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
558 while( mdItr.hasNext() ) {
559 MethodDescriptor mdPossible = mdItr.next();
560 FlatMethod fmPossible = state.getMethodFlat( mdPossible );
562 addDependent( mdPossible, // callee
565 // don't alter the working graph (rg) until we compute a
566 // result for every possible callee, merge them all together,
567 // then set rg to that
568 ReachGraph rgCopy = new ReachGraph();
571 ReachGraph rgEffect = getPartial( mdPossible );
573 if( rgEffect == null ) {
574 // if this method has never been analyzed just schedule it
575 // for analysis and skip over this call site for now
576 enqueue( mdPossible );
578 rgCopy.resolveMethodCall( fc, fmPossible, rgEffect );
581 rgMergeOfEffects.merge( rgCopy );
585 // now we're done, but BEFORE we set rg = rgMergeOfEffects:
586 // calculate the heap this call site can reach--note this is
587 // not used for the current call site transform, we are
588 // grabbing this heap model for future analysis of the callees,
589 // of if different results emerge we will return to this site
590 ReachGraph heapForThisCall_old =
591 getIHMcontribution( mdCallee, fc );
593 ReachGraph heapForThisCall_cur = rg.makeCalleeView( fc,
596 if( !heapForThisCall_cur.equals( heapForThisCall_old ) ) {
597 // if heap at call site changed, update the contribution,
598 // and reschedule the callee for analysis
599 addIHMcontribution( mdCallee, fc, heapForThisCall_cur );
604 // now that we've taken care of building heap models for
605 // callee analysis, finish this transformation
606 rg = rgMergeOfEffects;
610 case FKind.FlatReturnNode:
611 FlatReturnNode frn = (FlatReturnNode) fn;
612 rhs = frn.getReturnTemp();
613 if( rhs != null && !rhs.getType().isImmutable() ) {
614 rg.assignReturnEqualToTemp( rhs );
616 setRetNodes.add( frn );
621 // at this point rg should be the correct update
622 // by an above transfer function, or untouched if
623 // the flat node type doesn't affect the heap
627 // this method should generate integers strictly greater than zero!
628 // special "shadow" regions are made from a heap region by negating
630 static public Integer generateUniqueHeapRegionNodeID() {
632 return new Integer( uniqueIDcount );
637 static public FieldDescriptor getArrayField( TypeDescriptor tdElement ) {
638 FieldDescriptor fdElement = mapTypeToArrayField.get( tdElement );
639 if( fdElement == null ) {
640 fdElement = new FieldDescriptor( new Modifiers( Modifiers.PUBLIC ),
642 arrayElementFieldName,
645 mapTypeToArrayField.put( tdElement, fdElement );
652 private void writeFinalGraphs() {
653 Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
654 Iterator itr = entrySet.iterator();
655 while( itr.hasNext() ) {
656 Map.Entry me = (Map.Entry) itr.next();
657 Descriptor d = (Descriptor) me.getKey();
658 ReachGraph rg = (ReachGraph) me.getValue();
661 rg.writeGraph( d+"COMPLETE",
662 true, // write labels (variables)
663 true, // selectively hide intermediate temp vars
664 true, // prune unreachable heap regions
665 false, // show back edges to confirm graph validity
666 true, // hide subset reachability states
667 true ); // hide edge taints
668 } catch( IOException e ) {}
673 // return just the allocation site associated with one FlatNew node
674 protected AllocSite getAllocSiteFromFlatNewPRIVATE( FlatNew fnew ) {
676 if( !mapFlatNewToAllocSite.containsKey( fnew ) ) {
678 new AllocSite( allocationDepth, fnew, fnew.getDisjointId() );
680 // the newest nodes are single objects
681 for( int i = 0; i < allocationDepth; ++i ) {
682 Integer id = generateUniqueHeapRegionNodeID();
683 as.setIthOldest( i, id );
684 mapHrnIdToAllocSite.put( id, as );
687 // the oldest node is a summary node
688 as.setSummary( generateUniqueHeapRegionNodeID() );
690 // and one special node is older than all
691 // nodes and shadow nodes for the site
692 as.setSiteSummary( generateUniqueHeapRegionNodeID() );
694 mapFlatNewToAllocSite.put( fnew, as );
697 return mapFlatNewToAllocSite.get( fnew );
702 // return all allocation sites in the method (there is one allocation
703 // site per FlatNew node in a method)
704 protected HashSet<AllocSite> getAllocSiteSet(Descriptor d) {
705 if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
706 buildAllocSiteSet(d);
709 return mapDescriptorToAllocSiteSet.get(d);
715 protected void buildAllocSiteSet(Descriptor d) {
716 HashSet<AllocSite> s = new HashSet<AllocSite>();
718 FlatMethod fm = state.getMethodFlat( d );
720 // visit every node in this FlatMethod's IR graph
721 // and make a set of the allocation sites from the
722 // FlatNew node's visited
723 HashSet<FlatNode> visited = new HashSet<FlatNode>();
724 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
727 while( !toVisit.isEmpty() ) {
728 FlatNode n = toVisit.iterator().next();
730 if( n instanceof FlatNew ) {
731 s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
737 for( int i = 0; i < n.numNext(); ++i ) {
738 FlatNode child = n.getNext( i );
739 if( !visited.contains( child ) ) {
740 toVisit.add( child );
745 mapDescriptorToAllocSiteSet.put( d, s );
749 protected HashSet<AllocSite> getFlaggedAllocSites(Descriptor dIn) {
751 HashSet<AllocSite> out = new HashSet<AllocSite>();
752 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
753 HashSet<Descriptor> visited = new HashSet<Descriptor>();
757 while( !toVisit.isEmpty() ) {
758 Descriptor d = toVisit.iterator().next();
762 HashSet<AllocSite> asSet = getAllocSiteSet(d);
763 Iterator asItr = asSet.iterator();
764 while( asItr.hasNext() ) {
765 AllocSite as = (AllocSite) asItr.next();
766 if( as.getDisjointAnalysisId() != null ) {
771 // enqueue callees of this method to be searched for
772 // allocation sites also
773 Set callees = callGraph.getCalleeSet(d);
774 if( callees != null ) {
775 Iterator methItr = callees.iterator();
776 while( methItr.hasNext() ) {
777 MethodDescriptor md = (MethodDescriptor) methItr.next();
779 if( !visited.contains(md) ) {
791 protected HashSet<AllocSite>
792 getFlaggedAllocSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
794 HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
795 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
796 HashSet<Descriptor> visited = new HashSet<Descriptor>();
800 // traverse this task and all methods reachable from this task
801 while( !toVisit.isEmpty() ) {
802 Descriptor d = toVisit.iterator().next();
806 HashSet<AllocSite> asSet = getAllocSiteSet(d);
807 Iterator asItr = asSet.iterator();
808 while( asItr.hasNext() ) {
809 AllocSite as = (AllocSite) asItr.next();
810 TypeDescriptor typed = as.getType();
811 if( typed != null ) {
812 ClassDescriptor cd = typed.getClassDesc();
813 if( cd != null && cd.hasFlags() ) {
819 // enqueue callees of this method to be searched for
820 // allocation sites also
821 Set callees = callGraph.getCalleeSet(d);
822 if( callees != null ) {
823 Iterator methItr = callees.iterator();
824 while( methItr.hasNext() ) {
825 MethodDescriptor md = (MethodDescriptor) methItr.next();
827 if( !visited.contains(md) ) {
841 protected String computeAliasContextHistogram() {
843 Hashtable<Integer, Integer> mapNumContexts2NumDesc =
844 new Hashtable<Integer, Integer>();
846 Iterator itr = mapDescriptorToAllDescriptors.entrySet().iterator();
847 while( itr.hasNext() ) {
848 Map.Entry me = (Map.Entry) itr.next();
849 HashSet<Descriptor> s = (HashSet<Descriptor>) me.getValue();
851 Integer i = mapNumContexts2NumDesc.get( s.size() );
853 i = new Integer( 0 );
855 mapNumContexts2NumDesc.put( s.size(), i + 1 );
861 itr = mapNumContexts2NumDesc.entrySet().iterator();
862 while( itr.hasNext() ) {
863 Map.Entry me = (Map.Entry) itr.next();
864 Integer c0 = (Integer) me.getKey();
865 Integer d0 = (Integer) me.getValue();
867 s += String.format( "%4d methods had %4d unique alias contexts.\n", d0, c0 );
870 s += String.format( "\n%4d total methods analayzed.\n", total );
875 protected int numMethodsAnalyzed() {
876 return descriptorsToAnalyze.size();
882 // insert a call to debugSnapshot() somewhere in the analysis
883 // to get successive captures of the analysis state
884 boolean takeDebugSnapshots = false;
885 String mcDescSymbolDebug = "setRoute";
886 boolean stopAfterCapture = true;
888 // increments every visit to debugSnapshot, don't fiddle with it
889 // IMPORTANT NOTE FOR SETTING THE FOLLOWING VALUES: this
890 // counter increments just after every node is analyzed
891 // from the body of the method whose symbol is specified
893 int debugCounter = 0;
895 // the value of debugCounter to start reporting the debugCounter
896 // to the screen to let user know what debug iteration we're at
897 int numStartCountReport = 0;
899 // the frequency of debugCounter values to print out, 0 no report
900 int freqCountReport = 0;
902 // the debugCounter value at which to start taking snapshots
903 int iterStartCapture = 0;
905 // the number of snapshots to take
906 int numIterToCapture = 300;
908 void debugSnapshot(ReachabilityGraph og, FlatNode fn) {
909 if( debugCounter > iterStartCapture + numIterToCapture ) {
914 if( debugCounter > numStartCountReport &&
915 freqCountReport > 0 &&
916 debugCounter % freqCountReport == 0 ) {
917 System.out.println(" @@@ debug counter = "+debugCounter);
919 if( debugCounter > iterStartCapture ) {
920 System.out.println(" @@@ capturing debug "+(debugCounter-iterStartCapture)+" @@@");
921 String graphName = String.format("snap%04d",debugCounter-iterStartCapture);
923 graphName = graphName+fn;
926 og.writeGraph(graphName,
927 true, // write labels (variables)
928 true, // selectively hide intermediate temp vars
929 true, // prune unreachable heap regions
930 false, // show back edges to confirm graph validity
931 false, // show parameter indices (unmaintained!)
932 true, // hide subset reachability states
933 true); // hide edge taints
934 } catch( Exception e ) {
935 System.out.println("Error writing debug capture.");
940 if( debugCounter == iterStartCapture + numIterToCapture && stopAfterCapture ) {
941 System.out.println("Stopping analysis after debug captures.");
948 // Take in source entry which is the program's compiled entry and
949 // create a new analysis entry, a method that takes no parameters
950 // and appears to allocate the command line arguments and call the
951 // source entry with them. The purpose of this analysis entry is
952 // to provide a top-level method context with no parameters left.
953 protected void makeAnalysisEntryMethod( MethodDescriptor mdSourceEntry ) {
955 Modifiers mods = new Modifiers();
956 mods.addModifier( Modifiers.PUBLIC );
957 mods.addModifier( Modifiers.STATIC );
959 TypeDescriptor returnType =
960 new TypeDescriptor( TypeDescriptor.VOID );
962 this.mdAnalysisEntry =
963 new MethodDescriptor( mods,
965 "analysisEntryMethod"
968 TempDescriptor cmdLineArgs =
969 new TempDescriptor( "args",
970 mdSourceEntry.getParamType( 0 )
974 new FlatNew( mdSourceEntry.getParamType( 0 ),
979 TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
980 sourceEntryArgs[0] = cmdLineArgs;
983 new FlatCall( mdSourceEntry,
989 FlatReturnNode frn = new FlatReturnNode( null );
991 FlatExit fe = new FlatExit();
993 this.fmAnalysisEntry =
994 new FlatMethod( mdAnalysisEntry,
998 this.fmAnalysisEntry.addNext( fn );
1005 protected LinkedList<Descriptor> topologicalSort( Set<Descriptor> toSort ) {
1007 Set <Descriptor> discovered = new HashSet <Descriptor>();
1008 LinkedList<Descriptor> sorted = new LinkedList<Descriptor>();
1010 Iterator<Descriptor> itr = toSort.iterator();
1011 while( itr.hasNext() ) {
1012 Descriptor d = itr.next();
1014 if( !discovered.contains( d ) ) {
1015 dfsVisit( d, toSort, sorted, discovered );
1022 // While we're doing DFS on call graph, remember
1023 // dependencies for efficient queuing of methods
1024 // during interprocedural analysis:
1026 // a dependent of a method decriptor d for this analysis is:
1027 // 1) a method or task that invokes d
1028 // 2) in the descriptorsToAnalyze set
1029 protected void dfsVisit( Descriptor d,
1030 Set <Descriptor> toSort,
1031 LinkedList<Descriptor> sorted,
1032 Set <Descriptor> discovered ) {
1033 discovered.add( d );
1035 // only methods have callers, tasks never do
1036 if( d instanceof MethodDescriptor ) {
1038 MethodDescriptor md = (MethodDescriptor) d;
1040 // the call graph is not aware that we have a fabricated
1041 // analysis entry that calls the program source's entry
1042 if( md == mdSourceEntry ) {
1043 if( !discovered.contains( mdAnalysisEntry ) ) {
1044 addDependent( mdSourceEntry, // callee
1045 mdAnalysisEntry // caller
1047 dfsVisit( mdAnalysisEntry, toSort, sorted, discovered );
1051 // otherwise call graph guides DFS
1052 Iterator itr = callGraph.getCallerSet( md ).iterator();
1053 while( itr.hasNext() ) {
1054 Descriptor dCaller = (Descriptor) itr.next();
1056 // only consider callers in the original set to analyze
1057 if( !toSort.contains( dCaller ) ) {
1061 if( !discovered.contains( dCaller ) ) {
1062 addDependent( md, // callee
1066 dfsVisit( dCaller, toSort, sorted, discovered );
1071 sorted.addFirst( d );
1075 protected void enqueue( Descriptor d ) {
1076 if( !descriptorsToVisitSet.contains( d ) ) {
1077 Integer priority = mapDescriptorToPriority.get( d );
1078 descriptorsToVisitQ.add( new DescriptorQWrapper( priority,
1081 descriptorsToVisitSet.add( d );
1086 protected ReachGraph getPartial( Descriptor d ) {
1087 return mapDescriptorToCompleteReachGraph.get( d );
1090 protected void setPartial( Descriptor d, ReachGraph rg ) {
1091 mapDescriptorToCompleteReachGraph.put( d, rg );
1093 // when the flag for writing out every partial
1094 // result is set, we should spit out the graph,
1095 // but in order to give it a unique name we need
1096 // to track how many partial results for this
1097 // descriptor we've already written out
1098 if( writeAllIncrementalDOTs ) {
1099 if( !mapDescriptorToNumUpdates.containsKey( d ) ) {
1100 mapDescriptorToNumUpdates.put( d, new Integer( 0 ) );
1102 Integer n = mapDescriptorToNumUpdates.get( d );
1105 rg.writeGraph( d+"COMPLETE"+String.format( "%05d", n ),
1106 true, // write labels (variables)
1107 true, // selectively hide intermediate temp vars
1108 true, // prune unreachable heap regions
1109 false, // show back edges to confirm graph validity
1110 false, // show parameter indices (unmaintained!)
1111 true, // hide subset reachability states
1112 true); // hide edge taints
1113 } catch( IOException e ) {}
1115 mapDescriptorToNumUpdates.put( d, n + 1 );
1120 // a dependent of a method decriptor d for this analysis is:
1121 // 1) a method or task that invokes d
1122 // 2) in the descriptorsToAnalyze set
1123 protected void addDependent( Descriptor callee, Descriptor caller ) {
1124 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1125 if( deps == null ) {
1126 deps = new HashSet<Descriptor>();
1129 mapDescriptorToSetDependents.put( callee, deps );
1132 protected Set<Descriptor> getDependents( Descriptor callee ) {
1133 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1134 if( deps == null ) {
1135 deps = new HashSet<Descriptor>();
1136 mapDescriptorToSetDependents.put( callee, deps );
1142 public Hashtable<FlatCall, ReachGraph> getIHMcontributions( Descriptor d ) {
1144 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1145 mapDescriptorToIHMcontributions.get( d );
1147 if( heapsFromCallers == null ) {
1148 heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
1151 return heapsFromCallers;
1154 public ReachGraph getIHMcontribution( Descriptor d,
1157 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1158 getIHMcontributions( d );
1160 if( !heapsFromCallers.containsKey( fc ) ) {
1161 heapsFromCallers.put( fc, new ReachGraph() );
1164 return heapsFromCallers.get( fc );
1167 public void addIHMcontribution( Descriptor d,
1171 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1172 getIHMcontributions( d );
1174 heapsFromCallers.put( fc, rg );