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 // data from the compiler
316 public CallGraph callGraph;
317 public Liveness liveness;
318 public ArrayReferencees arrayReferencees;
319 public TypeUtil typeUtil;
320 public int allocationDepth;
322 // data structure for public interface
323 private Hashtable<Descriptor, HashSet<AllocSite> > mapDescriptorToAllocSiteSet;
326 // for public interface methods to warn that they
327 // are grabbing results during analysis
328 private boolean analysisComplete;
331 // used to identify HeapRegionNode objects
332 // A unique ID equates an object in one
333 // ownership graph with an object in another
334 // graph that logically represents the same
336 // start at 10 and increment to reserve some
337 // IDs for special purposes
338 static protected int uniqueIDcount = 10;
341 // An out-of-scope method created by the
342 // analysis that has no parameters, and
343 // appears to allocate the command line
344 // arguments, then invoke the source code's
345 // main method. The purpose of this is to
346 // provide the analysis with an explicit
347 // top-level context with no parameters
348 protected MethodDescriptor mdAnalysisEntry;
349 protected FlatMethod fmAnalysisEntry;
351 // main method defined by source program
352 protected MethodDescriptor mdSourceEntry;
354 // the set of task and/or method descriptors
355 // reachable in call graph
356 protected Set<Descriptor>
357 descriptorsToAnalyze;
359 // current descriptors to visit in fixed-point
360 // interprocedural analysis, prioritized by
361 // dependency in the call graph
362 protected PriorityQueue<DescriptorQWrapper>
365 // a duplication of the above structure, but
366 // for efficient testing of inclusion
367 protected HashSet<Descriptor>
368 descriptorsToVisitSet;
370 // storage for priorities (doesn't make sense)
371 // to add it to the Descriptor class, just in
373 protected Hashtable<Descriptor, Integer>
374 mapDescriptorToPriority;
377 // maps a descriptor to its current partial result
378 // from the intraprocedural fixed-point analysis--
379 // then the interprocedural analysis settles, this
380 // mapping will have the final results for each
382 protected Hashtable<Descriptor, ReachGraph>
383 mapDescriptorToCompleteReachGraph;
385 // maps a descriptor to its known dependents: namely
386 // methods or tasks that call the descriptor's method
387 // AND are part of this analysis (reachable from main)
388 protected Hashtable< Descriptor, Set<Descriptor> >
389 mapDescriptorToSetDependents;
391 // maps each flat new to one analysis abstraction
392 // allocate site object, these exist outside reach graphs
393 protected Hashtable<FlatNew, AllocSite>
394 mapFlatNewToAllocSite;
396 // maps intergraph heap region IDs to intergraph
397 // allocation sites that created them, a redundant
398 // structure for efficiency in some operations
399 protected Hashtable<Integer, AllocSite>
402 // maps a method to its initial heap model (IHM) that
403 // is the set of reachability graphs from every caller
404 // site, all merged together. The reason that we keep
405 // them separate is that any one call site's contribution
406 // to the IHM may changed along the path to the fixed point
407 protected Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >
408 mapDescriptorToIHMcontributions;
410 // TODO -- CHANGE EDGE/TYPE/FIELD storage!
411 public static final String arrayElementFieldName = "___element_";
412 static protected Hashtable<TypeDescriptor, FieldDescriptor>
415 // for controlling DOT file output
416 protected boolean writeFinalDOTs;
417 protected boolean writeAllIncrementalDOTs;
419 // supporting DOT output--when we want to write every
420 // partial method result, keep a tally for generating
422 protected Hashtable<Descriptor, Integer>
423 mapDescriptorToNumUpdates;
425 //map task descriptor to initial task parameter
426 protected Hashtable<Descriptor, ReachGraph>
427 mapDescriptorToReachGraph;
430 // allocate various structures that are not local
431 // to a single class method--should be done once
432 protected void allocateStructures() {
433 descriptorsToAnalyze = new HashSet<Descriptor>();
435 mapDescriptorToCompleteReachGraph =
436 new Hashtable<Descriptor, ReachGraph>();
438 mapDescriptorToNumUpdates =
439 new Hashtable<Descriptor, Integer>();
441 mapDescriptorToSetDependents =
442 new Hashtable< Descriptor, Set<Descriptor> >();
444 mapFlatNewToAllocSite =
445 new Hashtable<FlatNew, AllocSite>();
447 mapDescriptorToIHMcontributions =
448 new Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >();
450 mapHrnIdToAllocSite =
451 new Hashtable<Integer, AllocSite>();
453 mapTypeToArrayField =
454 new Hashtable <TypeDescriptor, FieldDescriptor>();
456 descriptorsToVisitQ =
457 new PriorityQueue<DescriptorQWrapper>();
459 descriptorsToVisitSet =
460 new HashSet<Descriptor>();
462 mapDescriptorToPriority =
463 new Hashtable<Descriptor, Integer>();
465 mapDescriptorToAllocSiteSet =
466 new Hashtable<Descriptor, HashSet<AllocSite> >();
468 mapDescriptorToReachGraph =
469 new Hashtable<Descriptor, ReachGraph>();
474 // this analysis generates a disjoint reachability
475 // graph for every reachable method in the program
476 public DisjointAnalysis( State s,
481 ) throws java.io.IOException {
482 init( s, tu, cg, l, ar );
485 protected void init( State state,
489 ArrayReferencees arrayReferencees
490 ) throws java.io.IOException {
492 analysisComplete = false;
495 this.typeUtil = typeUtil;
496 this.callGraph = callGraph;
497 this.liveness = liveness;
498 this.arrayReferencees = arrayReferencees;
499 this.allocationDepth = state.DISJOINTALLOCDEPTH;
501 this.writeFinalDOTs = state.DISJOINTWRITEDOTS && !state.DISJOINTWRITEALL;
502 this.writeAllIncrementalDOTs = state.DISJOINTWRITEDOTS && state.DISJOINTWRITEALL;
504 this.takeDebugSnapshots = state.DISJOINTSNAPSYMBOL != null;
505 this.descSymbolDebug = state.DISJOINTSNAPSYMBOL;
506 this.visitStartCapture = state.DISJOINTSNAPVISITTOSTART;
507 this.numVisitsToCapture = state.DISJOINTSNAPNUMVISITS;
508 this.stopAfterCapture = state.DISJOINTSNAPSTOPAFTER;
509 this.snapVisitCounter = 1; // count visits from 1 (user will write 1, means 1st visit)
510 this.snapNodeCounter = 0; // count nodes from 0
512 // set some static configuration for ReachGraphs
513 ReachGraph.allocationDepth = allocationDepth;
514 ReachGraph.typeUtil = typeUtil;
516 ReachGraph.debugCallSiteVisitsUntilExit = state.DISJOINTDEBUGCALLCOUNT;
518 allocateStructures();
520 double timeStartAnalysis = (double) System.nanoTime();
522 // start interprocedural fixed-point computation
524 analysisComplete=true;
526 double timeEndAnalysis = (double) System.nanoTime();
527 double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
528 String treport = String.format( "The reachability analysis took %.3f sec.", dt );
529 String justtime = String.format( "%.2f", dt );
530 System.out.println( treport );
532 if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
536 if( state.DISJOINTWRITEIHMS ) {
540 if( state.DISJOINTALIASFILE != null ) {
542 writeAllAliases(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines);
545 writeAllAliasesJava( aliasFile,
548 state.DISJOINTALIASTAB,
556 // fixed-point computation over the call graph--when a
557 // method's callees are updated, it must be reanalyzed
558 protected void analyzeMethods() throws java.io.IOException {
561 // This analysis does not support Bamboo at the moment,
562 // but if it does in the future we would initialize the
563 // set of descriptors to analyze as the program-reachable
564 // tasks and the methods callable by them. For Java,
565 // just methods reachable from the main method.
566 System.out.println( "Bamboo..." );
567 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
569 while (taskItr.hasNext()) {
570 TaskDescriptor td = (TaskDescriptor) taskItr.next();
571 if (!descriptorsToAnalyze.contains(td)) {
572 descriptorsToAnalyze.add(td);
573 descriptorsToAnalyze.addAll(callGraph.getAllMethods(td));
578 // add all methods transitively reachable from the
579 // source's main to set for analysis
580 mdSourceEntry = typeUtil.getMain();
581 descriptorsToAnalyze.add( mdSourceEntry );
582 descriptorsToAnalyze.addAll(
583 callGraph.getAllMethods( mdSourceEntry )
586 // fabricate an empty calling context that will call
587 // the source's main, but call graph doesn't know
588 // about it, so explicitly add it
589 makeAnalysisEntryMethod( mdSourceEntry );
590 descriptorsToAnalyze.add( mdAnalysisEntry );
593 // topologically sort according to the call graph so
594 // leaf calls are ordered first, smarter analysis order
595 // CHANGED: order leaf calls last!!
596 LinkedList<Descriptor> sortedDescriptors =
597 topologicalSort( descriptorsToAnalyze );
599 // add sorted descriptors to priority queue, and duplicate
600 // the queue as a set for efficiently testing whether some
601 // method is marked for analysis
603 Iterator<Descriptor> dItr = sortedDescriptors.iterator();
604 while( dItr.hasNext() ) {
605 Descriptor d = dItr.next();
606 mapDescriptorToPriority.put( d, new Integer( p ) );
607 descriptorsToVisitQ.add( new DescriptorQWrapper( p, d ) );
608 descriptorsToVisitSet.add( d );
612 // analyze methods from the priority queue until it is empty
613 while( !descriptorsToVisitQ.isEmpty() ) {
614 Descriptor d = descriptorsToVisitQ.poll().getDescriptor();
615 assert descriptorsToVisitSet.contains( d );
616 descriptorsToVisitSet.remove( d );
618 // because the task or method descriptor just extracted
619 // was in the "to visit" set it either hasn't been analyzed
620 // yet, or some method that it depends on has been
621 // updated. Recompute a complete reachability graph for
622 // this task/method and compare it to any previous result.
623 // If there is a change detected, add any methods/tasks
624 // that depend on this one to the "to visit" set.
626 System.out.println( "Analyzing " + d );
628 ReachGraph rg = analyzeMethod( d );
629 ReachGraph rgPrev = getPartial( d );
631 if( !rg.equals( rgPrev ) ) {
634 // results for d changed, so enqueue dependents
635 // of d for further analysis
636 Iterator<Descriptor> depsItr = getDependents( d ).iterator();
637 while( depsItr.hasNext() ) {
638 Descriptor dNext = depsItr.next();
645 protected ReachGraph analyzeMethod( Descriptor d )
646 throws java.io.IOException {
648 // get the flat code for this descriptor
650 if( d == mdAnalysisEntry ) {
651 fm = fmAnalysisEntry;
653 fm = state.getMethodFlat( d );
656 // intraprocedural work set
657 Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
658 flatNodesToVisit.add( fm );
660 // mapping of current partial results
661 Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraph =
662 new Hashtable<FlatNode, ReachGraph>();
664 // the set of return nodes partial results that will be combined as
665 // the final, conservative approximation of the entire method
666 HashSet<FlatReturnNode> setReturns = new HashSet<FlatReturnNode>();
668 while( !flatNodesToVisit.isEmpty() ) {
669 FlatNode fn = (FlatNode) flatNodesToVisit.iterator().next();
670 flatNodesToVisit.remove( fn );
672 // effect transfer function defined by this node,
673 // then compare it to the old graph at this node
674 // to see if anything was updated.
676 ReachGraph rg = new ReachGraph();
677 TaskDescriptor taskDesc;
678 if(fn instanceof FlatMethod && (taskDesc=((FlatMethod)fn).getTask())!=null){
679 if(mapDescriptorToReachGraph.containsKey(taskDesc)){
680 // retrieve existing reach graph if it is not first time
681 rg=mapDescriptorToReachGraph.get(taskDesc);
683 // create initial reach graph for a task
684 rg=createInitialTaskReachGraph((FlatMethod)fn);
686 mapDescriptorToReachGraph.put(taskDesc, rg);
690 // start by merging all node's parents' graphs
691 for( int i = 0; i < fn.numPrev(); ++i ) {
692 FlatNode pn = fn.getPrev( i );
693 if( mapFlatNodeToReachGraph.containsKey( pn ) ) {
694 ReachGraph rgParent = mapFlatNodeToReachGraph.get( pn );
695 rg.merge( rgParent );
700 if( takeDebugSnapshots &&
701 d.getSymbol().equals( descSymbolDebug )
703 debugSnapshot( rg, fn, true );
707 // modify rg with appropriate transfer function
708 rg = analyzeFlatNode( d, fm, fn, setReturns, rg );
711 if( takeDebugSnapshots &&
712 d.getSymbol().equals( descSymbolDebug )
714 debugSnapshot( rg, fn, false );
719 // if the results of the new graph are different from
720 // the current graph at this node, replace the graph
721 // with the update and enqueue the children
722 ReachGraph rgPrev = mapFlatNodeToReachGraph.get( fn );
723 if( !rg.equals( rgPrev ) ) {
724 mapFlatNodeToReachGraph.put( fn, rg );
726 for( int i = 0; i < fn.numNext(); i++ ) {
727 FlatNode nn = fn.getNext( i );
728 flatNodesToVisit.add( nn );
733 // end by merging all return nodes into a complete
734 // ownership graph that represents all possible heap
735 // states after the flat method returns
736 ReachGraph completeGraph = new ReachGraph();
738 assert !setReturns.isEmpty();
739 Iterator retItr = setReturns.iterator();
740 while( retItr.hasNext() ) {
741 FlatReturnNode frn = (FlatReturnNode) retItr.next();
743 assert mapFlatNodeToReachGraph.containsKey( frn );
744 ReachGraph rgRet = mapFlatNodeToReachGraph.get( frn );
746 completeGraph.merge( rgRet );
750 if( takeDebugSnapshots &&
751 d.getSymbol().equals( descSymbolDebug )
753 // increment that we've visited the debug snap
754 // method, and reset the node counter
755 System.out.println( " @@@ debug snap at visit "+snapVisitCounter );
759 if( snapVisitCounter == visitStartCapture + numVisitsToCapture &&
762 System.out.println( "!!! Stopping analysis after debug snap captures. !!!" );
768 return completeGraph;
773 analyzeFlatNode( Descriptor d,
774 FlatMethod fmContaining,
776 HashSet<FlatReturnNode> setRetNodes,
778 ) throws java.io.IOException {
781 // any variables that are no longer live should be
782 // nullified in the graph to reduce edges
783 //rg.nullifyDeadVars( liveness.getLiveInTemps( fmContaining, fn ) );
790 // use node type to decide what transfer function
791 // to apply to the reachability graph
792 switch( fn.kind() ) {
794 case FKind.FlatMethod: {
795 // construct this method's initial heap model (IHM)
796 // since we're working on the FlatMethod, we know
797 // the incoming ReachGraph 'rg' is empty
799 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
800 getIHMcontributions( d );
802 Set entrySet = heapsFromCallers.entrySet();
803 Iterator itr = entrySet.iterator();
804 while( itr.hasNext() ) {
805 Map.Entry me = (Map.Entry) itr.next();
806 FlatCall fc = (FlatCall) me.getKey();
807 ReachGraph rgContrib = (ReachGraph) me.getValue();
809 assert fc.getMethod().equals( d );
811 // some call sites are in same method context though,
812 // and all of them should be merged together first,
813 // then heaps from different contexts should be merged
814 // THIS ASSUMES DIFFERENT CONTEXTS NEED SPECIAL CONSIDERATION!
815 // such as, do allocation sites need to be aged?
817 rg.merge_diffMethodContext( rgContrib );
821 case FKind.FlatOpNode:
822 FlatOpNode fon = (FlatOpNode) fn;
823 if( fon.getOp().getOp() == Operation.ASSIGN ) {
826 rg.assignTempXEqualToTempY( lhs, rhs );
830 case FKind.FlatCastNode:
831 FlatCastNode fcn = (FlatCastNode) fn;
835 TypeDescriptor td = fcn.getType();
838 rg.assignTempXEqualToCastedTempY( lhs, rhs, td );
841 case FKind.FlatFieldNode:
842 FlatFieldNode ffn = (FlatFieldNode) fn;
845 fld = ffn.getField();
846 if( shouldAnalysisTrack( fld.getType() ) ) {
847 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fld );
851 case FKind.FlatSetFieldNode:
852 FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
854 fld = fsfn.getField();
856 if( shouldAnalysisTrack( fld.getType() ) ) {
857 rg.assignTempXFieldFEqualToTempY( lhs, fld, rhs );
861 case FKind.FlatElementNode:
862 FlatElementNode fen = (FlatElementNode) fn;
865 if( shouldAnalysisTrack( lhs.getType() ) ) {
867 assert rhs.getType() != null;
868 assert rhs.getType().isArray();
870 TypeDescriptor tdElement = rhs.getType().dereference();
871 FieldDescriptor fdElement = getArrayField( tdElement );
873 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fdElement );
877 case FKind.FlatSetElementNode:
878 FlatSetElementNode fsen = (FlatSetElementNode) fn;
880 if( arrayReferencees.doesNotCreateNewReaching( fsen ) ) {
881 // skip this node if it cannot create new reachability paths
887 if( shouldAnalysisTrack( rhs.getType() ) ) {
889 assert lhs.getType() != null;
890 assert lhs.getType().isArray();
892 TypeDescriptor tdElement = lhs.getType().dereference();
893 FieldDescriptor fdElement = getArrayField( tdElement );
895 rg.assignTempXFieldFEqualToTempY( lhs, fdElement, rhs );
900 FlatNew fnn = (FlatNew) fn;
902 if( shouldAnalysisTrack( lhs.getType() ) ) {
903 AllocSite as = getAllocSiteFromFlatNewPRIVATE( fnn );
904 rg.assignTempEqualToNewAlloc( lhs, as );
908 case FKind.FlatCall: {
909 //TODO: temporal fix for task descriptor case
910 //MethodDescriptor mdCaller = fmContaining.getMethod();
912 if(fmContaining.getMethod()!=null){
913 mdCaller = fmContaining.getMethod();
915 mdCaller = fmContaining.getTask();
917 FlatCall fc = (FlatCall) fn;
918 MethodDescriptor mdCallee = fc.getMethod();
919 FlatMethod fmCallee = state.getMethodFlat( mdCallee );
921 boolean writeDebugDOTs =
922 mdCaller.getSymbol().equals( state.DISJOINTDEBUGCALLER ) &&
923 mdCallee.getSymbol().equals( state.DISJOINTDEBUGCALLEE );
926 // calculate the heap this call site can reach--note this is
927 // not used for the current call site transform, we are
928 // grabbing this heap model for future analysis of the callees,
929 // so if different results emerge we will return to this site
930 ReachGraph heapForThisCall_old =
931 getIHMcontribution( mdCallee, fc );
933 // the computation of the callee-reachable heap
934 // is useful for making the callee starting point
935 // and for applying the call site transfer function
936 Set<Integer> callerNodeIDsCopiedToCallee =
937 new HashSet<Integer>();
939 ReachGraph heapForThisCall_cur =
940 rg.makeCalleeView( fc,
942 callerNodeIDsCopiedToCallee,
946 if( !heapForThisCall_cur.equals( heapForThisCall_old ) ) {
947 // if heap at call site changed, update the contribution,
948 // and reschedule the callee for analysis
949 addIHMcontribution( mdCallee, fc, heapForThisCall_cur );
956 // the transformation for a call site should update the
957 // current heap abstraction with any effects from the callee,
958 // or if the method is virtual, the effects from any possible
959 // callees, so find the set of callees...
960 Set<MethodDescriptor> setPossibleCallees =
961 new HashSet<MethodDescriptor>();
963 if( mdCallee.isStatic() ) {
964 setPossibleCallees.add( mdCallee );
966 TypeDescriptor typeDesc = fc.getThis().getType();
967 setPossibleCallees.addAll( callGraph.getMethods( mdCallee,
972 ReachGraph rgMergeOfEffects = new ReachGraph();
974 Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
975 while( mdItr.hasNext() ) {
976 MethodDescriptor mdPossible = mdItr.next();
977 FlatMethod fmPossible = state.getMethodFlat( mdPossible );
979 addDependent( mdPossible, // callee
982 // don't alter the working graph (rg) until we compute a
983 // result for every possible callee, merge them all together,
984 // then set rg to that
985 ReachGraph rgCopy = new ReachGraph();
988 ReachGraph rgEffect = getPartial( mdPossible );
990 if( rgEffect == null ) {
991 // if this method has never been analyzed just schedule it
992 // for analysis and skip over this call site for now
993 enqueue( mdPossible );
995 rgCopy.resolveMethodCall( fc,
998 callerNodeIDsCopiedToCallee,
1003 rgMergeOfEffects.merge( rgCopy );
1007 // now that we've taken care of building heap models for
1008 // callee analysis, finish this transformation
1009 rg = rgMergeOfEffects;
1013 case FKind.FlatReturnNode:
1014 FlatReturnNode frn = (FlatReturnNode) fn;
1015 rhs = frn.getReturnTemp();
1016 if( rhs != null && shouldAnalysisTrack( rhs.getType() ) ) {
1017 rg.assignReturnEqualToTemp( rhs );
1019 setRetNodes.add( frn );
1025 // dead variables were removed before the above transfer function
1026 // was applied, so eliminate heap regions and edges that are no
1027 // longer part of the abstractly-live heap graph, and sweep up
1028 // and reachability effects that are altered by the reduction
1029 //rg.abstractGarbageCollect();
1033 // at this point rg should be the correct update
1034 // by an above transfer function, or untouched if
1035 // the flat node type doesn't affect the heap
1040 // this method should generate integers strictly greater than zero!
1041 // special "shadow" regions are made from a heap region by negating
1043 static public Integer generateUniqueHeapRegionNodeID() {
1045 return new Integer( uniqueIDcount );
1050 static public FieldDescriptor getArrayField( TypeDescriptor tdElement ) {
1051 FieldDescriptor fdElement = mapTypeToArrayField.get( tdElement );
1052 if( fdElement == null ) {
1053 fdElement = new FieldDescriptor( new Modifiers( Modifiers.PUBLIC ),
1055 arrayElementFieldName,
1058 mapTypeToArrayField.put( tdElement, fdElement );
1065 private void writeFinalGraphs() {
1066 Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
1067 Iterator itr = entrySet.iterator();
1068 while( itr.hasNext() ) {
1069 Map.Entry me = (Map.Entry) itr.next();
1070 Descriptor d = (Descriptor) me.getKey();
1071 ReachGraph rg = (ReachGraph) me.getValue();
1073 rg.writeGraph( "COMPLETE"+d,
1074 true, // write labels (variables)
1075 true, // selectively hide intermediate temp vars
1076 true, // prune unreachable heap regions
1077 false, // hide subset reachability states
1078 true ); // hide edge taints
1082 private void writeFinalIHMs() {
1083 Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
1084 while( d2IHMsItr.hasNext() ) {
1085 Map.Entry me1 = (Map.Entry) d2IHMsItr.next();
1086 Descriptor d = (Descriptor) me1.getKey();
1087 Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>) me1.getValue();
1089 Iterator fc2rgItr = IHMs.entrySet().iterator();
1090 while( fc2rgItr.hasNext() ) {
1091 Map.Entry me2 = (Map.Entry) fc2rgItr.next();
1092 FlatCall fc = (FlatCall) me2.getKey();
1093 ReachGraph rg = (ReachGraph) me2.getValue();
1095 rg.writeGraph( "IHMPARTFOR"+d+"FROM"+fc,
1096 true, // write labels (variables)
1097 false, // selectively hide intermediate temp vars
1098 false, // prune unreachable heap regions
1099 false, // hide subset reachability states
1100 true ); // hide edge taints
1106 protected ReachGraph getPartial( Descriptor d ) {
1107 return mapDescriptorToCompleteReachGraph.get( d );
1110 protected void setPartial( Descriptor d, ReachGraph rg ) {
1111 mapDescriptorToCompleteReachGraph.put( d, rg );
1113 // when the flag for writing out every partial
1114 // result is set, we should spit out the graph,
1115 // but in order to give it a unique name we need
1116 // to track how many partial results for this
1117 // descriptor we've already written out
1118 if( writeAllIncrementalDOTs ) {
1119 if( !mapDescriptorToNumUpdates.containsKey( d ) ) {
1120 mapDescriptorToNumUpdates.put( d, new Integer( 0 ) );
1122 Integer n = mapDescriptorToNumUpdates.get( d );
1124 rg.writeGraph( d+"COMPLETE"+String.format( "%05d", n ),
1125 true, // write labels (variables)
1126 true, // selectively hide intermediate temp vars
1127 false, // prune unreachable heap regions
1128 false, // hide subset reachability states
1129 true ); // hide edge taints
1131 mapDescriptorToNumUpdates.put( d, n + 1 );
1137 // return just the allocation site associated with one FlatNew node
1138 protected AllocSite getAllocSiteFromFlatNewPRIVATE( FlatNew fnew ) {
1140 if( !mapFlatNewToAllocSite.containsKey( fnew ) ) {
1142 (AllocSite) Canonical.makeCanonical( new AllocSite( allocationDepth,
1144 fnew.getDisjointId()
1148 // the newest nodes are single objects
1149 for( int i = 0; i < allocationDepth; ++i ) {
1150 Integer id = generateUniqueHeapRegionNodeID();
1151 as.setIthOldest( i, id );
1152 mapHrnIdToAllocSite.put( id, as );
1155 // the oldest node is a summary node
1156 as.setSummary( generateUniqueHeapRegionNodeID() );
1158 mapFlatNewToAllocSite.put( fnew, as );
1161 return mapFlatNewToAllocSite.get( fnew );
1165 public static boolean shouldAnalysisTrack( TypeDescriptor type ) {
1166 // don't track primitive types, but an array
1167 // of primitives is heap memory
1168 if( type.isImmutable() ) {
1169 return type.isArray();
1172 // everything else is an object
1178 // return all allocation sites in the method (there is one allocation
1179 // site per FlatNew node in a method)
1180 protected HashSet<AllocSite> getAllocSiteSet(Descriptor d) {
1181 if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
1182 buildAllocSiteSet(d);
1185 return mapDescriptorToAllocSiteSet.get(d);
1191 protected void buildAllocSiteSet(Descriptor d) {
1192 HashSet<AllocSite> s = new HashSet<AllocSite>();
1194 FlatMethod fm = state.getMethodFlat( d );
1196 // visit every node in this FlatMethod's IR graph
1197 // and make a set of the allocation sites from the
1198 // FlatNew node's visited
1199 HashSet<FlatNode> visited = new HashSet<FlatNode>();
1200 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
1203 while( !toVisit.isEmpty() ) {
1204 FlatNode n = toVisit.iterator().next();
1206 if( n instanceof FlatNew ) {
1207 s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
1210 toVisit.remove( n );
1213 for( int i = 0; i < n.numNext(); ++i ) {
1214 FlatNode child = n.getNext( i );
1215 if( !visited.contains( child ) ) {
1216 toVisit.add( child );
1221 mapDescriptorToAllocSiteSet.put( d, s );
1225 protected HashSet<AllocSite> getFlaggedAllocSites(Descriptor dIn) {
1227 HashSet<AllocSite> out = new HashSet<AllocSite>();
1228 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1229 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1233 while( !toVisit.isEmpty() ) {
1234 Descriptor d = toVisit.iterator().next();
1238 HashSet<AllocSite> asSet = getAllocSiteSet(d);
1239 Iterator asItr = asSet.iterator();
1240 while( asItr.hasNext() ) {
1241 AllocSite as = (AllocSite) asItr.next();
1242 if( as.getDisjointAnalysisId() != null ) {
1247 // enqueue callees of this method to be searched for
1248 // allocation sites also
1249 Set callees = callGraph.getCalleeSet(d);
1250 if( callees != null ) {
1251 Iterator methItr = callees.iterator();
1252 while( methItr.hasNext() ) {
1253 MethodDescriptor md = (MethodDescriptor) methItr.next();
1255 if( !visited.contains(md) ) {
1267 protected HashSet<AllocSite>
1268 getFlaggedAllocSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
1270 HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
1271 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1272 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1276 // traverse this task and all methods reachable from this task
1277 while( !toVisit.isEmpty() ) {
1278 Descriptor d = toVisit.iterator().next();
1282 HashSet<AllocSite> asSet = getAllocSiteSet(d);
1283 Iterator asItr = asSet.iterator();
1284 while( asItr.hasNext() ) {
1285 AllocSite as = (AllocSite) asItr.next();
1286 TypeDescriptor typed = as.getType();
1287 if( typed != null ) {
1288 ClassDescriptor cd = typed.getClassDesc();
1289 if( cd != null && cd.hasFlags() ) {
1295 // enqueue callees of this method to be searched for
1296 // allocation sites also
1297 Set callees = callGraph.getCalleeSet(d);
1298 if( callees != null ) {
1299 Iterator methItr = callees.iterator();
1300 while( methItr.hasNext() ) {
1301 MethodDescriptor md = (MethodDescriptor) methItr.next();
1303 if( !visited.contains(md) ) {
1317 protected String computeAliasContextHistogram() {
1319 Hashtable<Integer, Integer> mapNumContexts2NumDesc =
1320 new Hashtable<Integer, Integer>();
1322 Iterator itr = mapDescriptorToAllDescriptors.entrySet().iterator();
1323 while( itr.hasNext() ) {
1324 Map.Entry me = (Map.Entry) itr.next();
1325 HashSet<Descriptor> s = (HashSet<Descriptor>) me.getValue();
1327 Integer i = mapNumContexts2NumDesc.get( s.size() );
1329 i = new Integer( 0 );
1331 mapNumContexts2NumDesc.put( s.size(), i + 1 );
1337 itr = mapNumContexts2NumDesc.entrySet().iterator();
1338 while( itr.hasNext() ) {
1339 Map.Entry me = (Map.Entry) itr.next();
1340 Integer c0 = (Integer) me.getKey();
1341 Integer d0 = (Integer) me.getValue();
1343 s += String.format( "%4d methods had %4d unique alias contexts.\n", d0, c0 );
1346 s += String.format( "\n%4d total methods analayzed.\n", total );
1351 protected int numMethodsAnalyzed() {
1352 return descriptorsToAnalyze.size();
1359 // Take in source entry which is the program's compiled entry and
1360 // create a new analysis entry, a method that takes no parameters
1361 // and appears to allocate the command line arguments and call the
1362 // source entry with them. The purpose of this analysis entry is
1363 // to provide a top-level method context with no parameters left.
1364 protected void makeAnalysisEntryMethod( MethodDescriptor mdSourceEntry ) {
1366 Modifiers mods = new Modifiers();
1367 mods.addModifier( Modifiers.PUBLIC );
1368 mods.addModifier( Modifiers.STATIC );
1370 TypeDescriptor returnType =
1371 new TypeDescriptor( TypeDescriptor.VOID );
1373 this.mdAnalysisEntry =
1374 new MethodDescriptor( mods,
1376 "analysisEntryMethod"
1379 TempDescriptor cmdLineArgs =
1380 new TempDescriptor( "args",
1381 mdSourceEntry.getParamType( 0 )
1385 new FlatNew( mdSourceEntry.getParamType( 0 ),
1390 TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
1391 sourceEntryArgs[0] = cmdLineArgs;
1394 new FlatCall( mdSourceEntry,
1400 FlatReturnNode frn = new FlatReturnNode( null );
1402 FlatExit fe = new FlatExit();
1404 this.fmAnalysisEntry =
1405 new FlatMethod( mdAnalysisEntry,
1409 this.fmAnalysisEntry.addNext( fn );
1416 protected LinkedList<Descriptor> topologicalSort( Set<Descriptor> toSort ) {
1418 Set <Descriptor> discovered = new HashSet <Descriptor>();
1419 LinkedList<Descriptor> sorted = new LinkedList<Descriptor>();
1421 Iterator<Descriptor> itr = toSort.iterator();
1422 while( itr.hasNext() ) {
1423 Descriptor d = itr.next();
1425 if( !discovered.contains( d ) ) {
1426 dfsVisit( d, toSort, sorted, discovered );
1433 // While we're doing DFS on call graph, remember
1434 // dependencies for efficient queuing of methods
1435 // during interprocedural analysis:
1437 // a dependent of a method decriptor d for this analysis is:
1438 // 1) a method or task that invokes d
1439 // 2) in the descriptorsToAnalyze set
1440 protected void dfsVisit( Descriptor d,
1441 Set <Descriptor> toSort,
1442 LinkedList<Descriptor> sorted,
1443 Set <Descriptor> discovered ) {
1444 discovered.add( d );
1446 // only methods have callers, tasks never do
1447 if( d instanceof MethodDescriptor ) {
1449 MethodDescriptor md = (MethodDescriptor) d;
1451 // the call graph is not aware that we have a fabricated
1452 // analysis entry that calls the program source's entry
1453 if( md == mdSourceEntry ) {
1454 if( !discovered.contains( mdAnalysisEntry ) ) {
1455 addDependent( mdSourceEntry, // callee
1456 mdAnalysisEntry // caller
1458 dfsVisit( mdAnalysisEntry, toSort, sorted, discovered );
1462 // otherwise call graph guides DFS
1463 Iterator itr = callGraph.getCallerSet( md ).iterator();
1464 while( itr.hasNext() ) {
1465 Descriptor dCaller = (Descriptor) itr.next();
1467 // only consider callers in the original set to analyze
1468 if( !toSort.contains( dCaller ) ) {
1472 if( !discovered.contains( dCaller ) ) {
1473 addDependent( md, // callee
1477 dfsVisit( dCaller, toSort, sorted, discovered );
1482 // for leaf-nodes last now!
1483 sorted.addLast( d );
1487 protected void enqueue( Descriptor d ) {
1488 if( !descriptorsToVisitSet.contains( d ) ) {
1489 Integer priority = mapDescriptorToPriority.get( d );
1490 descriptorsToVisitQ.add( new DescriptorQWrapper( priority,
1493 descriptorsToVisitSet.add( d );
1498 // a dependent of a method decriptor d for this analysis is:
1499 // 1) a method or task that invokes d
1500 // 2) in the descriptorsToAnalyze set
1501 protected void addDependent( Descriptor callee, Descriptor caller ) {
1502 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1503 if( deps == null ) {
1504 deps = new HashSet<Descriptor>();
1507 mapDescriptorToSetDependents.put( callee, deps );
1510 protected Set<Descriptor> getDependents( Descriptor callee ) {
1511 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1512 if( deps == null ) {
1513 deps = new HashSet<Descriptor>();
1514 mapDescriptorToSetDependents.put( callee, deps );
1520 public Hashtable<FlatCall, ReachGraph> getIHMcontributions( Descriptor d ) {
1522 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1523 mapDescriptorToIHMcontributions.get( d );
1525 if( heapsFromCallers == null ) {
1526 heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
1527 mapDescriptorToIHMcontributions.put( d, heapsFromCallers );
1530 return heapsFromCallers;
1533 public ReachGraph getIHMcontribution( Descriptor d,
1536 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1537 getIHMcontributions( d );
1539 if( !heapsFromCallers.containsKey( fc ) ) {
1540 heapsFromCallers.put( fc, new ReachGraph() );
1543 return heapsFromCallers.get( fc );
1546 public void addIHMcontribution( Descriptor d,
1550 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1551 getIHMcontributions( d );
1553 heapsFromCallers.put( fc, rg );
1556 private AllocSite createParameterAllocSite(ReachGraph rg, TempDescriptor tempDesc) {
1558 // create temp descriptor for each parameter variable
1559 FlatNew flatNew = new FlatNew(tempDesc.getType(), tempDesc, false);
1560 // create allocation site
1561 AllocSite as = (AllocSite) Canonical.makeCanonical(new AllocSite( allocationDepth, flatNew, flatNew.getDisjointId()));
1562 for (int i = 0; i < allocationDepth; ++i) {
1563 Integer id = generateUniqueHeapRegionNodeID();
1564 as.setIthOldest(i, id);
1565 mapHrnIdToAllocSite.put(id, as);
1567 // the oldest node is a summary node
1568 as.setSummary( generateUniqueHeapRegionNodeID() );
1576 private Set<FieldDescriptor> getFieldSetTobeAnalyzed(TypeDescriptor typeDesc){
1578 Set<FieldDescriptor> fieldSet=new HashSet<FieldDescriptor>();
1579 if(!typeDesc.isImmutable()){
1580 ClassDescriptor classDesc = typeDesc.getClassDesc();
1581 for (Iterator it = classDesc.getFields(); it.hasNext();) {
1582 FieldDescriptor field = (FieldDescriptor) it.next();
1583 TypeDescriptor fieldType = field.getType();
1584 if (shouldAnalysisTrack( fieldType )) {
1585 fieldSet.add(field);
1593 private HeapRegionNode createMultiDeimensionalArrayHRN(ReachGraph rg, AllocSite alloc, HeapRegionNode srcHRN, FieldDescriptor fd, Hashtable<HeapRegionNode, HeapRegionNode> map, Hashtable<TypeDescriptor, HeapRegionNode> mapToExistingNode ){
1595 int dimCount=fd.getType().getArrayCount();
1596 HeapRegionNode prevNode=null;
1597 HeapRegionNode arrayEntryNode=null;
1598 for(int i=dimCount;i>0;i--){
1599 TypeDescriptor typeDesc=fd.getType().dereference();//hack to get instance of type desc
1600 typeDesc.setArrayCount(i);
1601 TempDescriptor tempDesc=new TempDescriptor(typeDesc.getSymbol(),typeDesc);
1602 HeapRegionNode hrnSummary ;
1603 if(!mapToExistingNode.containsKey(typeDesc)){
1608 as = createParameterAllocSite(rg, tempDesc);
1610 // make a new reference to allocated node
1612 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1613 false, // single object?
1616 false, // out-of-context?
1617 as.getType(), // type
1618 as, // allocation site
1619 null, // inherent reach
1620 null, // current reach
1621 ExistPredSet.factory(), // predicates
1622 tempDesc.toString() // description
1624 rg.id2hrn.put(as.getSummary(),hrnSummary);
1626 mapToExistingNode.put(typeDesc, hrnSummary);
1628 hrnSummary=mapToExistingNode.get(typeDesc);
1632 // make a new reference between new summary node and source
1633 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1636 fd.getSymbol(), // field name
1637 srcHRN.getAlpha(), // beta
1638 ExistPredSet.factory(rg.predTrue) // predicates
1641 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1642 prevNode=hrnSummary;
1643 arrayEntryNode=hrnSummary;
1645 // make a new reference between summary nodes of array
1646 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1649 arrayElementFieldName, // field name
1650 srcHRN.getAlpha(), // beta
1651 ExistPredSet.factory(rg.predTrue) // predicates
1654 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1655 prevNode=hrnSummary;
1660 // create a new obj node if obj has at least one non-primitive field
1661 TypeDescriptor type=fd.getType();
1662 if(getFieldSetTobeAnalyzed(type).size()>0){
1663 TypeDescriptor typeDesc=type.dereference();
1664 typeDesc.setArrayCount(0);
1665 if(!mapToExistingNode.containsKey(typeDesc)){
1666 TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc);
1667 AllocSite as = createParameterAllocSite(rg, tempDesc);
1668 // make a new reference to allocated node
1669 HeapRegionNode hrnSummary =
1670 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1671 false, // single object?
1674 false, // out-of-context?
1676 as, // allocation site
1677 null, // inherent reach
1678 null, // current reach
1679 ExistPredSet.factory(), // predicates
1680 tempDesc.toString() // description
1682 rg.id2hrn.put(as.getSummary(),hrnSummary);
1683 mapToExistingNode.put(typeDesc, hrnSummary);
1684 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1687 arrayElementFieldName, // field name
1689 ExistPredSet.factory(rg.predTrue) // predicates
1691 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1692 prevNode=hrnSummary;
1694 HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc);
1695 if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null){
1696 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1699 arrayElementFieldName, // field name
1701 ExistPredSet.factory(rg.predTrue) // predicates
1703 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1705 prevNode=hrnSummary;
1709 map.put(arrayEntryNode, prevNode);
1710 return arrayEntryNode;
1713 private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
1714 ReachGraph rg = new ReachGraph();
1715 TaskDescriptor taskDesc = fm.getTask();
1717 for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
1718 Descriptor paramDesc = taskDesc.getParameter(idx);
1719 TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
1721 // setup data structure
1722 Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet =
1723 new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
1724 Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode =
1725 new Hashtable<TypeDescriptor, HeapRegionNode>();
1726 Hashtable<HeapRegionNode, HeapRegionNode> mapToFirstDimensionArrayNode =
1727 new Hashtable<HeapRegionNode, HeapRegionNode>();
1728 Set<String> doneSet = new HashSet<String>();
1730 TempDescriptor tempDesc = fm.getParameter(idx);
1732 AllocSite as = createParameterAllocSite(rg, tempDesc);
1733 VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
1734 Integer idNewest = as.getIthOldest(0);
1735 HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
1736 // make a new reference to allocated node
1737 RefEdge edgeNew = new RefEdge(lnX, // source
1739 taskDesc.getParamType(idx), // type
1741 hrnNewest.getAlpha(), // beta
1742 ExistPredSet.factory(rg.predTrue) // predicates
1744 rg.addRefEdge(lnX, hrnNewest, edgeNew);
1746 // set-up a work set for class field
1747 ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
1748 for (Iterator it = classDesc.getFields(); it.hasNext();) {
1749 FieldDescriptor fd = (FieldDescriptor) it.next();
1750 TypeDescriptor fieldType = fd.getType();
1751 if (shouldAnalysisTrack( fieldType )) {
1752 HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
1753 newMap.put(hrnNewest, fd);
1754 workSet.add(newMap);
1758 int uniqueIdentifier = 0;
1759 while (!workSet.isEmpty()) {
1760 HashMap<HeapRegionNode, FieldDescriptor> map = workSet
1762 workSet.remove(map);
1764 Set<HeapRegionNode> key = map.keySet();
1765 HeapRegionNode srcHRN = key.iterator().next();
1766 FieldDescriptor fd = map.get(srcHRN);
1767 TypeDescriptor type = fd.getType();
1768 String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
1770 if (!doneSet.contains(doneSetIdentifier)) {
1771 doneSet.add(doneSetIdentifier);
1772 if (!mapTypeToExistingSummaryNode.containsKey(type)) {
1773 // create new summary Node
1774 TempDescriptor td = new TempDescriptor("temp"
1775 + uniqueIdentifier, type);
1777 AllocSite allocSite;
1778 if(type.equals(paramTypeDesc)){
1779 //corresponding allocsite has already been created for a parameter variable.
1782 allocSite = createParameterAllocSite(rg, td);
1784 String strDesc = allocSite.toStringForDOT()
1786 TypeDescriptor allocType=allocSite.getType();
1788 HeapRegionNode hrnSummary;
1789 if(allocType.isArray() && allocType.getArrayCount()>0){
1790 hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode);
1793 rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
1794 false, // single object?
1797 false, // out-of-context?
1798 allocSite.getType(), // type
1799 allocSite, // allocation site
1800 null, // inherent reach
1801 srcHRN.getAlpha(), // current reach
1802 ExistPredSet.factory(), // predicates
1803 strDesc // description
1805 rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
1807 // make a new reference to summary node
1808 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1811 fd.getSymbol(), // field name
1812 srcHRN.getAlpha(), // beta
1813 ExistPredSet.factory(rg.predTrue) // predicates
1816 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1820 mapTypeToExistingSummaryNode.put(type, hrnSummary);
1822 // set-up a work set for fields of the class
1823 Set<FieldDescriptor> fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type);
1824 for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator
1826 FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator
1828 HeapRegionNode newDstHRN;
1829 if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)){
1830 //related heap region node is already exsited.
1831 newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary);
1833 newDstHRN=hrnSummary;
1835 doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor;
1836 if(!doneSet.contains(doneSetIdentifier)){
1837 // add new work item
1838 HashMap<HeapRegionNode, FieldDescriptor> newMap =
1839 new HashMap<HeapRegionNode, FieldDescriptor>();
1840 newMap.put(newDstHRN, fieldDescriptor);
1841 workSet.add(newMap);
1846 // if there exists corresponding summary node
1847 HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
1849 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1851 fd.getType(), // type
1852 fd.getSymbol(), // field name
1853 srcHRN.getAlpha(), // beta
1854 ExistPredSet.factory(rg.predTrue) // predicates
1856 rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
1862 // debugSnapshot(rg, fm, true);
1866 // return all allocation sites in the method (there is one allocation
1867 // site per FlatNew node in a method)
1868 private HashSet<AllocSite> getAllocationSiteSet(Descriptor d) {
1869 if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
1870 buildAllocationSiteSet(d);
1873 return mapDescriptorToAllocSiteSet.get(d);
1877 private void buildAllocationSiteSet(Descriptor d) {
1878 HashSet<AllocSite> s = new HashSet<AllocSite>();
1881 if( d instanceof MethodDescriptor ) {
1882 fm = state.getMethodFlat( (MethodDescriptor) d);
1884 assert d instanceof TaskDescriptor;
1885 fm = state.getMethodFlat( (TaskDescriptor) d);
1888 // visit every node in this FlatMethod's IR graph
1889 // and make a set of the allocation sites from the
1890 // FlatNew node's visited
1891 HashSet<FlatNode> visited = new HashSet<FlatNode>();
1892 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
1895 while( !toVisit.isEmpty() ) {
1896 FlatNode n = toVisit.iterator().next();
1898 if( n instanceof FlatNew ) {
1899 s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
1905 for( int i = 0; i < n.numNext(); ++i ) {
1906 FlatNode child = n.getNext(i);
1907 if( !visited.contains(child) ) {
1913 mapDescriptorToAllocSiteSet.put(d, s);
1916 private HashSet<AllocSite> getFlaggedAllocationSites(Descriptor dIn) {
1918 HashSet<AllocSite> out = new HashSet<AllocSite>();
1919 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1920 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1924 while (!toVisit.isEmpty()) {
1925 Descriptor d = toVisit.iterator().next();
1929 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
1930 Iterator asItr = asSet.iterator();
1931 while (asItr.hasNext()) {
1932 AllocSite as = (AllocSite) asItr.next();
1933 if (as.getDisjointAnalysisId() != null) {
1938 // enqueue callees of this method to be searched for
1939 // allocation sites also
1940 Set callees = callGraph.getCalleeSet(d);
1941 if (callees != null) {
1942 Iterator methItr = callees.iterator();
1943 while (methItr.hasNext()) {
1944 MethodDescriptor md = (MethodDescriptor) methItr.next();
1946 if (!visited.contains(md)) {
1957 private HashSet<AllocSite>
1958 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
1960 HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
1961 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1962 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1966 // traverse this task and all methods reachable from this task
1967 while( !toVisit.isEmpty() ) {
1968 Descriptor d = toVisit.iterator().next();
1972 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
1973 Iterator asItr = asSet.iterator();
1974 while( asItr.hasNext() ) {
1975 AllocSite as = (AllocSite) asItr.next();
1976 TypeDescriptor typed = as.getType();
1977 if( typed != null ) {
1978 ClassDescriptor cd = typed.getClassDesc();
1979 if( cd != null && cd.hasFlags() ) {
1985 // enqueue callees of this method to be searched for
1986 // allocation sites also
1987 Set callees = callGraph.getCalleeSet(d);
1988 if( callees != null ) {
1989 Iterator methItr = callees.iterator();
1990 while( methItr.hasNext() ) {
1991 MethodDescriptor md = (MethodDescriptor) methItr.next();
1993 if( !visited.contains(md) ) {
2006 // get successive captures of the analysis state, use compiler
2008 boolean takeDebugSnapshots = false;
2009 String descSymbolDebug = null;
2010 boolean stopAfterCapture = false;
2011 int snapVisitCounter = 0;
2012 int snapNodeCounter = 0;
2013 int visitStartCapture = 0;
2014 int numVisitsToCapture = 0;
2017 void debugSnapshot( ReachGraph rg, FlatNode fn, boolean in ) {
2018 if( snapVisitCounter > visitStartCapture + numVisitsToCapture ) {
2026 if( snapVisitCounter >= visitStartCapture ) {
2027 System.out.println( " @@@ snapping visit="+snapVisitCounter+
2028 ", node="+snapNodeCounter+
2032 graphName = String.format( "snap%02d_%04din",
2036 graphName = String.format( "snap%02d_%04dout",
2041 graphName = graphName + fn;
2043 rg.writeGraph( graphName,
2044 true, // write labels (variables)
2045 true, // selectively hide intermediate temp vars
2046 false, // prune unreachable heap regions
2047 false, // hide subset reachability states
2048 true );// hide edge taints