1 package Analysis.Disjoint;
3 import Analysis.CallGraph.*;
4 import Analysis.Liveness;
5 import Analysis.ArrayReferencees;
6 import Analysis.OoOJava.RBlockRelationAnalysis;
9 import IR.Tree.Modifiers;
14 public class DisjointAnalysis {
16 ///////////////////////////////////////////
18 // Public interface to discover possible
19 // sharing in the program under analysis
21 ///////////////////////////////////////////
23 // if an object allocated at the target site may be
24 // reachable from both an object from root1 and an
25 // object allocated at root2, return TRUE
26 public boolean mayBothReachTarget( FlatMethod fm,
31 AllocSite asr1 = getAllocationSiteFromFlatNew( fnRoot1 );
32 AllocSite asr2 = getAllocationSiteFromFlatNew( fnRoot2 );
33 assert asr1.isFlagged();
34 assert asr2.isFlagged();
36 AllocSite ast = getAllocationSiteFromFlatNew( fnTarget );
37 ReachGraph rg = getPartial( fm.getMethod() );
39 return rg.mayBothReachTarget( asr1, asr2, ast );
42 // similar to the method above, return TRUE if ever
43 // more than one object from the root allocation site
44 // may reach an object from the target site
45 public boolean mayManyReachTarget( FlatMethod fm,
49 AllocSite asr = getAllocationSiteFromFlatNew( fnRoot );
50 assert asr.isFlagged();
52 AllocSite ast = getAllocationSiteFromFlatNew( fnTarget );
53 ReachGraph rg = getPartial( fm.getMethod() );
55 return rg.mayManyReachTarget( asr, ast );
61 public HashSet<AllocSite>
62 getFlaggedAllocationSitesReachableFromTask(TaskDescriptor td) {
63 checkAnalysisComplete();
64 return getFlaggedAllocationSitesReachableFromTaskPRIVATE(td);
67 public AllocSite getAllocationSiteFromFlatNew(FlatNew fn) {
68 checkAnalysisComplete();
69 return getAllocSiteFromFlatNewPRIVATE(fn);
72 public AllocSite getAllocationSiteFromHeapRegionNodeID(Integer id) {
73 checkAnalysisComplete();
74 return mapHrnIdToAllocSite.get(id);
77 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
80 checkAnalysisComplete();
81 ReachGraph rg=mapDescriptorToCompleteReachGraph.get(taskOrMethod);
82 FlatMethod fm=state.getMethodFlat(taskOrMethod);
84 return rg.mayReachSharedObjects(fm, paramIndex1, paramIndex2);
87 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
88 int paramIndex, AllocSite alloc) {
89 checkAnalysisComplete();
90 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
91 FlatMethod fm=state.getMethodFlat(taskOrMethod);
93 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
96 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
97 AllocSite alloc, int paramIndex) {
98 checkAnalysisComplete();
99 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
100 FlatMethod fm=state.getMethodFlat(taskOrMethod);
102 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
105 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
106 AllocSite alloc1, AllocSite alloc2) {
107 checkAnalysisComplete();
108 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
110 return rg.mayReachSharedObjects(alloc1, alloc2);
113 public String prettyPrintNodeSet(Set<HeapRegionNode> s) {
114 checkAnalysisComplete();
118 Iterator<HeapRegionNode> i = s.iterator();
119 while (i.hasNext()) {
120 HeapRegionNode n = i.next();
122 AllocSite as = n.getAllocSite();
124 out += " " + n.toString() + ",\n";
126 out += " " + n.toString() + ": " + as.toStringVerbose()
135 // use the methods given above to check every possible sharing class
136 // between task parameters and flagged allocation sites reachable
138 public void writeAllSharing(String outputFile,
141 boolean tabularOutput,
144 throws java.io.IOException {
145 checkAnalysisComplete();
147 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
149 if (!tabularOutput) {
150 bw.write("Conducting ownership analysis with allocation depth = "
151 + allocationDepth + "\n");
152 bw.write(timeReport + "\n");
157 // look through every task for potential sharing
158 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
159 while (taskItr.hasNext()) {
160 TaskDescriptor td = (TaskDescriptor) taskItr.next();
162 if (!tabularOutput) {
163 bw.write("\n---------" + td + "--------\n");
166 HashSet<AllocSite> allocSites = getFlaggedAllocationSitesReachableFromTask(td);
168 Set<HeapRegionNode> common;
170 // for each task parameter, check for sharing classes with
171 // other task parameters and every allocation site
172 // reachable from this task
173 boolean foundSomeSharing = false;
175 FlatMethod fm = state.getMethodFlat(td);
176 for (int i = 0; i < fm.numParameters(); ++i) {
178 // skip parameters with types that cannot reference
180 if( !shouldAnalysisTrack( fm.getParameter( i ).getType() ) ) {
184 // for the ith parameter check for sharing classes to all
185 // higher numbered parameters
186 for (int j = i + 1; j < fm.numParameters(); ++j) {
188 // skip parameters with types that cannot reference
190 if( !shouldAnalysisTrack( fm.getParameter( j ).getType() ) ) {
195 common = hasPotentialSharing(td, i, j);
196 if (!common.isEmpty()) {
197 foundSomeSharing = true;
199 if (!tabularOutput) {
200 bw.write("Potential sharing between parameters " + i
201 + " and " + j + ".\n");
202 bw.write(prettyPrintNodeSet(common) + "\n");
207 // for the ith parameter, check for sharing classes against
208 // the set of allocation sites reachable from this
210 Iterator allocItr = allocSites.iterator();
211 while (allocItr.hasNext()) {
212 AllocSite as = (AllocSite) allocItr.next();
213 common = hasPotentialSharing(td, i, as);
214 if (!common.isEmpty()) {
215 foundSomeSharing = true;
217 if (!tabularOutput) {
218 bw.write("Potential sharing between parameter " + i
219 + " and " + as.getFlatNew() + ".\n");
220 bw.write(prettyPrintNodeSet(common) + "\n");
226 // for each allocation site check for sharing classes with
227 // other allocation sites in the context of execution
229 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
230 Iterator allocItr1 = allocSites.iterator();
231 while (allocItr1.hasNext()) {
232 AllocSite as1 = (AllocSite) allocItr1.next();
234 Iterator allocItr2 = allocSites.iterator();
235 while (allocItr2.hasNext()) {
236 AllocSite as2 = (AllocSite) allocItr2.next();
238 if (!outerChecked.contains(as2)) {
239 common = hasPotentialSharing(td, as1, as2);
241 if (!common.isEmpty()) {
242 foundSomeSharing = true;
244 if (!tabularOutput) {
245 bw.write("Potential sharing between "
246 + as1.getFlatNew() + " and "
247 + as2.getFlatNew() + ".\n");
248 bw.write(prettyPrintNodeSet(common) + "\n");
254 outerChecked.add(as1);
257 if (!foundSomeSharing) {
258 if (!tabularOutput) {
259 bw.write("No sharing between flagged objects in Task " + td
267 bw.write(" & " + numSharing + " & " + justTime + " & " + numLines
268 + " & " + numMethodsAnalyzed() + " \\\\\n");
270 bw.write("\nNumber sharing classes: "+numSharing);
278 // this version of writeAllSharing is for Java programs that have no tasks
279 // ***********************************
280 // WARNING: THIS DOES NOT DO THE RIGHT THING, REPORTS 0 ALWAYS!
281 // It should use mayBothReachTarget and mayManyReachTarget like
282 // OoOJava does to query analysis results
283 // ***********************************
284 public void writeAllSharingJava(String outputFile,
287 boolean tabularOutput,
290 throws java.io.IOException {
291 checkAnalysisComplete();
297 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
299 bw.write("Conducting disjoint reachability analysis with allocation depth = "
300 + allocationDepth + "\n");
301 bw.write(timeReport + "\n\n");
303 boolean foundSomeSharing = false;
305 Descriptor d = typeUtil.getMain();
306 HashSet<AllocSite> allocSites = getFlaggedAllocationSites(d);
308 // for each allocation site check for sharing classes with
309 // other allocation sites in the context of execution
311 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
312 Iterator allocItr1 = allocSites.iterator();
313 while (allocItr1.hasNext()) {
314 AllocSite as1 = (AllocSite) allocItr1.next();
316 Iterator allocItr2 = allocSites.iterator();
317 while (allocItr2.hasNext()) {
318 AllocSite as2 = (AllocSite) allocItr2.next();
320 if (!outerChecked.contains(as2)) {
321 Set<HeapRegionNode> common = hasPotentialSharing(d,
324 if (!common.isEmpty()) {
325 foundSomeSharing = true;
326 bw.write("Potential sharing between "
327 + as1.getDisjointAnalysisId() + " and "
328 + as2.getDisjointAnalysisId() + ".\n");
329 bw.write(prettyPrintNodeSet(common) + "\n");
335 outerChecked.add(as1);
338 if (!foundSomeSharing) {
339 bw.write("No sharing classes between flagged objects found.\n");
341 bw.write("\nNumber sharing classes: "+numSharing);
344 bw.write("Number of methods analyzed: "+numMethodsAnalyzed()+"\n");
349 ///////////////////////////////////////////
351 // end public interface
353 ///////////////////////////////////////////
357 protected void checkAnalysisComplete() {
358 if( !analysisComplete ) {
359 throw new Error("Warning: public interface method called while analysis is running.");
368 // run in faster mode, only when bugs wrung out!
369 public static boolean releaseMode;
371 // use command line option to set this, analysis
372 // should attempt to be deterministic
373 public static boolean determinismDesired;
375 // when we want to enforce determinism in the
376 // analysis we need to sort descriptors rather
377 // than toss them in efficient sets, use this
378 public static DescriptorComparator dComp =
379 new DescriptorComparator();
382 // data from the compiler
384 public CallGraph callGraph;
385 public Liveness liveness;
386 public ArrayReferencees arrayReferencees;
387 public RBlockRelationAnalysis rblockRel;
388 public TypeUtil typeUtil;
389 public int allocationDepth;
391 protected boolean doEffectsAnalysis = false;
392 protected EffectsAnalysis effectsAnalysis;
394 // data structure for public interface
395 private Hashtable< Descriptor, HashSet<AllocSite> >
396 mapDescriptorToAllocSiteSet;
399 // for public interface methods to warn that they
400 // are grabbing results during analysis
401 private boolean analysisComplete;
404 // used to identify HeapRegionNode objects
405 // A unique ID equates an object in one
406 // ownership graph with an object in another
407 // graph that logically represents the same
409 // start at 10 and increment to reserve some
410 // IDs for special purposes
411 static protected int uniqueIDcount = 10;
414 // An out-of-scope method created by the
415 // analysis that has no parameters, and
416 // appears to allocate the command line
417 // arguments, then invoke the source code's
418 // main method. The purpose of this is to
419 // provide the analysis with an explicit
420 // top-level context with no parameters
421 protected MethodDescriptor mdAnalysisEntry;
422 protected FlatMethod fmAnalysisEntry;
424 // main method defined by source program
425 protected MethodDescriptor mdSourceEntry;
427 // the set of task and/or method descriptors
428 // reachable in call graph
429 protected Set<Descriptor>
430 descriptorsToAnalyze;
432 // current descriptors to visit in fixed-point
433 // interprocedural analysis, prioritized by
434 // dependency in the call graph
435 protected Stack<Descriptor>
436 descriptorsToVisitStack;
437 protected PriorityQueue<DescriptorQWrapper>
440 // a duplication of the above structure, but
441 // for efficient testing of inclusion
442 protected HashSet<Descriptor>
443 descriptorsToVisitSet;
445 // storage for priorities (doesn't make sense)
446 // to add it to the Descriptor class, just in
448 protected Hashtable<Descriptor, Integer>
449 mapDescriptorToPriority;
451 // when analyzing a method and scheduling more:
452 // remember set of callee's enqueued for analysis
453 // so they can be put on top of the callers in
454 // the stack-visit mode
455 protected Set<Descriptor>
458 // maps a descriptor to its current partial result
459 // from the intraprocedural fixed-point analysis--
460 // then the interprocedural analysis settles, this
461 // mapping will have the final results for each
463 protected Hashtable<Descriptor, ReachGraph>
464 mapDescriptorToCompleteReachGraph;
466 // maps a descriptor to its known dependents: namely
467 // methods or tasks that call the descriptor's method
468 // AND are part of this analysis (reachable from main)
469 protected Hashtable< Descriptor, Set<Descriptor> >
470 mapDescriptorToSetDependents;
472 // if the analysis client wants to flag allocation sites
473 // programmatically, it should provide a set of FlatNew
474 // statements--this may be null if unneeded
475 protected Set<FlatNew> sitesToFlag;
477 // maps each flat new to one analysis abstraction
478 // allocate site object, these exist outside reach graphs
479 protected Hashtable<FlatNew, AllocSite>
480 mapFlatNewToAllocSite;
482 // maps intergraph heap region IDs to intergraph
483 // allocation sites that created them, a redundant
484 // structure for efficiency in some operations
485 protected Hashtable<Integer, AllocSite>
488 // maps a method to its initial heap model (IHM) that
489 // is the set of reachability graphs from every caller
490 // site, all merged together. The reason that we keep
491 // them separate is that any one call site's contribution
492 // to the IHM may changed along the path to the fixed point
493 protected Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >
494 mapDescriptorToIHMcontributions;
496 // additionally, keep a mapping from descriptors to the
497 // merged in-coming initial context, because we want this
498 // initial context to be STRICTLY MONOTONIC
499 protected Hashtable<Descriptor, ReachGraph>
500 mapDescriptorToInitialContext;
502 // make the result for back edges analysis-wide STRICTLY
503 // MONOTONIC as well, but notice we use FlatNode as the
504 // key for this map: in case we want to consider other
505 // nodes as back edge's in future implementations
506 protected Hashtable<FlatNode, ReachGraph>
507 mapBackEdgeToMonotone;
510 public static final String arrayElementFieldName = "___element_";
511 static protected Hashtable<TypeDescriptor, FieldDescriptor>
515 protected boolean suppressOutput;
517 // for controlling DOT file output
518 protected boolean writeFinalDOTs;
519 protected boolean writeAllIncrementalDOTs;
521 // supporting DOT output--when we want to write every
522 // partial method result, keep a tally for generating
524 protected Hashtable<Descriptor, Integer>
525 mapDescriptorToNumUpdates;
527 //map task descriptor to initial task parameter
528 protected Hashtable<Descriptor, ReachGraph>
529 mapDescriptorToReachGraph;
531 protected PointerMethod pm;
533 //Keeps track of all the reach graphs at every program point
534 //DO NOT USE UNLESS YOU REALLY NEED IT
535 static protected Hashtable<FlatNode, ReachGraph> fn2rgAtEnter =
536 new Hashtable<FlatNode, ReachGraph>();
538 private Hashtable<FlatCall, Descriptor> fc2enclosing;
541 // allocate various structures that are not local
542 // to a single class method--should be done once
543 protected void allocateStructures() {
545 if( determinismDesired ) {
546 // use an ordered set
547 descriptorsToAnalyze = new TreeSet<Descriptor>( dComp );
549 // otherwise use a speedy hashset
550 descriptorsToAnalyze = new HashSet<Descriptor>();
553 mapDescriptorToCompleteReachGraph =
554 new Hashtable<Descriptor, ReachGraph>();
556 mapDescriptorToNumUpdates =
557 new Hashtable<Descriptor, Integer>();
559 mapDescriptorToSetDependents =
560 new Hashtable< Descriptor, Set<Descriptor> >();
562 mapFlatNewToAllocSite =
563 new Hashtable<FlatNew, AllocSite>();
565 mapDescriptorToIHMcontributions =
566 new Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >();
568 mapDescriptorToInitialContext =
569 new Hashtable<Descriptor, ReachGraph>();
571 mapBackEdgeToMonotone =
572 new Hashtable<FlatNode, ReachGraph>();
574 mapHrnIdToAllocSite =
575 new Hashtable<Integer, AllocSite>();
577 mapTypeToArrayField =
578 new Hashtable <TypeDescriptor, FieldDescriptor>();
580 if( state.DISJOINTDVISITSTACK ||
581 state.DISJOINTDVISITSTACKEESONTOP
583 descriptorsToVisitStack =
584 new Stack<Descriptor>();
587 if( state.DISJOINTDVISITPQUE ) {
588 descriptorsToVisitQ =
589 new PriorityQueue<DescriptorQWrapper>();
592 descriptorsToVisitSet =
593 new HashSet<Descriptor>();
595 mapDescriptorToPriority =
596 new Hashtable<Descriptor, Integer>();
599 new HashSet<Descriptor>();
601 mapDescriptorToAllocSiteSet =
602 new Hashtable<Descriptor, HashSet<AllocSite> >();
604 mapDescriptorToReachGraph =
605 new Hashtable<Descriptor, ReachGraph>();
607 pm = new PointerMethod();
609 fc2enclosing = new Hashtable<FlatCall, Descriptor>();
614 // this analysis generates a disjoint reachability
615 // graph for every reachable method in the program
616 public DisjointAnalysis( State s,
621 Set<FlatNew> sitesToFlag,
622 RBlockRelationAnalysis rra
624 init( s, tu, cg, l, ar, sitesToFlag, rra, false );
627 public DisjointAnalysis( State s,
632 Set<FlatNew> sitesToFlag,
633 RBlockRelationAnalysis rra,
634 boolean suppressOutput
636 init( s, tu, cg, l, ar, sitesToFlag, rra, suppressOutput );
639 protected void init( State state,
643 ArrayReferencees arrayReferencees,
644 Set<FlatNew> sitesToFlag,
645 RBlockRelationAnalysis rra,
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.suppressOutput = suppressOutput;
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;
691 ReachGraph.state = state;
694 ReachGraph.debugCallSiteVisitStartCapture
695 = state.DISJOINTDEBUGCALLVISITTOSTART;
697 ReachGraph.debugCallSiteNumVisitsToCapture
698 = state.DISJOINTDEBUGCALLNUMVISITS;
700 ReachGraph.debugCallSiteStopAfter
701 = state.DISJOINTDEBUGCALLSTOPAFTER;
703 ReachGraph.debugCallSiteVisitCounter
704 = 0; // count visits from 1, is incremented before first visit
706 if( suppressOutput ) {
707 System.out.println( "* Running disjoint reachability analysis with output suppressed! *" );
710 allocateStructures();
712 double timeStartAnalysis = (double) System.nanoTime();
714 // start interprocedural fixed-point computation
717 } catch( IOException e ) {
718 throw new Error( "IO Exception while writing disjointness analysis output." );
721 analysisComplete=true;
724 double timeEndAnalysis = (double) System.nanoTime();
725 double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
728 if( sitesToFlag != null ) {
729 treport = String.format( "Disjoint reachability analysis flagged %d sites and took %.3f sec.", sitesToFlag.size(), dt );
730 if(sitesToFlag.size()>0){
731 treport+="\nFlagged sites:"+"\n"+sitesToFlag.toString();
734 treport = String.format( "Disjoint reachability analysis took %.3f sec.", dt );
736 String justtime = String.format( "%.2f", dt );
737 System.out.println( treport );
741 if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
745 if( state.DISJOINTWRITEIHMS && !suppressOutput ) {
749 if( state.DISJOINTWRITEINITCONTEXTS && !suppressOutput ) {
750 writeInitialContexts();
753 if( state.DISJOINTALIASFILE != null && !suppressOutput ) {
755 writeAllSharing(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines);
757 writeAllSharingJava(state.DISJOINTALIASFILE,
760 state.DISJOINTALIASTAB,
765 } catch( IOException e ) {
766 throw new Error( "IO Exception while writing disjointness analysis output." );
772 protected boolean moreDescriptorsToVisit() {
773 if( state.DISJOINTDVISITSTACK ||
774 state.DISJOINTDVISITSTACKEESONTOP
776 return !descriptorsToVisitStack.isEmpty();
778 } else if( state.DISJOINTDVISITPQUE ) {
779 return !descriptorsToVisitQ.isEmpty();
782 throw new Error( "Neither descriptor visiting mode set" );
786 // fixed-point computation over the call graph--when a
787 // method's callees are updated, it must be reanalyzed
788 protected void analyzeMethods() throws java.io.IOException {
790 // task or non-task (java) mode determines what the roots
791 // of the call chain are, and establishes the set of methods
792 // reachable from the roots that will be analyzed
795 if( !suppressOutput ) {
796 System.out.println( "Bamboo mode..." );
799 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
800 while( taskItr.hasNext() ) {
801 TaskDescriptor td = (TaskDescriptor) taskItr.next();
802 if( !descriptorsToAnalyze.contains( td ) ) {
803 // add all methods transitively reachable from the
805 descriptorsToAnalyze.add( td );
806 descriptorsToAnalyze.addAll( callGraph.getAllMethods( td ) );
811 if( !suppressOutput ) {
812 System.out.println( "Java mode..." );
815 // add all methods transitively reachable from the
816 // source's main to set for analysis
817 mdSourceEntry = typeUtil.getMain();
818 descriptorsToAnalyze.add( mdSourceEntry );
819 descriptorsToAnalyze.addAll( callGraph.getAllMethods( mdSourceEntry ) );
821 // fabricate an empty calling context that will call
822 // the source's main, but call graph doesn't know
823 // about it, so explicitly add it
824 makeAnalysisEntryMethod( mdSourceEntry );
825 descriptorsToAnalyze.add( mdAnalysisEntry );
829 // now, depending on the interprocedural mode for visiting
830 // methods, set up the needed data structures
832 if( state.DISJOINTDVISITPQUE ) {
834 // topologically sort according to the call graph so
835 // leaf calls are last, helps build contexts up first
836 LinkedList<Descriptor> sortedDescriptors =
837 topologicalSort( descriptorsToAnalyze );
839 // add sorted descriptors to priority queue, and duplicate
840 // the queue as a set for efficiently testing whether some
841 // method is marked for analysis
843 Iterator<Descriptor> dItr;
845 // for the priority queue, give items at the head
846 // of the sorted list a low number (highest priority)
847 while( !sortedDescriptors.isEmpty() ) {
848 Descriptor d = sortedDescriptors.removeFirst();
849 mapDescriptorToPriority.put( d, new Integer( p ) );
850 descriptorsToVisitQ.add( new DescriptorQWrapper( p, d ) );
851 descriptorsToVisitSet.add( d );
855 } else if( state.DISJOINTDVISITSTACK ||
856 state.DISJOINTDVISITSTACKEESONTOP
858 // if we're doing the stack scheme, just throw the root
859 // method or tasks on the stack
861 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
862 while( taskItr.hasNext() ) {
863 TaskDescriptor td = (TaskDescriptor) taskItr.next();
864 descriptorsToVisitStack.add( td );
865 descriptorsToVisitSet.add( td );
869 descriptorsToVisitStack.add( mdAnalysisEntry );
870 descriptorsToVisitSet.add( mdAnalysisEntry );
874 throw new Error( "Unknown method scheduling mode" );
878 // analyze scheduled methods until there are no more to visit
879 while( moreDescriptorsToVisit() ) {
882 if( state.DISJOINTDVISITSTACK ||
883 state.DISJOINTDVISITSTACKEESONTOP
885 d = descriptorsToVisitStack.pop();
887 } else if( state.DISJOINTDVISITPQUE ) {
888 d = descriptorsToVisitQ.poll().getDescriptor();
891 assert descriptorsToVisitSet.contains( d );
892 descriptorsToVisitSet.remove( d );
894 // because the task or method descriptor just extracted
895 // was in the "to visit" set it either hasn't been analyzed
896 // yet, or some method that it depends on has been
897 // updated. Recompute a complete reachability graph for
898 // this task/method and compare it to any previous result.
899 // If there is a change detected, add any methods/tasks
900 // that depend on this one to the "to visit" set.
902 if( !suppressOutput ) {
903 System.out.println( "Analyzing " + d );
906 if( state.DISJOINTDVISITSTACKEESONTOP ) {
907 assert calleesToEnqueue.isEmpty();
910 ReachGraph rg = analyzeMethod( d );
911 ReachGraph rgPrev = getPartial( d );
913 if( !rg.equals( rgPrev ) ) {
916 if( state.DISJOINTDEBUGSCHEDULING ) {
917 System.out.println( " complete graph changed, scheduling callers for analysis:" );
920 // results for d changed, so enqueue dependents
921 // of d for further analysis
922 Iterator<Descriptor> depsItr = getDependents( d ).iterator();
923 while( depsItr.hasNext() ) {
924 Descriptor dNext = depsItr.next();
927 if( state.DISJOINTDEBUGSCHEDULING ) {
928 System.out.println( " "+dNext );
933 // whether or not the method under analysis changed,
934 // we may have some callees that are scheduled for
935 // more analysis, and they should go on the top of
936 // the stack now (in other method-visiting modes they
937 // are already enqueued at this point
938 if( state.DISJOINTDVISITSTACKEESONTOP ) {
939 Iterator<Descriptor> depsItr = calleesToEnqueue.iterator();
940 while( depsItr.hasNext() ) {
941 Descriptor dNext = depsItr.next();
944 calleesToEnqueue.clear();
950 protected ReachGraph analyzeMethod( Descriptor d )
951 throws java.io.IOException {
953 // get the flat code for this descriptor
955 if( d == mdAnalysisEntry ) {
956 fm = fmAnalysisEntry;
958 fm = state.getMethodFlat( d );
960 pm.analyzeMethod( fm );
962 // intraprocedural work set
963 Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
964 flatNodesToVisit.add( fm );
966 // if determinism is desired by client, shadow the
967 // set with a queue to make visit order deterministic
968 Queue<FlatNode> flatNodesToVisitQ = null;
969 if( determinismDesired ) {
970 flatNodesToVisitQ = new LinkedList<FlatNode>();
971 flatNodesToVisitQ.add( fm );
974 // mapping of current partial results
975 Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraph =
976 new Hashtable<FlatNode, ReachGraph>();
978 // the set of return nodes partial results that will be combined as
979 // the final, conservative approximation of the entire method
980 HashSet<FlatReturnNode> setReturns = new HashSet<FlatReturnNode>();
982 while( !flatNodesToVisit.isEmpty() ) {
985 if( determinismDesired ) {
986 assert !flatNodesToVisitQ.isEmpty();
987 fn = flatNodesToVisitQ.remove();
989 fn = flatNodesToVisit.iterator().next();
991 flatNodesToVisit.remove( fn );
993 // effect transfer function defined by this node,
994 // then compare it to the old graph at this node
995 // to see if anything was updated.
997 ReachGraph rg = new ReachGraph();
998 TaskDescriptor taskDesc;
999 if(fn instanceof FlatMethod && (taskDesc=((FlatMethod)fn).getTask())!=null){
1000 if(mapDescriptorToReachGraph.containsKey(taskDesc)){
1001 // retrieve existing reach graph if it is not first time
1002 rg=mapDescriptorToReachGraph.get(taskDesc);
1004 // create initial reach graph for a task
1005 rg=createInitialTaskReachGraph((FlatMethod)fn);
1007 mapDescriptorToReachGraph.put(taskDesc, rg);
1011 // start by merging all node's parents' graphs
1012 for( int i = 0; i < pm.numPrev(fn); ++i ) {
1013 FlatNode pn = pm.getPrev(fn,i);
1014 if( mapFlatNodeToReachGraph.containsKey( pn ) ) {
1015 ReachGraph rgParent = mapFlatNodeToReachGraph.get( pn );
1016 rg.merge( rgParent );
1021 if( takeDebugSnapshots &&
1022 d.getSymbol().equals( descSymbolDebug )
1024 debugSnapshot( rg, fn, true );
1028 // modify rg with appropriate transfer function
1029 rg = analyzeFlatNode( d, fm, fn, setReturns, rg );
1032 if( takeDebugSnapshots &&
1033 d.getSymbol().equals( descSymbolDebug )
1035 debugSnapshot( rg, fn, false );
1040 // if the results of the new graph are different from
1041 // the current graph at this node, replace the graph
1042 // with the update and enqueue the children
1043 ReachGraph rgPrev = mapFlatNodeToReachGraph.get( fn );
1044 if( !rg.equals( rgPrev ) ) {
1045 mapFlatNodeToReachGraph.put( fn, rg );
1047 for( int i = 0; i < pm.numNext( fn ); i++ ) {
1048 FlatNode nn = pm.getNext( fn, i );
1050 flatNodesToVisit.add( nn );
1051 if( determinismDesired ) {
1052 flatNodesToVisitQ.add( nn );
1059 // end by merging all return nodes into a complete
1060 // reach graph that represents all possible heap
1061 // states after the flat method returns
1062 ReachGraph completeGraph = new ReachGraph();
1064 assert !setReturns.isEmpty();
1065 Iterator retItr = setReturns.iterator();
1066 while( retItr.hasNext() ) {
1067 FlatReturnNode frn = (FlatReturnNode) retItr.next();
1069 assert mapFlatNodeToReachGraph.containsKey( frn );
1070 ReachGraph rgRet = mapFlatNodeToReachGraph.get( frn );
1072 completeGraph.merge( rgRet );
1076 if( takeDebugSnapshots &&
1077 d.getSymbol().equals( descSymbolDebug )
1079 // increment that we've visited the debug snap
1080 // method, and reset the node counter
1081 System.out.println( " @@@ debug snap at visit "+snapVisitCounter );
1083 snapNodeCounter = 0;
1085 if( snapVisitCounter == visitStartCapture + numVisitsToCapture &&
1088 System.out.println( "!!! Stopping analysis after debug snap captures. !!!" );
1094 return completeGraph;
1098 protected ReachGraph
1099 analyzeFlatNode( Descriptor d,
1100 FlatMethod fmContaining,
1102 HashSet<FlatReturnNode> setRetNodes,
1104 ) throws java.io.IOException {
1107 // any variables that are no longer live should be
1108 // nullified in the graph to reduce edges
1109 //rg.nullifyDeadVars( liveness.getLiveInTemps( fmContaining, fn ) );
1113 FieldDescriptor fld;
1114 TypeDescriptor tdElement;
1115 FieldDescriptor fdElement;
1116 FlatSESEEnterNode sese;
1117 FlatSESEExitNode fsexn;
1119 //Stores the flatnode's reach graph at enter
1120 ReachGraph rgOnEnter = new ReachGraph();
1121 rgOnEnter.merge( rg );
1122 fn2rgAtEnter.put(fn, rgOnEnter);
1124 // use node type to decide what transfer function
1125 // to apply to the reachability graph
1126 switch( fn.kind() ) {
1128 case FKind.FlatGenReachNode: {
1129 FlatGenReachNode fgrn = (FlatGenReachNode) fn;
1131 System.out.println( " Generating reach graph for program point: "+fgrn.getGraphName() );
1133 rg.writeGraph( "genReach"+fgrn.getGraphName(),
1134 true, // write labels (variables)
1135 true, // selectively hide intermediate temp vars
1136 true, // prune unreachable heap regions
1137 true, // hide reachability altogether
1138 false, // hide subset reachability states
1139 true, // hide predicates
1140 false ); // hide edge taints
1144 case FKind.FlatMethod: {
1145 // construct this method's initial heap model (IHM)
1146 // since we're working on the FlatMethod, we know
1147 // the incoming ReachGraph 'rg' is empty
1149 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1150 getIHMcontributions( d );
1152 Set entrySet = heapsFromCallers.entrySet();
1153 Iterator itr = entrySet.iterator();
1154 while( itr.hasNext() ) {
1155 Map.Entry me = (Map.Entry) itr.next();
1156 FlatCall fc = (FlatCall) me.getKey();
1157 ReachGraph rgContrib = (ReachGraph) me.getValue();
1159 assert fc.getMethod().equals( d );
1161 rg.merge( rgContrib );
1164 // additionally, we are enforcing STRICT MONOTONICITY for the
1165 // method's initial context, so grow the context by whatever
1166 // the previously computed context was, and put the most
1167 // up-to-date context back in the map
1168 ReachGraph rgPrevContext = mapDescriptorToInitialContext.get( d );
1169 rg.merge( rgPrevContext );
1170 mapDescriptorToInitialContext.put( d, rg );
1174 case FKind.FlatOpNode:
1175 FlatOpNode fon = (FlatOpNode) fn;
1176 if( fon.getOp().getOp() == Operation.ASSIGN ) {
1177 lhs = fon.getDest();
1178 rhs = fon.getLeft();
1180 // before transfer, do effects analysis support
1181 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1182 if(rblockRel.isPotentialStallSite(fn)){
1183 // x gets status of y
1184 if(!rg.isAccessible(rhs)){
1185 rg.makeInaccessible(lhs);
1191 rg.assignTempXEqualToTempY( lhs, rhs );
1195 case FKind.FlatCastNode:
1196 FlatCastNode fcn = (FlatCastNode) fn;
1200 TypeDescriptor td = fcn.getType();
1203 // before transfer, do effects analysis support
1204 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1205 if(rblockRel.isPotentialStallSite(fn)){
1206 // x gets status of y
1207 if(!rg.isAccessible(rhs)){
1208 rg.makeInaccessible(lhs);
1214 rg.assignTempXEqualToCastedTempY( lhs, rhs, td );
1217 case FKind.FlatFieldNode:
1218 FlatFieldNode ffn = (FlatFieldNode) fn;
1222 fld = ffn.getField();
1224 // before graph transform, possible inject
1225 // a stall-site taint
1226 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1228 if(rblockRel.isPotentialStallSite(fn)){
1229 // x=y.f, stall y if not accessible
1230 // contributes read effects on stall site of y
1231 if(!rg.isAccessible(rhs)) {
1232 rg.taintStallSite(fn, rhs);
1235 // after this, x and y are accessbile.
1236 rg.makeAccessible(lhs);
1237 rg.makeAccessible(rhs);
1241 if( shouldAnalysisTrack( fld.getType() ) ) {
1243 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fld );
1246 // after transfer, use updated graph to
1247 // do effects analysis
1248 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1249 effectsAnalysis.analyzeFlatFieldNode( rg, rhs, fld );
1253 case FKind.FlatSetFieldNode:
1254 FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
1256 lhs = fsfn.getDst();
1257 fld = fsfn.getField();
1258 rhs = fsfn.getSrc();
1260 boolean strongUpdate = false;
1262 // before transfer func, possibly inject
1263 // stall-site taints
1264 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1266 if(rblockRel.isPotentialStallSite(fn)){
1267 // x.y=f , stall x and y if they are not accessible
1268 // also contribute write effects on stall site of x
1269 if(!rg.isAccessible(lhs)) {
1270 rg.taintStallSite(fn, lhs);
1273 if(!rg.isAccessible(rhs)) {
1274 rg.taintStallSite(fn, rhs);
1277 // accessible status update
1278 rg.makeAccessible(lhs);
1279 rg.makeAccessible(rhs);
1283 if( shouldAnalysisTrack( fld.getType() ) ) {
1285 strongUpdate = rg.assignTempXFieldFEqualToTempY( lhs, fld, rhs );
1288 // use transformed graph to do effects analysis
1289 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1290 effectsAnalysis.analyzeFlatSetFieldNode( rg, lhs, fld, strongUpdate );
1294 case FKind.FlatElementNode:
1295 FlatElementNode fen = (FlatElementNode) fn;
1300 assert rhs.getType() != null;
1301 assert rhs.getType().isArray();
1303 tdElement = rhs.getType().dereference();
1304 fdElement = getArrayField( tdElement );
1306 // before transfer func, possibly inject
1308 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1309 if(rblockRel.isPotentialStallSite(fn)){
1310 // x=y.f, stall y if not accessible
1311 // contributes read effects on stall site of y
1312 // after this, x and y are accessbile.
1313 if(!rg.isAccessible(rhs)) {
1314 rg.taintStallSite(fn, rhs);
1317 rg.makeAccessible(lhs);
1318 rg.makeAccessible(rhs);
1322 if( shouldAnalysisTrack( lhs.getType() ) ) {
1324 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fdElement );
1327 // use transformed graph to do effects analysis
1328 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1329 effectsAnalysis.analyzeFlatFieldNode( rg, rhs, fdElement );
1333 case FKind.FlatSetElementNode:
1334 FlatSetElementNode fsen = (FlatSetElementNode) fn;
1336 lhs = fsen.getDst();
1337 rhs = fsen.getSrc();
1339 assert lhs.getType() != null;
1340 assert lhs.getType().isArray();
1342 tdElement = lhs.getType().dereference();
1343 fdElement = getArrayField( tdElement );
1345 // before transfer func, possibly inject
1346 // stall-site taints
1347 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1349 if(rblockRel.isPotentialStallSite(fn)){
1350 // x.y=f , stall x and y if they are not accessible
1351 // also contribute write effects on stall site of x
1352 if(!rg.isAccessible(lhs)) {
1353 rg.taintStallSite(fn, lhs);
1356 if(!rg.isAccessible(rhs)) {
1357 rg.taintStallSite(fn, rhs);
1360 // accessible status update
1361 rg.makeAccessible(lhs);
1362 rg.makeAccessible(rhs);
1366 if( shouldAnalysisTrack( rhs.getType() ) ) {
1367 // transfer func, BUT
1368 // skip this node if it cannot create new reachability paths
1369 if( !arrayReferencees.doesNotCreateNewReaching( fsen ) ) {
1370 rg.assignTempXFieldFEqualToTempY( lhs, fdElement, rhs );
1374 // use transformed graph to do effects analysis
1375 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1376 effectsAnalysis.analyzeFlatSetFieldNode( rg, lhs, fdElement,
1382 FlatNew fnn = (FlatNew) fn;
1384 if( shouldAnalysisTrack( lhs.getType() ) ) {
1385 AllocSite as = getAllocSiteFromFlatNewPRIVATE( fnn );
1387 // before transform, support effects analysis
1388 if (doEffectsAnalysis && fmContaining != fmAnalysisEntry) {
1389 if (rblockRel.isPotentialStallSite(fn)) {
1390 // after creating new object, lhs is accessible
1391 rg.makeAccessible(lhs);
1396 rg.assignTempEqualToNewAlloc( lhs, as );
1400 case FKind.FlatSESEEnterNode:
1401 sese = (FlatSESEEnterNode) fn;
1403 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1405 // always remove ALL stall site taints at enter
1406 rg.removeAllStallSiteTaints();
1408 // inject taints for in-set vars
1409 rg.taintInSetVars( sese );
1414 case FKind.FlatSESEExitNode:
1415 fsexn = (FlatSESEExitNode) fn;
1416 sese = fsexn.getFlatEnter();
1418 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1420 // @ sese exit make all live variables
1421 // inaccessible to later parent statements
1422 rg.makeInaccessible( liveness.getLiveInTemps( fmContaining, fn ) );
1424 // always remove ALL stall site taints at exit
1425 rg.removeAllStallSiteTaints();
1427 // remove in-set var taints for the exiting rblock
1428 rg.removeInContextTaints( sese );
1433 case FKind.FlatCall: {
1434 Descriptor mdCaller;
1435 if( fmContaining.getMethod() != null ){
1436 mdCaller = fmContaining.getMethod();
1438 mdCaller = fmContaining.getTask();
1440 FlatCall fc = (FlatCall) fn;
1441 MethodDescriptor mdCallee = fc.getMethod();
1442 FlatMethod fmCallee = state.getMethodFlat( mdCallee );
1445 if( mdCallee.getSymbol().equals( "genReach" ) ) {
1446 rg.writeGraph( "genReach"+d,
1447 true, // write labels (variables)
1448 true, // selectively hide intermediate temp vars
1449 true, // prune unreachable heap regions
1450 false, // hide reachability altogether
1451 true, // hide subset reachability states
1452 true, // hide predicates
1453 true ); // hide edge taints
1459 boolean debugCallSite =
1460 mdCaller.getSymbol().equals( state.DISJOINTDEBUGCALLER ) &&
1461 mdCallee.getSymbol().equals( state.DISJOINTDEBUGCALLEE );
1463 boolean writeDebugDOTs = false;
1464 boolean stopAfter = false;
1465 if( debugCallSite ) {
1466 ++ReachGraph.debugCallSiteVisitCounter;
1467 System.out.println( " $$$ Debug call site visit "+
1468 ReachGraph.debugCallSiteVisitCounter+
1472 (ReachGraph.debugCallSiteVisitCounter >=
1473 ReachGraph.debugCallSiteVisitStartCapture) &&
1475 (ReachGraph.debugCallSiteVisitCounter <
1476 ReachGraph.debugCallSiteVisitStartCapture +
1477 ReachGraph.debugCallSiteNumVisitsToCapture)
1479 writeDebugDOTs = true;
1480 System.out.println( " $$$ Capturing this call site visit $$$" );
1481 if( ReachGraph.debugCallSiteStopAfter &&
1482 (ReachGraph.debugCallSiteVisitCounter ==
1483 ReachGraph.debugCallSiteVisitStartCapture +
1484 ReachGraph.debugCallSiteNumVisitsToCapture - 1)
1492 // calculate the heap this call site can reach--note this is
1493 // not used for the current call site transform, we are
1494 // grabbing this heap model for future analysis of the callees,
1495 // so if different results emerge we will return to this site
1496 ReachGraph heapForThisCall_old =
1497 getIHMcontribution( mdCallee, fc );
1499 // the computation of the callee-reachable heap
1500 // is useful for making the callee starting point
1501 // and for applying the call site transfer function
1502 Set<Integer> callerNodeIDsCopiedToCallee =
1503 new HashSet<Integer>();
1505 ReachGraph heapForThisCall_cur =
1506 rg.makeCalleeView( fc,
1508 callerNodeIDsCopiedToCallee,
1512 // enforce that a call site contribution can only
1513 // monotonically increase
1514 heapForThisCall_cur.merge( heapForThisCall_old );
1516 if( !heapForThisCall_cur.equals( heapForThisCall_old ) ) {
1517 // if heap at call site changed, update the contribution,
1518 // and reschedule the callee for analysis
1519 addIHMcontribution( mdCallee, fc, heapForThisCall_cur );
1521 // map a FlatCall to its enclosing method/task descriptor
1522 // so we can write that info out later
1523 fc2enclosing.put( fc, mdCaller );
1525 if( state.DISJOINTDEBUGSCHEDULING ) {
1526 System.out.println( " context changed, scheduling callee: "+mdCallee );
1529 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1530 calleesToEnqueue.add( mdCallee );
1532 enqueue( mdCallee );
1537 // the transformation for a call site should update the
1538 // current heap abstraction with any effects from the callee,
1539 // or if the method is virtual, the effects from any possible
1540 // callees, so find the set of callees...
1541 Set<MethodDescriptor> setPossibleCallees;
1542 if( determinismDesired ) {
1543 // use an ordered set
1544 setPossibleCallees = new TreeSet<MethodDescriptor>( dComp );
1546 // otherwise use a speedy hashset
1547 setPossibleCallees = new HashSet<MethodDescriptor>();
1550 if( mdCallee.isStatic() ) {
1551 setPossibleCallees.add( mdCallee );
1553 TypeDescriptor typeDesc = fc.getThis().getType();
1554 setPossibleCallees.addAll( callGraph.getMethods( mdCallee,
1559 ReachGraph rgMergeOfPossibleCallers = new ReachGraph();
1561 Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
1562 while( mdItr.hasNext() ) {
1563 MethodDescriptor mdPossible = mdItr.next();
1564 FlatMethod fmPossible = state.getMethodFlat( mdPossible );
1566 addDependent( mdPossible, // callee
1569 // don't alter the working graph (rg) until we compute a
1570 // result for every possible callee, merge them all together,
1571 // then set rg to that
1572 ReachGraph rgPossibleCaller = new ReachGraph();
1573 rgPossibleCaller.merge( rg );
1575 ReachGraph rgPossibleCallee = getPartial( mdPossible );
1577 if( rgPossibleCallee == null ) {
1578 // if this method has never been analyzed just schedule it
1579 // for analysis and skip over this call site for now
1580 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1581 calleesToEnqueue.add( mdPossible );
1583 enqueue( mdPossible );
1586 if( state.DISJOINTDEBUGSCHEDULING ) {
1587 System.out.println( " callee hasn't been analyzed, scheduling: "+mdPossible );
1591 // calculate the method call transform
1592 rgPossibleCaller.resolveMethodCall( fc,
1595 callerNodeIDsCopiedToCallee,
1599 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1600 if( !rgPossibleCallee.isAccessible( ReachGraph.tdReturn ) ) {
1601 rgPossibleCaller.makeInaccessible( fc.getReturnTemp() );
1607 rgMergeOfPossibleCallers.merge( rgPossibleCaller );
1612 System.out.println( "$$$ Exiting after requested captures of call site. $$$" );
1617 // now that we've taken care of building heap models for
1618 // callee analysis, finish this transformation
1619 rg = rgMergeOfPossibleCallers;
1622 // jjenista: what is this? It breaks compilation
1623 // of programs with no tasks/SESEs/rblocks...
1624 //XXXXXXXXXXXXXXXXXXXXXXXXX
1625 //need to consider more
1626 FlatNode nextFN=fmCallee.getNext(0);
1627 if( nextFN instanceof FlatSESEEnterNode ) {
1628 FlatSESEEnterNode calleeSESE=(FlatSESEEnterNode)nextFN;
1629 if(!calleeSESE.getIsLeafSESE()){
1630 rg.makeInaccessible( liveness.getLiveInTemps( fmContaining, fn ) );
1637 case FKind.FlatReturnNode:
1638 FlatReturnNode frn = (FlatReturnNode) fn;
1639 rhs = frn.getReturnTemp();
1641 // before transfer, do effects analysis support
1642 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1643 if(!rg.isAccessible(rhs)){
1644 rg.makeInaccessible(ReachGraph.tdReturn);
1648 if( rhs != null && shouldAnalysisTrack( rhs.getType() ) ) {
1649 rg.assignReturnEqualToTemp( rhs );
1652 setRetNodes.add( frn );
1658 // dead variables were removed before the above transfer function
1659 // was applied, so eliminate heap regions and edges that are no
1660 // longer part of the abstractly-live heap graph, and sweep up
1661 // and reachability effects that are altered by the reduction
1662 //rg.abstractGarbageCollect();
1666 // back edges are strictly monotonic
1667 if( pm.isBackEdge( fn ) ) {
1668 ReachGraph rgPrevResult = mapBackEdgeToMonotone.get( fn );
1669 rg.merge( rgPrevResult );
1670 mapBackEdgeToMonotone.put( fn, rg );
1673 // at this point rg should be the correct update
1674 // by an above transfer function, or untouched if
1675 // the flat node type doesn't affect the heap
1681 // this method should generate integers strictly greater than zero!
1682 // special "shadow" regions are made from a heap region by negating
1684 static public Integer generateUniqueHeapRegionNodeID() {
1686 return new Integer( uniqueIDcount );
1691 static public FieldDescriptor getArrayField( TypeDescriptor tdElement ) {
1692 FieldDescriptor fdElement = mapTypeToArrayField.get( tdElement );
1693 if( fdElement == null ) {
1694 fdElement = new FieldDescriptor( new Modifiers( Modifiers.PUBLIC ),
1696 arrayElementFieldName,
1699 mapTypeToArrayField.put( tdElement, fdElement );
1706 private void writeFinalGraphs() {
1707 Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
1708 Iterator itr = entrySet.iterator();
1709 while( itr.hasNext() ) {
1710 Map.Entry me = (Map.Entry) itr.next();
1711 Descriptor d = (Descriptor) me.getKey();
1712 ReachGraph rg = (ReachGraph) me.getValue();
1715 if( d instanceof TaskDescriptor ) {
1716 graphName = "COMPLETEtask"+d;
1718 graphName = "COMPLETE"+d;
1721 rg.writeGraph( graphName,
1722 true, // write labels (variables)
1723 true, // selectively hide intermediate temp vars
1724 true, // prune unreachable heap regions
1725 false, // hide reachability altogether
1726 true, // hide subset reachability states
1727 true, // hide predicates
1728 false ); // hide edge taints
1732 private void writeFinalIHMs() {
1733 Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
1734 while( d2IHMsItr.hasNext() ) {
1735 Map.Entry me1 = (Map.Entry) d2IHMsItr.next();
1736 Descriptor d = (Descriptor) me1.getKey();
1737 Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>) me1.getValue();
1739 Iterator fc2rgItr = IHMs.entrySet().iterator();
1740 while( fc2rgItr.hasNext() ) {
1741 Map.Entry me2 = (Map.Entry) fc2rgItr.next();
1742 FlatCall fc = (FlatCall) me2.getKey();
1743 ReachGraph rg = (ReachGraph) me2.getValue();
1745 rg.writeGraph( "IHMPARTFOR"+d+"FROM"+fc2enclosing.get( fc )+fc,
1746 true, // write labels (variables)
1747 true, // selectively hide intermediate temp vars
1748 true, // hide reachability altogether
1749 true, // prune unreachable heap regions
1750 true, // hide subset reachability states
1751 false, // hide predicates
1752 true ); // hide edge taints
1757 private void writeInitialContexts() {
1758 Set entrySet = mapDescriptorToInitialContext.entrySet();
1759 Iterator itr = entrySet.iterator();
1760 while( itr.hasNext() ) {
1761 Map.Entry me = (Map.Entry) itr.next();
1762 Descriptor d = (Descriptor) me.getKey();
1763 ReachGraph rg = (ReachGraph) me.getValue();
1765 rg.writeGraph( "INITIAL"+d,
1766 true, // write labels (variables)
1767 true, // selectively hide intermediate temp vars
1768 true, // prune unreachable heap regions
1769 false, // hide all reachability
1770 true, // hide subset reachability states
1771 true, // hide predicates
1772 false );// hide edge taints
1777 protected ReachGraph getPartial( Descriptor d ) {
1778 return mapDescriptorToCompleteReachGraph.get( d );
1781 protected void setPartial( Descriptor d, ReachGraph rg ) {
1782 mapDescriptorToCompleteReachGraph.put( d, rg );
1784 // when the flag for writing out every partial
1785 // result is set, we should spit out the graph,
1786 // but in order to give it a unique name we need
1787 // to track how many partial results for this
1788 // descriptor we've already written out
1789 if( writeAllIncrementalDOTs ) {
1790 if( !mapDescriptorToNumUpdates.containsKey( d ) ) {
1791 mapDescriptorToNumUpdates.put( d, new Integer( 0 ) );
1793 Integer n = mapDescriptorToNumUpdates.get( d );
1796 if( d instanceof TaskDescriptor ) {
1797 graphName = d+"COMPLETEtask"+String.format( "%05d", n );
1799 graphName = d+"COMPLETE"+String.format( "%05d", n );
1802 rg.writeGraph( graphName,
1803 true, // write labels (variables)
1804 true, // selectively hide intermediate temp vars
1805 true, // prune unreachable heap regions
1806 false, // hide all reachability
1807 true, // hide subset reachability states
1808 false, // hide predicates
1809 false); // hide edge taints
1811 mapDescriptorToNumUpdates.put( d, n + 1 );
1817 // return just the allocation site associated with one FlatNew node
1818 protected AllocSite getAllocSiteFromFlatNewPRIVATE( FlatNew fnew ) {
1820 boolean flagProgrammatically = false;
1821 if( sitesToFlag != null && sitesToFlag.contains( fnew ) ) {
1822 flagProgrammatically = true;
1825 if( !mapFlatNewToAllocSite.containsKey( fnew ) ) {
1826 AllocSite as = AllocSite.factory( allocationDepth,
1828 fnew.getDisjointId(),
1829 flagProgrammatically
1832 // the newest nodes are single objects
1833 for( int i = 0; i < allocationDepth; ++i ) {
1834 Integer id = generateUniqueHeapRegionNodeID();
1835 as.setIthOldest( i, id );
1836 mapHrnIdToAllocSite.put( id, as );
1839 // the oldest node is a summary node
1840 as.setSummary( generateUniqueHeapRegionNodeID() );
1842 mapFlatNewToAllocSite.put( fnew, as );
1845 return mapFlatNewToAllocSite.get( fnew );
1849 public static boolean shouldAnalysisTrack( TypeDescriptor type ) {
1850 // don't track primitive types, but an array
1851 // of primitives is heap memory
1852 if( type.isImmutable() ) {
1853 return type.isArray();
1856 // everything else is an object
1860 protected int numMethodsAnalyzed() {
1861 return descriptorsToAnalyze.size();
1868 // Take in source entry which is the program's compiled entry and
1869 // create a new analysis entry, a method that takes no parameters
1870 // and appears to allocate the command line arguments and call the
1871 // source entry with them. The purpose of this analysis entry is
1872 // to provide a top-level method context with no parameters left.
1873 protected void makeAnalysisEntryMethod( MethodDescriptor mdSourceEntry ) {
1875 Modifiers mods = new Modifiers();
1876 mods.addModifier( Modifiers.PUBLIC );
1877 mods.addModifier( Modifiers.STATIC );
1879 TypeDescriptor returnType =
1880 new TypeDescriptor( TypeDescriptor.VOID );
1882 this.mdAnalysisEntry =
1883 new MethodDescriptor( mods,
1885 "analysisEntryMethod"
1888 TempDescriptor cmdLineArgs =
1889 new TempDescriptor( "args",
1890 mdSourceEntry.getParamType( 0 )
1894 new FlatNew( mdSourceEntry.getParamType( 0 ),
1899 TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
1900 sourceEntryArgs[0] = cmdLineArgs;
1903 new FlatCall( mdSourceEntry,
1909 FlatReturnNode frn = new FlatReturnNode( null );
1911 FlatExit fe = new FlatExit();
1913 this.fmAnalysisEntry =
1914 new FlatMethod( mdAnalysisEntry,
1918 this.fmAnalysisEntry.addNext( fn );
1925 protected LinkedList<Descriptor> topologicalSort( Set<Descriptor> toSort ) {
1927 Set<Descriptor> discovered;
1929 if( determinismDesired ) {
1930 // use an ordered set
1931 discovered = new TreeSet<Descriptor>( dComp );
1933 // otherwise use a speedy hashset
1934 discovered = new HashSet<Descriptor>();
1937 LinkedList<Descriptor> sorted = new LinkedList<Descriptor>();
1939 Iterator<Descriptor> itr = toSort.iterator();
1940 while( itr.hasNext() ) {
1941 Descriptor d = itr.next();
1943 if( !discovered.contains( d ) ) {
1944 dfsVisit( d, toSort, sorted, discovered );
1951 // While we're doing DFS on call graph, remember
1952 // dependencies for efficient queuing of methods
1953 // during interprocedural analysis:
1955 // a dependent of a method decriptor d for this analysis is:
1956 // 1) a method or task that invokes d
1957 // 2) in the descriptorsToAnalyze set
1958 protected void dfsVisit( Descriptor d,
1959 Set <Descriptor> toSort,
1960 LinkedList<Descriptor> sorted,
1961 Set <Descriptor> discovered ) {
1962 discovered.add( d );
1964 // only methods have callers, tasks never do
1965 if( d instanceof MethodDescriptor ) {
1967 MethodDescriptor md = (MethodDescriptor) d;
1969 // the call graph is not aware that we have a fabricated
1970 // analysis entry that calls the program source's entry
1971 if( md == mdSourceEntry ) {
1972 if( !discovered.contains( mdAnalysisEntry ) ) {
1973 addDependent( mdSourceEntry, // callee
1974 mdAnalysisEntry // caller
1976 dfsVisit( mdAnalysisEntry, toSort, sorted, discovered );
1980 // otherwise call graph guides DFS
1981 Iterator itr = callGraph.getCallerSet( md ).iterator();
1982 while( itr.hasNext() ) {
1983 Descriptor dCaller = (Descriptor) itr.next();
1985 // only consider callers in the original set to analyze
1986 if( !toSort.contains( dCaller ) ) {
1990 if( !discovered.contains( dCaller ) ) {
1991 addDependent( md, // callee
1995 dfsVisit( dCaller, toSort, sorted, discovered );
2000 // for leaf-nodes last now!
2001 sorted.addLast( d );
2005 protected void enqueue( Descriptor d ) {
2007 if( !descriptorsToVisitSet.contains( d ) ) {
2009 if( state.DISJOINTDVISITSTACK ||
2010 state.DISJOINTDVISITSTACKEESONTOP
2012 descriptorsToVisitStack.add( d );
2014 } else if( state.DISJOINTDVISITPQUE ) {
2015 Integer priority = mapDescriptorToPriority.get( d );
2016 descriptorsToVisitQ.add( new DescriptorQWrapper( priority,
2021 descriptorsToVisitSet.add( d );
2026 // a dependent of a method decriptor d for this analysis is:
2027 // 1) a method or task that invokes d
2028 // 2) in the descriptorsToAnalyze set
2029 protected void addDependent( Descriptor callee, Descriptor caller ) {
2030 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
2031 if( deps == null ) {
2032 deps = new HashSet<Descriptor>();
2035 mapDescriptorToSetDependents.put( callee, deps );
2038 protected Set<Descriptor> getDependents( Descriptor callee ) {
2039 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
2040 if( deps == null ) {
2041 deps = new HashSet<Descriptor>();
2042 mapDescriptorToSetDependents.put( callee, deps );
2048 public Hashtable<FlatCall, ReachGraph> getIHMcontributions( Descriptor d ) {
2050 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2051 mapDescriptorToIHMcontributions.get( d );
2053 if( heapsFromCallers == null ) {
2054 heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
2055 mapDescriptorToIHMcontributions.put( d, heapsFromCallers );
2058 return heapsFromCallers;
2061 public ReachGraph getIHMcontribution( Descriptor d,
2064 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2065 getIHMcontributions( d );
2067 if( !heapsFromCallers.containsKey( fc ) ) {
2071 return heapsFromCallers.get( fc );
2075 public void addIHMcontribution( Descriptor d,
2079 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2080 getIHMcontributions( d );
2082 heapsFromCallers.put( fc, rg );
2086 private AllocSite createParameterAllocSite( ReachGraph rg,
2087 TempDescriptor tempDesc,
2093 flatNew = new FlatNew( tempDesc.getType(), // type
2094 tempDesc, // param temp
2095 false, // global alloc?
2096 "param"+tempDesc // disjoint site ID string
2099 flatNew = new FlatNew( tempDesc.getType(), // type
2100 tempDesc, // param temp
2101 false, // global alloc?
2102 null // disjoint site ID string
2106 // create allocation site
2107 AllocSite as = AllocSite.factory( allocationDepth,
2109 flatNew.getDisjointId(),
2112 for (int i = 0; i < allocationDepth; ++i) {
2113 Integer id = generateUniqueHeapRegionNodeID();
2114 as.setIthOldest(i, id);
2115 mapHrnIdToAllocSite.put(id, as);
2117 // the oldest node is a summary node
2118 as.setSummary( generateUniqueHeapRegionNodeID() );
2126 private Set<FieldDescriptor> getFieldSetTobeAnalyzed(TypeDescriptor typeDesc){
2128 Set<FieldDescriptor> fieldSet=new HashSet<FieldDescriptor>();
2129 if(!typeDesc.isImmutable()){
2130 ClassDescriptor classDesc = typeDesc.getClassDesc();
2131 for (Iterator it = classDesc.getFields(); it.hasNext();) {
2132 FieldDescriptor field = (FieldDescriptor) it.next();
2133 TypeDescriptor fieldType = field.getType();
2134 if (shouldAnalysisTrack( fieldType )) {
2135 fieldSet.add(field);
2143 private HeapRegionNode createMultiDeimensionalArrayHRN(ReachGraph rg, AllocSite alloc, HeapRegionNode srcHRN, FieldDescriptor fd, Hashtable<HeapRegionNode, HeapRegionNode> map, Hashtable<TypeDescriptor, HeapRegionNode> mapToExistingNode, ReachSet alpha ){
2145 int dimCount=fd.getType().getArrayCount();
2146 HeapRegionNode prevNode=null;
2147 HeapRegionNode arrayEntryNode=null;
2148 for(int i=dimCount;i>0;i--){
2149 TypeDescriptor typeDesc=fd.getType().dereference();//hack to get instance of type desc
2150 typeDesc.setArrayCount(i);
2151 TempDescriptor tempDesc=new TempDescriptor(typeDesc.getSymbol(),typeDesc);
2152 HeapRegionNode hrnSummary ;
2153 if(!mapToExistingNode.containsKey(typeDesc)){
2158 as = createParameterAllocSite(rg, tempDesc, false);
2160 // make a new reference to allocated node
2162 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
2163 false, // single object?
2165 false, // out-of-context?
2166 as.getType(), // type
2167 as, // allocation site
2168 alpha, // inherent reach
2169 alpha, // current reach
2170 ExistPredSet.factory(rg.predTrue), // predicates
2171 tempDesc.toString() // description
2173 rg.id2hrn.put(as.getSummary(),hrnSummary);
2175 mapToExistingNode.put(typeDesc, hrnSummary);
2177 hrnSummary=mapToExistingNode.get(typeDesc);
2181 // make a new reference between new summary node and source
2182 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2185 fd.getSymbol(), // field name
2187 ExistPredSet.factory(rg.predTrue), // predicates
2191 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
2192 prevNode=hrnSummary;
2193 arrayEntryNode=hrnSummary;
2195 // make a new reference between summary nodes of array
2196 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2199 arrayElementFieldName, // field name
2201 ExistPredSet.factory(rg.predTrue), // predicates
2205 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2206 prevNode=hrnSummary;
2211 // create a new obj node if obj has at least one non-primitive field
2212 TypeDescriptor type=fd.getType();
2213 if(getFieldSetTobeAnalyzed(type).size()>0){
2214 TypeDescriptor typeDesc=type.dereference();
2215 typeDesc.setArrayCount(0);
2216 if(!mapToExistingNode.containsKey(typeDesc)){
2217 TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc);
2218 AllocSite as = createParameterAllocSite(rg, tempDesc, false);
2219 // make a new reference to allocated node
2220 HeapRegionNode hrnSummary =
2221 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
2222 false, // single object?
2224 false, // out-of-context?
2226 as, // allocation site
2227 alpha, // inherent reach
2228 alpha, // current reach
2229 ExistPredSet.factory(rg.predTrue), // predicates
2230 tempDesc.toString() // description
2232 rg.id2hrn.put(as.getSummary(),hrnSummary);
2233 mapToExistingNode.put(typeDesc, hrnSummary);
2234 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2237 arrayElementFieldName, // field name
2239 ExistPredSet.factory(rg.predTrue), // predicates
2242 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2243 prevNode=hrnSummary;
2245 HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc);
2246 if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null){
2247 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2250 arrayElementFieldName, // field name
2252 ExistPredSet.factory(rg.predTrue), // predicates
2255 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2257 prevNode=hrnSummary;
2261 map.put(arrayEntryNode, prevNode);
2262 return arrayEntryNode;
2265 private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
2266 ReachGraph rg = new ReachGraph();
2267 TaskDescriptor taskDesc = fm.getTask();
2269 for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
2270 Descriptor paramDesc = taskDesc.getParameter(idx);
2271 TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
2273 // setup data structure
2274 Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet =
2275 new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
2276 Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode =
2277 new Hashtable<TypeDescriptor, HeapRegionNode>();
2278 Hashtable<HeapRegionNode, HeapRegionNode> mapToFirstDimensionArrayNode =
2279 new Hashtable<HeapRegionNode, HeapRegionNode>();
2280 Set<String> doneSet = new HashSet<String>();
2282 TempDescriptor tempDesc = fm.getParameter(idx);
2284 AllocSite as = createParameterAllocSite(rg, tempDesc, true);
2285 VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
2286 Integer idNewest = as.getIthOldest(0);
2287 HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
2289 // make a new reference to allocated node
2290 RefEdge edgeNew = new RefEdge(lnX, // source
2292 taskDesc.getParamType(idx), // type
2294 hrnNewest.getAlpha(), // beta
2295 ExistPredSet.factory(rg.predTrue), // predicates
2298 rg.addRefEdge(lnX, hrnNewest, edgeNew);
2300 // set-up a work set for class field
2301 ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
2302 for (Iterator it = classDesc.getFields(); it.hasNext();) {
2303 FieldDescriptor fd = (FieldDescriptor) it.next();
2304 TypeDescriptor fieldType = fd.getType();
2305 if (shouldAnalysisTrack( fieldType )) {
2306 HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
2307 newMap.put(hrnNewest, fd);
2308 workSet.add(newMap);
2312 int uniqueIdentifier = 0;
2313 while (!workSet.isEmpty()) {
2314 HashMap<HeapRegionNode, FieldDescriptor> map = workSet
2316 workSet.remove(map);
2318 Set<HeapRegionNode> key = map.keySet();
2319 HeapRegionNode srcHRN = key.iterator().next();
2320 FieldDescriptor fd = map.get(srcHRN);
2321 TypeDescriptor type = fd.getType();
2322 String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
2324 if (!doneSet.contains(doneSetIdentifier)) {
2325 doneSet.add(doneSetIdentifier);
2326 if (!mapTypeToExistingSummaryNode.containsKey(type)) {
2327 // create new summary Node
2328 TempDescriptor td = new TempDescriptor("temp"
2329 + uniqueIdentifier, type);
2331 AllocSite allocSite;
2332 if(type.equals(paramTypeDesc)){
2333 //corresponding allocsite has already been created for a parameter variable.
2336 allocSite = createParameterAllocSite(rg, td, false);
2338 String strDesc = allocSite.toStringForDOT()
2340 TypeDescriptor allocType=allocSite.getType();
2342 HeapRegionNode hrnSummary;
2343 if(allocType.isArray() && allocType.getArrayCount()>0){
2344 hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha());
2347 rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
2348 false, // single object?
2350 false, // out-of-context?
2351 allocSite.getType(), // type
2352 allocSite, // allocation site
2353 hrnNewest.getAlpha(), // inherent reach
2354 hrnNewest.getAlpha(), // current reach
2355 ExistPredSet.factory(rg.predTrue), // predicates
2356 strDesc // description
2358 rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
2360 // make a new reference to summary node
2361 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2364 fd.getSymbol(), // field name
2365 hrnNewest.getAlpha(), // beta
2366 ExistPredSet.factory(rg.predTrue), // predicates
2370 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
2374 mapTypeToExistingSummaryNode.put(type, hrnSummary);
2376 // set-up a work set for fields of the class
2377 Set<FieldDescriptor> fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type);
2378 for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator
2380 FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator
2382 HeapRegionNode newDstHRN;
2383 if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)){
2384 //related heap region node is already exsited.
2385 newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary);
2387 newDstHRN=hrnSummary;
2389 doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor;
2390 if(!doneSet.contains(doneSetIdentifier)){
2391 // add new work item
2392 HashMap<HeapRegionNode, FieldDescriptor> newMap =
2393 new HashMap<HeapRegionNode, FieldDescriptor>();
2394 newMap.put(newDstHRN, fieldDescriptor);
2395 workSet.add(newMap);
2400 // if there exists corresponding summary node
2401 HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
2403 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2405 fd.getType(), // type
2406 fd.getSymbol(), // field name
2407 srcHRN.getAlpha(), // beta
2408 ExistPredSet.factory(rg.predTrue), // predicates
2411 rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
2421 // return all allocation sites in the method (there is one allocation
2422 // site per FlatNew node in a method)
2423 private HashSet<AllocSite> getAllocationSiteSet(Descriptor d) {
2424 if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
2425 buildAllocationSiteSet(d);
2428 return mapDescriptorToAllocSiteSet.get(d);
2432 private void buildAllocationSiteSet(Descriptor d) {
2433 HashSet<AllocSite> s = new HashSet<AllocSite>();
2436 if( d instanceof MethodDescriptor ) {
2437 fm = state.getMethodFlat( (MethodDescriptor) d);
2439 assert d instanceof TaskDescriptor;
2440 fm = state.getMethodFlat( (TaskDescriptor) d);
2442 pm.analyzeMethod(fm);
2444 // visit every node in this FlatMethod's IR graph
2445 // and make a set of the allocation sites from the
2446 // FlatNew node's visited
2447 HashSet<FlatNode> visited = new HashSet<FlatNode>();
2448 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
2451 while( !toVisit.isEmpty() ) {
2452 FlatNode n = toVisit.iterator().next();
2454 if( n instanceof FlatNew ) {
2455 s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
2461 for( int i = 0; i < pm.numNext(n); ++i ) {
2462 FlatNode child = pm.getNext(n, i);
2463 if( !visited.contains(child) ) {
2469 mapDescriptorToAllocSiteSet.put(d, s);
2472 private HashSet<AllocSite> getFlaggedAllocationSites(Descriptor dIn) {
2474 HashSet<AllocSite> out = new HashSet<AllocSite>();
2475 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2476 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2480 while (!toVisit.isEmpty()) {
2481 Descriptor d = toVisit.iterator().next();
2485 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2486 Iterator asItr = asSet.iterator();
2487 while (asItr.hasNext()) {
2488 AllocSite as = (AllocSite) asItr.next();
2489 if (as.getDisjointAnalysisId() != null) {
2494 // enqueue callees of this method to be searched for
2495 // allocation sites also
2496 Set callees = callGraph.getCalleeSet(d);
2497 if (callees != null) {
2498 Iterator methItr = callees.iterator();
2499 while (methItr.hasNext()) {
2500 MethodDescriptor md = (MethodDescriptor) methItr.next();
2502 if (!visited.contains(md)) {
2513 private HashSet<AllocSite>
2514 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
2516 HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
2517 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2518 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2522 // traverse this task and all methods reachable from this task
2523 while( !toVisit.isEmpty() ) {
2524 Descriptor d = toVisit.iterator().next();
2528 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2529 Iterator asItr = asSet.iterator();
2530 while( asItr.hasNext() ) {
2531 AllocSite as = (AllocSite) asItr.next();
2532 TypeDescriptor typed = as.getType();
2533 if( typed != null ) {
2534 ClassDescriptor cd = typed.getClassDesc();
2535 if( cd != null && cd.hasFlags() ) {
2541 // enqueue callees of this method to be searched for
2542 // allocation sites also
2543 Set callees = callGraph.getCalleeSet(d);
2544 if( callees != null ) {
2545 Iterator methItr = callees.iterator();
2546 while( methItr.hasNext() ) {
2547 MethodDescriptor md = (MethodDescriptor) methItr.next();
2549 if( !visited.contains(md) ) {
2559 public Set<Descriptor> getDescriptorsToAnalyze() {
2560 return descriptorsToAnalyze;
2563 public EffectsAnalysis getEffectsAnalysis(){
2564 return effectsAnalysis;
2567 public ReachGraph getReachGraph(Descriptor d){
2568 return mapDescriptorToCompleteReachGraph.get(d);
2571 public ReachGraph getEnterReachGraph(FlatNode fn){
2572 return fn2rgAtEnter.get(fn);
2575 // get successive captures of the analysis state, use compiler
2577 boolean takeDebugSnapshots = false;
2578 String descSymbolDebug = null;
2579 boolean stopAfterCapture = false;
2580 int snapVisitCounter = 0;
2581 int snapNodeCounter = 0;
2582 int visitStartCapture = 0;
2583 int numVisitsToCapture = 0;
2586 void debugSnapshot( ReachGraph rg, FlatNode fn, boolean in ) {
2587 if( snapVisitCounter > visitStartCapture + numVisitsToCapture ) {
2595 if( snapVisitCounter >= visitStartCapture ) {
2596 System.out.println( " @@@ snapping visit="+snapVisitCounter+
2597 ", node="+snapNodeCounter+
2601 graphName = String.format( "snap%03d_%04din",
2605 graphName = String.format( "snap%03d_%04dout",
2610 graphName = graphName + fn;
2612 rg.writeGraph( graphName,
2613 true, // write labels (variables)
2614 true, // selectively hide intermediate temp vars
2615 true, // prune unreachable heap regions
2616 false, // hide reachability
2617 false, // hide subset reachability states
2618 true, // hide predicates
2619 true ); // hide edge taints