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 alias
97 // between task parameters and flagged allocation sites reachable
99 public void writeAllAliases(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 aliases
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 aliases with
132 // other task parameters and every allocation site
133 // reachable from this task
134 boolean foundSomeAlias = 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 aliases 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 foundSomeAlias = true;
159 if (!tabularOutput) {
160 bw.write("Potential alias between parameters " + i
161 + " and " + j + ".\n");
162 bw.write(prettyPrintNodeSet(common) + "\n");
169 // for the ith parameter, check for aliases against
170 // the set of allocation sites reachable from this
172 Iterator allocItr = allocSites.iterator();
173 while (allocItr.hasNext()) {
174 AllocSite as = (AllocSite) allocItr.next();
175 common = hasPotentialSharing(td, i, as);
176 if (!common.isEmpty()) {
177 foundSomeAlias = true;
178 if (!tabularOutput) {
179 bw.write("Potential alias between parameter " + i
180 + " and " + as.getFlatNew() + ".\n");
181 bw.write(prettyPrintNodeSet(common) + "\n");
189 // for each allocation site check for aliases with
190 // other allocation sites in the context of execution
192 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
193 Iterator allocItr1 = allocSites.iterator();
194 while (allocItr1.hasNext()) {
195 AllocSite as1 = (AllocSite) allocItr1.next();
197 Iterator allocItr2 = allocSites.iterator();
198 while (allocItr2.hasNext()) {
199 AllocSite as2 = (AllocSite) allocItr2.next();
201 if (!outerChecked.contains(as2)) {
202 common = hasPotentialSharing(td, as1, as2);
204 if (!common.isEmpty()) {
205 foundSomeAlias = true;
206 if (!tabularOutput) {
207 bw.write("Potential alias between "
208 + as1.getFlatNew() + " and "
209 + as2.getFlatNew() + ".\n");
210 bw.write(prettyPrintNodeSet(common) + "\n");
218 outerChecked.add(as1);
221 if (!foundSomeAlias) {
222 if (!tabularOutput) {
223 bw.write("No aliases between flagged objects in Task " + td
230 if (!tabularOutput) {
231 bw.write("\n" + computeAliasContextHistogram());
233 bw.write(" & " + numAlias + " & " + justTime + " & " + numLines
234 + " & " + numMethodsAnalyzed() + " \\\\\n");
241 // this version of writeAllAliases is for Java programs that have no tasks
242 public void writeAllAliasesJava(String outputFile,
245 boolean tabularOutput,
248 throws java.io.IOException {
249 checkAnalysisComplete();
253 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
255 bw.write("Conducting disjoint reachability analysis with allocation depth = "
256 + allocationDepth + "\n");
257 bw.write(timeReport + "\n\n");
259 boolean foundSomeAlias = false;
261 Descriptor d = typeUtil.getMain();
262 HashSet<AllocSite> allocSites = getFlaggedAllocationSites(d);
264 // for each allocation site check for aliases with
265 // other allocation sites in the context of execution
267 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
268 Iterator allocItr1 = allocSites.iterator();
269 while (allocItr1.hasNext()) {
270 AllocSite as1 = (AllocSite) allocItr1.next();
272 Iterator allocItr2 = allocSites.iterator();
273 while (allocItr2.hasNext()) {
274 AllocSite as2 = (AllocSite) allocItr2.next();
276 if (!outerChecked.contains(as2)) {
277 Set<HeapRegionNode> common = hasPotentialSharing(d,
280 if (!common.isEmpty()) {
281 foundSomeAlias = true;
282 bw.write("Potential alias between "
283 + as1.getDisjointAnalysisId() + " and "
284 + as2.getDisjointAnalysisId() + ".\n");
285 bw.write(prettyPrintNodeSet(common) + "\n");
290 outerChecked.add(as1);
293 if (!foundSomeAlias) {
294 bw.write("No aliases between flagged objects found.\n");
297 // bw.write("\n" + computeAliasContextHistogram());
301 ///////////////////////////////////////////
303 // end public interface
305 ///////////////////////////////////////////
307 protected void checkAnalysisComplete() {
308 if( !analysisComplete ) {
309 throw new Error("Warning: public interface method called while analysis is running.");
314 // run in faster mode, only when bugs wrung out!
315 public static boolean releaseMode;
317 // data from the compiler
319 public CallGraph callGraph;
320 public Liveness liveness;
321 public ArrayReferencees arrayReferencees;
322 public TypeUtil typeUtil;
323 public int allocationDepth;
325 // data structure for public interface
326 private Hashtable<Descriptor, HashSet<AllocSite> > mapDescriptorToAllocSiteSet;
329 // for public interface methods to warn that they
330 // are grabbing results during analysis
331 private boolean analysisComplete;
334 // used to identify HeapRegionNode objects
335 // A unique ID equates an object in one
336 // ownership graph with an object in another
337 // graph that logically represents the same
339 // start at 10 and increment to reserve some
340 // IDs for special purposes
341 static protected int uniqueIDcount = 10;
344 // An out-of-scope method created by the
345 // analysis that has no parameters, and
346 // appears to allocate the command line
347 // arguments, then invoke the source code's
348 // main method. The purpose of this is to
349 // provide the analysis with an explicit
350 // top-level context with no parameters
351 protected MethodDescriptor mdAnalysisEntry;
352 protected FlatMethod fmAnalysisEntry;
354 // main method defined by source program
355 protected MethodDescriptor mdSourceEntry;
357 // the set of task and/or method descriptors
358 // reachable in call graph
359 protected Set<Descriptor>
360 descriptorsToAnalyze;
362 // current descriptors to visit in fixed-point
363 // interprocedural analysis, prioritized by
364 // dependency in the call graph
365 protected PriorityQueue<DescriptorQWrapper>
368 // a duplication of the above structure, but
369 // for efficient testing of inclusion
370 protected HashSet<Descriptor>
371 descriptorsToVisitSet;
373 // storage for priorities (doesn't make sense)
374 // to add it to the Descriptor class, just in
376 protected Hashtable<Descriptor, Integer>
377 mapDescriptorToPriority;
380 // maps a descriptor to its current partial result
381 // from the intraprocedural fixed-point analysis--
382 // then the interprocedural analysis settles, this
383 // mapping will have the final results for each
385 protected Hashtable<Descriptor, ReachGraph>
386 mapDescriptorToCompleteReachGraph;
388 // maps a descriptor to its known dependents: namely
389 // methods or tasks that call the descriptor's method
390 // AND are part of this analysis (reachable from main)
391 protected Hashtable< Descriptor, Set<Descriptor> >
392 mapDescriptorToSetDependents;
394 // maps each flat new to one analysis abstraction
395 // allocate site object, these exist outside reach graphs
396 protected Hashtable<FlatNew, AllocSite>
397 mapFlatNewToAllocSite;
399 // maps intergraph heap region IDs to intergraph
400 // allocation sites that created them, a redundant
401 // structure for efficiency in some operations
402 protected Hashtable<Integer, AllocSite>
405 // maps a method to its initial heap model (IHM) that
406 // is the set of reachability graphs from every caller
407 // site, all merged together. The reason that we keep
408 // them separate is that any one call site's contribution
409 // to the IHM may changed along the path to the fixed point
410 protected Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >
411 mapDescriptorToIHMcontributions;
413 // TODO -- CHANGE EDGE/TYPE/FIELD storage!
414 public static final String arrayElementFieldName = "___element_";
415 static protected Hashtable<TypeDescriptor, FieldDescriptor>
418 // for controlling DOT file output
419 protected boolean writeFinalDOTs;
420 protected boolean writeAllIncrementalDOTs;
422 // supporting DOT output--when we want to write every
423 // partial method result, keep a tally for generating
425 protected Hashtable<Descriptor, Integer>
426 mapDescriptorToNumUpdates;
428 //map task descriptor to initial task parameter
429 protected Hashtable<Descriptor, ReachGraph>
430 mapDescriptorToReachGraph;
433 // allocate various structures that are not local
434 // to a single class method--should be done once
435 protected void allocateStructures() {
436 descriptorsToAnalyze = new HashSet<Descriptor>();
438 mapDescriptorToCompleteReachGraph =
439 new Hashtable<Descriptor, ReachGraph>();
441 mapDescriptorToNumUpdates =
442 new Hashtable<Descriptor, Integer>();
444 mapDescriptorToSetDependents =
445 new Hashtable< Descriptor, Set<Descriptor> >();
447 mapFlatNewToAllocSite =
448 new Hashtable<FlatNew, AllocSite>();
450 mapDescriptorToIHMcontributions =
451 new Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >();
453 mapHrnIdToAllocSite =
454 new Hashtable<Integer, AllocSite>();
456 mapTypeToArrayField =
457 new Hashtable <TypeDescriptor, FieldDescriptor>();
459 descriptorsToVisitQ =
460 new PriorityQueue<DescriptorQWrapper>();
462 descriptorsToVisitSet =
463 new HashSet<Descriptor>();
465 mapDescriptorToPriority =
466 new Hashtable<Descriptor, Integer>();
468 mapDescriptorToAllocSiteSet =
469 new Hashtable<Descriptor, HashSet<AllocSite> >();
471 mapDescriptorToReachGraph =
472 new Hashtable<Descriptor, ReachGraph>();
477 // this analysis generates a disjoint reachability
478 // graph for every reachable method in the program
479 public DisjointAnalysis( State s,
484 ) throws java.io.IOException {
485 init( s, tu, cg, l, ar );
488 protected void init( State state,
492 ArrayReferencees arrayReferencees
493 ) throws java.io.IOException {
495 analysisComplete = false;
498 this.typeUtil = typeUtil;
499 this.callGraph = callGraph;
500 this.liveness = liveness;
501 this.arrayReferencees = arrayReferencees;
502 this.allocationDepth = state.DISJOINTALLOCDEPTH;
503 this.releaseMode = state.DISJOINTRELEASEMODE;
505 this.writeFinalDOTs = state.DISJOINTWRITEDOTS && !state.DISJOINTWRITEALL;
506 this.writeAllIncrementalDOTs = state.DISJOINTWRITEDOTS && state.DISJOINTWRITEALL;
508 this.takeDebugSnapshots = state.DISJOINTSNAPSYMBOL != null;
509 this.descSymbolDebug = state.DISJOINTSNAPSYMBOL;
510 this.visitStartCapture = state.DISJOINTSNAPVISITTOSTART;
511 this.numVisitsToCapture = state.DISJOINTSNAPNUMVISITS;
512 this.stopAfterCapture = state.DISJOINTSNAPSTOPAFTER;
513 this.snapVisitCounter = 1; // count visits from 1 (user will write 1, means 1st visit)
514 this.snapNodeCounter = 0; // count nodes from 0
516 // set some static configuration for ReachGraphs
517 ReachGraph.allocationDepth = allocationDepth;
518 ReachGraph.typeUtil = typeUtil;
520 ReachGraph.debugCallSiteVisitsUntilExit = state.DISJOINTDEBUGCALLCOUNT;
522 allocateStructures();
524 double timeStartAnalysis = (double) System.nanoTime();
526 // start interprocedural fixed-point computation
528 analysisComplete=true;
530 double timeEndAnalysis = (double) System.nanoTime();
531 double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
532 String treport = String.format( "The reachability analysis took %.3f sec.", dt );
533 String justtime = String.format( "%.2f", dt );
534 System.out.println( treport );
536 if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
540 if( state.DISJOINTWRITEIHMS ) {
544 if( state.DISJOINTALIASFILE != null ) {
546 writeAllAliases(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines);
549 writeAllAliasesJava( aliasFile,
552 state.DISJOINTALIASTAB,
560 // fixed-point computation over the call graph--when a
561 // method's callees are updated, it must be reanalyzed
562 protected void analyzeMethods() throws java.io.IOException {
565 // This analysis does not support Bamboo at the moment,
566 // but if it does in the future we would initialize the
567 // set of descriptors to analyze as the program-reachable
568 // tasks and the methods callable by them. For Java,
569 // just methods reachable from the main method.
570 System.out.println( "Bamboo..." );
571 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
573 while (taskItr.hasNext()) {
574 TaskDescriptor td = (TaskDescriptor) taskItr.next();
575 if (!descriptorsToAnalyze.contains(td)) {
576 descriptorsToAnalyze.add(td);
577 descriptorsToAnalyze.addAll(callGraph.getAllMethods(td));
582 // add all methods transitively reachable from the
583 // source's main to set for analysis
584 mdSourceEntry = typeUtil.getMain();
585 descriptorsToAnalyze.add( mdSourceEntry );
586 descriptorsToAnalyze.addAll(
587 callGraph.getAllMethods( mdSourceEntry )
590 // fabricate an empty calling context that will call
591 // the source's main, but call graph doesn't know
592 // about it, so explicitly add it
593 makeAnalysisEntryMethod( mdSourceEntry );
594 descriptorsToAnalyze.add( mdAnalysisEntry );
597 // topologically sort according to the call graph so
598 // leaf calls are ordered first, smarter analysis order
599 // CHANGED: order leaf calls last!!
600 LinkedList<Descriptor> sortedDescriptors =
601 topologicalSort( descriptorsToAnalyze );
603 // add sorted descriptors to priority queue, and duplicate
604 // the queue as a set for efficiently testing whether some
605 // method is marked for analysis
607 Iterator<Descriptor> dItr = sortedDescriptors.iterator();
608 while( dItr.hasNext() ) {
609 Descriptor d = dItr.next();
610 mapDescriptorToPriority.put( d, new Integer( p ) );
611 descriptorsToVisitQ.add( new DescriptorQWrapper( p, d ) );
612 descriptorsToVisitSet.add( d );
616 // analyze methods from the priority queue until it is empty
617 while( !descriptorsToVisitQ.isEmpty() ) {
618 Descriptor d = descriptorsToVisitQ.poll().getDescriptor();
619 assert descriptorsToVisitSet.contains( d );
620 descriptorsToVisitSet.remove( d );
622 // because the task or method descriptor just extracted
623 // was in the "to visit" set it either hasn't been analyzed
624 // yet, or some method that it depends on has been
625 // updated. Recompute a complete reachability graph for
626 // this task/method and compare it to any previous result.
627 // If there is a change detected, add any methods/tasks
628 // that depend on this one to the "to visit" set.
630 System.out.println( "Analyzing " + d );
632 ReachGraph rg = analyzeMethod( d );
633 ReachGraph rgPrev = getPartial( d );
635 if( !rg.equals( rgPrev ) ) {
638 // results for d changed, so enqueue dependents
639 // of d for further analysis
640 Iterator<Descriptor> depsItr = getDependents( d ).iterator();
641 while( depsItr.hasNext() ) {
642 Descriptor dNext = depsItr.next();
649 protected ReachGraph analyzeMethod( Descriptor d )
650 throws java.io.IOException {
652 // get the flat code for this descriptor
654 if( d == mdAnalysisEntry ) {
655 fm = fmAnalysisEntry;
657 fm = state.getMethodFlat( d );
660 // intraprocedural work set
661 Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
662 flatNodesToVisit.add( fm );
664 // mapping of current partial results
665 Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraph =
666 new Hashtable<FlatNode, ReachGraph>();
668 // the set of return nodes partial results that will be combined as
669 // the final, conservative approximation of the entire method
670 HashSet<FlatReturnNode> setReturns = new HashSet<FlatReturnNode>();
672 while( !flatNodesToVisit.isEmpty() ) {
673 FlatNode fn = (FlatNode) flatNodesToVisit.iterator().next();
674 flatNodesToVisit.remove( fn );
676 // effect transfer function defined by this node,
677 // then compare it to the old graph at this node
678 // to see if anything was updated.
680 ReachGraph rg = new ReachGraph();
681 TaskDescriptor taskDesc;
682 if(fn instanceof FlatMethod && (taskDesc=((FlatMethod)fn).getTask())!=null){
683 if(mapDescriptorToReachGraph.containsKey(taskDesc)){
684 // retrieve existing reach graph if it is not first time
685 rg=mapDescriptorToReachGraph.get(taskDesc);
687 // create initial reach graph for a task
688 rg=createInitialTaskReachGraph((FlatMethod)fn);
690 mapDescriptorToReachGraph.put(taskDesc, rg);
694 // start by merging all node's parents' graphs
695 for( int i = 0; i < fn.numPrev(); ++i ) {
696 FlatNode pn = fn.getPrev( i );
697 if( mapFlatNodeToReachGraph.containsKey( pn ) ) {
698 ReachGraph rgParent = mapFlatNodeToReachGraph.get( pn );
699 rg.merge( rgParent );
704 if( takeDebugSnapshots &&
705 d.getSymbol().equals( descSymbolDebug )
707 debugSnapshot( rg, fn, true );
711 // modify rg with appropriate transfer function
712 rg = analyzeFlatNode( d, fm, fn, setReturns, rg );
715 if( takeDebugSnapshots &&
716 d.getSymbol().equals( descSymbolDebug )
718 debugSnapshot( rg, fn, false );
723 // if the results of the new graph are different from
724 // the current graph at this node, replace the graph
725 // with the update and enqueue the children
726 ReachGraph rgPrev = mapFlatNodeToReachGraph.get( fn );
727 if( !rg.equals( rgPrev ) ) {
728 mapFlatNodeToReachGraph.put( fn, rg );
730 for( int i = 0; i < fn.numNext(); i++ ) {
731 FlatNode nn = fn.getNext( i );
732 flatNodesToVisit.add( nn );
737 // end by merging all return nodes into a complete
738 // ownership graph that represents all possible heap
739 // states after the flat method returns
740 ReachGraph completeGraph = new ReachGraph();
742 assert !setReturns.isEmpty();
743 Iterator retItr = setReturns.iterator();
744 while( retItr.hasNext() ) {
745 FlatReturnNode frn = (FlatReturnNode) retItr.next();
747 assert mapFlatNodeToReachGraph.containsKey( frn );
748 ReachGraph rgRet = mapFlatNodeToReachGraph.get( frn );
750 completeGraph.merge( rgRet );
754 if( takeDebugSnapshots &&
755 d.getSymbol().equals( descSymbolDebug )
757 // increment that we've visited the debug snap
758 // method, and reset the node counter
759 System.out.println( " @@@ debug snap at visit "+snapVisitCounter );
763 if( snapVisitCounter == visitStartCapture + numVisitsToCapture &&
766 System.out.println( "!!! Stopping analysis after debug snap captures. !!!" );
772 return completeGraph;
777 analyzeFlatNode( Descriptor d,
778 FlatMethod fmContaining,
780 HashSet<FlatReturnNode> setRetNodes,
782 ) throws java.io.IOException {
785 // any variables that are no longer live should be
786 // nullified in the graph to reduce edges
787 //rg.nullifyDeadVars( liveness.getLiveInTemps( fmContaining, fn ) );
794 // use node type to decide what transfer function
795 // to apply to the reachability graph
796 switch( fn.kind() ) {
798 case FKind.FlatMethod: {
799 // construct this method's initial heap model (IHM)
800 // since we're working on the FlatMethod, we know
801 // the incoming ReachGraph 'rg' is empty
803 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
804 getIHMcontributions( d );
806 Set entrySet = heapsFromCallers.entrySet();
807 Iterator itr = entrySet.iterator();
808 while( itr.hasNext() ) {
809 Map.Entry me = (Map.Entry) itr.next();
810 FlatCall fc = (FlatCall) me.getKey();
811 ReachGraph rgContrib = (ReachGraph) me.getValue();
813 assert fc.getMethod().equals( d );
815 // some call sites are in same method context though,
816 // and all of them should be merged together first,
817 // then heaps from different contexts should be merged
818 // THIS ASSUMES DIFFERENT CONTEXTS NEED SPECIAL CONSIDERATION!
819 // such as, do allocation sites need to be aged?
821 rg.merge_diffMethodContext( rgContrib );
825 case FKind.FlatOpNode:
826 FlatOpNode fon = (FlatOpNode) fn;
827 if( fon.getOp().getOp() == Operation.ASSIGN ) {
830 rg.assignTempXEqualToTempY( lhs, rhs );
834 case FKind.FlatCastNode:
835 FlatCastNode fcn = (FlatCastNode) fn;
839 TypeDescriptor td = fcn.getType();
842 rg.assignTempXEqualToCastedTempY( lhs, rhs, td );
845 case FKind.FlatFieldNode:
846 FlatFieldNode ffn = (FlatFieldNode) fn;
849 fld = ffn.getField();
850 if( shouldAnalysisTrack( fld.getType() ) ) {
851 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fld );
855 case FKind.FlatSetFieldNode:
856 FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
858 fld = fsfn.getField();
860 if( shouldAnalysisTrack( fld.getType() ) ) {
861 rg.assignTempXFieldFEqualToTempY( lhs, fld, rhs );
865 case FKind.FlatElementNode:
866 FlatElementNode fen = (FlatElementNode) fn;
869 if( shouldAnalysisTrack( lhs.getType() ) ) {
871 assert rhs.getType() != null;
872 assert rhs.getType().isArray();
874 TypeDescriptor tdElement = rhs.getType().dereference();
875 FieldDescriptor fdElement = getArrayField( tdElement );
877 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fdElement );
881 case FKind.FlatSetElementNode:
882 FlatSetElementNode fsen = (FlatSetElementNode) fn;
884 if( arrayReferencees.doesNotCreateNewReaching( fsen ) ) {
885 // skip this node if it cannot create new reachability paths
891 if( shouldAnalysisTrack( rhs.getType() ) ) {
893 assert lhs.getType() != null;
894 assert lhs.getType().isArray();
896 TypeDescriptor tdElement = lhs.getType().dereference();
897 FieldDescriptor fdElement = getArrayField( tdElement );
899 rg.assignTempXFieldFEqualToTempY( lhs, fdElement, rhs );
904 FlatNew fnn = (FlatNew) fn;
906 if( shouldAnalysisTrack( lhs.getType() ) ) {
907 AllocSite as = getAllocSiteFromFlatNewPRIVATE( fnn );
908 rg.assignTempEqualToNewAlloc( lhs, as );
912 case FKind.FlatCall: {
913 //TODO: temporal fix for task descriptor case
914 //MethodDescriptor mdCaller = fmContaining.getMethod();
916 if(fmContaining.getMethod()!=null){
917 mdCaller = fmContaining.getMethod();
919 mdCaller = fmContaining.getTask();
921 FlatCall fc = (FlatCall) fn;
922 MethodDescriptor mdCallee = fc.getMethod();
923 FlatMethod fmCallee = state.getMethodFlat( mdCallee );
925 boolean writeDebugDOTs =
926 mdCaller.getSymbol().equals( state.DISJOINTDEBUGCALLER ) &&
927 mdCallee.getSymbol().equals( state.DISJOINTDEBUGCALLEE );
930 // calculate the heap this call site can reach--note this is
931 // not used for the current call site transform, we are
932 // grabbing this heap model for future analysis of the callees,
933 // so if different results emerge we will return to this site
934 ReachGraph heapForThisCall_old =
935 getIHMcontribution( mdCallee, fc );
937 // the computation of the callee-reachable heap
938 // is useful for making the callee starting point
939 // and for applying the call site transfer function
940 Set<Integer> callerNodeIDsCopiedToCallee =
941 new HashSet<Integer>();
943 ReachGraph heapForThisCall_cur =
944 rg.makeCalleeView( fc,
946 callerNodeIDsCopiedToCallee,
950 if( !heapForThisCall_cur.equals( heapForThisCall_old ) ) {
951 // if heap at call site changed, update the contribution,
952 // and reschedule the callee for analysis
953 addIHMcontribution( mdCallee, fc, heapForThisCall_cur );
960 // the transformation for a call site should update the
961 // current heap abstraction with any effects from the callee,
962 // or if the method is virtual, the effects from any possible
963 // callees, so find the set of callees...
964 Set<MethodDescriptor> setPossibleCallees =
965 new HashSet<MethodDescriptor>();
967 if( mdCallee.isStatic() ) {
968 setPossibleCallees.add( mdCallee );
970 TypeDescriptor typeDesc = fc.getThis().getType();
971 setPossibleCallees.addAll( callGraph.getMethods( mdCallee,
976 ReachGraph rgMergeOfEffects = new ReachGraph();
978 Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
979 while( mdItr.hasNext() ) {
980 MethodDescriptor mdPossible = mdItr.next();
981 FlatMethod fmPossible = state.getMethodFlat( mdPossible );
983 addDependent( mdPossible, // callee
986 // don't alter the working graph (rg) until we compute a
987 // result for every possible callee, merge them all together,
988 // then set rg to that
989 ReachGraph rgCopy = new ReachGraph();
992 ReachGraph rgEffect = getPartial( mdPossible );
994 if( rgEffect == null ) {
995 // if this method has never been analyzed just schedule it
996 // for analysis and skip over this call site for now
997 enqueue( mdPossible );
999 rgCopy.resolveMethodCall( fc,
1002 callerNodeIDsCopiedToCallee,
1007 rgMergeOfEffects.merge( rgCopy );
1011 // now that we've taken care of building heap models for
1012 // callee analysis, finish this transformation
1013 rg = rgMergeOfEffects;
1017 case FKind.FlatReturnNode:
1018 FlatReturnNode frn = (FlatReturnNode) fn;
1019 rhs = frn.getReturnTemp();
1020 if( rhs != null && shouldAnalysisTrack( rhs.getType() ) ) {
1021 rg.assignReturnEqualToTemp( rhs );
1023 setRetNodes.add( frn );
1029 // dead variables were removed before the above transfer function
1030 // was applied, so eliminate heap regions and edges that are no
1031 // longer part of the abstractly-live heap graph, and sweep up
1032 // and reachability effects that are altered by the reduction
1033 //rg.abstractGarbageCollect();
1037 // at this point rg should be the correct update
1038 // by an above transfer function, or untouched if
1039 // the flat node type doesn't affect the heap
1044 // this method should generate integers strictly greater than zero!
1045 // special "shadow" regions are made from a heap region by negating
1047 static public Integer generateUniqueHeapRegionNodeID() {
1049 return new Integer( uniqueIDcount );
1054 static public FieldDescriptor getArrayField( TypeDescriptor tdElement ) {
1055 FieldDescriptor fdElement = mapTypeToArrayField.get( tdElement );
1056 if( fdElement == null ) {
1057 fdElement = new FieldDescriptor( new Modifiers( Modifiers.PUBLIC ),
1059 arrayElementFieldName,
1062 mapTypeToArrayField.put( tdElement, fdElement );
1069 private void writeFinalGraphs() {
1070 Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
1071 Iterator itr = entrySet.iterator();
1072 while( itr.hasNext() ) {
1073 Map.Entry me = (Map.Entry) itr.next();
1074 Descriptor d = (Descriptor) me.getKey();
1075 ReachGraph rg = (ReachGraph) me.getValue();
1077 rg.writeGraph( "COMPLETE"+d,
1078 true, // write labels (variables)
1079 true, // selectively hide intermediate temp vars
1080 true, // prune unreachable heap regions
1081 false, // hide subset reachability states
1082 true ); // hide edge taints
1086 private void writeFinalIHMs() {
1087 Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
1088 while( d2IHMsItr.hasNext() ) {
1089 Map.Entry me1 = (Map.Entry) d2IHMsItr.next();
1090 Descriptor d = (Descriptor) me1.getKey();
1091 Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>) me1.getValue();
1093 Iterator fc2rgItr = IHMs.entrySet().iterator();
1094 while( fc2rgItr.hasNext() ) {
1095 Map.Entry me2 = (Map.Entry) fc2rgItr.next();
1096 FlatCall fc = (FlatCall) me2.getKey();
1097 ReachGraph rg = (ReachGraph) me2.getValue();
1099 rg.writeGraph( "IHMPARTFOR"+d+"FROM"+fc,
1100 true, // write labels (variables)
1101 true, // selectively hide intermediate temp vars
1102 true, // prune unreachable heap regions
1103 false, // hide subset reachability states
1104 true ); // hide edge taints
1110 protected ReachGraph getPartial( Descriptor d ) {
1111 return mapDescriptorToCompleteReachGraph.get( d );
1114 protected void setPartial( Descriptor d, ReachGraph rg ) {
1115 mapDescriptorToCompleteReachGraph.put( d, rg );
1117 // when the flag for writing out every partial
1118 // result is set, we should spit out the graph,
1119 // but in order to give it a unique name we need
1120 // to track how many partial results for this
1121 // descriptor we've already written out
1122 if( writeAllIncrementalDOTs ) {
1123 if( !mapDescriptorToNumUpdates.containsKey( d ) ) {
1124 mapDescriptorToNumUpdates.put( d, new Integer( 0 ) );
1126 Integer n = mapDescriptorToNumUpdates.get( d );
1128 rg.writeGraph( d+"COMPLETE"+String.format( "%05d", n ),
1129 true, // write labels (variables)
1130 true, // selectively hide intermediate temp vars
1131 true, // prune unreachable heap regions
1132 false, // hide subset reachability states
1133 true ); // hide edge taints
1135 mapDescriptorToNumUpdates.put( d, n + 1 );
1141 // return just the allocation site associated with one FlatNew node
1142 protected AllocSite getAllocSiteFromFlatNewPRIVATE( FlatNew fnew ) {
1144 if( !mapFlatNewToAllocSite.containsKey( fnew ) ) {
1146 (AllocSite) Canonical.makeCanonical( new AllocSite( allocationDepth,
1148 fnew.getDisjointId()
1152 // the newest nodes are single objects
1153 for( int i = 0; i < allocationDepth; ++i ) {
1154 Integer id = generateUniqueHeapRegionNodeID();
1155 as.setIthOldest( i, id );
1156 mapHrnIdToAllocSite.put( id, as );
1159 // the oldest node is a summary node
1160 as.setSummary( generateUniqueHeapRegionNodeID() );
1162 mapFlatNewToAllocSite.put( fnew, as );
1165 return mapFlatNewToAllocSite.get( fnew );
1169 public static boolean shouldAnalysisTrack( TypeDescriptor type ) {
1170 // don't track primitive types, but an array
1171 // of primitives is heap memory
1172 if( type.isImmutable() ) {
1173 return type.isArray();
1176 // everything else is an object
1182 // return all allocation sites in the method (there is one allocation
1183 // site per FlatNew node in a method)
1184 protected HashSet<AllocSite> getAllocSiteSet(Descriptor d) {
1185 if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
1186 buildAllocSiteSet(d);
1189 return mapDescriptorToAllocSiteSet.get(d);
1195 protected void buildAllocSiteSet(Descriptor d) {
1196 HashSet<AllocSite> s = new HashSet<AllocSite>();
1198 FlatMethod fm = state.getMethodFlat( d );
1200 // visit every node in this FlatMethod's IR graph
1201 // and make a set of the allocation sites from the
1202 // FlatNew node's visited
1203 HashSet<FlatNode> visited = new HashSet<FlatNode>();
1204 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
1207 while( !toVisit.isEmpty() ) {
1208 FlatNode n = toVisit.iterator().next();
1210 if( n instanceof FlatNew ) {
1211 s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
1214 toVisit.remove( n );
1217 for( int i = 0; i < n.numNext(); ++i ) {
1218 FlatNode child = n.getNext( i );
1219 if( !visited.contains( child ) ) {
1220 toVisit.add( child );
1225 mapDescriptorToAllocSiteSet.put( d, s );
1229 protected HashSet<AllocSite> getFlaggedAllocSites(Descriptor dIn) {
1231 HashSet<AllocSite> out = new HashSet<AllocSite>();
1232 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1233 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1237 while( !toVisit.isEmpty() ) {
1238 Descriptor d = toVisit.iterator().next();
1242 HashSet<AllocSite> asSet = getAllocSiteSet(d);
1243 Iterator asItr = asSet.iterator();
1244 while( asItr.hasNext() ) {
1245 AllocSite as = (AllocSite) asItr.next();
1246 if( as.getDisjointAnalysisId() != null ) {
1251 // enqueue callees of this method to be searched for
1252 // allocation sites also
1253 Set callees = callGraph.getCalleeSet(d);
1254 if( callees != null ) {
1255 Iterator methItr = callees.iterator();
1256 while( methItr.hasNext() ) {
1257 MethodDescriptor md = (MethodDescriptor) methItr.next();
1259 if( !visited.contains(md) ) {
1271 protected HashSet<AllocSite>
1272 getFlaggedAllocSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
1274 HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
1275 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1276 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1280 // traverse this task and all methods reachable from this task
1281 while( !toVisit.isEmpty() ) {
1282 Descriptor d = toVisit.iterator().next();
1286 HashSet<AllocSite> asSet = getAllocSiteSet(d);
1287 Iterator asItr = asSet.iterator();
1288 while( asItr.hasNext() ) {
1289 AllocSite as = (AllocSite) asItr.next();
1290 TypeDescriptor typed = as.getType();
1291 if( typed != null ) {
1292 ClassDescriptor cd = typed.getClassDesc();
1293 if( cd != null && cd.hasFlags() ) {
1299 // enqueue callees of this method to be searched for
1300 // allocation sites also
1301 Set callees = callGraph.getCalleeSet(d);
1302 if( callees != null ) {
1303 Iterator methItr = callees.iterator();
1304 while( methItr.hasNext() ) {
1305 MethodDescriptor md = (MethodDescriptor) methItr.next();
1307 if( !visited.contains(md) ) {
1321 protected String computeAliasContextHistogram() {
1323 Hashtable<Integer, Integer> mapNumContexts2NumDesc =
1324 new Hashtable<Integer, Integer>();
1326 Iterator itr = mapDescriptorToAllDescriptors.entrySet().iterator();
1327 while( itr.hasNext() ) {
1328 Map.Entry me = (Map.Entry) itr.next();
1329 HashSet<Descriptor> s = (HashSet<Descriptor>) me.getValue();
1331 Integer i = mapNumContexts2NumDesc.get( s.size() );
1333 i = new Integer( 0 );
1335 mapNumContexts2NumDesc.put( s.size(), i + 1 );
1341 itr = mapNumContexts2NumDesc.entrySet().iterator();
1342 while( itr.hasNext() ) {
1343 Map.Entry me = (Map.Entry) itr.next();
1344 Integer c0 = (Integer) me.getKey();
1345 Integer d0 = (Integer) me.getValue();
1347 s += String.format( "%4d methods had %4d unique alias contexts.\n", d0, c0 );
1350 s += String.format( "\n%4d total methods analayzed.\n", total );
1355 protected int numMethodsAnalyzed() {
1356 return descriptorsToAnalyze.size();
1363 // Take in source entry which is the program's compiled entry and
1364 // create a new analysis entry, a method that takes no parameters
1365 // and appears to allocate the command line arguments and call the
1366 // source entry with them. The purpose of this analysis entry is
1367 // to provide a top-level method context with no parameters left.
1368 protected void makeAnalysisEntryMethod( MethodDescriptor mdSourceEntry ) {
1370 Modifiers mods = new Modifiers();
1371 mods.addModifier( Modifiers.PUBLIC );
1372 mods.addModifier( Modifiers.STATIC );
1374 TypeDescriptor returnType =
1375 new TypeDescriptor( TypeDescriptor.VOID );
1377 this.mdAnalysisEntry =
1378 new MethodDescriptor( mods,
1380 "analysisEntryMethod"
1383 TempDescriptor cmdLineArgs =
1384 new TempDescriptor( "args",
1385 mdSourceEntry.getParamType( 0 )
1389 new FlatNew( mdSourceEntry.getParamType( 0 ),
1394 TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
1395 sourceEntryArgs[0] = cmdLineArgs;
1398 new FlatCall( mdSourceEntry,
1404 FlatReturnNode frn = new FlatReturnNode( null );
1406 FlatExit fe = new FlatExit();
1408 this.fmAnalysisEntry =
1409 new FlatMethod( mdAnalysisEntry,
1413 this.fmAnalysisEntry.addNext( fn );
1420 protected LinkedList<Descriptor> topologicalSort( Set<Descriptor> toSort ) {
1422 Set <Descriptor> discovered = new HashSet <Descriptor>();
1423 LinkedList<Descriptor> sorted = new LinkedList<Descriptor>();
1425 Iterator<Descriptor> itr = toSort.iterator();
1426 while( itr.hasNext() ) {
1427 Descriptor d = itr.next();
1429 if( !discovered.contains( d ) ) {
1430 dfsVisit( d, toSort, sorted, discovered );
1437 // While we're doing DFS on call graph, remember
1438 // dependencies for efficient queuing of methods
1439 // during interprocedural analysis:
1441 // a dependent of a method decriptor d for this analysis is:
1442 // 1) a method or task that invokes d
1443 // 2) in the descriptorsToAnalyze set
1444 protected void dfsVisit( Descriptor d,
1445 Set <Descriptor> toSort,
1446 LinkedList<Descriptor> sorted,
1447 Set <Descriptor> discovered ) {
1448 discovered.add( d );
1450 // only methods have callers, tasks never do
1451 if( d instanceof MethodDescriptor ) {
1453 MethodDescriptor md = (MethodDescriptor) d;
1455 // the call graph is not aware that we have a fabricated
1456 // analysis entry that calls the program source's entry
1457 if( md == mdSourceEntry ) {
1458 if( !discovered.contains( mdAnalysisEntry ) ) {
1459 addDependent( mdSourceEntry, // callee
1460 mdAnalysisEntry // caller
1462 dfsVisit( mdAnalysisEntry, toSort, sorted, discovered );
1466 // otherwise call graph guides DFS
1467 Iterator itr = callGraph.getCallerSet( md ).iterator();
1468 while( itr.hasNext() ) {
1469 Descriptor dCaller = (Descriptor) itr.next();
1471 // only consider callers in the original set to analyze
1472 if( !toSort.contains( dCaller ) ) {
1476 if( !discovered.contains( dCaller ) ) {
1477 addDependent( md, // callee
1481 dfsVisit( dCaller, toSort, sorted, discovered );
1486 // for leaf-nodes last now!
1487 sorted.addLast( d );
1491 protected void enqueue( Descriptor d ) {
1492 if( !descriptorsToVisitSet.contains( d ) ) {
1493 Integer priority = mapDescriptorToPriority.get( d );
1494 descriptorsToVisitQ.add( new DescriptorQWrapper( priority,
1497 descriptorsToVisitSet.add( d );
1502 // a dependent of a method decriptor d for this analysis is:
1503 // 1) a method or task that invokes d
1504 // 2) in the descriptorsToAnalyze set
1505 protected void addDependent( Descriptor callee, Descriptor caller ) {
1506 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1507 if( deps == null ) {
1508 deps = new HashSet<Descriptor>();
1511 mapDescriptorToSetDependents.put( callee, deps );
1514 protected Set<Descriptor> getDependents( Descriptor callee ) {
1515 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1516 if( deps == null ) {
1517 deps = new HashSet<Descriptor>();
1518 mapDescriptorToSetDependents.put( callee, deps );
1524 public Hashtable<FlatCall, ReachGraph> getIHMcontributions( Descriptor d ) {
1526 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1527 mapDescriptorToIHMcontributions.get( d );
1529 if( heapsFromCallers == null ) {
1530 heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
1531 mapDescriptorToIHMcontributions.put( d, heapsFromCallers );
1534 return heapsFromCallers;
1537 public ReachGraph getIHMcontribution( Descriptor d,
1540 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1541 getIHMcontributions( d );
1543 if( !heapsFromCallers.containsKey( fc ) ) {
1544 heapsFromCallers.put( fc, new ReachGraph() );
1547 return heapsFromCallers.get( fc );
1550 public void addIHMcontribution( Descriptor d,
1554 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1555 getIHMcontributions( d );
1557 heapsFromCallers.put( fc, rg );
1560 private AllocSite createParameterAllocSite(ReachGraph rg, TempDescriptor tempDesc) {
1562 // create temp descriptor for each parameter variable
1563 FlatNew flatNew = new FlatNew(tempDesc.getType(), tempDesc, false);
1564 // create allocation site
1565 AllocSite as = (AllocSite) Canonical.makeCanonical(new AllocSite( allocationDepth, flatNew, flatNew.getDisjointId()));
1566 for (int i = 0; i < allocationDepth; ++i) {
1567 Integer id = generateUniqueHeapRegionNodeID();
1568 as.setIthOldest(i, id);
1569 mapHrnIdToAllocSite.put(id, as);
1571 // the oldest node is a summary node
1572 as.setSummary( generateUniqueHeapRegionNodeID() );
1580 private Set<FieldDescriptor> getFieldSetTobeAnalyzed(TypeDescriptor typeDesc){
1582 Set<FieldDescriptor> fieldSet=new HashSet<FieldDescriptor>();
1583 if(!typeDesc.isImmutable()){
1584 ClassDescriptor classDesc = typeDesc.getClassDesc();
1585 for (Iterator it = classDesc.getFields(); it.hasNext();) {
1586 FieldDescriptor field = (FieldDescriptor) it.next();
1587 TypeDescriptor fieldType = field.getType();
1588 if (shouldAnalysisTrack( fieldType )) {
1589 fieldSet.add(field);
1597 private HeapRegionNode createMultiDeimensionalArrayHRN(ReachGraph rg, AllocSite alloc, HeapRegionNode srcHRN, FieldDescriptor fd, Hashtable<HeapRegionNode, HeapRegionNode> map, Hashtable<TypeDescriptor, HeapRegionNode> mapToExistingNode, ReachSet alpha ){
1599 int dimCount=fd.getType().getArrayCount();
1600 HeapRegionNode prevNode=null;
1601 HeapRegionNode arrayEntryNode=null;
1602 for(int i=dimCount;i>0;i--){
1603 TypeDescriptor typeDesc=fd.getType().dereference();//hack to get instance of type desc
1604 typeDesc.setArrayCount(i);
1605 TempDescriptor tempDesc=new TempDescriptor(typeDesc.getSymbol(),typeDesc);
1606 HeapRegionNode hrnSummary ;
1607 if(!mapToExistingNode.containsKey(typeDesc)){
1612 as = createParameterAllocSite(rg, tempDesc);
1614 // make a new reference to allocated node
1616 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1617 false, // single object?
1620 false, // out-of-context?
1621 as.getType(), // type
1622 as, // allocation site
1623 null, // inherent reach
1624 alpha, // current reach
1625 ExistPredSet.factory(rg.predTrue), // predicates
1626 tempDesc.toString() // description
1628 rg.id2hrn.put(as.getSummary(),hrnSummary);
1630 mapToExistingNode.put(typeDesc, hrnSummary);
1632 hrnSummary=mapToExistingNode.get(typeDesc);
1636 // make a new reference between new summary node and source
1637 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1640 fd.getSymbol(), // field name
1642 ExistPredSet.factory(rg.predTrue) // predicates
1645 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1646 prevNode=hrnSummary;
1647 arrayEntryNode=hrnSummary;
1649 // make a new reference between summary nodes of array
1650 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1653 arrayElementFieldName, // field name
1655 ExistPredSet.factory(rg.predTrue) // predicates
1658 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1659 prevNode=hrnSummary;
1664 // create a new obj node if obj has at least one non-primitive field
1665 TypeDescriptor type=fd.getType();
1666 if(getFieldSetTobeAnalyzed(type).size()>0){
1667 TypeDescriptor typeDesc=type.dereference();
1668 typeDesc.setArrayCount(0);
1669 if(!mapToExistingNode.containsKey(typeDesc)){
1670 TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc);
1671 AllocSite as = createParameterAllocSite(rg, tempDesc);
1672 // make a new reference to allocated node
1673 HeapRegionNode hrnSummary =
1674 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1675 false, // single object?
1678 false, // out-of-context?
1680 as, // allocation site
1681 null, // inherent reach
1682 alpha, // current reach
1683 ExistPredSet.factory(rg.predTrue), // predicates
1684 tempDesc.toString() // description
1686 rg.id2hrn.put(as.getSummary(),hrnSummary);
1687 mapToExistingNode.put(typeDesc, hrnSummary);
1688 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1691 arrayElementFieldName, // field name
1693 ExistPredSet.factory(rg.predTrue) // predicates
1695 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1696 prevNode=hrnSummary;
1698 HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc);
1699 if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null){
1700 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1703 arrayElementFieldName, // field name
1705 ExistPredSet.factory(rg.predTrue) // predicates
1707 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1709 prevNode=hrnSummary;
1713 map.put(arrayEntryNode, prevNode);
1714 return arrayEntryNode;
1717 private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
1718 ReachGraph rg = new ReachGraph();
1719 TaskDescriptor taskDesc = fm.getTask();
1721 for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
1722 Descriptor paramDesc = taskDesc.getParameter(idx);
1723 TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
1725 // setup data structure
1726 Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet =
1727 new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
1728 Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode =
1729 new Hashtable<TypeDescriptor, HeapRegionNode>();
1730 Hashtable<HeapRegionNode, HeapRegionNode> mapToFirstDimensionArrayNode =
1731 new Hashtable<HeapRegionNode, HeapRegionNode>();
1732 Set<String> doneSet = new HashSet<String>();
1734 TempDescriptor tempDesc = fm.getParameter(idx);
1736 AllocSite as = createParameterAllocSite(rg, tempDesc);
1737 VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
1738 Integer idNewest = as.getIthOldest(0);
1739 HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
1740 // make a new reference to allocated node
1741 RefEdge edgeNew = new RefEdge(lnX, // source
1743 taskDesc.getParamType(idx), // type
1745 hrnNewest.getAlpha(), // beta
1746 ExistPredSet.factory(rg.predTrue) // predicates
1748 rg.addRefEdge(lnX, hrnNewest, edgeNew);
1750 // set-up a work set for class field
1751 ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
1752 for (Iterator it = classDesc.getFields(); it.hasNext();) {
1753 FieldDescriptor fd = (FieldDescriptor) it.next();
1754 TypeDescriptor fieldType = fd.getType();
1755 if (shouldAnalysisTrack( fieldType )) {
1756 HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
1757 newMap.put(hrnNewest, fd);
1758 workSet.add(newMap);
1762 int uniqueIdentifier = 0;
1763 while (!workSet.isEmpty()) {
1764 HashMap<HeapRegionNode, FieldDescriptor> map = workSet
1766 workSet.remove(map);
1768 Set<HeapRegionNode> key = map.keySet();
1769 HeapRegionNode srcHRN = key.iterator().next();
1770 FieldDescriptor fd = map.get(srcHRN);
1771 TypeDescriptor type = fd.getType();
1772 String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
1774 if (!doneSet.contains(doneSetIdentifier)) {
1775 doneSet.add(doneSetIdentifier);
1776 if (!mapTypeToExistingSummaryNode.containsKey(type)) {
1777 // create new summary Node
1778 TempDescriptor td = new TempDescriptor("temp"
1779 + uniqueIdentifier, type);
1781 AllocSite allocSite;
1782 if(type.equals(paramTypeDesc)){
1783 //corresponding allocsite has already been created for a parameter variable.
1786 allocSite = createParameterAllocSite(rg, td);
1788 String strDesc = allocSite.toStringForDOT()
1790 TypeDescriptor allocType=allocSite.getType();
1792 HeapRegionNode hrnSummary;
1793 if(allocType.isArray() && allocType.getArrayCount()>0){
1794 hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha());
1797 rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
1798 false, // single object?
1801 false, // out-of-context?
1802 allocSite.getType(), // type
1803 allocSite, // allocation site
1804 null, // inherent reach
1805 hrnNewest.getAlpha(), // current reach
1806 ExistPredSet.factory(rg.predTrue), // predicates
1807 strDesc // description
1809 rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
1811 // make a new reference to summary node
1812 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1815 fd.getSymbol(), // field name
1816 hrnNewest.getAlpha(), // beta
1817 ExistPredSet.factory(rg.predTrue) // predicates
1820 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1824 mapTypeToExistingSummaryNode.put(type, hrnSummary);
1826 // set-up a work set for fields of the class
1827 Set<FieldDescriptor> fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type);
1828 for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator
1830 FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator
1832 HeapRegionNode newDstHRN;
1833 if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)){
1834 //related heap region node is already exsited.
1835 newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary);
1837 newDstHRN=hrnSummary;
1839 doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor;
1840 if(!doneSet.contains(doneSetIdentifier)){
1841 // add new work item
1842 HashMap<HeapRegionNode, FieldDescriptor> newMap =
1843 new HashMap<HeapRegionNode, FieldDescriptor>();
1844 newMap.put(newDstHRN, fieldDescriptor);
1845 workSet.add(newMap);
1850 // if there exists corresponding summary node
1851 HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
1853 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1855 fd.getType(), // type
1856 fd.getSymbol(), // field name
1857 srcHRN.getAlpha(), // beta
1858 ExistPredSet.factory(rg.predTrue) // predicates
1860 rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
1866 // debugSnapshot(rg, fm, true);
1870 // return all allocation sites in the method (there is one allocation
1871 // site per FlatNew node in a method)
1872 private HashSet<AllocSite> getAllocationSiteSet(Descriptor d) {
1873 if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
1874 buildAllocationSiteSet(d);
1877 return mapDescriptorToAllocSiteSet.get(d);
1881 private void buildAllocationSiteSet(Descriptor d) {
1882 HashSet<AllocSite> s = new HashSet<AllocSite>();
1885 if( d instanceof MethodDescriptor ) {
1886 fm = state.getMethodFlat( (MethodDescriptor) d);
1888 assert d instanceof TaskDescriptor;
1889 fm = state.getMethodFlat( (TaskDescriptor) d);
1892 // visit every node in this FlatMethod's IR graph
1893 // and make a set of the allocation sites from the
1894 // FlatNew node's visited
1895 HashSet<FlatNode> visited = new HashSet<FlatNode>();
1896 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
1899 while( !toVisit.isEmpty() ) {
1900 FlatNode n = toVisit.iterator().next();
1902 if( n instanceof FlatNew ) {
1903 s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
1909 for( int i = 0; i < n.numNext(); ++i ) {
1910 FlatNode child = n.getNext(i);
1911 if( !visited.contains(child) ) {
1917 mapDescriptorToAllocSiteSet.put(d, s);
1920 private HashSet<AllocSite> getFlaggedAllocationSites(Descriptor dIn) {
1922 HashSet<AllocSite> out = new HashSet<AllocSite>();
1923 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1924 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1928 while (!toVisit.isEmpty()) {
1929 Descriptor d = toVisit.iterator().next();
1933 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
1934 Iterator asItr = asSet.iterator();
1935 while (asItr.hasNext()) {
1936 AllocSite as = (AllocSite) asItr.next();
1937 if (as.getDisjointAnalysisId() != null) {
1942 // enqueue callees of this method to be searched for
1943 // allocation sites also
1944 Set callees = callGraph.getCalleeSet(d);
1945 if (callees != null) {
1946 Iterator methItr = callees.iterator();
1947 while (methItr.hasNext()) {
1948 MethodDescriptor md = (MethodDescriptor) methItr.next();
1950 if (!visited.contains(md)) {
1961 private HashSet<AllocSite>
1962 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
1964 HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
1965 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1966 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1970 // traverse this task and all methods reachable from this task
1971 while( !toVisit.isEmpty() ) {
1972 Descriptor d = toVisit.iterator().next();
1976 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
1977 Iterator asItr = asSet.iterator();
1978 while( asItr.hasNext() ) {
1979 AllocSite as = (AllocSite) asItr.next();
1980 TypeDescriptor typed = as.getType();
1981 if( typed != null ) {
1982 ClassDescriptor cd = typed.getClassDesc();
1983 if( cd != null && cd.hasFlags() ) {
1989 // enqueue callees of this method to be searched for
1990 // allocation sites also
1991 Set callees = callGraph.getCalleeSet(d);
1992 if( callees != null ) {
1993 Iterator methItr = callees.iterator();
1994 while( methItr.hasNext() ) {
1995 MethodDescriptor md = (MethodDescriptor) methItr.next();
1997 if( !visited.contains(md) ) {
2010 // get successive captures of the analysis state, use compiler
2012 boolean takeDebugSnapshots = false;
2013 String descSymbolDebug = null;
2014 boolean stopAfterCapture = false;
2015 int snapVisitCounter = 0;
2016 int snapNodeCounter = 0;
2017 int visitStartCapture = 0;
2018 int numVisitsToCapture = 0;
2021 void debugSnapshot( ReachGraph rg, FlatNode fn, boolean in ) {
2022 if( snapVisitCounter > visitStartCapture + numVisitsToCapture ) {
2030 if( snapVisitCounter >= visitStartCapture ) {
2031 System.out.println( " @@@ snapping visit="+snapVisitCounter+
2032 ", node="+snapNodeCounter+
2036 graphName = String.format( "snap%02d_%04din",
2040 graphName = String.format( "snap%02d_%04dout",
2045 graphName = graphName + fn;
2047 rg.writeGraph( graphName,
2048 true, // write labels (variables)
2049 true, // selectively hide intermediate temp vars
2050 true, // prune unreachable heap regions
2051 false, // hide subset reachability states
2052 true );// hide edge taints