1 package Analysis.Disjoint;
3 import Analysis.CallGraph.*;
4 import Analysis.Liveness;
5 import Analysis.ArrayReferencees;
8 import IR.Tree.Modifiers;
13 public class DisjointAnalysis {
15 ///////////////////////////////////////////
17 // Public interface to discover possible
18 // aliases in the program under analysis
20 ///////////////////////////////////////////
22 public HashSet<AllocSite>
23 getFlaggedAllocationSitesReachableFromTask(TaskDescriptor td) {
24 checkAnalysisComplete();
25 return getFlaggedAllocationSitesReachableFromTaskPRIVATE(td);
28 public AllocSite getAllocationSiteFromFlatNew(FlatNew fn) {
29 checkAnalysisComplete();
30 return getAllocSiteFromFlatNewPRIVATE(fn);
33 public AllocSite getAllocationSiteFromHeapRegionNodeID(Integer id) {
34 checkAnalysisComplete();
35 return mapHrnIdToAllocSite.get(id);
38 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
41 checkAnalysisComplete();
42 ReachGraph rg=mapDescriptorToCompleteReachGraph.get(taskOrMethod);
43 FlatMethod fm=state.getMethodFlat(taskOrMethod);
45 return rg.mayReachSharedObjects(fm, paramIndex1, paramIndex2);
48 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
49 int paramIndex, AllocSite alloc) {
50 checkAnalysisComplete();
51 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
52 FlatMethod fm=state.getMethodFlat(taskOrMethod);
54 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
57 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
58 AllocSite alloc, int paramIndex) {
59 checkAnalysisComplete();
60 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
61 FlatMethod fm=state.getMethodFlat(taskOrMethod);
63 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
66 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
67 AllocSite alloc1, AllocSite alloc2) {
68 checkAnalysisComplete();
69 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
71 return rg.mayReachSharedObjects(alloc1, alloc2);
74 public String prettyPrintNodeSet(Set<HeapRegionNode> s) {
75 checkAnalysisComplete();
79 Iterator<HeapRegionNode> i = s.iterator();
81 HeapRegionNode n = i.next();
83 AllocSite as = n.getAllocSite();
85 out += " " + n.toString() + ",\n";
87 out += " " + n.toString() + ": " + as.toStringVerbose()
96 // use the methods given above to check every possible sharing class
97 // between task parameters and flagged allocation sites reachable
99 public void writeAllSharing(String outputFile,
102 boolean tabularOutput,
105 throws java.io.IOException {
106 checkAnalysisComplete();
108 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
110 if (!tabularOutput) {
111 bw.write("Conducting ownership analysis with allocation depth = "
112 + allocationDepth + "\n");
113 bw.write(timeReport + "\n");
118 // look through every task for potential sharing
119 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
120 while (taskItr.hasNext()) {
121 TaskDescriptor td = (TaskDescriptor) taskItr.next();
123 if (!tabularOutput) {
124 bw.write("\n---------" + td + "--------\n");
127 HashSet<AllocSite> allocSites = getFlaggedAllocationSitesReachableFromTask(td);
129 Set<HeapRegionNode> common;
131 // for each task parameter, check for sharing classes with
132 // other task parameters and every allocation site
133 // reachable from this task
134 boolean foundSomeSharing = false;
136 FlatMethod fm = state.getMethodFlat(td);
137 for (int i = 0; i < fm.numParameters(); ++i) {
139 // skip parameters with types that cannot reference
141 if( !shouldAnalysisTrack( fm.getParameter( i ).getType() ) ) {
145 // for the ith parameter check for sharing classes to all
146 // higher numbered parameters
147 for (int j = i + 1; j < fm.numParameters(); ++j) {
149 // skip parameters with types that cannot reference
151 if( !shouldAnalysisTrack( fm.getParameter( j ).getType() ) ) {
156 common = hasPotentialSharing(td, i, j);
157 if (!common.isEmpty()) {
158 foundSomeSharing = true;
160 if (!tabularOutput) {
161 bw.write("Potential sharing between parameters " + i
162 + " and " + j + ".\n");
163 bw.write(prettyPrintNodeSet(common) + "\n");
168 // for the ith parameter, check for sharing classes against
169 // the set of allocation sites reachable from this
171 Iterator allocItr = allocSites.iterator();
172 while (allocItr.hasNext()) {
173 AllocSite as = (AllocSite) allocItr.next();
174 common = hasPotentialSharing(td, i, as);
175 if (!common.isEmpty()) {
176 foundSomeSharing = true;
178 if (!tabularOutput) {
179 bw.write("Potential sharing between parameter " + i
180 + " and " + as.getFlatNew() + ".\n");
181 bw.write(prettyPrintNodeSet(common) + "\n");
187 // for each allocation site check for sharing classes with
188 // other allocation sites in the context of execution
190 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
191 Iterator allocItr1 = allocSites.iterator();
192 while (allocItr1.hasNext()) {
193 AllocSite as1 = (AllocSite) allocItr1.next();
195 Iterator allocItr2 = allocSites.iterator();
196 while (allocItr2.hasNext()) {
197 AllocSite as2 = (AllocSite) allocItr2.next();
199 if (!outerChecked.contains(as2)) {
200 common = hasPotentialSharing(td, as1, as2);
202 if (!common.isEmpty()) {
203 foundSomeSharing = true;
205 if (!tabularOutput) {
206 bw.write("Potential sharing between "
207 + as1.getFlatNew() + " and "
208 + as2.getFlatNew() + ".\n");
209 bw.write(prettyPrintNodeSet(common) + "\n");
215 outerChecked.add(as1);
218 if (!foundSomeSharing) {
219 if (!tabularOutput) {
220 bw.write("No sharing between flagged objects in Task " + td
228 bw.write(" & " + numSharing + " & " + justTime + " & " + numLines
229 + " & " + numMethodsAnalyzed() + " \\\\\n");
231 bw.write("\nNumber sharing classes: "+numSharing);
237 // this version of writeAllSharing is for Java programs that have no tasks
238 public void writeAllSharingJava(String outputFile,
241 boolean tabularOutput,
244 throws java.io.IOException {
245 checkAnalysisComplete();
251 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
253 bw.write("Conducting disjoint reachability analysis with allocation depth = "
254 + allocationDepth + "\n");
255 bw.write(timeReport + "\n\n");
257 boolean foundSomeSharing = false;
259 Descriptor d = typeUtil.getMain();
260 HashSet<AllocSite> allocSites = getFlaggedAllocationSites(d);
262 // for each allocation site check for sharing classes with
263 // other allocation sites in the context of execution
265 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
266 Iterator allocItr1 = allocSites.iterator();
267 while (allocItr1.hasNext()) {
268 AllocSite as1 = (AllocSite) allocItr1.next();
270 Iterator allocItr2 = allocSites.iterator();
271 while (allocItr2.hasNext()) {
272 AllocSite as2 = (AllocSite) allocItr2.next();
274 if (!outerChecked.contains(as2)) {
275 Set<HeapRegionNode> common = hasPotentialSharing(d,
278 if (!common.isEmpty()) {
279 foundSomeSharing = true;
280 bw.write("Potential sharing between "
281 + as1.getDisjointAnalysisId() + " and "
282 + as2.getDisjointAnalysisId() + ".\n");
283 bw.write(prettyPrintNodeSet(common) + "\n");
289 outerChecked.add(as1);
292 if (!foundSomeSharing) {
293 bw.write("No sharing classes between flagged objects found.\n");
295 bw.write("\nNumber sharing classes: "+numSharing);
298 bw.write("Number of methods analyzed: "+numMethodsAnalyzed()+"\n");
303 ///////////////////////////////////////////
305 // end public interface
307 ///////////////////////////////////////////
309 protected void checkAnalysisComplete() {
310 if( !analysisComplete ) {
311 throw new Error("Warning: public interface method called while analysis is running.");
316 // run in faster mode, only when bugs wrung out!
317 public static boolean releaseMode;
319 // data from the compiler
321 public CallGraph callGraph;
322 public Liveness liveness;
323 public ArrayReferencees arrayReferencees;
324 public TypeUtil typeUtil;
325 public int allocationDepth;
327 // data structure for public interface
328 private Hashtable<Descriptor, HashSet<AllocSite> > mapDescriptorToAllocSiteSet;
331 // for public interface methods to warn that they
332 // are grabbing results during analysis
333 private boolean analysisComplete;
336 // used to identify HeapRegionNode objects
337 // A unique ID equates an object in one
338 // ownership graph with an object in another
339 // graph that logically represents the same
341 // start at 10 and increment to reserve some
342 // IDs for special purposes
343 static protected int uniqueIDcount = 10;
346 // An out-of-scope method created by the
347 // analysis that has no parameters, and
348 // appears to allocate the command line
349 // arguments, then invoke the source code's
350 // main method. The purpose of this is to
351 // provide the analysis with an explicit
352 // top-level context with no parameters
353 protected MethodDescriptor mdAnalysisEntry;
354 protected FlatMethod fmAnalysisEntry;
356 // main method defined by source program
357 protected MethodDescriptor mdSourceEntry;
359 // the set of task and/or method descriptors
360 // reachable in call graph
361 protected Set<Descriptor>
362 descriptorsToAnalyze;
364 // current descriptors to visit in fixed-point
365 // interprocedural analysis, prioritized by
366 // dependency in the call graph
367 protected Stack<DescriptorQWrapper>
368 descriptorsToVisitStack;
369 protected PriorityQueue<DescriptorQWrapper>
372 // a duplication of the above structure, but
373 // for efficient testing of inclusion
374 protected HashSet<Descriptor>
375 descriptorsToVisitSet;
377 // storage for priorities (doesn't make sense)
378 // to add it to the Descriptor class, just in
380 protected Hashtable<Descriptor, Integer>
381 mapDescriptorToPriority;
384 // maps a descriptor to its current partial result
385 // from the intraprocedural fixed-point analysis--
386 // then the interprocedural analysis settles, this
387 // mapping will have the final results for each
389 protected Hashtable<Descriptor, ReachGraph>
390 mapDescriptorToCompleteReachGraph;
392 // maps a descriptor to its known dependents: namely
393 // methods or tasks that call the descriptor's method
394 // AND are part of this analysis (reachable from main)
395 protected Hashtable< Descriptor, Set<Descriptor> >
396 mapDescriptorToSetDependents;
398 // maps each flat new to one analysis abstraction
399 // allocate site object, these exist outside reach graphs
400 protected Hashtable<FlatNew, AllocSite>
401 mapFlatNewToAllocSite;
403 // maps intergraph heap region IDs to intergraph
404 // allocation sites that created them, a redundant
405 // structure for efficiency in some operations
406 protected Hashtable<Integer, AllocSite>
409 // maps a method to its initial heap model (IHM) that
410 // is the set of reachability graphs from every caller
411 // site, all merged together. The reason that we keep
412 // them separate is that any one call site's contribution
413 // to the IHM may changed along the path to the fixed point
414 protected Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >
415 mapDescriptorToIHMcontributions;
417 // additionally, keep a mapping from descriptors to the
418 // merged in-coming initial context, because we want this
419 // initial context to be STRICTLY MONOTONIC
420 protected Hashtable<Descriptor, ReachGraph>
421 mapDescriptorToInitialContext;
423 // make the result for back edges analysis-wide STRICTLY
424 // MONOTONIC as well, but notice we use FlatNode as the
425 // key for this map: in case we want to consider other
426 // nodes as back edge's in future implementations
427 protected Hashtable<FlatNode, ReachGraph>
428 mapBackEdgeToMonotone;
431 public static final String arrayElementFieldName = "___element_";
432 static protected Hashtable<TypeDescriptor, FieldDescriptor>
435 // for controlling DOT file output
436 protected boolean writeFinalDOTs;
437 protected boolean writeAllIncrementalDOTs;
439 // supporting DOT output--when we want to write every
440 // partial method result, keep a tally for generating
442 protected Hashtable<Descriptor, Integer>
443 mapDescriptorToNumUpdates;
445 //map task descriptor to initial task parameter
446 protected Hashtable<Descriptor, ReachGraph>
447 mapDescriptorToReachGraph;
449 protected PointerMethod pm;
451 static protected Hashtable<FlatNode, ReachGraph> fn2rg =
452 new Hashtable<FlatNode, ReachGraph>();
455 // allocate various structures that are not local
456 // to a single class method--should be done once
457 protected void allocateStructures() {
458 descriptorsToAnalyze = new HashSet<Descriptor>();
460 mapDescriptorToCompleteReachGraph =
461 new Hashtable<Descriptor, ReachGraph>();
463 mapDescriptorToNumUpdates =
464 new Hashtable<Descriptor, Integer>();
466 mapDescriptorToSetDependents =
467 new Hashtable< Descriptor, Set<Descriptor> >();
469 mapFlatNewToAllocSite =
470 new Hashtable<FlatNew, AllocSite>();
472 mapDescriptorToIHMcontributions =
473 new Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >();
475 mapDescriptorToInitialContext =
476 new Hashtable<Descriptor, ReachGraph>();
478 mapBackEdgeToMonotone =
479 new Hashtable<FlatNode, ReachGraph>();
481 mapHrnIdToAllocSite =
482 new Hashtable<Integer, AllocSite>();
484 mapTypeToArrayField =
485 new Hashtable <TypeDescriptor, FieldDescriptor>();
487 if( state.DISJOINTDVISITSTACK ) {
488 descriptorsToVisitStack =
489 new Stack<DescriptorQWrapper>();
492 if( state.DISJOINTDVISITPQUE ) {
493 descriptorsToVisitQ =
494 new PriorityQueue<DescriptorQWrapper>();
497 descriptorsToVisitSet =
498 new HashSet<Descriptor>();
500 mapDescriptorToPriority =
501 new Hashtable<Descriptor, Integer>();
503 mapDescriptorToAllocSiteSet =
504 new Hashtable<Descriptor, HashSet<AllocSite> >();
506 mapDescriptorToReachGraph =
507 new Hashtable<Descriptor, ReachGraph>();
512 // this analysis generates a disjoint reachability
513 // graph for every reachable method in the program
514 public DisjointAnalysis( State s,
519 ) throws java.io.IOException {
520 init( s, tu, cg, l, ar );
523 protected void init( State state,
527 ArrayReferencees arrayReferencees
528 ) throws java.io.IOException {
530 analysisComplete = false;
533 this.typeUtil = typeUtil;
534 this.callGraph = callGraph;
535 this.liveness = liveness;
536 this.arrayReferencees = arrayReferencees;
537 this.allocationDepth = state.DISJOINTALLOCDEPTH;
538 this.releaseMode = state.DISJOINTRELEASEMODE;
540 this.writeFinalDOTs = state.DISJOINTWRITEDOTS && !state.DISJOINTWRITEALL;
541 this.writeAllIncrementalDOTs = state.DISJOINTWRITEDOTS && state.DISJOINTWRITEALL;
543 this.takeDebugSnapshots = state.DISJOINTSNAPSYMBOL != null;
544 this.descSymbolDebug = state.DISJOINTSNAPSYMBOL;
545 this.visitStartCapture = state.DISJOINTSNAPVISITTOSTART;
546 this.numVisitsToCapture = state.DISJOINTSNAPNUMVISITS;
547 this.stopAfterCapture = state.DISJOINTSNAPSTOPAFTER;
548 this.snapVisitCounter = 1; // count visits from 1 (user will write 1, means 1st visit)
549 this.snapNodeCounter = 0; // count nodes from 0
550 this.pm=new PointerMethod();
552 assert state.DISJOINTDVISITSTACK || state.DISJOINTDVISITPQUE;
553 assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITPQUE);
555 // set some static configuration for ReachGraphs
556 ReachGraph.allocationDepth = allocationDepth;
557 ReachGraph.typeUtil = typeUtil;
559 ReachGraph.debugCallSiteVisitsUntilExit = state.DISJOINTDEBUGCALLCOUNT;
561 allocateStructures();
563 double timeStartAnalysis = (double) System.nanoTime();
565 // start interprocedural fixed-point computation
567 analysisComplete=true;
569 double timeEndAnalysis = (double) System.nanoTime();
570 double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
571 String treport = String.format( "The reachability analysis took %.3f sec.", dt );
572 String justtime = String.format( "%.2f", dt );
573 System.out.println( treport );
575 if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
579 if( state.DISJOINTWRITEIHMS ) {
583 if( state.DISJOINTALIASFILE != null ) {
585 writeAllSharing(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines);
587 writeAllSharingJava(state.DISJOINTALIASFILE,
590 state.DISJOINTALIASTAB,
598 protected boolean moreDescriptorsToVisit() {
599 if( state.DISJOINTDVISITSTACK ) {
600 return !descriptorsToVisitStack.isEmpty();
602 } else if( state.DISJOINTDVISITPQUE ) {
603 return !descriptorsToVisitQ.isEmpty();
606 throw new Error( "Neither descriptor visiting mode set" );
610 // fixed-point computation over the call graph--when a
611 // method's callees are updated, it must be reanalyzed
612 protected void analyzeMethods() throws java.io.IOException {
615 // This analysis does not support Bamboo at the moment,
616 // but if it does in the future we would initialize the
617 // set of descriptors to analyze as the program-reachable
618 // tasks and the methods callable by them. For Java,
619 // just methods reachable from the main method.
620 System.out.println( "Bamboo..." );
621 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
623 while (taskItr.hasNext()) {
624 TaskDescriptor td = (TaskDescriptor) taskItr.next();
625 if (!descriptorsToAnalyze.contains(td)) {
626 descriptorsToAnalyze.add(td);
627 descriptorsToAnalyze.addAll(callGraph.getAllMethods(td));
632 // add all methods transitively reachable from the
633 // source's main to set for analysis
634 mdSourceEntry = typeUtil.getMain();
635 descriptorsToAnalyze.add( mdSourceEntry );
636 descriptorsToAnalyze.addAll(
637 callGraph.getAllMethods( mdSourceEntry )
640 // fabricate an empty calling context that will call
641 // the source's main, but call graph doesn't know
642 // about it, so explicitly add it
643 makeAnalysisEntryMethod( mdSourceEntry );
644 descriptorsToAnalyze.add( mdAnalysisEntry );
647 // topologically sort according to the call graph so
648 // leaf calls are ordered first, smarter analysis order
649 // CHANGED: order leaf calls last!!
650 LinkedList<Descriptor> sortedDescriptors =
651 topologicalSort( descriptorsToAnalyze );
653 // add sorted descriptors to priority queue, and duplicate
654 // the queue as a set for efficiently testing whether some
655 // method is marked for analysis
657 Iterator<Descriptor> dItr = sortedDescriptors.iterator();
658 while( dItr.hasNext() ) {
659 Descriptor d = dItr.next();
661 mapDescriptorToPriority.put( d, new Integer( p ) );
663 if( state.DISJOINTDVISITSTACK ) {
664 descriptorsToVisitStack.add( new DescriptorQWrapper( p, d ) );
666 } else if( state.DISJOINTDVISITPQUE ) {
667 descriptorsToVisitQ.add( new DescriptorQWrapper( p, d ) );
670 descriptorsToVisitSet.add( d );
674 // analyze methods from the priority queue until it is empty
675 while( moreDescriptorsToVisit() ) {
678 if( state.DISJOINTDVISITSTACK ) {
679 d = descriptorsToVisitStack.pop().getDescriptor();
681 } else if( state.DISJOINTDVISITPQUE ) {
682 d = descriptorsToVisitQ.poll().getDescriptor();
685 assert descriptorsToVisitSet.contains( d );
686 descriptorsToVisitSet.remove( d );
688 // because the task or method descriptor just extracted
689 // was in the "to visit" set it either hasn't been analyzed
690 // yet, or some method that it depends on has been
691 // updated. Recompute a complete reachability graph for
692 // this task/method and compare it to any previous result.
693 // If there is a change detected, add any methods/tasks
694 // that depend on this one to the "to visit" set.
696 System.out.println( "Analyzing " + d );
698 ReachGraph rg = analyzeMethod( d );
699 ReachGraph rgPrev = getPartial( d );
701 if( !rg.equals( rgPrev ) ) {
704 // results for d changed, so enqueue dependents
705 // of d for further analysis
706 Iterator<Descriptor> depsItr = getDependents( d ).iterator();
707 while( depsItr.hasNext() ) {
708 Descriptor dNext = depsItr.next();
715 protected ReachGraph analyzeMethod( Descriptor d )
716 throws java.io.IOException {
718 // get the flat code for this descriptor
720 if( d == mdAnalysisEntry ) {
721 fm = fmAnalysisEntry;
723 fm = state.getMethodFlat( d );
725 pm.analyzeMethod( fm );
727 // intraprocedural work set
728 Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
729 flatNodesToVisit.add( fm );
731 Set<FlatNode> debugVisited = new HashSet<FlatNode>();
733 // mapping of current partial results
734 Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraph =
735 new Hashtable<FlatNode, ReachGraph>();
737 // the set of return nodes partial results that will be combined as
738 // the final, conservative approximation of the entire method
739 HashSet<FlatReturnNode> setReturns = new HashSet<FlatReturnNode>();
741 while( !flatNodesToVisit.isEmpty() ) {
742 FlatNode fn = (FlatNode) flatNodesToVisit.iterator().next();
743 flatNodesToVisit.remove( fn );
745 debugVisited.add( fn );
747 // effect transfer function defined by this node,
748 // then compare it to the old graph at this node
749 // to see if anything was updated.
751 ReachGraph rg = new ReachGraph();
752 TaskDescriptor taskDesc;
753 if(fn instanceof FlatMethod && (taskDesc=((FlatMethod)fn).getTask())!=null){
754 if(mapDescriptorToReachGraph.containsKey(taskDesc)){
755 // retrieve existing reach graph if it is not first time
756 rg=mapDescriptorToReachGraph.get(taskDesc);
758 // create initial reach graph for a task
759 rg=createInitialTaskReachGraph((FlatMethod)fn);
761 mapDescriptorToReachGraph.put(taskDesc, rg);
765 // start by merging all node's parents' graphs
766 for( int i = 0; i < pm.numPrev(fn); ++i ) {
767 FlatNode pn = pm.getPrev(fn,i);
768 if( mapFlatNodeToReachGraph.containsKey( pn ) ) {
769 ReachGraph rgParent = mapFlatNodeToReachGraph.get( pn );
770 rg.merge( rgParent );
775 if( takeDebugSnapshots &&
776 d.getSymbol().equals( descSymbolDebug )
778 debugSnapshot( rg, fn, true );
782 // modify rg with appropriate transfer function
783 rg = analyzeFlatNode( d, fm, fn, setReturns, rg );
786 if( takeDebugSnapshots &&
787 d.getSymbol().equals( descSymbolDebug )
789 debugSnapshot( rg, fn, false );
794 // if the results of the new graph are different from
795 // the current graph at this node, replace the graph
796 // with the update and enqueue the children
797 ReachGraph rgPrev = mapFlatNodeToReachGraph.get( fn );
798 if( !rg.equals( rgPrev ) ) {
799 mapFlatNodeToReachGraph.put( fn, rg );
801 for( int i = 0; i < pm.numNext(fn); i++ ) {
802 FlatNode nn = pm.getNext(fn, i);
803 flatNodesToVisit.add( nn );
809 // assert that the fixed-point results for each
810 // node in the method is no smaller than the last
811 // time this method was analyzed (monotonicity)
813 Iterator<FlatNode> nItr = fm.getNodeSet().iterator();
814 while( nItr.hasNext() ) {
815 FlatNode fn = nItr.next();
816 ReachGraph last = fn2rg.get( fn );
817 ReachGraph newest = mapFlatNodeToReachGraph.get( fn );
819 if( newest == null ) {
820 System.out.println( "**********\nfn null result: "+fn+
821 "\nnum visited="+debugVisited.size()+", num in set="+fm.getNodeSet().size()+
822 "\nvisited:"+debugVisited );
825 assert newest != null;
827 if( !ReachGraph.isNoSmallerThan( last, newest ) ) {
828 last.writeGraph( "last", true, false, false, true, true );
829 newest.writeGraph( "newest", true, false, false, true, true );
830 throw new Error( "transfer func for "+fn+" was not monotic" );
833 fn2rg.put( fn, newest );
837 // end by merging all return nodes into a complete
838 // reach graph that represents all possible heap
839 // states after the flat method returns
840 ReachGraph completeGraph = new ReachGraph();
842 assert !setReturns.isEmpty();
843 Iterator retItr = setReturns.iterator();
844 while( retItr.hasNext() ) {
845 FlatReturnNode frn = (FlatReturnNode) retItr.next();
847 assert mapFlatNodeToReachGraph.containsKey( frn );
848 ReachGraph rgRet = mapFlatNodeToReachGraph.get( frn );
850 completeGraph.merge( rgRet );
854 if( takeDebugSnapshots &&
855 d.getSymbol().equals( descSymbolDebug )
857 // increment that we've visited the debug snap
858 // method, and reset the node counter
859 System.out.println( " @@@ debug snap at visit "+snapVisitCounter );
863 if( snapVisitCounter == visitStartCapture + numVisitsToCapture &&
866 System.out.println( "!!! Stopping analysis after debug snap captures. !!!" );
872 return completeGraph;
877 analyzeFlatNode( Descriptor d,
878 FlatMethod fmContaining,
880 HashSet<FlatReturnNode> setRetNodes,
882 ) throws java.io.IOException {
885 // any variables that are no longer live should be
886 // nullified in the graph to reduce edges
887 //rg.nullifyDeadVars( liveness.getLiveInTemps( fmContaining, fn ) );
894 // use node type to decide what transfer function
895 // to apply to the reachability graph
896 switch( fn.kind() ) {
898 case FKind.FlatMethod: {
899 // construct this method's initial heap model (IHM)
900 // since we're working on the FlatMethod, we know
901 // the incoming ReachGraph 'rg' is empty
903 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
904 getIHMcontributions( d );
906 Set entrySet = heapsFromCallers.entrySet();
907 Iterator itr = entrySet.iterator();
908 while( itr.hasNext() ) {
909 Map.Entry me = (Map.Entry) itr.next();
910 FlatCall fc = (FlatCall) me.getKey();
911 ReachGraph rgContrib = (ReachGraph) me.getValue();
913 assert fc.getMethod().equals( d );
915 rg.merge( rgContrib );
918 // additionally, we are enforcing STRICT MONOTONICITY for the
919 // method's initial context, so grow the context by whatever
920 // the previously computed context was, and put the most
921 // up-to-date context back in the map
922 ReachGraph rgPrevContext = mapDescriptorToInitialContext.get( d );
923 rg.merge( rgPrevContext );
924 mapDescriptorToInitialContext.put( d, rg );
928 case FKind.FlatOpNode:
929 FlatOpNode fon = (FlatOpNode) fn;
930 if( fon.getOp().getOp() == Operation.ASSIGN ) {
933 rg.assignTempXEqualToTempY( lhs, rhs );
937 case FKind.FlatCastNode:
938 FlatCastNode fcn = (FlatCastNode) fn;
942 TypeDescriptor td = fcn.getType();
945 rg.assignTempXEqualToCastedTempY( lhs, rhs, td );
948 case FKind.FlatFieldNode:
949 FlatFieldNode ffn = (FlatFieldNode) fn;
952 fld = ffn.getField();
953 if( shouldAnalysisTrack( fld.getType() ) ) {
954 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fld );
958 case FKind.FlatSetFieldNode:
959 FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
961 fld = fsfn.getField();
963 if( shouldAnalysisTrack( fld.getType() ) ) {
964 rg.assignTempXFieldFEqualToTempY( lhs, fld, rhs );
968 case FKind.FlatElementNode:
969 FlatElementNode fen = (FlatElementNode) fn;
972 if( shouldAnalysisTrack( lhs.getType() ) ) {
974 assert rhs.getType() != null;
975 assert rhs.getType().isArray();
977 TypeDescriptor tdElement = rhs.getType().dereference();
978 FieldDescriptor fdElement = getArrayField( tdElement );
980 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fdElement );
984 case FKind.FlatSetElementNode:
985 FlatSetElementNode fsen = (FlatSetElementNode) fn;
987 if( arrayReferencees.doesNotCreateNewReaching( fsen ) ) {
988 // skip this node if it cannot create new reachability paths
994 if( shouldAnalysisTrack( rhs.getType() ) ) {
996 assert lhs.getType() != null;
997 assert lhs.getType().isArray();
999 TypeDescriptor tdElement = lhs.getType().dereference();
1000 FieldDescriptor fdElement = getArrayField( tdElement );
1002 rg.assignTempXFieldFEqualToTempY( lhs, fdElement, rhs );
1007 FlatNew fnn = (FlatNew) fn;
1009 if( shouldAnalysisTrack( lhs.getType() ) ) {
1010 AllocSite as = getAllocSiteFromFlatNewPRIVATE( fnn );
1011 rg.assignTempEqualToNewAlloc( lhs, as );
1015 case FKind.FlatCall: {
1016 //TODO: temporal fix for task descriptor case
1017 //MethodDescriptor mdCaller = fmContaining.getMethod();
1018 Descriptor mdCaller;
1019 if(fmContaining.getMethod()!=null){
1020 mdCaller = fmContaining.getMethod();
1022 mdCaller = fmContaining.getTask();
1024 FlatCall fc = (FlatCall) fn;
1025 MethodDescriptor mdCallee = fc.getMethod();
1026 FlatMethod fmCallee = state.getMethodFlat( mdCallee );
1028 boolean writeDebugDOTs =
1029 mdCaller.getSymbol().equals( state.DISJOINTDEBUGCALLER ) &&
1030 mdCallee.getSymbol().equals( state.DISJOINTDEBUGCALLEE );
1033 // calculate the heap this call site can reach--note this is
1034 // not used for the current call site transform, we are
1035 // grabbing this heap model for future analysis of the callees,
1036 // so if different results emerge we will return to this site
1037 ReachGraph heapForThisCall_old =
1038 getIHMcontribution( mdCallee, fc );
1040 // the computation of the callee-reachable heap
1041 // is useful for making the callee starting point
1042 // and for applying the call site transfer function
1043 Set<Integer> callerNodeIDsCopiedToCallee =
1044 new HashSet<Integer>();
1046 ReachGraph heapForThisCall_cur =
1047 rg.makeCalleeView( fc,
1049 callerNodeIDsCopiedToCallee,
1053 if( !heapForThisCall_cur.equals( heapForThisCall_old ) ) {
1054 // if heap at call site changed, update the contribution,
1055 // and reschedule the callee for analysis
1056 addIHMcontribution( mdCallee, fc, heapForThisCall_cur );
1057 enqueue( mdCallee );
1063 // the transformation for a call site should update the
1064 // current heap abstraction with any effects from the callee,
1065 // or if the method is virtual, the effects from any possible
1066 // callees, so find the set of callees...
1067 Set<MethodDescriptor> setPossibleCallees =
1068 new HashSet<MethodDescriptor>();
1070 if( mdCallee.isStatic() ) {
1071 setPossibleCallees.add( mdCallee );
1073 TypeDescriptor typeDesc = fc.getThis().getType();
1074 setPossibleCallees.addAll( callGraph.getMethods( mdCallee,
1079 ReachGraph rgMergeOfEffects = new ReachGraph();
1081 Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
1082 while( mdItr.hasNext() ) {
1083 MethodDescriptor mdPossible = mdItr.next();
1084 FlatMethod fmPossible = state.getMethodFlat( mdPossible );
1086 addDependent( mdPossible, // callee
1089 // don't alter the working graph (rg) until we compute a
1090 // result for every possible callee, merge them all together,
1091 // then set rg to that
1092 ReachGraph rgCopy = new ReachGraph();
1095 ReachGraph rgEffect = getPartial( mdPossible );
1097 if( rgEffect == null ) {
1098 // if this method has never been analyzed just schedule it
1099 // for analysis and skip over this call site for now
1100 enqueue( mdPossible );
1102 rgCopy.resolveMethodCall( fc,
1105 callerNodeIDsCopiedToCallee,
1110 rgMergeOfEffects.merge( rgCopy );
1114 // now that we've taken care of building heap models for
1115 // callee analysis, finish this transformation
1116 rg = rgMergeOfEffects;
1120 case FKind.FlatReturnNode:
1121 FlatReturnNode frn = (FlatReturnNode) fn;
1122 rhs = frn.getReturnTemp();
1123 if( rhs != null && shouldAnalysisTrack( rhs.getType() ) ) {
1124 rg.assignReturnEqualToTemp( rhs );
1126 setRetNodes.add( frn );
1132 // dead variables were removed before the above transfer function
1133 // was applied, so eliminate heap regions and edges that are no
1134 // longer part of the abstractly-live heap graph, and sweep up
1135 // and reachability effects that are altered by the reduction
1136 //rg.abstractGarbageCollect();
1140 // back edges are strictly monotonic
1141 if( pm.isBackEdge( fn ) ) {
1142 ReachGraph rgPrevResult = mapBackEdgeToMonotone.get( fn );
1143 rg.merge( rgPrevResult );
1144 mapBackEdgeToMonotone.put( fn, rg );
1147 // at this point rg should be the correct update
1148 // by an above transfer function, or untouched if
1149 // the flat node type doesn't affect the heap
1155 // this method should generate integers strictly greater than zero!
1156 // special "shadow" regions are made from a heap region by negating
1158 static public Integer generateUniqueHeapRegionNodeID() {
1160 return new Integer( uniqueIDcount );
1165 static public FieldDescriptor getArrayField( TypeDescriptor tdElement ) {
1166 FieldDescriptor fdElement = mapTypeToArrayField.get( tdElement );
1167 if( fdElement == null ) {
1168 fdElement = new FieldDescriptor( new Modifiers( Modifiers.PUBLIC ),
1170 arrayElementFieldName,
1173 mapTypeToArrayField.put( tdElement, fdElement );
1180 private void writeFinalGraphs() {
1181 Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
1182 Iterator itr = entrySet.iterator();
1183 while( itr.hasNext() ) {
1184 Map.Entry me = (Map.Entry) itr.next();
1185 Descriptor d = (Descriptor) me.getKey();
1186 ReachGraph rg = (ReachGraph) me.getValue();
1188 rg.writeGraph( "COMPLETE"+d,
1189 true, // write labels (variables)
1190 true, // selectively hide intermediate temp vars
1191 true, // prune unreachable heap regions
1192 false, // hide subset reachability states
1193 true ); // hide edge taints
1197 private void writeFinalIHMs() {
1198 Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
1199 while( d2IHMsItr.hasNext() ) {
1200 Map.Entry me1 = (Map.Entry) d2IHMsItr.next();
1201 Descriptor d = (Descriptor) me1.getKey();
1202 Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>) me1.getValue();
1204 Iterator fc2rgItr = IHMs.entrySet().iterator();
1205 while( fc2rgItr.hasNext() ) {
1206 Map.Entry me2 = (Map.Entry) fc2rgItr.next();
1207 FlatCall fc = (FlatCall) me2.getKey();
1208 ReachGraph rg = (ReachGraph) me2.getValue();
1210 rg.writeGraph( "IHMPARTFOR"+d+"FROM"+fc,
1211 true, // write labels (variables)
1212 true, // selectively hide intermediate temp vars
1213 true, // prune unreachable heap regions
1214 false, // hide subset reachability states
1215 true ); // hide edge taints
1221 protected ReachGraph getPartial( Descriptor d ) {
1222 return mapDescriptorToCompleteReachGraph.get( d );
1225 protected void setPartial( Descriptor d, ReachGraph rg ) {
1226 mapDescriptorToCompleteReachGraph.put( d, rg );
1228 // when the flag for writing out every partial
1229 // result is set, we should spit out the graph,
1230 // but in order to give it a unique name we need
1231 // to track how many partial results for this
1232 // descriptor we've already written out
1233 if( writeAllIncrementalDOTs ) {
1234 if( !mapDescriptorToNumUpdates.containsKey( d ) ) {
1235 mapDescriptorToNumUpdates.put( d, new Integer( 0 ) );
1237 Integer n = mapDescriptorToNumUpdates.get( d );
1239 rg.writeGraph( d+"COMPLETE"+String.format( "%05d", n ),
1240 true, // write labels (variables)
1241 true, // selectively hide intermediate temp vars
1242 true, // prune unreachable heap regions
1243 false, // hide subset reachability states
1244 true ); // hide edge taints
1246 mapDescriptorToNumUpdates.put( d, n + 1 );
1252 // return just the allocation site associated with one FlatNew node
1253 protected AllocSite getAllocSiteFromFlatNewPRIVATE( FlatNew fnew ) {
1255 if( !mapFlatNewToAllocSite.containsKey( fnew ) ) {
1256 AllocSite as = AllocSite.factory( allocationDepth,
1258 fnew.getDisjointId()
1261 // the newest nodes are single objects
1262 for( int i = 0; i < allocationDepth; ++i ) {
1263 Integer id = generateUniqueHeapRegionNodeID();
1264 as.setIthOldest( i, id );
1265 mapHrnIdToAllocSite.put( id, as );
1268 // the oldest node is a summary node
1269 as.setSummary( generateUniqueHeapRegionNodeID() );
1271 mapFlatNewToAllocSite.put( fnew, as );
1274 return mapFlatNewToAllocSite.get( fnew );
1278 public static boolean shouldAnalysisTrack( TypeDescriptor type ) {
1279 // don't track primitive types, but an array
1280 // of primitives is heap memory
1281 if( type.isImmutable() ) {
1282 return type.isArray();
1285 // everything else is an object
1289 protected int numMethodsAnalyzed() {
1290 return descriptorsToAnalyze.size();
1297 // Take in source entry which is the program's compiled entry and
1298 // create a new analysis entry, a method that takes no parameters
1299 // and appears to allocate the command line arguments and call the
1300 // source entry with them. The purpose of this analysis entry is
1301 // to provide a top-level method context with no parameters left.
1302 protected void makeAnalysisEntryMethod( MethodDescriptor mdSourceEntry ) {
1304 Modifiers mods = new Modifiers();
1305 mods.addModifier( Modifiers.PUBLIC );
1306 mods.addModifier( Modifiers.STATIC );
1308 TypeDescriptor returnType =
1309 new TypeDescriptor( TypeDescriptor.VOID );
1311 this.mdAnalysisEntry =
1312 new MethodDescriptor( mods,
1314 "analysisEntryMethod"
1317 TempDescriptor cmdLineArgs =
1318 new TempDescriptor( "args",
1319 mdSourceEntry.getParamType( 0 )
1323 new FlatNew( mdSourceEntry.getParamType( 0 ),
1328 TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
1329 sourceEntryArgs[0] = cmdLineArgs;
1332 new FlatCall( mdSourceEntry,
1338 FlatReturnNode frn = new FlatReturnNode( null );
1340 FlatExit fe = new FlatExit();
1342 this.fmAnalysisEntry =
1343 new FlatMethod( mdAnalysisEntry,
1347 this.fmAnalysisEntry.addNext( fn );
1354 protected LinkedList<Descriptor> topologicalSort( Set<Descriptor> toSort ) {
1356 Set <Descriptor> discovered = new HashSet <Descriptor>();
1357 LinkedList<Descriptor> sorted = new LinkedList<Descriptor>();
1359 Iterator<Descriptor> itr = toSort.iterator();
1360 while( itr.hasNext() ) {
1361 Descriptor d = itr.next();
1363 if( !discovered.contains( d ) ) {
1364 dfsVisit( d, toSort, sorted, discovered );
1371 // While we're doing DFS on call graph, remember
1372 // dependencies for efficient queuing of methods
1373 // during interprocedural analysis:
1375 // a dependent of a method decriptor d for this analysis is:
1376 // 1) a method or task that invokes d
1377 // 2) in the descriptorsToAnalyze set
1378 protected void dfsVisit( Descriptor d,
1379 Set <Descriptor> toSort,
1380 LinkedList<Descriptor> sorted,
1381 Set <Descriptor> discovered ) {
1382 discovered.add( d );
1384 // only methods have callers, tasks never do
1385 if( d instanceof MethodDescriptor ) {
1387 MethodDescriptor md = (MethodDescriptor) d;
1389 // the call graph is not aware that we have a fabricated
1390 // analysis entry that calls the program source's entry
1391 if( md == mdSourceEntry ) {
1392 if( !discovered.contains( mdAnalysisEntry ) ) {
1393 addDependent( mdSourceEntry, // callee
1394 mdAnalysisEntry // caller
1396 dfsVisit( mdAnalysisEntry, toSort, sorted, discovered );
1400 // otherwise call graph guides DFS
1401 Iterator itr = callGraph.getCallerSet( md ).iterator();
1402 while( itr.hasNext() ) {
1403 Descriptor dCaller = (Descriptor) itr.next();
1405 // only consider callers in the original set to analyze
1406 if( !toSort.contains( dCaller ) ) {
1410 if( !discovered.contains( dCaller ) ) {
1411 addDependent( md, // callee
1415 dfsVisit( dCaller, toSort, sorted, discovered );
1420 // for leaf-nodes last now!
1421 sorted.addLast( d );
1425 protected void enqueue( Descriptor d ) {
1426 if( !descriptorsToVisitSet.contains( d ) ) {
1427 Integer priority = mapDescriptorToPriority.get( d );
1429 if( state.DISJOINTDVISITSTACK ) {
1430 descriptorsToVisitStack.add( new DescriptorQWrapper( priority,
1434 } else if( state.DISJOINTDVISITPQUE ) {
1435 descriptorsToVisitQ.add( new DescriptorQWrapper( priority,
1440 descriptorsToVisitSet.add( d );
1445 // a dependent of a method decriptor d for this analysis is:
1446 // 1) a method or task that invokes d
1447 // 2) in the descriptorsToAnalyze set
1448 protected void addDependent( Descriptor callee, Descriptor caller ) {
1449 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1450 if( deps == null ) {
1451 deps = new HashSet<Descriptor>();
1454 mapDescriptorToSetDependents.put( callee, deps );
1457 protected Set<Descriptor> getDependents( Descriptor callee ) {
1458 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1459 if( deps == null ) {
1460 deps = new HashSet<Descriptor>();
1461 mapDescriptorToSetDependents.put( callee, deps );
1467 public Hashtable<FlatCall, ReachGraph> getIHMcontributions( Descriptor d ) {
1469 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1470 mapDescriptorToIHMcontributions.get( d );
1472 if( heapsFromCallers == null ) {
1473 heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
1474 mapDescriptorToIHMcontributions.put( d, heapsFromCallers );
1477 return heapsFromCallers;
1480 public ReachGraph getIHMcontribution( Descriptor d,
1483 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1484 getIHMcontributions( d );
1486 if( !heapsFromCallers.containsKey( fc ) ) {
1487 heapsFromCallers.put( fc, new ReachGraph() );
1490 return heapsFromCallers.get( fc );
1493 public void addIHMcontribution( Descriptor d,
1497 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1498 getIHMcontributions( d );
1500 heapsFromCallers.put( fc, rg );
1503 private AllocSite createParameterAllocSite( ReachGraph rg,
1504 TempDescriptor tempDesc
1507 FlatNew flatNew = new FlatNew( tempDesc.getType(), // type
1508 tempDesc, // param temp
1509 false, // global alloc?
1510 "param"+tempDesc // disjoint site ID string
1512 // create allocation site
1513 AllocSite as = AllocSite.factory( allocationDepth,
1515 flatNew.getDisjointId()
1517 for (int i = 0; i < allocationDepth; ++i) {
1518 Integer id = generateUniqueHeapRegionNodeID();
1519 as.setIthOldest(i, id);
1520 mapHrnIdToAllocSite.put(id, as);
1522 // the oldest node is a summary node
1523 as.setSummary( generateUniqueHeapRegionNodeID() );
1531 private Set<FieldDescriptor> getFieldSetTobeAnalyzed(TypeDescriptor typeDesc){
1533 Set<FieldDescriptor> fieldSet=new HashSet<FieldDescriptor>();
1534 if(!typeDesc.isImmutable()){
1535 ClassDescriptor classDesc = typeDesc.getClassDesc();
1536 for (Iterator it = classDesc.getFields(); it.hasNext();) {
1537 FieldDescriptor field = (FieldDescriptor) it.next();
1538 TypeDescriptor fieldType = field.getType();
1539 if (shouldAnalysisTrack( fieldType )) {
1540 fieldSet.add(field);
1548 private HeapRegionNode createMultiDeimensionalArrayHRN(ReachGraph rg, AllocSite alloc, HeapRegionNode srcHRN, FieldDescriptor fd, Hashtable<HeapRegionNode, HeapRegionNode> map, Hashtable<TypeDescriptor, HeapRegionNode> mapToExistingNode, ReachSet alpha ){
1550 int dimCount=fd.getType().getArrayCount();
1551 HeapRegionNode prevNode=null;
1552 HeapRegionNode arrayEntryNode=null;
1553 for(int i=dimCount;i>0;i--){
1554 TypeDescriptor typeDesc=fd.getType().dereference();//hack to get instance of type desc
1555 typeDesc.setArrayCount(i);
1556 TempDescriptor tempDesc=new TempDescriptor(typeDesc.getSymbol(),typeDesc);
1557 HeapRegionNode hrnSummary ;
1558 if(!mapToExistingNode.containsKey(typeDesc)){
1563 as = createParameterAllocSite(rg, tempDesc);
1565 // make a new reference to allocated node
1567 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1568 false, // single object?
1570 false, // out-of-context?
1571 as.getType(), // type
1572 as, // allocation site
1573 alpha, // inherent reach
1574 alpha, // current reach
1575 ExistPredSet.factory(rg.predTrue), // predicates
1576 tempDesc.toString() // description
1578 rg.id2hrn.put(as.getSummary(),hrnSummary);
1580 mapToExistingNode.put(typeDesc, hrnSummary);
1582 hrnSummary=mapToExistingNode.get(typeDesc);
1586 // make a new reference between new summary node and source
1587 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1590 fd.getSymbol(), // field name
1592 ExistPredSet.factory(rg.predTrue) // predicates
1595 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1596 prevNode=hrnSummary;
1597 arrayEntryNode=hrnSummary;
1599 // make a new reference between summary nodes of array
1600 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1603 arrayElementFieldName, // field name
1605 ExistPredSet.factory(rg.predTrue) // predicates
1608 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1609 prevNode=hrnSummary;
1614 // create a new obj node if obj has at least one non-primitive field
1615 TypeDescriptor type=fd.getType();
1616 if(getFieldSetTobeAnalyzed(type).size()>0){
1617 TypeDescriptor typeDesc=type.dereference();
1618 typeDesc.setArrayCount(0);
1619 if(!mapToExistingNode.containsKey(typeDesc)){
1620 TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc);
1621 AllocSite as = createParameterAllocSite(rg, tempDesc);
1622 // make a new reference to allocated node
1623 HeapRegionNode hrnSummary =
1624 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1625 false, // single object?
1627 false, // out-of-context?
1629 as, // allocation site
1630 alpha, // inherent reach
1631 alpha, // current reach
1632 ExistPredSet.factory(rg.predTrue), // predicates
1633 tempDesc.toString() // description
1635 rg.id2hrn.put(as.getSummary(),hrnSummary);
1636 mapToExistingNode.put(typeDesc, hrnSummary);
1637 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1640 arrayElementFieldName, // field name
1642 ExistPredSet.factory(rg.predTrue) // predicates
1644 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1645 prevNode=hrnSummary;
1647 HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc);
1648 if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null){
1649 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1652 arrayElementFieldName, // field name
1654 ExistPredSet.factory(rg.predTrue) // predicates
1656 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1658 prevNode=hrnSummary;
1662 map.put(arrayEntryNode, prevNode);
1663 return arrayEntryNode;
1666 private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
1667 ReachGraph rg = new ReachGraph();
1668 TaskDescriptor taskDesc = fm.getTask();
1670 for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
1671 Descriptor paramDesc = taskDesc.getParameter(idx);
1672 TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
1674 // setup data structure
1675 Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet =
1676 new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
1677 Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode =
1678 new Hashtable<TypeDescriptor, HeapRegionNode>();
1679 Hashtable<HeapRegionNode, HeapRegionNode> mapToFirstDimensionArrayNode =
1680 new Hashtable<HeapRegionNode, HeapRegionNode>();
1681 Set<String> doneSet = new HashSet<String>();
1683 TempDescriptor tempDesc = fm.getParameter(idx);
1685 AllocSite as = createParameterAllocSite(rg, tempDesc);
1686 VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
1687 Integer idNewest = as.getIthOldest(0);
1688 HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
1690 // make a new reference to allocated node
1691 RefEdge edgeNew = new RefEdge(lnX, // source
1693 taskDesc.getParamType(idx), // type
1695 hrnNewest.getAlpha(), // beta
1696 ExistPredSet.factory(rg.predTrue) // predicates
1698 rg.addRefEdge(lnX, hrnNewest, edgeNew);
1700 // set-up a work set for class field
1701 ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
1702 for (Iterator it = classDesc.getFields(); it.hasNext();) {
1703 FieldDescriptor fd = (FieldDescriptor) it.next();
1704 TypeDescriptor fieldType = fd.getType();
1705 if (shouldAnalysisTrack( fieldType )) {
1706 HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
1707 newMap.put(hrnNewest, fd);
1708 workSet.add(newMap);
1712 int uniqueIdentifier = 0;
1713 while (!workSet.isEmpty()) {
1714 HashMap<HeapRegionNode, FieldDescriptor> map = workSet
1716 workSet.remove(map);
1718 Set<HeapRegionNode> key = map.keySet();
1719 HeapRegionNode srcHRN = key.iterator().next();
1720 FieldDescriptor fd = map.get(srcHRN);
1721 TypeDescriptor type = fd.getType();
1722 String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
1724 if (!doneSet.contains(doneSetIdentifier)) {
1725 doneSet.add(doneSetIdentifier);
1726 if (!mapTypeToExistingSummaryNode.containsKey(type)) {
1727 // create new summary Node
1728 TempDescriptor td = new TempDescriptor("temp"
1729 + uniqueIdentifier, type);
1731 AllocSite allocSite;
1732 if(type.equals(paramTypeDesc)){
1733 //corresponding allocsite has already been created for a parameter variable.
1736 allocSite = createParameterAllocSite(rg, td);
1738 String strDesc = allocSite.toStringForDOT()
1740 TypeDescriptor allocType=allocSite.getType();
1742 HeapRegionNode hrnSummary;
1743 if(allocType.isArray() && allocType.getArrayCount()>0){
1744 hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha());
1747 rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
1748 false, // single object?
1750 false, // out-of-context?
1751 allocSite.getType(), // type
1752 allocSite, // allocation site
1753 hrnNewest.getAlpha(), // inherent reach
1754 hrnNewest.getAlpha(), // current reach
1755 ExistPredSet.factory(rg.predTrue), // predicates
1756 strDesc // description
1758 rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
1760 // make a new reference to summary node
1761 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1764 fd.getSymbol(), // field name
1765 hrnNewest.getAlpha(), // beta
1766 ExistPredSet.factory(rg.predTrue) // predicates
1769 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1773 mapTypeToExistingSummaryNode.put(type, hrnSummary);
1775 // set-up a work set for fields of the class
1776 Set<FieldDescriptor> fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type);
1777 for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator
1779 FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator
1781 HeapRegionNode newDstHRN;
1782 if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)){
1783 //related heap region node is already exsited.
1784 newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary);
1786 newDstHRN=hrnSummary;
1788 doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor;
1789 if(!doneSet.contains(doneSetIdentifier)){
1790 // add new work item
1791 HashMap<HeapRegionNode, FieldDescriptor> newMap =
1792 new HashMap<HeapRegionNode, FieldDescriptor>();
1793 newMap.put(newDstHRN, fieldDescriptor);
1794 workSet.add(newMap);
1799 // if there exists corresponding summary node
1800 HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
1802 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1804 fd.getType(), // type
1805 fd.getSymbol(), // field name
1806 srcHRN.getAlpha(), // beta
1807 ExistPredSet.factory(rg.predTrue) // predicates
1809 rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
1815 // debugSnapshot(rg, fm, true);
1819 // return all allocation sites in the method (there is one allocation
1820 // site per FlatNew node in a method)
1821 private HashSet<AllocSite> getAllocationSiteSet(Descriptor d) {
1822 if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
1823 buildAllocationSiteSet(d);
1826 return mapDescriptorToAllocSiteSet.get(d);
1830 private void buildAllocationSiteSet(Descriptor d) {
1831 HashSet<AllocSite> s = new HashSet<AllocSite>();
1834 if( d instanceof MethodDescriptor ) {
1835 fm = state.getMethodFlat( (MethodDescriptor) d);
1837 assert d instanceof TaskDescriptor;
1838 fm = state.getMethodFlat( (TaskDescriptor) d);
1840 pm.analyzeMethod(fm);
1842 // visit every node in this FlatMethod's IR graph
1843 // and make a set of the allocation sites from the
1844 // FlatNew node's visited
1845 HashSet<FlatNode> visited = new HashSet<FlatNode>();
1846 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
1849 while( !toVisit.isEmpty() ) {
1850 FlatNode n = toVisit.iterator().next();
1852 if( n instanceof FlatNew ) {
1853 s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
1859 for( int i = 0; i < pm.numNext(n); ++i ) {
1860 FlatNode child = pm.getNext(n, i);
1861 if( !visited.contains(child) ) {
1867 mapDescriptorToAllocSiteSet.put(d, s);
1870 private HashSet<AllocSite> getFlaggedAllocationSites(Descriptor dIn) {
1872 HashSet<AllocSite> out = new HashSet<AllocSite>();
1873 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1874 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1878 while (!toVisit.isEmpty()) {
1879 Descriptor d = toVisit.iterator().next();
1883 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
1884 Iterator asItr = asSet.iterator();
1885 while (asItr.hasNext()) {
1886 AllocSite as = (AllocSite) asItr.next();
1887 if (as.getDisjointAnalysisId() != null) {
1892 // enqueue callees of this method to be searched for
1893 // allocation sites also
1894 Set callees = callGraph.getCalleeSet(d);
1895 if (callees != null) {
1896 Iterator methItr = callees.iterator();
1897 while (methItr.hasNext()) {
1898 MethodDescriptor md = (MethodDescriptor) methItr.next();
1900 if (!visited.contains(md)) {
1911 private HashSet<AllocSite>
1912 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
1914 HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
1915 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1916 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1920 // traverse this task and all methods reachable from this task
1921 while( !toVisit.isEmpty() ) {
1922 Descriptor d = toVisit.iterator().next();
1926 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
1927 Iterator asItr = asSet.iterator();
1928 while( asItr.hasNext() ) {
1929 AllocSite as = (AllocSite) asItr.next();
1930 TypeDescriptor typed = as.getType();
1931 if( typed != null ) {
1932 ClassDescriptor cd = typed.getClassDesc();
1933 if( cd != null && cd.hasFlags() ) {
1939 // enqueue callees of this method to be searched for
1940 // allocation sites also
1941 Set callees = callGraph.getCalleeSet(d);
1942 if( callees != null ) {
1943 Iterator methItr = callees.iterator();
1944 while( methItr.hasNext() ) {
1945 MethodDescriptor md = (MethodDescriptor) methItr.next();
1947 if( !visited.contains(md) ) {
1960 // get successive captures of the analysis state, use compiler
1962 boolean takeDebugSnapshots = false;
1963 String descSymbolDebug = null;
1964 boolean stopAfterCapture = false;
1965 int snapVisitCounter = 0;
1966 int snapNodeCounter = 0;
1967 int visitStartCapture = 0;
1968 int numVisitsToCapture = 0;
1971 void debugSnapshot( ReachGraph rg, FlatNode fn, boolean in ) {
1972 if( snapVisitCounter > visitStartCapture + numVisitsToCapture ) {
1980 if( snapVisitCounter >= visitStartCapture ) {
1981 System.out.println( " @@@ snapping visit="+snapVisitCounter+
1982 ", node="+snapNodeCounter+
1986 graphName = String.format( "snap%02d_%04din",
1990 graphName = String.format( "snap%02d_%04dout",
1995 graphName = graphName + fn;
1997 rg.writeGraph( graphName,
1998 true, // write labels (variables)
1999 true, // selectively hide intermediate temp vars
2000 true, // prune unreachable heap regions
2001 false, // hide subset reachability states
2002 true );// hide edge taints