1 package Analysis.Disjoint;
3 import Analysis.CallGraph.*;
4 import Analysis.Liveness;
5 import Analysis.ArrayReferencees;
6 import Analysis.OoOJava.RBlockRelationAnalysis;
7 import Analysis.OoOJava.RBlockStatusAnalysis;
10 import IR.Tree.Modifiers;
15 public class DisjointAnalysis {
17 ///////////////////////////////////////////
19 // Public interface to discover possible
20 // sharing in the program under analysis
22 ///////////////////////////////////////////
24 // if an object allocated at the target site may be
25 // reachable from both an object from root1 and an
26 // object allocated at root2, return TRUE
27 public boolean mayBothReachTarget( FlatMethod fm,
32 AllocSite asr1 = getAllocationSiteFromFlatNew( fnRoot1 );
33 AllocSite asr2 = getAllocationSiteFromFlatNew( fnRoot2 );
34 assert asr1.isFlagged();
35 assert asr2.isFlagged();
37 AllocSite ast = getAllocationSiteFromFlatNew( fnTarget );
38 ReachGraph rg = getPartial( fm.getMethod() );
40 return rg.mayBothReachTarget( asr1, asr2, ast );
43 // similar to the method above, return TRUE if ever
44 // more than one object from the root allocation site
45 // may reach an object from the target site
46 public boolean mayManyReachTarget( FlatMethod fm,
50 AllocSite asr = getAllocationSiteFromFlatNew( fnRoot );
51 assert asr.isFlagged();
53 AllocSite ast = getAllocationSiteFromFlatNew( fnTarget );
54 ReachGraph rg = getPartial( fm.getMethod() );
56 return rg.mayManyReachTarget( asr, ast );
62 public HashSet<AllocSite>
63 getFlaggedAllocationSitesReachableFromTask(TaskDescriptor td) {
64 checkAnalysisComplete();
65 return getFlaggedAllocationSitesReachableFromTaskPRIVATE(td);
68 public AllocSite getAllocationSiteFromFlatNew(FlatNew fn) {
69 checkAnalysisComplete();
70 return getAllocSiteFromFlatNewPRIVATE(fn);
73 public AllocSite getAllocationSiteFromHeapRegionNodeID(Integer id) {
74 checkAnalysisComplete();
75 return mapHrnIdToAllocSite.get(id);
78 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
81 checkAnalysisComplete();
82 ReachGraph rg=mapDescriptorToCompleteReachGraph.get(taskOrMethod);
83 FlatMethod fm=state.getMethodFlat(taskOrMethod);
85 return rg.mayReachSharedObjects(fm, paramIndex1, paramIndex2);
88 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
89 int paramIndex, AllocSite alloc) {
90 checkAnalysisComplete();
91 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
92 FlatMethod fm=state.getMethodFlat(taskOrMethod);
94 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
97 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
98 AllocSite alloc, int paramIndex) {
99 checkAnalysisComplete();
100 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
101 FlatMethod fm=state.getMethodFlat(taskOrMethod);
103 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
106 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
107 AllocSite alloc1, AllocSite alloc2) {
108 checkAnalysisComplete();
109 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
111 return rg.mayReachSharedObjects(alloc1, alloc2);
114 public String prettyPrintNodeSet(Set<HeapRegionNode> s) {
115 checkAnalysisComplete();
119 Iterator<HeapRegionNode> i = s.iterator();
120 while (i.hasNext()) {
121 HeapRegionNode n = i.next();
123 AllocSite as = n.getAllocSite();
125 out += " " + n.toString() + ",\n";
127 out += " " + n.toString() + ": " + as.toStringVerbose()
136 // use the methods given above to check every possible sharing class
137 // between task parameters and flagged allocation sites reachable
139 public void writeAllSharing(String outputFile,
142 boolean tabularOutput,
145 throws java.io.IOException {
146 checkAnalysisComplete();
148 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
150 if (!tabularOutput) {
151 bw.write("Conducting ownership analysis with allocation depth = "
152 + allocationDepth + "\n");
153 bw.write(timeReport + "\n");
158 // look through every task for potential sharing
159 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
160 while (taskItr.hasNext()) {
161 TaskDescriptor td = (TaskDescriptor) taskItr.next();
163 if (!tabularOutput) {
164 bw.write("\n---------" + td + "--------\n");
167 HashSet<AllocSite> allocSites = getFlaggedAllocationSitesReachableFromTask(td);
169 Set<HeapRegionNode> common;
171 // for each task parameter, check for sharing classes with
172 // other task parameters and every allocation site
173 // reachable from this task
174 boolean foundSomeSharing = false;
176 FlatMethod fm = state.getMethodFlat(td);
177 for (int i = 0; i < fm.numParameters(); ++i) {
179 // skip parameters with types that cannot reference
181 if( !shouldAnalysisTrack( fm.getParameter( i ).getType() ) ) {
185 // for the ith parameter check for sharing classes to all
186 // higher numbered parameters
187 for (int j = i + 1; j < fm.numParameters(); ++j) {
189 // skip parameters with types that cannot reference
191 if( !shouldAnalysisTrack( fm.getParameter( j ).getType() ) ) {
196 common = hasPotentialSharing(td, i, j);
197 if (!common.isEmpty()) {
198 foundSomeSharing = true;
200 if (!tabularOutput) {
201 bw.write("Potential sharing between parameters " + i
202 + " and " + j + ".\n");
203 bw.write(prettyPrintNodeSet(common) + "\n");
208 // for the ith parameter, check for sharing classes against
209 // the set of allocation sites reachable from this
211 Iterator allocItr = allocSites.iterator();
212 while (allocItr.hasNext()) {
213 AllocSite as = (AllocSite) allocItr.next();
214 common = hasPotentialSharing(td, i, as);
215 if (!common.isEmpty()) {
216 foundSomeSharing = true;
218 if (!tabularOutput) {
219 bw.write("Potential sharing between parameter " + i
220 + " and " + as.getFlatNew() + ".\n");
221 bw.write(prettyPrintNodeSet(common) + "\n");
227 // for each allocation site check for sharing classes with
228 // other allocation sites in the context of execution
230 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
231 Iterator allocItr1 = allocSites.iterator();
232 while (allocItr1.hasNext()) {
233 AllocSite as1 = (AllocSite) allocItr1.next();
235 Iterator allocItr2 = allocSites.iterator();
236 while (allocItr2.hasNext()) {
237 AllocSite as2 = (AllocSite) allocItr2.next();
239 if (!outerChecked.contains(as2)) {
240 common = hasPotentialSharing(td, as1, as2);
242 if (!common.isEmpty()) {
243 foundSomeSharing = true;
245 if (!tabularOutput) {
246 bw.write("Potential sharing between "
247 + as1.getFlatNew() + " and "
248 + as2.getFlatNew() + ".\n");
249 bw.write(prettyPrintNodeSet(common) + "\n");
255 outerChecked.add(as1);
258 if (!foundSomeSharing) {
259 if (!tabularOutput) {
260 bw.write("No sharing between flagged objects in Task " + td
268 bw.write(" & " + numSharing + " & " + justTime + " & " + numLines
269 + " & " + numMethodsAnalyzed() + " \\\\\n");
271 bw.write("\nNumber sharing classes: "+numSharing);
279 // this version of writeAllSharing is for Java programs that have no tasks
280 // ***********************************
281 // WARNING: THIS DOES NOT DO THE RIGHT THING, REPORTS 0 ALWAYS!
282 // It should use mayBothReachTarget and mayManyReachTarget like
283 // OoOJava does to query analysis results
284 // ***********************************
285 public void writeAllSharingJava(String outputFile,
288 boolean tabularOutput,
291 throws java.io.IOException {
292 checkAnalysisComplete();
298 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
300 bw.write("Conducting disjoint reachability analysis with allocation depth = "
301 + allocationDepth + "\n");
302 bw.write(timeReport + "\n\n");
304 boolean foundSomeSharing = false;
306 Descriptor d = typeUtil.getMain();
307 HashSet<AllocSite> allocSites = getFlaggedAllocationSites(d);
309 // for each allocation site check for sharing classes with
310 // other allocation sites in the context of execution
312 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
313 Iterator allocItr1 = allocSites.iterator();
314 while (allocItr1.hasNext()) {
315 AllocSite as1 = (AllocSite) allocItr1.next();
317 Iterator allocItr2 = allocSites.iterator();
318 while (allocItr2.hasNext()) {
319 AllocSite as2 = (AllocSite) allocItr2.next();
321 if (!outerChecked.contains(as2)) {
322 Set<HeapRegionNode> common = hasPotentialSharing(d,
325 if (!common.isEmpty()) {
326 foundSomeSharing = true;
327 bw.write("Potential sharing between "
328 + as1.getDisjointAnalysisId() + " and "
329 + as2.getDisjointAnalysisId() + ".\n");
330 bw.write(prettyPrintNodeSet(common) + "\n");
336 outerChecked.add(as1);
339 if (!foundSomeSharing) {
340 bw.write("No sharing classes between flagged objects found.\n");
342 bw.write("\nNumber sharing classes: "+numSharing);
345 bw.write("Number of methods analyzed: "+numMethodsAnalyzed()+"\n");
350 ///////////////////////////////////////////
352 // end public interface
354 ///////////////////////////////////////////
358 protected void checkAnalysisComplete() {
359 if( !analysisComplete ) {
360 throw new Error("Warning: public interface method called while analysis is running.");
369 // run in faster mode, only when bugs wrung out!
370 public static boolean releaseMode;
372 // use command line option to set this, analysis
373 // should attempt to be deterministic
374 public static boolean determinismDesired;
376 // when we want to enforce determinism in the
377 // analysis we need to sort descriptors rather
378 // than toss them in efficient sets, use this
379 public static DescriptorComparator dComp =
380 new DescriptorComparator();
383 // data from the compiler
385 public CallGraph callGraph;
386 public Liveness liveness;
387 public ArrayReferencees arrayReferencees;
388 public RBlockRelationAnalysis rblockRel;
389 public RBlockStatusAnalysis rblockStatus;
390 public TypeUtil typeUtil;
391 public int allocationDepth;
393 protected boolean doEffectsAnalysis = false;
394 protected EffectsAnalysis effectsAnalysis;
396 // data structure for public interface
397 private Hashtable< Descriptor, HashSet<AllocSite> >
398 mapDescriptorToAllocSiteSet;
401 // for public interface methods to warn that they
402 // are grabbing results during analysis
403 private boolean analysisComplete;
406 // used to identify HeapRegionNode objects
407 // A unique ID equates an object in one
408 // ownership graph with an object in another
409 // graph that logically represents the same
411 // start at 10 and increment to reserve some
412 // IDs for special purposes
413 static protected int uniqueIDcount = 10;
416 // An out-of-scope method created by the
417 // analysis that has no parameters, and
418 // appears to allocate the command line
419 // arguments, then invoke the source code's
420 // main method. The purpose of this is to
421 // provide the analysis with an explicit
422 // top-level context with no parameters
423 protected MethodDescriptor mdAnalysisEntry;
424 protected FlatMethod fmAnalysisEntry;
426 // main method defined by source program
427 protected MethodDescriptor mdSourceEntry;
429 // the set of task and/or method descriptors
430 // reachable in call graph
431 protected Set<Descriptor>
432 descriptorsToAnalyze;
434 // current descriptors to visit in fixed-point
435 // interprocedural analysis, prioritized by
436 // dependency in the call graph
437 protected Stack<Descriptor>
438 descriptorsToVisitStack;
439 protected PriorityQueue<DescriptorQWrapper>
442 // a duplication of the above structure, but
443 // for efficient testing of inclusion
444 protected HashSet<Descriptor>
445 descriptorsToVisitSet;
447 // storage for priorities (doesn't make sense)
448 // to add it to the Descriptor class, just in
450 protected Hashtable<Descriptor, Integer>
451 mapDescriptorToPriority;
453 // when analyzing a method and scheduling more:
454 // remember set of callee's enqueued for analysis
455 // so they can be put on top of the callers in
456 // the stack-visit mode
457 protected Set<Descriptor>
460 // maps a descriptor to its current partial result
461 // from the intraprocedural fixed-point analysis--
462 // then the interprocedural analysis settles, this
463 // mapping will have the final results for each
465 protected Hashtable<Descriptor, ReachGraph>
466 mapDescriptorToCompleteReachGraph;
468 // maps a descriptor to its known dependents: namely
469 // methods or tasks that call the descriptor's method
470 // AND are part of this analysis (reachable from main)
471 protected Hashtable< Descriptor, Set<Descriptor> >
472 mapDescriptorToSetDependents;
474 // if the analysis client wants to flag allocation sites
475 // programmatically, it should provide a set of FlatNew
476 // statements--this may be null if unneeded
477 protected Set<FlatNew> sitesToFlag;
479 // maps each flat new to one analysis abstraction
480 // allocate site object, these exist outside reach graphs
481 protected Hashtable<FlatNew, AllocSite>
482 mapFlatNewToAllocSite;
484 // maps intergraph heap region IDs to intergraph
485 // allocation sites that created them, a redundant
486 // structure for efficiency in some operations
487 protected Hashtable<Integer, AllocSite>
490 // maps a method to its initial heap model (IHM) that
491 // is the set of reachability graphs from every caller
492 // site, all merged together. The reason that we keep
493 // them separate is that any one call site's contribution
494 // to the IHM may changed along the path to the fixed point
495 protected Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >
496 mapDescriptorToIHMcontributions;
498 // additionally, keep a mapping from descriptors to the
499 // merged in-coming initial context, because we want this
500 // initial context to be STRICTLY MONOTONIC
501 protected Hashtable<Descriptor, ReachGraph>
502 mapDescriptorToInitialContext;
504 // make the result for back edges analysis-wide STRICTLY
505 // MONOTONIC as well, but notice we use FlatNode as the
506 // key for this map: in case we want to consider other
507 // nodes as back edge's in future implementations
508 protected Hashtable<FlatNode, ReachGraph>
509 mapBackEdgeToMonotone;
512 public static final String arrayElementFieldName = "___element_";
513 static protected Hashtable<TypeDescriptor, FieldDescriptor>
516 // for controlling DOT file output
517 protected boolean writeFinalDOTs;
518 protected boolean writeAllIncrementalDOTs;
520 // supporting DOT output--when we want to write every
521 // partial method result, keep a tally for generating
523 protected Hashtable<Descriptor, Integer>
524 mapDescriptorToNumUpdates;
526 //map task descriptor to initial task parameter
527 protected Hashtable<Descriptor, ReachGraph>
528 mapDescriptorToReachGraph;
530 protected PointerMethod pm;
532 static protected Hashtable<FlatNode, ReachGraph> fn2rg =
533 new Hashtable<FlatNode, ReachGraph>();
535 private Hashtable<FlatCall, Descriptor> fc2enclosing;
538 // allocate various structures that are not local
539 // to a single class method--should be done once
540 protected void allocateStructures() {
542 if( determinismDesired ) {
543 // use an ordered set
544 descriptorsToAnalyze = new TreeSet<Descriptor>( dComp );
546 // otherwise use a speedy hashset
547 descriptorsToAnalyze = new HashSet<Descriptor>();
550 mapDescriptorToCompleteReachGraph =
551 new Hashtable<Descriptor, ReachGraph>();
553 mapDescriptorToNumUpdates =
554 new Hashtable<Descriptor, Integer>();
556 mapDescriptorToSetDependents =
557 new Hashtable< Descriptor, Set<Descriptor> >();
559 mapFlatNewToAllocSite =
560 new Hashtable<FlatNew, AllocSite>();
562 mapDescriptorToIHMcontributions =
563 new Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >();
565 mapDescriptorToInitialContext =
566 new Hashtable<Descriptor, ReachGraph>();
568 mapBackEdgeToMonotone =
569 new Hashtable<FlatNode, ReachGraph>();
571 mapHrnIdToAllocSite =
572 new Hashtable<Integer, AllocSite>();
574 mapTypeToArrayField =
575 new Hashtable <TypeDescriptor, FieldDescriptor>();
577 if( state.DISJOINTDVISITSTACK ||
578 state.DISJOINTDVISITSTACKEESONTOP
580 descriptorsToVisitStack =
581 new Stack<Descriptor>();
584 if( state.DISJOINTDVISITPQUE ) {
585 descriptorsToVisitQ =
586 new PriorityQueue<DescriptorQWrapper>();
589 descriptorsToVisitSet =
590 new HashSet<Descriptor>();
592 mapDescriptorToPriority =
593 new Hashtable<Descriptor, Integer>();
596 new HashSet<Descriptor>();
598 mapDescriptorToAllocSiteSet =
599 new Hashtable<Descriptor, HashSet<AllocSite> >();
601 mapDescriptorToReachGraph =
602 new Hashtable<Descriptor, ReachGraph>();
604 pm = new PointerMethod();
606 fc2enclosing = new Hashtable<FlatCall, Descriptor>();
611 // this analysis generates a disjoint reachability
612 // graph for every reachable method in the program
613 public DisjointAnalysis( State s,
618 Set<FlatNew> sitesToFlag,
619 RBlockRelationAnalysis rra,
620 RBlockStatusAnalysis rsa
622 init( s, tu, cg, l, ar, sitesToFlag, rra, rsa, false );
625 public DisjointAnalysis( State s,
630 Set<FlatNew> sitesToFlag,
631 RBlockRelationAnalysis rra,
632 RBlockStatusAnalysis rsa,
633 boolean suppressOutput
635 init( s, tu, cg, l, ar, sitesToFlag, rra, rsa, suppressOutput );
638 protected void init( State state,
642 ArrayReferencees arrayReferencees,
643 Set<FlatNew> sitesToFlag,
644 RBlockRelationAnalysis rra,
645 RBlockStatusAnalysis rsa,
646 boolean suppressOutput
649 analysisComplete = false;
652 this.typeUtil = typeUtil;
653 this.callGraph = callGraph;
654 this.liveness = liveness;
655 this.arrayReferencees = arrayReferencees;
656 this.sitesToFlag = sitesToFlag;
657 this.rblockRel = rra;
658 this.rblockStatus = rsa;
660 if( rblockRel != null ) {
661 doEffectsAnalysis = true;
662 effectsAnalysis = new EffectsAnalysis();
665 this.allocationDepth = state.DISJOINTALLOCDEPTH;
666 this.releaseMode = state.DISJOINTRELEASEMODE;
667 this.determinismDesired = state.DISJOINTDETERMINISM;
669 this.writeFinalDOTs = state.DISJOINTWRITEDOTS && !state.DISJOINTWRITEALL && !suppressOutput;
670 this.writeAllIncrementalDOTs = state.DISJOINTWRITEDOTS && state.DISJOINTWRITEALL && !suppressOutput;
672 this.takeDebugSnapshots = state.DISJOINTSNAPSYMBOL != null;
673 this.descSymbolDebug = state.DISJOINTSNAPSYMBOL;
674 this.visitStartCapture = state.DISJOINTSNAPVISITTOSTART;
675 this.numVisitsToCapture = state.DISJOINTSNAPNUMVISITS;
676 this.stopAfterCapture = state.DISJOINTSNAPSTOPAFTER;
677 this.snapVisitCounter = 1; // count visits from 1 (user will write 1, means 1st visit)
678 this.snapNodeCounter = 0; // count nodes from 0
681 state.DISJOINTDVISITSTACK ||
682 state.DISJOINTDVISITPQUE ||
683 state.DISJOINTDVISITSTACKEESONTOP;
684 assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITPQUE);
685 assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITSTACKEESONTOP);
686 assert !(state.DISJOINTDVISITPQUE && state.DISJOINTDVISITSTACKEESONTOP);
688 // set some static configuration for ReachGraphs
689 ReachGraph.allocationDepth = allocationDepth;
690 ReachGraph.typeUtil = typeUtil;
692 ReachGraph.debugCallSiteVisitStartCapture
693 = state.DISJOINTDEBUGCALLVISITTOSTART;
695 ReachGraph.debugCallSiteNumVisitsToCapture
696 = state.DISJOINTDEBUGCALLNUMVISITS;
698 ReachGraph.debugCallSiteStopAfter
699 = state.DISJOINTDEBUGCALLSTOPAFTER;
701 ReachGraph.debugCallSiteVisitCounter
702 = 0; // count visits from 1, is incremented before first visit
706 allocateStructures();
708 double timeStartAnalysis = (double) System.nanoTime();
710 // start interprocedural fixed-point computation
713 } catch( IOException e ) {
714 throw new Error( "IO Exception while writing disjointness analysis output." );
717 analysisComplete=true;
720 double timeEndAnalysis = (double) System.nanoTime();
721 double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
724 if( sitesToFlag != null ) {
725 treport = String.format( "Disjoint reachability analysis flagged %d sites and took %.3f sec.", sitesToFlag.size(), dt );
727 treport = String.format( "Disjoint reachability analysis took %.3f sec.", dt );
729 String justtime = String.format( "%.2f", dt );
730 System.out.println( treport );
734 if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
738 if( state.DISJOINTWRITEIHMS && !suppressOutput ) {
742 if( state.DISJOINTWRITEINITCONTEXTS && !suppressOutput ) {
743 writeInitialContexts();
746 if( state.DISJOINTALIASFILE != null && !suppressOutput ) {
748 writeAllSharing(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines);
750 writeAllSharingJava(state.DISJOINTALIASFILE,
753 state.DISJOINTALIASTAB,
758 } catch( IOException e ) {
759 throw new Error( "IO Exception while writing disjointness analysis output." );
765 protected boolean moreDescriptorsToVisit() {
766 if( state.DISJOINTDVISITSTACK ||
767 state.DISJOINTDVISITSTACKEESONTOP
769 return !descriptorsToVisitStack.isEmpty();
771 } else if( state.DISJOINTDVISITPQUE ) {
772 return !descriptorsToVisitQ.isEmpty();
775 throw new Error( "Neither descriptor visiting mode set" );
779 // fixed-point computation over the call graph--when a
780 // method's callees are updated, it must be reanalyzed
781 protected void analyzeMethods() throws java.io.IOException {
783 // task or non-task (java) mode determines what the roots
784 // of the call chain are, and establishes the set of methods
785 // reachable from the roots that will be analyzed
788 System.out.println( "Bamboo mode..." );
790 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
791 while( taskItr.hasNext() ) {
792 TaskDescriptor td = (TaskDescriptor) taskItr.next();
793 if( !descriptorsToAnalyze.contains( td ) ) {
794 // add all methods transitively reachable from the
796 descriptorsToAnalyze.add( td );
797 descriptorsToAnalyze.addAll( callGraph.getAllMethods( td ) );
802 System.out.println( "Java mode..." );
804 // add all methods transitively reachable from the
805 // source's main to set for analysis
806 mdSourceEntry = typeUtil.getMain();
807 descriptorsToAnalyze.add( mdSourceEntry );
808 descriptorsToAnalyze.addAll( callGraph.getAllMethods( mdSourceEntry ) );
810 // fabricate an empty calling context that will call
811 // the source's main, but call graph doesn't know
812 // about it, so explicitly add it
813 makeAnalysisEntryMethod( mdSourceEntry );
814 descriptorsToAnalyze.add( mdAnalysisEntry );
818 // now, depending on the interprocedural mode for visiting
819 // methods, set up the needed data structures
821 if( state.DISJOINTDVISITPQUE ) {
823 // topologically sort according to the call graph so
824 // leaf calls are last, helps build contexts up first
825 LinkedList<Descriptor> sortedDescriptors =
826 topologicalSort( descriptorsToAnalyze );
828 // add sorted descriptors to priority queue, and duplicate
829 // the queue as a set for efficiently testing whether some
830 // method is marked for analysis
832 Iterator<Descriptor> dItr;
834 // for the priority queue, give items at the head
835 // of the sorted list a low number (highest priority)
836 while( !sortedDescriptors.isEmpty() ) {
837 Descriptor d = sortedDescriptors.removeFirst();
838 mapDescriptorToPriority.put( d, new Integer( p ) );
839 descriptorsToVisitQ.add( new DescriptorQWrapper( p, d ) );
840 descriptorsToVisitSet.add( d );
844 } else if( state.DISJOINTDVISITSTACK ||
845 state.DISJOINTDVISITSTACKEESONTOP
847 // if we're doing the stack scheme, just throw the root
848 // method or tasks on the stack
850 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
851 while( taskItr.hasNext() ) {
852 TaskDescriptor td = (TaskDescriptor) taskItr.next();
853 descriptorsToVisitStack.add( td );
854 descriptorsToVisitSet.add( td );
858 descriptorsToVisitStack.add( mdAnalysisEntry );
859 descriptorsToVisitSet.add( mdAnalysisEntry );
863 throw new Error( "Unknown method scheduling mode" );
867 // analyze scheduled methods until there are no more to visit
868 while( moreDescriptorsToVisit() ) {
871 if( state.DISJOINTDVISITSTACK ||
872 state.DISJOINTDVISITSTACKEESONTOP
874 d = descriptorsToVisitStack.pop();
876 } else if( state.DISJOINTDVISITPQUE ) {
877 d = descriptorsToVisitQ.poll().getDescriptor();
880 assert descriptorsToVisitSet.contains( d );
881 descriptorsToVisitSet.remove( d );
883 // because the task or method descriptor just extracted
884 // was in the "to visit" set it either hasn't been analyzed
885 // yet, or some method that it depends on has been
886 // updated. Recompute a complete reachability graph for
887 // this task/method and compare it to any previous result.
888 // If there is a change detected, add any methods/tasks
889 // that depend on this one to the "to visit" set.
891 System.out.println( "Analyzing " + d );
893 if( state.DISJOINTDVISITSTACKEESONTOP ) {
894 assert calleesToEnqueue.isEmpty();
897 ReachGraph rg = analyzeMethod( d );
898 ReachGraph rgPrev = getPartial( d );
900 if( !rg.equals( rgPrev ) ) {
903 if( state.DISJOINTDEBUGSCHEDULING ) {
904 System.out.println( " complete graph changed, scheduling callers for analysis:" );
907 // results for d changed, so enqueue dependents
908 // of d for further analysis
909 Iterator<Descriptor> depsItr = getDependents( d ).iterator();
910 while( depsItr.hasNext() ) {
911 Descriptor dNext = depsItr.next();
914 if( state.DISJOINTDEBUGSCHEDULING ) {
915 System.out.println( " "+dNext );
920 // whether or not the method under analysis changed,
921 // we may have some callees that are scheduled for
922 // more analysis, and they should go on the top of
923 // the stack now (in other method-visiting modes they
924 // are already enqueued at this point
925 if( state.DISJOINTDVISITSTACKEESONTOP ) {
926 Iterator<Descriptor> depsItr = calleesToEnqueue.iterator();
927 while( depsItr.hasNext() ) {
928 Descriptor dNext = depsItr.next();
931 calleesToEnqueue.clear();
937 protected ReachGraph analyzeMethod( Descriptor d )
938 throws java.io.IOException {
940 // get the flat code for this descriptor
942 if( d == mdAnalysisEntry ) {
943 fm = fmAnalysisEntry;
945 fm = state.getMethodFlat( d );
947 pm.analyzeMethod( fm );
949 // intraprocedural work set
950 Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
951 flatNodesToVisit.add( fm );
953 // if determinism is desired by client, shadow the
954 // set with a queue to make visit order deterministic
955 Queue<FlatNode> flatNodesToVisitQ = null;
956 if( determinismDesired ) {
957 flatNodesToVisitQ = new LinkedList<FlatNode>();
958 flatNodesToVisitQ.add( fm );
961 // mapping of current partial results
962 Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraph =
963 new Hashtable<FlatNode, ReachGraph>();
965 // the set of return nodes partial results that will be combined as
966 // the final, conservative approximation of the entire method
967 HashSet<FlatReturnNode> setReturns = new HashSet<FlatReturnNode>();
969 while( !flatNodesToVisit.isEmpty() ) {
972 if( determinismDesired ) {
973 assert !flatNodesToVisitQ.isEmpty();
974 fn = flatNodesToVisitQ.remove();
976 fn = flatNodesToVisit.iterator().next();
978 flatNodesToVisit.remove( fn );
980 // effect transfer function defined by this node,
981 // then compare it to the old graph at this node
982 // to see if anything was updated.
984 ReachGraph rg = new ReachGraph();
985 TaskDescriptor taskDesc;
986 if(fn instanceof FlatMethod && (taskDesc=((FlatMethod)fn).getTask())!=null){
987 if(mapDescriptorToReachGraph.containsKey(taskDesc)){
988 // retrieve existing reach graph if it is not first time
989 rg=mapDescriptorToReachGraph.get(taskDesc);
991 // create initial reach graph for a task
992 rg=createInitialTaskReachGraph((FlatMethod)fn);
994 mapDescriptorToReachGraph.put(taskDesc, rg);
998 // start by merging all node's parents' graphs
999 for( int i = 0; i < pm.numPrev(fn); ++i ) {
1000 FlatNode pn = pm.getPrev(fn,i);
1001 if( mapFlatNodeToReachGraph.containsKey( pn ) ) {
1002 ReachGraph rgParent = mapFlatNodeToReachGraph.get( pn );
1003 rg.merge( rgParent );
1008 if( takeDebugSnapshots &&
1009 d.getSymbol().equals( descSymbolDebug )
1011 debugSnapshot( rg, fn, true );
1015 // modify rg with appropriate transfer function
1016 rg = analyzeFlatNode( d, fm, fn, setReturns, rg );
1019 if( takeDebugSnapshots &&
1020 d.getSymbol().equals( descSymbolDebug )
1022 debugSnapshot( rg, fn, false );
1027 // if the results of the new graph are different from
1028 // the current graph at this node, replace the graph
1029 // with the update and enqueue the children
1030 ReachGraph rgPrev = mapFlatNodeToReachGraph.get( fn );
1031 if( !rg.equals( rgPrev ) ) {
1032 mapFlatNodeToReachGraph.put( fn, rg );
1034 for( int i = 0; i < pm.numNext( fn ); i++ ) {
1035 FlatNode nn = pm.getNext( fn, i );
1037 flatNodesToVisit.add( nn );
1038 if( determinismDesired ) {
1039 flatNodesToVisitQ.add( nn );
1046 // end by merging all return nodes into a complete
1047 // reach graph that represents all possible heap
1048 // states after the flat method returns
1049 ReachGraph completeGraph = new ReachGraph();
1051 assert !setReturns.isEmpty();
1052 Iterator retItr = setReturns.iterator();
1053 while( retItr.hasNext() ) {
1054 FlatReturnNode frn = (FlatReturnNode) retItr.next();
1056 assert mapFlatNodeToReachGraph.containsKey( frn );
1057 ReachGraph rgRet = mapFlatNodeToReachGraph.get( frn );
1059 completeGraph.merge( rgRet );
1063 if( takeDebugSnapshots &&
1064 d.getSymbol().equals( descSymbolDebug )
1066 // increment that we've visited the debug snap
1067 // method, and reset the node counter
1068 System.out.println( " @@@ debug snap at visit "+snapVisitCounter );
1070 snapNodeCounter = 0;
1072 if( snapVisitCounter == visitStartCapture + numVisitsToCapture &&
1075 System.out.println( "!!! Stopping analysis after debug snap captures. !!!" );
1081 return completeGraph;
1085 protected ReachGraph
1086 analyzeFlatNode( Descriptor d,
1087 FlatMethod fmContaining,
1089 HashSet<FlatReturnNode> setRetNodes,
1091 ) throws java.io.IOException {
1094 // any variables that are no longer live should be
1095 // nullified in the graph to reduce edges
1096 //rg.nullifyDeadVars( liveness.getLiveInTemps( fmContaining, fn ) );
1100 FieldDescriptor fld;
1101 TypeDescriptor tdElement;
1102 FieldDescriptor fdElement;
1103 FlatSESEEnterNode sese;
1104 FlatSESEExitNode fsexn;
1106 // use node type to decide what transfer function
1107 // to apply to the reachability graph
1108 switch( fn.kind() ) {
1110 case FKind.FlatMethod: {
1111 // construct this method's initial heap model (IHM)
1112 // since we're working on the FlatMethod, we know
1113 // the incoming ReachGraph 'rg' is empty
1115 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1116 getIHMcontributions( d );
1118 Set entrySet = heapsFromCallers.entrySet();
1119 Iterator itr = entrySet.iterator();
1120 while( itr.hasNext() ) {
1121 Map.Entry me = (Map.Entry) itr.next();
1122 FlatCall fc = (FlatCall) me.getKey();
1123 ReachGraph rgContrib = (ReachGraph) me.getValue();
1125 assert fc.getMethod().equals( d );
1127 rg.merge( rgContrib );
1130 // additionally, we are enforcing STRICT MONOTONICITY for the
1131 // method's initial context, so grow the context by whatever
1132 // the previously computed context was, and put the most
1133 // up-to-date context back in the map
1134 ReachGraph rgPrevContext = mapDescriptorToInitialContext.get( d );
1135 rg.merge( rgPrevContext );
1136 mapDescriptorToInitialContext.put( d, rg );
1140 case FKind.FlatOpNode:
1141 FlatOpNode fon = (FlatOpNode) fn;
1142 if( fon.getOp().getOp() == Operation.ASSIGN ) {
1143 lhs = fon.getDest();
1144 rhs = fon.getLeft();
1146 // before transfer, do effects analysis support
1147 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1148 if(rblockStatus.isInCriticalRegion(fmContaining, fn)){
1149 // x gets status of y
1150 if(!rg.isAccessible(rhs)){
1151 rg.makeInaccessible(lhs);
1157 rg.assignTempXEqualToTempY( lhs, rhs );
1161 case FKind.FlatCastNode:
1162 FlatCastNode fcn = (FlatCastNode) fn;
1166 TypeDescriptor td = fcn.getType();
1169 // before transfer, do effects analysis support
1170 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1171 if(rblockStatus.isInCriticalRegion(fmContaining, fn)){
1172 // x gets status of y
1173 if(!rg.isAccessible(rhs)){
1174 rg.makeInaccessible(lhs);
1180 rg.assignTempXEqualToCastedTempY( lhs, rhs, td );
1183 case FKind.FlatFieldNode:
1184 FlatFieldNode ffn = (FlatFieldNode) fn;
1188 fld = ffn.getField();
1190 // before graph transform, possible inject
1191 // a stall-site taint
1192 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1194 if(rblockStatus.isInCriticalRegion(fmContaining, fn)){
1195 // x=y.f, stall y if not accessible
1196 // contributes read effects on stall site of y
1197 if(!rg.isAccessible(rhs)) {
1198 rg.taintStallSite(fn, rhs);
1201 // after this, x and y are accessbile.
1202 rg.makeAccessible(lhs);
1203 rg.makeAccessible(rhs);
1207 if( shouldAnalysisTrack( fld.getType() ) ) {
1209 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fld );
1212 // after transfer, use updated graph to
1213 // do effects analysis
1214 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1215 effectsAnalysis.analyzeFlatFieldNode( rg, rhs, fld );
1219 case FKind.FlatSetFieldNode:
1220 FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
1222 lhs = fsfn.getDst();
1223 fld = fsfn.getField();
1224 rhs = fsfn.getSrc();
1226 boolean strongUpdate = false;
1228 // before transfer func, possibly inject
1229 // stall-site taints
1230 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1232 if(rblockStatus.isInCriticalRegion(fmContaining, fn)){
1233 // x.y=f , stall x and y if they are not accessible
1234 // also contribute write effects on stall site of x
1235 if(!rg.isAccessible(lhs)) {
1236 rg.taintStallSite(fn, lhs);
1239 if(!rg.isAccessible(rhs)) {
1240 rg.taintStallSite(fn, rhs);
1243 // accessible status update
1244 rg.makeAccessible(lhs);
1245 rg.makeAccessible(rhs);
1249 if( shouldAnalysisTrack( fld.getType() ) ) {
1251 strongUpdate = rg.assignTempXFieldFEqualToTempY( lhs, fld, rhs );
1254 // use transformed graph to do effects analysis
1255 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1256 effectsAnalysis.analyzeFlatSetFieldNode( rg, lhs, fld, strongUpdate );
1260 case FKind.FlatElementNode:
1261 FlatElementNode fen = (FlatElementNode) fn;
1266 assert rhs.getType() != null;
1267 assert rhs.getType().isArray();
1269 tdElement = rhs.getType().dereference();
1270 fdElement = getArrayField( tdElement );
1272 // before transfer func, possibly inject
1274 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1276 if(rblockStatus.isInCriticalRegion(fmContaining, fn)){
1277 // x=y.f, stall y if not accessible
1278 // contributes read effects on stall site of y
1279 // after this, x and y are accessbile.
1280 if(!rg.isAccessible(rhs)) {
1281 rg.taintStallSite(fn, rhs);
1284 rg.makeAccessible(lhs);
1285 rg.makeAccessible(rhs);
1289 if( shouldAnalysisTrack( lhs.getType() ) ) {
1291 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fdElement );
1294 // use transformed graph to do effects analysis
1295 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1296 effectsAnalysis.analyzeFlatFieldNode( rg, rhs, fdElement );
1300 case FKind.FlatSetElementNode:
1301 FlatSetElementNode fsen = (FlatSetElementNode) fn;
1303 lhs = fsen.getDst();
1304 rhs = fsen.getSrc();
1306 assert lhs.getType() != null;
1307 assert lhs.getType().isArray();
1309 tdElement = lhs.getType().dereference();
1310 fdElement = getArrayField( tdElement );
1312 // before transfer func, possibly inject
1313 // stall-site taints
1314 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1316 if(rblockStatus.isInCriticalRegion(fmContaining, fn)){
1317 // x.y=f , stall x and y if they are not accessible
1318 // also contribute write effects on stall site of x
1319 if(!rg.isAccessible(lhs)) {
1320 rg.taintStallSite(fn, lhs);
1323 if(!rg.isAccessible(rhs)) {
1324 rg.taintStallSite(fn, rhs);
1327 // accessible status update
1328 rg.makeAccessible(lhs);
1329 rg.makeAccessible(rhs);
1333 if( shouldAnalysisTrack( rhs.getType() ) ) {
1334 // transfer func, BUT
1335 // skip this node if it cannot create new reachability paths
1336 if( !arrayReferencees.doesNotCreateNewReaching( fsen ) ) {
1337 rg.assignTempXFieldFEqualToTempY( lhs, fdElement, rhs );
1341 // use transformed graph to do effects analysis
1342 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1343 effectsAnalysis.analyzeFlatSetFieldNode( rg, lhs, fdElement,
1349 FlatNew fnn = (FlatNew) fn;
1351 if( shouldAnalysisTrack( lhs.getType() ) ) {
1352 AllocSite as = getAllocSiteFromFlatNewPRIVATE( fnn );
1354 // before transform, support effects analysis
1355 if (doEffectsAnalysis && fmContaining != fmAnalysisEntry) {
1356 if (rblockStatus.isInCriticalRegion(fmContaining, fn)) {
1357 // after creating new object, lhs is accessible
1358 rg.makeAccessible(lhs);
1363 rg.assignTempEqualToNewAlloc( lhs, as );
1367 case FKind.FlatSESEEnterNode:
1368 sese = (FlatSESEEnterNode) fn;
1370 if( sese.getIsCallerSESEplaceholder() ) {
1371 // ignore these dummy rblocks!
1375 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1377 // always remove ALL stall site taints at enter
1378 rg.removeAllStallSiteTaints();
1380 // inject taints for in-set vars
1381 rg.taintInSetVars( sese );
1386 case FKind.FlatSESEExitNode:
1387 fsexn = (FlatSESEExitNode) fn;
1388 sese = fsexn.getFlatEnter();
1390 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1392 // @ sese exit make all live variables
1393 // inaccessible to later parent statements
1394 rg.makeInaccessible( liveness.getLiveInTemps( fmContaining, fn ) );
1396 // always remove ALL stall site taints at exit
1397 rg.removeAllStallSiteTaints();
1399 // remove in-set var taints for the exiting rblock
1400 rg.removeInContextTaints( sese );
1405 case FKind.FlatCall: {
1406 Descriptor mdCaller;
1407 if( fmContaining.getMethod() != null ){
1408 mdCaller = fmContaining.getMethod();
1410 mdCaller = fmContaining.getTask();
1412 FlatCall fc = (FlatCall) fn;
1413 MethodDescriptor mdCallee = fc.getMethod();
1414 FlatMethod fmCallee = state.getMethodFlat( mdCallee );
1416 boolean debugCallSite =
1417 mdCaller.getSymbol().equals( state.DISJOINTDEBUGCALLER ) &&
1418 mdCallee.getSymbol().equals( state.DISJOINTDEBUGCALLEE );
1420 boolean writeDebugDOTs = false;
1421 boolean stopAfter = false;
1422 if( debugCallSite ) {
1423 ++ReachGraph.debugCallSiteVisitCounter;
1424 System.out.println( " $$$ Debug call site visit "+
1425 ReachGraph.debugCallSiteVisitCounter+
1429 (ReachGraph.debugCallSiteVisitCounter >=
1430 ReachGraph.debugCallSiteVisitStartCapture) &&
1432 (ReachGraph.debugCallSiteVisitCounter <
1433 ReachGraph.debugCallSiteVisitStartCapture +
1434 ReachGraph.debugCallSiteNumVisitsToCapture)
1436 writeDebugDOTs = true;
1437 System.out.println( " $$$ Capturing this call site visit $$$" );
1438 if( ReachGraph.debugCallSiteStopAfter &&
1439 (ReachGraph.debugCallSiteVisitCounter ==
1440 ReachGraph.debugCallSiteVisitStartCapture +
1441 ReachGraph.debugCallSiteNumVisitsToCapture - 1)
1449 // calculate the heap this call site can reach--note this is
1450 // not used for the current call site transform, we are
1451 // grabbing this heap model for future analysis of the callees,
1452 // so if different results emerge we will return to this site
1453 ReachGraph heapForThisCall_old =
1454 getIHMcontribution( mdCallee, fc );
1456 // the computation of the callee-reachable heap
1457 // is useful for making the callee starting point
1458 // and for applying the call site transfer function
1459 Set<Integer> callerNodeIDsCopiedToCallee =
1460 new HashSet<Integer>();
1462 ReachGraph heapForThisCall_cur =
1463 rg.makeCalleeView( fc,
1465 callerNodeIDsCopiedToCallee,
1469 if( !heapForThisCall_cur.equals( heapForThisCall_old ) ) {
1470 // if heap at call site changed, update the contribution,
1471 // and reschedule the callee for analysis
1472 addIHMcontribution( mdCallee, fc, heapForThisCall_cur );
1474 // map a FlatCall to its enclosing method/task descriptor
1475 // so we can write that info out later
1476 fc2enclosing.put( fc, mdCaller );
1478 if( state.DISJOINTDEBUGSCHEDULING ) {
1479 System.out.println( " context changed, scheduling callee: "+mdCallee );
1482 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1483 calleesToEnqueue.add( mdCallee );
1485 enqueue( mdCallee );
1490 // the transformation for a call site should update the
1491 // current heap abstraction with any effects from the callee,
1492 // or if the method is virtual, the effects from any possible
1493 // callees, so find the set of callees...
1494 Set<MethodDescriptor> setPossibleCallees;
1495 if( determinismDesired ) {
1496 // use an ordered set
1497 setPossibleCallees = new TreeSet<MethodDescriptor>( dComp );
1499 // otherwise use a speedy hashset
1500 setPossibleCallees = new HashSet<MethodDescriptor>();
1503 if( mdCallee.isStatic() ) {
1504 setPossibleCallees.add( mdCallee );
1506 TypeDescriptor typeDesc = fc.getThis().getType();
1507 setPossibleCallees.addAll( callGraph.getMethods( mdCallee,
1512 ReachGraph rgMergeOfPossibleCallers = new ReachGraph();
1514 Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
1515 while( mdItr.hasNext() ) {
1516 MethodDescriptor mdPossible = mdItr.next();
1517 FlatMethod fmPossible = state.getMethodFlat( mdPossible );
1519 addDependent( mdPossible, // callee
1522 // don't alter the working graph (rg) until we compute a
1523 // result for every possible callee, merge them all together,
1524 // then set rg to that
1525 ReachGraph rgPossibleCaller = new ReachGraph();
1526 rgPossibleCaller.merge( rg );
1528 ReachGraph rgPossibleCallee = getPartial( mdPossible );
1530 if( rgPossibleCallee == null ) {
1531 // if this method has never been analyzed just schedule it
1532 // for analysis and skip over this call site for now
1533 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1534 calleesToEnqueue.add( mdPossible );
1536 enqueue( mdPossible );
1539 if( state.DISJOINTDEBUGSCHEDULING ) {
1540 System.out.println( " callee hasn't been analyzed, scheduling: "+mdPossible );
1545 // calculate the method call transform
1546 rgPossibleCaller.resolveMethodCall( fc,
1549 callerNodeIDsCopiedToCallee,
1553 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1554 if( !rgPossibleCallee.isAccessible( ReachGraph.tdReturn ) ) {
1555 rgPossibleCaller.makeInaccessible( fc.getReturnTemp() );
1561 rgMergeOfPossibleCallers.merge( rgPossibleCaller );
1566 System.out.println( "$$$ Exiting after requested captures of call site. $$$" );
1571 // now that we've taken care of building heap models for
1572 // callee analysis, finish this transformation
1573 rg = rgMergeOfPossibleCallers;
1577 case FKind.FlatReturnNode:
1578 FlatReturnNode frn = (FlatReturnNode) fn;
1579 rhs = frn.getReturnTemp();
1581 // before transfer, do effects analysis support
1582 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1583 if(!rg.isAccessible(rhs)){
1584 rg.makeInaccessible(ReachGraph.tdReturn);
1588 if( rhs != null && shouldAnalysisTrack( rhs.getType() ) ) {
1589 rg.assignReturnEqualToTemp( rhs );
1592 setRetNodes.add( frn );
1598 // dead variables were removed before the above transfer function
1599 // was applied, so eliminate heap regions and edges that are no
1600 // longer part of the abstractly-live heap graph, and sweep up
1601 // and reachability effects that are altered by the reduction
1602 //rg.abstractGarbageCollect();
1606 // back edges are strictly monotonic
1607 if( pm.isBackEdge( fn ) ) {
1608 ReachGraph rgPrevResult = mapBackEdgeToMonotone.get( fn );
1609 rg.merge( rgPrevResult );
1610 mapBackEdgeToMonotone.put( fn, rg );
1613 // at this point rg should be the correct update
1614 // by an above transfer function, or untouched if
1615 // the flat node type doesn't affect the heap
1621 // this method should generate integers strictly greater than zero!
1622 // special "shadow" regions are made from a heap region by negating
1624 static public Integer generateUniqueHeapRegionNodeID() {
1626 return new Integer( uniqueIDcount );
1631 static public FieldDescriptor getArrayField( TypeDescriptor tdElement ) {
1632 FieldDescriptor fdElement = mapTypeToArrayField.get( tdElement );
1633 if( fdElement == null ) {
1634 fdElement = new FieldDescriptor( new Modifiers( Modifiers.PUBLIC ),
1636 arrayElementFieldName,
1639 mapTypeToArrayField.put( tdElement, fdElement );
1646 private void writeFinalGraphs() {
1647 Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
1648 Iterator itr = entrySet.iterator();
1649 while( itr.hasNext() ) {
1650 Map.Entry me = (Map.Entry) itr.next();
1651 Descriptor d = (Descriptor) me.getKey();
1652 ReachGraph rg = (ReachGraph) me.getValue();
1654 rg.writeGraph( "COMPLETE"+d,
1655 true, // write labels (variables)
1656 true, // selectively hide intermediate temp vars
1657 true, // prune unreachable heap regions
1658 false, // hide reachability altogether
1659 true, // hide subset reachability states
1660 true, // hide predicates
1661 false ); // hide edge taints
1665 private void writeFinalIHMs() {
1666 Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
1667 while( d2IHMsItr.hasNext() ) {
1668 Map.Entry me1 = (Map.Entry) d2IHMsItr.next();
1669 Descriptor d = (Descriptor) me1.getKey();
1670 Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>) me1.getValue();
1672 Iterator fc2rgItr = IHMs.entrySet().iterator();
1673 while( fc2rgItr.hasNext() ) {
1674 Map.Entry me2 = (Map.Entry) fc2rgItr.next();
1675 FlatCall fc = (FlatCall) me2.getKey();
1676 ReachGraph rg = (ReachGraph) me2.getValue();
1678 rg.writeGraph( "IHMPARTFOR"+d+"FROM"+fc2enclosing.get( fc )+fc,
1679 true, // write labels (variables)
1680 true, // selectively hide intermediate temp vars
1681 true, // hide reachability altogether
1682 true, // prune unreachable heap regions
1683 true, // hide subset reachability states
1684 false, // hide predicates
1685 true ); // hide edge taints
1690 private void writeInitialContexts() {
1691 Set entrySet = mapDescriptorToInitialContext.entrySet();
1692 Iterator itr = entrySet.iterator();
1693 while( itr.hasNext() ) {
1694 Map.Entry me = (Map.Entry) itr.next();
1695 Descriptor d = (Descriptor) me.getKey();
1696 ReachGraph rg = (ReachGraph) me.getValue();
1698 rg.writeGraph( "INITIAL"+d,
1699 true, // write labels (variables)
1700 true, // selectively hide intermediate temp vars
1701 true, // prune unreachable heap regions
1702 false, // hide all reachability
1703 true, // hide subset reachability states
1704 true, // hide predicates
1705 false );// hide edge taints
1710 protected ReachGraph getPartial( Descriptor d ) {
1711 return mapDescriptorToCompleteReachGraph.get( d );
1714 protected void setPartial( Descriptor d, ReachGraph rg ) {
1715 mapDescriptorToCompleteReachGraph.put( d, rg );
1717 // when the flag for writing out every partial
1718 // result is set, we should spit out the graph,
1719 // but in order to give it a unique name we need
1720 // to track how many partial results for this
1721 // descriptor we've already written out
1722 if( writeAllIncrementalDOTs ) {
1723 if( !mapDescriptorToNumUpdates.containsKey( d ) ) {
1724 mapDescriptorToNumUpdates.put( d, new Integer( 0 ) );
1726 Integer n = mapDescriptorToNumUpdates.get( d );
1728 rg.writeGraph( d+"COMPLETE"+String.format( "%05d", n ),
1729 true, // write labels (variables)
1730 true, // selectively hide intermediate temp vars
1731 true, // prune unreachable heap regions
1732 false, // hide all reachability
1733 true, // hide subset reachability states
1734 false, // hide predicates
1735 false); // hide edge taints
1737 mapDescriptorToNumUpdates.put( d, n + 1 );
1743 // return just the allocation site associated with one FlatNew node
1744 protected AllocSite getAllocSiteFromFlatNewPRIVATE( FlatNew fnew ) {
1746 boolean flagProgrammatically = false;
1747 if( sitesToFlag != null && sitesToFlag.contains( fnew ) ) {
1748 flagProgrammatically = true;
1751 if( !mapFlatNewToAllocSite.containsKey( fnew ) ) {
1752 AllocSite as = AllocSite.factory( allocationDepth,
1754 fnew.getDisjointId(),
1755 flagProgrammatically
1758 // the newest nodes are single objects
1759 for( int i = 0; i < allocationDepth; ++i ) {
1760 Integer id = generateUniqueHeapRegionNodeID();
1761 as.setIthOldest( i, id );
1762 mapHrnIdToAllocSite.put( id, as );
1765 // the oldest node is a summary node
1766 as.setSummary( generateUniqueHeapRegionNodeID() );
1768 mapFlatNewToAllocSite.put( fnew, as );
1771 return mapFlatNewToAllocSite.get( fnew );
1775 public static boolean shouldAnalysisTrack( TypeDescriptor type ) {
1776 // don't track primitive types, but an array
1777 // of primitives is heap memory
1778 if( type.isImmutable() ) {
1779 return type.isArray();
1782 // everything else is an object
1786 protected int numMethodsAnalyzed() {
1787 return descriptorsToAnalyze.size();
1794 // Take in source entry which is the program's compiled entry and
1795 // create a new analysis entry, a method that takes no parameters
1796 // and appears to allocate the command line arguments and call the
1797 // source entry with them. The purpose of this analysis entry is
1798 // to provide a top-level method context with no parameters left.
1799 protected void makeAnalysisEntryMethod( MethodDescriptor mdSourceEntry ) {
1801 Modifiers mods = new Modifiers();
1802 mods.addModifier( Modifiers.PUBLIC );
1803 mods.addModifier( Modifiers.STATIC );
1805 TypeDescriptor returnType =
1806 new TypeDescriptor( TypeDescriptor.VOID );
1808 this.mdAnalysisEntry =
1809 new MethodDescriptor( mods,
1811 "analysisEntryMethod"
1814 TempDescriptor cmdLineArgs =
1815 new TempDescriptor( "args",
1816 mdSourceEntry.getParamType( 0 )
1820 new FlatNew( mdSourceEntry.getParamType( 0 ),
1825 TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
1826 sourceEntryArgs[0] = cmdLineArgs;
1829 new FlatCall( mdSourceEntry,
1835 FlatReturnNode frn = new FlatReturnNode( null );
1837 FlatExit fe = new FlatExit();
1839 this.fmAnalysisEntry =
1840 new FlatMethod( mdAnalysisEntry,
1844 this.fmAnalysisEntry.addNext( fn );
1851 protected LinkedList<Descriptor> topologicalSort( Set<Descriptor> toSort ) {
1853 Set<Descriptor> discovered;
1855 if( determinismDesired ) {
1856 // use an ordered set
1857 discovered = new TreeSet<Descriptor>( dComp );
1859 // otherwise use a speedy hashset
1860 discovered = new HashSet<Descriptor>();
1863 LinkedList<Descriptor> sorted = new LinkedList<Descriptor>();
1865 Iterator<Descriptor> itr = toSort.iterator();
1866 while( itr.hasNext() ) {
1867 Descriptor d = itr.next();
1869 if( !discovered.contains( d ) ) {
1870 dfsVisit( d, toSort, sorted, discovered );
1877 // While we're doing DFS on call graph, remember
1878 // dependencies for efficient queuing of methods
1879 // during interprocedural analysis:
1881 // a dependent of a method decriptor d for this analysis is:
1882 // 1) a method or task that invokes d
1883 // 2) in the descriptorsToAnalyze set
1884 protected void dfsVisit( Descriptor d,
1885 Set <Descriptor> toSort,
1886 LinkedList<Descriptor> sorted,
1887 Set <Descriptor> discovered ) {
1888 discovered.add( d );
1890 // only methods have callers, tasks never do
1891 if( d instanceof MethodDescriptor ) {
1893 MethodDescriptor md = (MethodDescriptor) d;
1895 // the call graph is not aware that we have a fabricated
1896 // analysis entry that calls the program source's entry
1897 if( md == mdSourceEntry ) {
1898 if( !discovered.contains( mdAnalysisEntry ) ) {
1899 addDependent( mdSourceEntry, // callee
1900 mdAnalysisEntry // caller
1902 dfsVisit( mdAnalysisEntry, toSort, sorted, discovered );
1906 // otherwise call graph guides DFS
1907 Iterator itr = callGraph.getCallerSet( md ).iterator();
1908 while( itr.hasNext() ) {
1909 Descriptor dCaller = (Descriptor) itr.next();
1911 // only consider callers in the original set to analyze
1912 if( !toSort.contains( dCaller ) ) {
1916 if( !discovered.contains( dCaller ) ) {
1917 addDependent( md, // callee
1921 dfsVisit( dCaller, toSort, sorted, discovered );
1926 // for leaf-nodes last now!
1927 sorted.addLast( d );
1931 protected void enqueue( Descriptor d ) {
1933 if( !descriptorsToVisitSet.contains( d ) ) {
1935 if( state.DISJOINTDVISITSTACK ||
1936 state.DISJOINTDVISITSTACKEESONTOP
1938 descriptorsToVisitStack.add( d );
1940 } else if( state.DISJOINTDVISITPQUE ) {
1941 Integer priority = mapDescriptorToPriority.get( d );
1942 descriptorsToVisitQ.add( new DescriptorQWrapper( priority,
1947 descriptorsToVisitSet.add( d );
1952 // a dependent of a method decriptor d for this analysis is:
1953 // 1) a method or task that invokes d
1954 // 2) in the descriptorsToAnalyze set
1955 protected void addDependent( Descriptor callee, Descriptor caller ) {
1956 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1957 if( deps == null ) {
1958 deps = new HashSet<Descriptor>();
1961 mapDescriptorToSetDependents.put( callee, deps );
1964 protected Set<Descriptor> getDependents( Descriptor callee ) {
1965 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1966 if( deps == null ) {
1967 deps = new HashSet<Descriptor>();
1968 mapDescriptorToSetDependents.put( callee, deps );
1974 public Hashtable<FlatCall, ReachGraph> getIHMcontributions( Descriptor d ) {
1976 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1977 mapDescriptorToIHMcontributions.get( d );
1979 if( heapsFromCallers == null ) {
1980 heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
1981 mapDescriptorToIHMcontributions.put( d, heapsFromCallers );
1984 return heapsFromCallers;
1987 public ReachGraph getIHMcontribution( Descriptor d,
1990 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1991 getIHMcontributions( d );
1993 if( !heapsFromCallers.containsKey( fc ) ) {
1997 return heapsFromCallers.get( fc );
2001 public void addIHMcontribution( Descriptor d,
2005 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2006 getIHMcontributions( d );
2008 heapsFromCallers.put( fc, rg );
2012 private AllocSite createParameterAllocSite( ReachGraph rg,
2013 TempDescriptor tempDesc,
2019 flatNew = new FlatNew( tempDesc.getType(), // type
2020 tempDesc, // param temp
2021 false, // global alloc?
2022 "param"+tempDesc // disjoint site ID string
2025 flatNew = new FlatNew( tempDesc.getType(), // type
2026 tempDesc, // param temp
2027 false, // global alloc?
2028 null // disjoint site ID string
2032 // create allocation site
2033 AllocSite as = AllocSite.factory( allocationDepth,
2035 flatNew.getDisjointId(),
2038 for (int i = 0; i < allocationDepth; ++i) {
2039 Integer id = generateUniqueHeapRegionNodeID();
2040 as.setIthOldest(i, id);
2041 mapHrnIdToAllocSite.put(id, as);
2043 // the oldest node is a summary node
2044 as.setSummary( generateUniqueHeapRegionNodeID() );
2052 private Set<FieldDescriptor> getFieldSetTobeAnalyzed(TypeDescriptor typeDesc){
2054 Set<FieldDescriptor> fieldSet=new HashSet<FieldDescriptor>();
2055 if(!typeDesc.isImmutable()){
2056 ClassDescriptor classDesc = typeDesc.getClassDesc();
2057 for (Iterator it = classDesc.getFields(); it.hasNext();) {
2058 FieldDescriptor field = (FieldDescriptor) it.next();
2059 TypeDescriptor fieldType = field.getType();
2060 if (shouldAnalysisTrack( fieldType )) {
2061 fieldSet.add(field);
2069 private HeapRegionNode createMultiDeimensionalArrayHRN(ReachGraph rg, AllocSite alloc, HeapRegionNode srcHRN, FieldDescriptor fd, Hashtable<HeapRegionNode, HeapRegionNode> map, Hashtable<TypeDescriptor, HeapRegionNode> mapToExistingNode, ReachSet alpha ){
2071 int dimCount=fd.getType().getArrayCount();
2072 HeapRegionNode prevNode=null;
2073 HeapRegionNode arrayEntryNode=null;
2074 for(int i=dimCount;i>0;i--){
2075 TypeDescriptor typeDesc=fd.getType().dereference();//hack to get instance of type desc
2076 typeDesc.setArrayCount(i);
2077 TempDescriptor tempDesc=new TempDescriptor(typeDesc.getSymbol(),typeDesc);
2078 HeapRegionNode hrnSummary ;
2079 if(!mapToExistingNode.containsKey(typeDesc)){
2084 as = createParameterAllocSite(rg, tempDesc, false);
2086 // make a new reference to allocated node
2088 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
2089 false, // single object?
2091 false, // out-of-context?
2092 as.getType(), // type
2093 as, // allocation site
2094 alpha, // inherent reach
2095 alpha, // current reach
2096 ExistPredSet.factory(rg.predTrue), // predicates
2097 tempDesc.toString() // description
2099 rg.id2hrn.put(as.getSummary(),hrnSummary);
2101 mapToExistingNode.put(typeDesc, hrnSummary);
2103 hrnSummary=mapToExistingNode.get(typeDesc);
2107 // make a new reference between new summary node and source
2108 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2111 fd.getSymbol(), // field name
2113 ExistPredSet.factory(rg.predTrue), // predicates
2117 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
2118 prevNode=hrnSummary;
2119 arrayEntryNode=hrnSummary;
2121 // make a new reference between summary nodes of array
2122 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2125 arrayElementFieldName, // field name
2127 ExistPredSet.factory(rg.predTrue), // predicates
2131 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2132 prevNode=hrnSummary;
2137 // create a new obj node if obj has at least one non-primitive field
2138 TypeDescriptor type=fd.getType();
2139 if(getFieldSetTobeAnalyzed(type).size()>0){
2140 TypeDescriptor typeDesc=type.dereference();
2141 typeDesc.setArrayCount(0);
2142 if(!mapToExistingNode.containsKey(typeDesc)){
2143 TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc);
2144 AllocSite as = createParameterAllocSite(rg, tempDesc, false);
2145 // make a new reference to allocated node
2146 HeapRegionNode hrnSummary =
2147 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
2148 false, // single object?
2150 false, // out-of-context?
2152 as, // allocation site
2153 alpha, // inherent reach
2154 alpha, // current reach
2155 ExistPredSet.factory(rg.predTrue), // predicates
2156 tempDesc.toString() // description
2158 rg.id2hrn.put(as.getSummary(),hrnSummary);
2159 mapToExistingNode.put(typeDesc, hrnSummary);
2160 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2163 arrayElementFieldName, // field name
2165 ExistPredSet.factory(rg.predTrue), // predicates
2168 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2169 prevNode=hrnSummary;
2171 HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc);
2172 if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null){
2173 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2176 arrayElementFieldName, // field name
2178 ExistPredSet.factory(rg.predTrue), // predicates
2181 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2183 prevNode=hrnSummary;
2187 map.put(arrayEntryNode, prevNode);
2188 return arrayEntryNode;
2191 private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
2192 ReachGraph rg = new ReachGraph();
2193 TaskDescriptor taskDesc = fm.getTask();
2195 for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
2196 Descriptor paramDesc = taskDesc.getParameter(idx);
2197 TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
2199 // setup data structure
2200 Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet =
2201 new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
2202 Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode =
2203 new Hashtable<TypeDescriptor, HeapRegionNode>();
2204 Hashtable<HeapRegionNode, HeapRegionNode> mapToFirstDimensionArrayNode =
2205 new Hashtable<HeapRegionNode, HeapRegionNode>();
2206 Set<String> doneSet = new HashSet<String>();
2208 TempDescriptor tempDesc = fm.getParameter(idx);
2210 AllocSite as = createParameterAllocSite(rg, tempDesc, true);
2211 VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
2212 Integer idNewest = as.getIthOldest(0);
2213 HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
2215 // make a new reference to allocated node
2216 RefEdge edgeNew = new RefEdge(lnX, // source
2218 taskDesc.getParamType(idx), // type
2220 hrnNewest.getAlpha(), // beta
2221 ExistPredSet.factory(rg.predTrue), // predicates
2224 rg.addRefEdge(lnX, hrnNewest, edgeNew);
2226 // set-up a work set for class field
2227 ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
2228 for (Iterator it = classDesc.getFields(); it.hasNext();) {
2229 FieldDescriptor fd = (FieldDescriptor) it.next();
2230 TypeDescriptor fieldType = fd.getType();
2231 if (shouldAnalysisTrack( fieldType )) {
2232 HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
2233 newMap.put(hrnNewest, fd);
2234 workSet.add(newMap);
2238 int uniqueIdentifier = 0;
2239 while (!workSet.isEmpty()) {
2240 HashMap<HeapRegionNode, FieldDescriptor> map = workSet
2242 workSet.remove(map);
2244 Set<HeapRegionNode> key = map.keySet();
2245 HeapRegionNode srcHRN = key.iterator().next();
2246 FieldDescriptor fd = map.get(srcHRN);
2247 TypeDescriptor type = fd.getType();
2248 String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
2250 if (!doneSet.contains(doneSetIdentifier)) {
2251 doneSet.add(doneSetIdentifier);
2252 if (!mapTypeToExistingSummaryNode.containsKey(type)) {
2253 // create new summary Node
2254 TempDescriptor td = new TempDescriptor("temp"
2255 + uniqueIdentifier, type);
2257 AllocSite allocSite;
2258 if(type.equals(paramTypeDesc)){
2259 //corresponding allocsite has already been created for a parameter variable.
2262 allocSite = createParameterAllocSite(rg, td, false);
2264 String strDesc = allocSite.toStringForDOT()
2266 TypeDescriptor allocType=allocSite.getType();
2268 HeapRegionNode hrnSummary;
2269 if(allocType.isArray() && allocType.getArrayCount()>0){
2270 hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha());
2273 rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
2274 false, // single object?
2276 false, // out-of-context?
2277 allocSite.getType(), // type
2278 allocSite, // allocation site
2279 hrnNewest.getAlpha(), // inherent reach
2280 hrnNewest.getAlpha(), // current reach
2281 ExistPredSet.factory(rg.predTrue), // predicates
2282 strDesc // description
2284 rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
2286 // make a new reference to summary node
2287 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2290 fd.getSymbol(), // field name
2291 hrnNewest.getAlpha(), // beta
2292 ExistPredSet.factory(rg.predTrue), // predicates
2296 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
2300 mapTypeToExistingSummaryNode.put(type, hrnSummary);
2302 // set-up a work set for fields of the class
2303 Set<FieldDescriptor> fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type);
2304 for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator
2306 FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator
2308 HeapRegionNode newDstHRN;
2309 if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)){
2310 //related heap region node is already exsited.
2311 newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary);
2313 newDstHRN=hrnSummary;
2315 doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor;
2316 if(!doneSet.contains(doneSetIdentifier)){
2317 // add new work item
2318 HashMap<HeapRegionNode, FieldDescriptor> newMap =
2319 new HashMap<HeapRegionNode, FieldDescriptor>();
2320 newMap.put(newDstHRN, fieldDescriptor);
2321 workSet.add(newMap);
2326 // if there exists corresponding summary node
2327 HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
2329 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2331 fd.getType(), // type
2332 fd.getSymbol(), // field name
2333 srcHRN.getAlpha(), // beta
2334 ExistPredSet.factory(rg.predTrue), // predicates
2337 rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
2343 // debugSnapshot(rg, fm, true);
2347 // return all allocation sites in the method (there is one allocation
2348 // site per FlatNew node in a method)
2349 private HashSet<AllocSite> getAllocationSiteSet(Descriptor d) {
2350 if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
2351 buildAllocationSiteSet(d);
2354 return mapDescriptorToAllocSiteSet.get(d);
2358 private void buildAllocationSiteSet(Descriptor d) {
2359 HashSet<AllocSite> s = new HashSet<AllocSite>();
2362 if( d instanceof MethodDescriptor ) {
2363 fm = state.getMethodFlat( (MethodDescriptor) d);
2365 assert d instanceof TaskDescriptor;
2366 fm = state.getMethodFlat( (TaskDescriptor) d);
2368 pm.analyzeMethod(fm);
2370 // visit every node in this FlatMethod's IR graph
2371 // and make a set of the allocation sites from the
2372 // FlatNew node's visited
2373 HashSet<FlatNode> visited = new HashSet<FlatNode>();
2374 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
2377 while( !toVisit.isEmpty() ) {
2378 FlatNode n = toVisit.iterator().next();
2380 if( n instanceof FlatNew ) {
2381 s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
2387 for( int i = 0; i < pm.numNext(n); ++i ) {
2388 FlatNode child = pm.getNext(n, i);
2389 if( !visited.contains(child) ) {
2395 mapDescriptorToAllocSiteSet.put(d, s);
2398 private HashSet<AllocSite> getFlaggedAllocationSites(Descriptor dIn) {
2400 HashSet<AllocSite> out = new HashSet<AllocSite>();
2401 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2402 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2406 while (!toVisit.isEmpty()) {
2407 Descriptor d = toVisit.iterator().next();
2411 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2412 Iterator asItr = asSet.iterator();
2413 while (asItr.hasNext()) {
2414 AllocSite as = (AllocSite) asItr.next();
2415 if (as.getDisjointAnalysisId() != null) {
2420 // enqueue callees of this method to be searched for
2421 // allocation sites also
2422 Set callees = callGraph.getCalleeSet(d);
2423 if (callees != null) {
2424 Iterator methItr = callees.iterator();
2425 while (methItr.hasNext()) {
2426 MethodDescriptor md = (MethodDescriptor) methItr.next();
2428 if (!visited.contains(md)) {
2439 private HashSet<AllocSite>
2440 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
2442 HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
2443 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2444 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2448 // traverse this task and all methods reachable from this task
2449 while( !toVisit.isEmpty() ) {
2450 Descriptor d = toVisit.iterator().next();
2454 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2455 Iterator asItr = asSet.iterator();
2456 while( asItr.hasNext() ) {
2457 AllocSite as = (AllocSite) asItr.next();
2458 TypeDescriptor typed = as.getType();
2459 if( typed != null ) {
2460 ClassDescriptor cd = typed.getClassDesc();
2461 if( cd != null && cd.hasFlags() ) {
2467 // enqueue callees of this method to be searched for
2468 // allocation sites also
2469 Set callees = callGraph.getCalleeSet(d);
2470 if( callees != null ) {
2471 Iterator methItr = callees.iterator();
2472 while( methItr.hasNext() ) {
2473 MethodDescriptor md = (MethodDescriptor) methItr.next();
2475 if( !visited.contains(md) ) {
2485 public Set<Descriptor> getDescriptorsToAnalyze() {
2486 return descriptorsToAnalyze;
2489 public EffectsAnalysis getEffectsAnalysis(){
2490 return effectsAnalysis;
2493 public ReachGraph getReachGraph(Descriptor d){
2494 return mapDescriptorToCompleteReachGraph.get(d);
2498 // get successive captures of the analysis state, use compiler
2500 boolean takeDebugSnapshots = false;
2501 String descSymbolDebug = null;
2502 boolean stopAfterCapture = false;
2503 int snapVisitCounter = 0;
2504 int snapNodeCounter = 0;
2505 int visitStartCapture = 0;
2506 int numVisitsToCapture = 0;
2509 void debugSnapshot( ReachGraph rg, FlatNode fn, boolean in ) {
2510 if( snapVisitCounter > visitStartCapture + numVisitsToCapture ) {
2518 if( snapVisitCounter >= visitStartCapture ) {
2519 System.out.println( " @@@ snapping visit="+snapVisitCounter+
2520 ", node="+snapNodeCounter+
2524 graphName = String.format( "snap%03d_%04din",
2528 graphName = String.format( "snap%03d_%04dout",
2533 graphName = graphName + fn;
2535 rg.writeGraph( graphName,
2536 true, // write labels (variables)
2537 true, // selectively hide intermediate temp vars
2538 true, // prune unreachable heap regions
2539 false, // hide reachability
2540 true, // hide subset reachability states
2541 true, // hide predicates
2542 false );// hide edge taints