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;
121 // allocate various structures that are not local
122 // to a single class method--should be done once
123 protected void allocateStructures() {
124 descriptorsToAnalyze = new HashSet<Descriptor>();
126 mapDescriptorToCompleteReachGraph =
127 new Hashtable<Descriptor, ReachGraph>();
129 mapDescriptorToNumUpdates =
130 new Hashtable<Descriptor, Integer>();
132 mapDescriptorToSetDependents =
133 new Hashtable< Descriptor, Set<Descriptor> >();
135 mapFlatNewToAllocSite =
136 new Hashtable<FlatNew, AllocSite>();
138 mapDescriptorToIHMcontributions =
139 new Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >();
141 mapHrnIdToAllocSite =
142 new Hashtable<Integer, AllocSite>();
144 mapTypeToArrayField =
145 new Hashtable <TypeDescriptor, FieldDescriptor>();
147 descriptorsToVisitQ =
148 new PriorityQueue<DescriptorQWrapper>();
150 descriptorsToVisitSet =
151 new HashSet<Descriptor>();
153 mapDescriptorToPriority =
154 new Hashtable<Descriptor, Integer>();
159 // this analysis generates a disjoint reachability
160 // graph for every reachable method in the program
161 public DisjointAnalysis( State s,
166 ) throws java.io.IOException {
167 init( s, tu, cg, l, ar );
170 protected void init( State state,
174 ArrayReferencees arrayReferencees
175 ) throws java.io.IOException {
178 this.typeUtil = typeUtil;
179 this.callGraph = callGraph;
180 this.liveness = liveness;
181 this.arrayReferencees = arrayReferencees;
182 this.allocationDepth = state.DISJOINTALLOCDEPTH;
183 this.writeFinalDOTs = state.DISJOINTWRITEDOTS && !state.DISJOINTWRITEALL;
184 this.writeAllIncrementalDOTs = state.DISJOINTWRITEDOTS && state.DISJOINTWRITEALL;
186 // set some static configuration for ReachGraphs
187 ReachGraph.allocationDepth = allocationDepth;
188 ReachGraph.typeUtil = typeUtil;
190 allocateStructures();
192 double timeStartAnalysis = (double) System.nanoTime();
194 // start interprocedural fixed-point computation
197 double timeEndAnalysis = (double) System.nanoTime();
198 double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
199 String treport = String.format( "The reachability analysis took %.3f sec.", dt );
200 String justtime = String.format( "%.2f", dt );
201 System.out.println( treport );
203 if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
207 if( state.DISJOINTWRITEIHMS ) {
211 if( state.DISJOINTALIASFILE != null ) {
213 // not supporting tasks yet...
216 writeAllAliasesJava( aliasFile,
219 state.DISJOINTALIASTAB,
227 // fixed-point computation over the call graph--when a
228 // method's callees are updated, it must be reanalyzed
229 protected void analyzeMethods() throws java.io.IOException {
232 // This analysis does not support Bamboo at the moment,
233 // but if it does in the future we would initialize the
234 // set of descriptors to analyze as the program-reachable
235 // tasks and the methods callable by them. For Java,
236 // just methods reachable from the main method.
237 System.out.println( "Bamboo..." );
238 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
240 while (taskItr.hasNext()) {
241 TaskDescriptor td = (TaskDescriptor) taskItr.next();
242 if (!descriptorsToAnalyze.contains(td)) {
243 descriptorsToAnalyze.add(td);
244 descriptorsToAnalyze.addAll(callGraph.getAllMethods(td));
249 // add all methods transitively reachable from the
250 // source's main to set for analysis
251 mdSourceEntry = typeUtil.getMain();
252 descriptorsToAnalyze.add( mdSourceEntry );
253 descriptorsToAnalyze.addAll(
254 callGraph.getAllMethods( mdSourceEntry )
257 // fabricate an empty calling context that will call
258 // the source's main, but call graph doesn't know
259 // about it, so explicitly add it
260 makeAnalysisEntryMethod( mdSourceEntry );
261 descriptorsToAnalyze.add( mdAnalysisEntry );
264 // topologically sort according to the call graph so
265 // leaf calls are ordered first, smarter analysis order
266 LinkedList<Descriptor> sortedDescriptors =
267 topologicalSort( descriptorsToAnalyze );
269 // add sorted descriptors to priority queue, and duplicate
270 // the queue as a set for efficiently testing whether some
271 // method is marked for analysis
273 Iterator<Descriptor> dItr = sortedDescriptors.iterator();
274 while( dItr.hasNext() ) {
275 Descriptor d = dItr.next();
276 mapDescriptorToPriority.put( d, new Integer( p ) );
277 descriptorsToVisitQ.add( new DescriptorQWrapper( p, d ) );
278 descriptorsToVisitSet.add( d );
282 // analyze methods from the priority queue until it is empty
283 while( !descriptorsToVisitQ.isEmpty() ) {
284 Descriptor d = descriptorsToVisitQ.poll().getDescriptor();
285 assert descriptorsToVisitSet.contains( d );
286 descriptorsToVisitSet.remove( d );
288 // because the task or method descriptor just extracted
289 // was in the "to visit" set it either hasn't been analyzed
290 // yet, or some method that it depends on has been
291 // updated. Recompute a complete reachability graph for
292 // this task/method and compare it to any previous result.
293 // If there is a change detected, add any methods/tasks
294 // that depend on this one to the "to visit" set.
296 System.out.println( "Analyzing " + d );
298 ReachGraph rg = analyzeMethod( d );
299 ReachGraph rgPrev = getPartial( d );
301 if( !rg.equals( rgPrev ) ) {
304 // results for d changed, so enqueue dependents
305 // of d for further analysis
306 Iterator<Descriptor> depsItr = getDependents( d ).iterator();
307 while( depsItr.hasNext() ) {
308 Descriptor dNext = depsItr.next();
315 protected ReachGraph analyzeMethod( Descriptor d )
316 throws java.io.IOException {
318 // get the flat code for this descriptor
320 if( d == mdAnalysisEntry ) {
321 fm = fmAnalysisEntry;
323 fm = state.getMethodFlat( d );
326 // intraprocedural work set
327 Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
328 flatNodesToVisit.add( fm );
330 // mapping of current partial results
331 Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraph =
332 new Hashtable<FlatNode, ReachGraph>();
334 // the set of return nodes partial results that will be combined as
335 // the final, conservative approximation of the entire method
336 HashSet<FlatReturnNode> setReturns = new HashSet<FlatReturnNode>();
338 while( !flatNodesToVisit.isEmpty() ) {
339 FlatNode fn = (FlatNode) flatNodesToVisit.iterator().next();
340 flatNodesToVisit.remove( fn );
342 //System.out.println( " "+fn );
344 // effect transfer function defined by this node,
345 // then compare it to the old graph at this node
346 // to see if anything was updated.
348 ReachGraph rg = new ReachGraph();
350 if(fn instanceof FlatMethod && ((FlatMethod)fn).getTask()!=null){
351 // create initial reach graph for a task
352 rg=createInitialTaskReachGraph((FlatMethod)fn);
355 // start by merging all node's parents' graphs
356 for( int i = 0; i < fn.numPrev(); ++i ) {
357 FlatNode pn = fn.getPrev( i );
358 if( mapFlatNodeToReachGraph.containsKey( pn ) ) {
359 ReachGraph rgParent = mapFlatNodeToReachGraph.get( pn );
360 rg.merge( rgParent );
364 if( takeDebugSnapshots &&
365 d.getSymbol().equals( descSymbolDebug )
367 debugSnapshot( rg, fn, true );
370 // modify rg with appropriate transfer function
371 rg = analyzeFlatNode( d, fm, fn, setReturns, rg );
373 if( takeDebugSnapshots &&
374 d.getSymbol().equals( descSymbolDebug )
376 debugSnapshot( rg, fn, false );
380 // if the results of the new graph are different from
381 // the current graph at this node, replace the graph
382 // with the update and enqueue the children
383 ReachGraph rgPrev = mapFlatNodeToReachGraph.get( fn );
384 if( !rg.equals( rgPrev ) ) {
385 mapFlatNodeToReachGraph.put( fn, rg );
387 for( int i = 0; i < fn.numNext(); i++ ) {
388 FlatNode nn = fn.getNext( i );
389 flatNodesToVisit.add( nn );
394 // end by merging all return nodes into a complete
395 // ownership graph that represents all possible heap
396 // states after the flat method returns
397 ReachGraph completeGraph = new ReachGraph();
399 assert !setReturns.isEmpty();
400 Iterator retItr = setReturns.iterator();
401 while( retItr.hasNext() ) {
402 FlatReturnNode frn = (FlatReturnNode) retItr.next();
404 assert mapFlatNodeToReachGraph.containsKey( frn );
405 ReachGraph rgRet = mapFlatNodeToReachGraph.get( frn );
407 completeGraph.merge( rgRet );
410 return completeGraph;
415 analyzeFlatNode( Descriptor d,
416 FlatMethod fmContaining,
418 HashSet<FlatReturnNode> setRetNodes,
420 ) throws java.io.IOException {
423 // any variables that are no longer live should be
424 // nullified in the graph to reduce edges
425 //rg.nullifyDeadVars( liveness.getLiveInTemps( fmContaining, fn ) );
432 // use node type to decide what transfer function
433 // to apply to the reachability graph
434 switch( fn.kind() ) {
436 case FKind.FlatMethod: {
437 // construct this method's initial heap model (IHM)
438 // since we're working on the FlatMethod, we know
439 // the incoming ReachGraph 'rg' is empty
441 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
442 getIHMcontributions( d );
444 Set entrySet = heapsFromCallers.entrySet();
445 Iterator itr = entrySet.iterator();
446 while( itr.hasNext() ) {
447 Map.Entry me = (Map.Entry) itr.next();
448 FlatCall fc = (FlatCall) me.getKey();
449 ReachGraph rgContrib = (ReachGraph) me.getValue();
451 assert fc.getMethod().equals( d );
453 // some call sites are in same method context though,
454 // and all of them should be merged together first,
455 // then heaps from different contexts should be merged
456 // THIS ASSUMES DIFFERENT CONTEXTS NEED SPECIAL CONSIDERATION!
457 // such as, do allocation sites need to be aged?
459 rg.merge_diffMethodContext( rgContrib );
463 case FKind.FlatOpNode:
464 FlatOpNode fon = (FlatOpNode) fn;
465 if( fon.getOp().getOp() == Operation.ASSIGN ) {
468 rg.assignTempXEqualToTempY( lhs, rhs );
472 case FKind.FlatCastNode:
473 FlatCastNode fcn = (FlatCastNode) fn;
477 TypeDescriptor td = fcn.getType();
480 rg.assignTempXEqualToCastedTempY( lhs, rhs, td );
483 case FKind.FlatFieldNode:
484 FlatFieldNode ffn = (FlatFieldNode) fn;
487 fld = ffn.getField();
488 if( !fld.getType().isImmutable() || fld.getType().isArray() ) {
489 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fld );
493 case FKind.FlatSetFieldNode:
494 FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
496 fld = fsfn.getField();
498 if( !fld.getType().isImmutable() || fld.getType().isArray() ) {
499 rg.assignTempXFieldFEqualToTempY( lhs, fld, rhs );
503 case FKind.FlatElementNode:
504 FlatElementNode fen = (FlatElementNode) fn;
507 if( !lhs.getType().isImmutable() || lhs.getType().isArray() ) {
509 assert rhs.getType() != null;
510 assert rhs.getType().isArray();
512 TypeDescriptor tdElement = rhs.getType().dereference();
513 FieldDescriptor fdElement = getArrayField( tdElement );
515 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fdElement );
519 case FKind.FlatSetElementNode:
520 FlatSetElementNode fsen = (FlatSetElementNode) fn;
522 if( arrayReferencees.doesNotCreateNewReaching( fsen ) ) {
523 // skip this node if it cannot create new reachability paths
529 if( !rhs.getType().isImmutable() || rhs.getType().isArray() ) {
531 assert lhs.getType() != null;
532 assert lhs.getType().isArray();
534 TypeDescriptor tdElement = lhs.getType().dereference();
535 FieldDescriptor fdElement = getArrayField( tdElement );
537 rg.assignTempXFieldFEqualToTempY( lhs, fdElement, rhs );
542 FlatNew fnn = (FlatNew) fn;
544 if( !lhs.getType().isImmutable() || lhs.getType().isArray() ) {
545 AllocSite as = getAllocSiteFromFlatNewPRIVATE( fnn );
546 rg.assignTempEqualToNewAlloc( lhs, as );
550 case FKind.FlatCall: {
551 //TODO: temporal fix for task descriptor case
552 //MethodDescriptor mdCaller = fmContaining.getMethod();
554 if(fmContaining.getMethod()!=null){
555 mdCaller = fmContaining.getMethod();
557 mdCaller = fmContaining.getTask();
559 FlatCall fc = (FlatCall) fn;
560 MethodDescriptor mdCallee = fc.getMethod();
561 FlatMethod fmCallee = state.getMethodFlat( mdCallee );
563 boolean writeDebugDOTs =
564 mdCaller.getSymbol().equals( state.DISJOINTDEBUGCALLER ) &&
565 mdCallee.getSymbol().equals( state.DISJOINTDEBUGCALLEE );
568 // calculate the heap this call site can reach--note this is
569 // not used for the current call site transform, we are
570 // grabbing this heap model for future analysis of the callees,
571 // so if different results emerge we will return to this site
572 ReachGraph heapForThisCall_old =
573 getIHMcontribution( mdCallee, fc );
575 // the computation of the callee-reachable heap
576 // is useful for making the callee starting point
577 // and for applying the call site transfer function
578 Set<Integer> callerNodeIDsCopiedToCallee =
579 new HashSet<Integer>();
581 ReachGraph heapForThisCall_cur =
582 rg.makeCalleeView( fc,
584 callerNodeIDsCopiedToCallee,
588 if( !heapForThisCall_cur.equals( heapForThisCall_old ) ) {
589 // if heap at call site changed, update the contribution,
590 // and reschedule the callee for analysis
591 addIHMcontribution( mdCallee, fc, heapForThisCall_cur );
598 // the transformation for a call site should update the
599 // current heap abstraction with any effects from the callee,
600 // or if the method is virtual, the effects from any possible
601 // callees, so find the set of callees...
602 Set<MethodDescriptor> setPossibleCallees =
603 new HashSet<MethodDescriptor>();
605 if( mdCallee.isStatic() ) {
606 setPossibleCallees.add( mdCallee );
608 TypeDescriptor typeDesc = fc.getThis().getType();
609 setPossibleCallees.addAll( callGraph.getMethods( mdCallee,
614 ReachGraph rgMergeOfEffects = new ReachGraph();
616 Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
617 while( mdItr.hasNext() ) {
618 MethodDescriptor mdPossible = mdItr.next();
619 FlatMethod fmPossible = state.getMethodFlat( mdPossible );
621 addDependent( mdPossible, // callee
624 // don't alter the working graph (rg) until we compute a
625 // result for every possible callee, merge them all together,
626 // then set rg to that
627 ReachGraph rgCopy = new ReachGraph();
630 ReachGraph rgEffect = getPartial( mdPossible );
632 if( rgEffect == null ) {
633 // if this method has never been analyzed just schedule it
634 // for analysis and skip over this call site for now
635 enqueue( mdPossible );
637 rgCopy.resolveMethodCall( fc,
640 callerNodeIDsCopiedToCallee,
645 rgMergeOfEffects.merge( rgCopy );
649 // now that we've taken care of building heap models for
650 // callee analysis, finish this transformation
651 rg = rgMergeOfEffects;
655 case FKind.FlatReturnNode:
656 FlatReturnNode frn = (FlatReturnNode) fn;
657 rhs = frn.getReturnTemp();
658 if( rhs != null && !rhs.getType().isImmutable() ) {
659 rg.assignReturnEqualToTemp( rhs );
661 setRetNodes.add( frn );
667 // dead variables were removed before the above transfer function
668 // was applied, so eliminate heap regions and edges that are no
669 // longer part of the abstractly-live heap graph, and sweep up
670 // and reachability effects that are altered by the reduction
671 //rg.abstractGarbageCollect();
675 // at this point rg should be the correct update
676 // by an above transfer function, or untouched if
677 // the flat node type doesn't affect the heap
682 // this method should generate integers strictly greater than zero!
683 // special "shadow" regions are made from a heap region by negating
685 static public Integer generateUniqueHeapRegionNodeID() {
687 return new Integer( uniqueIDcount );
692 static public FieldDescriptor getArrayField( TypeDescriptor tdElement ) {
693 FieldDescriptor fdElement = mapTypeToArrayField.get( tdElement );
694 if( fdElement == null ) {
695 fdElement = new FieldDescriptor( new Modifiers( Modifiers.PUBLIC ),
697 arrayElementFieldName,
700 mapTypeToArrayField.put( tdElement, fdElement );
707 private void writeFinalGraphs() {
708 Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
709 Iterator itr = entrySet.iterator();
710 while( itr.hasNext() ) {
711 Map.Entry me = (Map.Entry) itr.next();
712 Descriptor d = (Descriptor) me.getKey();
713 ReachGraph rg = (ReachGraph) me.getValue();
716 rg.writeGraph( "COMPLETE"+d,
717 true, // write labels (variables)
718 true, // selectively hide intermediate temp vars
719 true, // prune unreachable heap regions
720 false, // show back edges to confirm graph validity
721 true, // hide subset reachability states
722 true ); // hide edge taints
723 } catch( IOException e ) {}
727 private void writeFinalIHMs() {
728 Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
729 while( d2IHMsItr.hasNext() ) {
730 Map.Entry me1 = (Map.Entry) d2IHMsItr.next();
731 Descriptor d = (Descriptor) me1.getKey();
732 Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>) me1.getValue();
734 Iterator fc2rgItr = IHMs.entrySet().iterator();
735 while( fc2rgItr.hasNext() ) {
736 Map.Entry me2 = (Map.Entry) fc2rgItr.next();
737 FlatCall fc = (FlatCall) me2.getKey();
738 ReachGraph rg = (ReachGraph) me2.getValue();
741 rg.writeGraph( "IHMPARTFOR"+d+"FROM"+fc,
742 true, // write labels (variables)
743 false, // selectively hide intermediate temp vars
744 false, // prune unreachable heap regions
745 false, // show back edges to confirm graph validity
746 true, // hide subset reachability states
747 true ); // hide edge taints
748 } catch( IOException e ) {}
756 // return just the allocation site associated with one FlatNew node
757 protected AllocSite getAllocSiteFromFlatNewPRIVATE( FlatNew fnew ) {
759 if( !mapFlatNewToAllocSite.containsKey( fnew ) ) {
761 (AllocSite) Canonical.makeCanonical( new AllocSite( allocationDepth,
767 // the newest nodes are single objects
768 for( int i = 0; i < allocationDepth; ++i ) {
769 Integer id = generateUniqueHeapRegionNodeID();
770 as.setIthOldest( i, id );
771 mapHrnIdToAllocSite.put( id, as );
774 // the oldest node is a summary node
775 as.setSummary( generateUniqueHeapRegionNodeID() );
777 mapFlatNewToAllocSite.put( fnew, as );
780 return mapFlatNewToAllocSite.get( fnew );
785 // return all allocation sites in the method (there is one allocation
786 // site per FlatNew node in a method)
787 protected HashSet<AllocSite> getAllocSiteSet(Descriptor d) {
788 if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
789 buildAllocSiteSet(d);
792 return mapDescriptorToAllocSiteSet.get(d);
798 protected void buildAllocSiteSet(Descriptor d) {
799 HashSet<AllocSite> s = new HashSet<AllocSite>();
801 FlatMethod fm = state.getMethodFlat( d );
803 // visit every node in this FlatMethod's IR graph
804 // and make a set of the allocation sites from the
805 // FlatNew node's visited
806 HashSet<FlatNode> visited = new HashSet<FlatNode>();
807 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
810 while( !toVisit.isEmpty() ) {
811 FlatNode n = toVisit.iterator().next();
813 if( n instanceof FlatNew ) {
814 s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
820 for( int i = 0; i < n.numNext(); ++i ) {
821 FlatNode child = n.getNext( i );
822 if( !visited.contains( child ) ) {
823 toVisit.add( child );
828 mapDescriptorToAllocSiteSet.put( d, s );
832 protected HashSet<AllocSite> getFlaggedAllocSites(Descriptor dIn) {
834 HashSet<AllocSite> out = new HashSet<AllocSite>();
835 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
836 HashSet<Descriptor> visited = new HashSet<Descriptor>();
840 while( !toVisit.isEmpty() ) {
841 Descriptor d = toVisit.iterator().next();
845 HashSet<AllocSite> asSet = getAllocSiteSet(d);
846 Iterator asItr = asSet.iterator();
847 while( asItr.hasNext() ) {
848 AllocSite as = (AllocSite) asItr.next();
849 if( as.getDisjointAnalysisId() != null ) {
854 // enqueue callees of this method to be searched for
855 // allocation sites also
856 Set callees = callGraph.getCalleeSet(d);
857 if( callees != null ) {
858 Iterator methItr = callees.iterator();
859 while( methItr.hasNext() ) {
860 MethodDescriptor md = (MethodDescriptor) methItr.next();
862 if( !visited.contains(md) ) {
874 protected HashSet<AllocSite>
875 getFlaggedAllocSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
877 HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
878 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
879 HashSet<Descriptor> visited = new HashSet<Descriptor>();
883 // traverse this task and all methods reachable from this task
884 while( !toVisit.isEmpty() ) {
885 Descriptor d = toVisit.iterator().next();
889 HashSet<AllocSite> asSet = getAllocSiteSet(d);
890 Iterator asItr = asSet.iterator();
891 while( asItr.hasNext() ) {
892 AllocSite as = (AllocSite) asItr.next();
893 TypeDescriptor typed = as.getType();
894 if( typed != null ) {
895 ClassDescriptor cd = typed.getClassDesc();
896 if( cd != null && cd.hasFlags() ) {
902 // enqueue callees of this method to be searched for
903 // allocation sites also
904 Set callees = callGraph.getCalleeSet(d);
905 if( callees != null ) {
906 Iterator methItr = callees.iterator();
907 while( methItr.hasNext() ) {
908 MethodDescriptor md = (MethodDescriptor) methItr.next();
910 if( !visited.contains(md) ) {
924 protected String computeAliasContextHistogram() {
926 Hashtable<Integer, Integer> mapNumContexts2NumDesc =
927 new Hashtable<Integer, Integer>();
929 Iterator itr = mapDescriptorToAllDescriptors.entrySet().iterator();
930 while( itr.hasNext() ) {
931 Map.Entry me = (Map.Entry) itr.next();
932 HashSet<Descriptor> s = (HashSet<Descriptor>) me.getValue();
934 Integer i = mapNumContexts2NumDesc.get( s.size() );
936 i = new Integer( 0 );
938 mapNumContexts2NumDesc.put( s.size(), i + 1 );
944 itr = mapNumContexts2NumDesc.entrySet().iterator();
945 while( itr.hasNext() ) {
946 Map.Entry me = (Map.Entry) itr.next();
947 Integer c0 = (Integer) me.getKey();
948 Integer d0 = (Integer) me.getValue();
950 s += String.format( "%4d methods had %4d unique alias contexts.\n", d0, c0 );
953 s += String.format( "\n%4d total methods analayzed.\n", total );
958 protected int numMethodsAnalyzed() {
959 return descriptorsToAnalyze.size();
966 // Take in source entry which is the program's compiled entry and
967 // create a new analysis entry, a method that takes no parameters
968 // and appears to allocate the command line arguments and call the
969 // source entry with them. The purpose of this analysis entry is
970 // to provide a top-level method context with no parameters left.
971 protected void makeAnalysisEntryMethod( MethodDescriptor mdSourceEntry ) {
973 Modifiers mods = new Modifiers();
974 mods.addModifier( Modifiers.PUBLIC );
975 mods.addModifier( Modifiers.STATIC );
977 TypeDescriptor returnType =
978 new TypeDescriptor( TypeDescriptor.VOID );
980 this.mdAnalysisEntry =
981 new MethodDescriptor( mods,
983 "analysisEntryMethod"
986 TempDescriptor cmdLineArgs =
987 new TempDescriptor( "args",
988 mdSourceEntry.getParamType( 0 )
992 new FlatNew( mdSourceEntry.getParamType( 0 ),
997 TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
998 sourceEntryArgs[0] = cmdLineArgs;
1001 new FlatCall( mdSourceEntry,
1007 FlatReturnNode frn = new FlatReturnNode( null );
1009 FlatExit fe = new FlatExit();
1011 this.fmAnalysisEntry =
1012 new FlatMethod( mdAnalysisEntry,
1016 this.fmAnalysisEntry.addNext( fn );
1023 protected LinkedList<Descriptor> topologicalSort( Set<Descriptor> toSort ) {
1025 Set <Descriptor> discovered = new HashSet <Descriptor>();
1026 LinkedList<Descriptor> sorted = new LinkedList<Descriptor>();
1028 Iterator<Descriptor> itr = toSort.iterator();
1029 while( itr.hasNext() ) {
1030 Descriptor d = itr.next();
1032 if( !discovered.contains( d ) ) {
1033 dfsVisit( d, toSort, sorted, discovered );
1040 // While we're doing DFS on call graph, remember
1041 // dependencies for efficient queuing of methods
1042 // during interprocedural analysis:
1044 // a dependent of a method decriptor d for this analysis is:
1045 // 1) a method or task that invokes d
1046 // 2) in the descriptorsToAnalyze set
1047 protected void dfsVisit( Descriptor d,
1048 Set <Descriptor> toSort,
1049 LinkedList<Descriptor> sorted,
1050 Set <Descriptor> discovered ) {
1051 discovered.add( d );
1053 // only methods have callers, tasks never do
1054 if( d instanceof MethodDescriptor ) {
1056 MethodDescriptor md = (MethodDescriptor) d;
1058 // the call graph is not aware that we have a fabricated
1059 // analysis entry that calls the program source's entry
1060 if( md == mdSourceEntry ) {
1061 if( !discovered.contains( mdAnalysisEntry ) ) {
1062 addDependent( mdSourceEntry, // callee
1063 mdAnalysisEntry // caller
1065 dfsVisit( mdAnalysisEntry, toSort, sorted, discovered );
1069 // otherwise call graph guides DFS
1070 Iterator itr = callGraph.getCallerSet( md ).iterator();
1071 while( itr.hasNext() ) {
1072 Descriptor dCaller = (Descriptor) itr.next();
1074 // only consider callers in the original set to analyze
1075 if( !toSort.contains( dCaller ) ) {
1079 if( !discovered.contains( dCaller ) ) {
1080 addDependent( md, // callee
1084 dfsVisit( dCaller, toSort, sorted, discovered );
1089 sorted.addFirst( d );
1093 protected void enqueue( Descriptor d ) {
1094 if( !descriptorsToVisitSet.contains( d ) ) {
1095 Integer priority = mapDescriptorToPriority.get( d );
1096 descriptorsToVisitQ.add( new DescriptorQWrapper( priority,
1099 descriptorsToVisitSet.add( d );
1104 protected ReachGraph getPartial( Descriptor d ) {
1105 return mapDescriptorToCompleteReachGraph.get( d );
1108 protected void setPartial( Descriptor d, ReachGraph rg ) {
1109 mapDescriptorToCompleteReachGraph.put( d, rg );
1111 // when the flag for writing out every partial
1112 // result is set, we should spit out the graph,
1113 // but in order to give it a unique name we need
1114 // to track how many partial results for this
1115 // descriptor we've already written out
1116 if( writeAllIncrementalDOTs ) {
1117 if( !mapDescriptorToNumUpdates.containsKey( d ) ) {
1118 mapDescriptorToNumUpdates.put( d, new Integer( 0 ) );
1120 Integer n = mapDescriptorToNumUpdates.get( d );
1123 rg.writeGraph( d+"COMPLETE"+String.format( "%05d", n ),
1124 true, // write labels (variables)
1125 true, // selectively hide intermediate temp vars
1126 true, // prune unreachable heap regions
1127 false, // show back edges to confirm graph validity
1128 false, // show parameter indices (unmaintained!)
1129 true, // hide subset reachability states
1130 true); // hide edge taints
1131 } catch( IOException e ) {}
1133 mapDescriptorToNumUpdates.put( d, n + 1 );
1138 // a dependent of a method decriptor d for this analysis is:
1139 // 1) a method or task that invokes d
1140 // 2) in the descriptorsToAnalyze set
1141 protected void addDependent( Descriptor callee, Descriptor caller ) {
1142 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1143 if( deps == null ) {
1144 deps = new HashSet<Descriptor>();
1147 mapDescriptorToSetDependents.put( callee, deps );
1150 protected Set<Descriptor> getDependents( Descriptor callee ) {
1151 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1152 if( deps == null ) {
1153 deps = new HashSet<Descriptor>();
1154 mapDescriptorToSetDependents.put( callee, deps );
1160 public Hashtable<FlatCall, ReachGraph> getIHMcontributions( Descriptor d ) {
1162 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1163 mapDescriptorToIHMcontributions.get( d );
1165 if( heapsFromCallers == null ) {
1166 heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
1167 mapDescriptorToIHMcontributions.put( d, heapsFromCallers );
1170 return heapsFromCallers;
1173 public ReachGraph getIHMcontribution( Descriptor d,
1176 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1177 getIHMcontributions( d );
1179 if( !heapsFromCallers.containsKey( fc ) ) {
1180 heapsFromCallers.put( fc, new ReachGraph() );
1183 return heapsFromCallers.get( fc );
1186 public void addIHMcontribution( Descriptor d,
1190 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1191 getIHMcontributions( d );
1193 heapsFromCallers.put( fc, rg );
1196 private AllocSite createParameterAllocSite(ReachGraph rg, TempDescriptor tempDesc) {
1198 // create temp descriptor for each parameter variable
1199 FlatNew flatNew = new FlatNew(tempDesc.getType(), tempDesc, false);
1200 // create allocation site
1201 AllocSite as = (AllocSite) Canonical.makeCanonical(new AllocSite( allocationDepth, flatNew, flatNew.getDisjointId()));
1202 for (int i = 0; i < allocationDepth; ++i) {
1203 Integer id = generateUniqueHeapRegionNodeID();
1204 as.setIthOldest(i, id);
1205 mapHrnIdToAllocSite.put(id, as);
1207 // the oldest node is a summary node
1208 as.setSummary( generateUniqueHeapRegionNodeID() );
1216 private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
1217 ReachGraph rg = new ReachGraph();
1218 TaskDescriptor taskDesc = fm.getTask();
1220 for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
1221 Descriptor paramDesc = taskDesc.getParameter(idx);
1222 TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
1224 // setup data structure
1225 Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet =
1226 new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
1227 Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode =
1228 new Hashtable<TypeDescriptor, HeapRegionNode>();
1229 Set<String> doneSet = new HashSet<String>();
1231 TempDescriptor tempDesc = new TempDescriptor(paramDesc.getSymbol(),
1234 AllocSite as = createParameterAllocSite(rg, tempDesc);
1235 VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
1237 Integer idNewest = as.getIthOldest(0);
1238 HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
1239 // make a new reference to allocated node
1240 RefEdge edgeNew = new RefEdge(lnX, // source
1242 taskDesc.getParamType(idx), // type
1244 hrnNewest.getAlpha(), // beta
1245 ExistPredSet.factory(rg.predTrue) // predicates
1247 rg.addRefEdge(lnX, hrnNewest, edgeNew);
1249 // set-up a work set for class field
1250 ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
1251 for (Iterator it = classDesc.getFields(); it.hasNext();) {
1252 FieldDescriptor fd = (FieldDescriptor) it.next();
1253 TypeDescriptor fieldType = fd.getType();
1254 if (!fieldType.isImmutable()) {
1255 HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
1256 newMap.put(hrnNewest, fd);
1257 workSet.add(newMap);
1261 int uniqueIdentifier = 0;
1262 while (!workSet.isEmpty()) {
1263 HashMap<HeapRegionNode, FieldDescriptor> map = workSet
1265 workSet.remove(map);
1267 Set<HeapRegionNode> key = map.keySet();
1268 HeapRegionNode srcHRN = key.iterator().next();
1269 FieldDescriptor fd = map.get(srcHRN);
1270 TypeDescriptor type = fd.getType();
1271 String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
1273 if (!doneSet.contains(doneSetIdentifier)) {
1274 doneSet.add(doneSetIdentifier);
1275 if (!mapTypeToExistingSummaryNode.containsKey(type)) {
1276 // create new summary Node
1277 TempDescriptor td = new TempDescriptor("temp"
1278 + uniqueIdentifier, type);
1280 AllocSite allocSite;
1281 if(type.equals(paramTypeDesc)){
1282 //corresponding allocsite has already been created for a parameter variable.
1285 allocSite = createParameterAllocSite(rg, td);
1287 String strDesc = allocSite.toStringForDOT()
1289 HeapRegionNode hrnSummary =
1290 rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
1291 false, // single object?
1294 false, // out-of-context?
1295 allocSite.getType(), // type
1296 allocSite, // allocation site
1297 null, // inherent reach
1298 srcHRN.getAlpha(), // current reach
1299 ExistPredSet.factory(), // predicates
1300 strDesc // description
1303 // make a new reference to summary node
1304 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1306 fd.getType(), // type
1307 fd.getSymbol(), // field name
1308 srcHRN.getAlpha(), // beta
1309 ExistPredSet.factory(rg.predTrue) // predicates
1312 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1316 mapTypeToExistingSummaryNode.put(type, hrnSummary);
1318 // set-up a work set for fields of the class
1319 classDesc = type.getClassDesc();
1320 for (Iterator it = classDesc.getFields(); it.hasNext();) {
1321 FieldDescriptor typeFieldDesc = (FieldDescriptor) it.next();
1322 TypeDescriptor fieldType = typeFieldDesc.getType();
1323 if (!fieldType.isImmutable()) {
1324 doneSetIdentifier = hrnSummary.getIDString() + "_" + typeFieldDesc;
1325 if(!doneSet.contains(doneSetIdentifier)){
1326 // add new work item
1327 HashMap<HeapRegionNode, FieldDescriptor> newMap =
1328 new HashMap<HeapRegionNode, FieldDescriptor>();
1329 newMap.put(hrnSummary, typeFieldDesc);
1330 workSet.add(newMap);
1336 // if there exists corresponding summary node
1337 HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
1339 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1341 fd.getType(), // type
1342 fd.getSymbol(), // field name
1343 srcHRN.getAlpha(), // beta
1344 ExistPredSet.factory(rg.predTrue) // predicates
1346 rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
1352 // debugSnapshot(rg, fm, true);
1364 // get successive captures of the analysis state
1365 boolean takeDebugSnapshots = false;
1366 String descSymbolDebug = "addBar";
1367 boolean stopAfterCapture = true;
1369 // increments every visit to debugSnapshot, don't fiddle with it
1370 int debugCounter = 0;
1372 // the value of debugCounter to start reporting the debugCounter
1373 // to the screen to let user know what debug iteration we're at
1374 int numStartCountReport = 0;
1376 // the frequency of debugCounter values to print out, 0 no report
1377 int freqCountReport = 0;
1379 // the debugCounter value at which to start taking snapshots
1380 int iterStartCapture = 0;
1382 // the number of snapshots to take
1383 int numIterToCapture = 300;
1385 void debugSnapshot( ReachGraph rg, FlatNode fn, boolean in ) {
1386 if( debugCounter > iterStartCapture + numIterToCapture ) {
1394 if( debugCounter > numStartCountReport &&
1395 freqCountReport > 0 &&
1396 debugCounter % freqCountReport == 0
1398 System.out.println( " @@@ debug counter = "+
1402 if( debugCounter > iterStartCapture ) {
1403 System.out.println( " @@@ capturing debug "+
1404 (debugCounter - iterStartCapture)+
1408 graphName = String.format( "snap%04din",
1409 debugCounter - iterStartCapture );
1411 graphName = String.format( "snap%04dout",
1412 debugCounter - iterStartCapture );
1415 graphName = graphName + fn;
1418 rg.writeGraph( graphName,
1419 true, // write labels (variables)
1420 false, // selectively hide intermediate temp vars
1421 false, // prune unreachable heap regions
1422 false, // show back edges to confirm graph validity
1423 true, // hide subset reachability states
1424 true );// hide edge taints
1425 } catch( Exception e ) {
1426 System.out.println( "Error writing debug capture." );
1431 if( debugCounter == iterStartCapture + numIterToCapture &&
1434 System.out.println( "Stopping analysis after debug captures." );