new Canonical hash and equals, also running with assertions disabled, barely improved
[IRC.git] / Robust / src / Analysis / Disjoint / DisjointAnalysis.java
1 package Analysis.Disjoint;
2
3 import Analysis.CallGraph.*;
4 import Analysis.Liveness;
5 import Analysis.ArrayReferencees;
6 import IR.*;
7 import IR.Flat.*;
8 import IR.Tree.Modifiers;
9 import java.util.*;
10 import java.io.*;
11
12
13 public class DisjointAnalysis {
14         
15           ///////////////////////////////////////////
16           //
17           //  Public interface to discover possible
18           //  aliases in the program under analysis
19           //
20           ///////////////////////////////////////////
21         
22           public HashSet<AllocSite>
23           getFlaggedAllocationSitesReachableFromTask(TaskDescriptor td) {
24             checkAnalysisComplete();
25             return getFlaggedAllocationSitesReachableFromTaskPRIVATE(td);
26           }
27           
28           public AllocSite getAllocationSiteFromFlatNew(FlatNew fn) {
29                     checkAnalysisComplete();
30                     return getAllocSiteFromFlatNewPRIVATE(fn);
31            }      
32           
33           public AllocSite getAllocationSiteFromHeapRegionNodeID(Integer id) {
34                     checkAnalysisComplete();
35                     return mapHrnIdToAllocSite.get(id);
36           }
37           
38           public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
39               int paramIndex1,
40               int paramIndex2) {
41                   checkAnalysisComplete();
42                   ReachGraph rg=mapDescriptorToCompleteReachGraph.get(taskOrMethod);
43                   FlatMethod fm=state.getMethodFlat(taskOrMethod);
44                   assert(rg != null);
45                   return rg.mayReachSharedObjects(fm, paramIndex1, paramIndex2);
46           }
47           
48         public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
49                         int paramIndex, AllocSite alloc) {
50                 checkAnalysisComplete();
51                 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
52             FlatMethod fm=state.getMethodFlat(taskOrMethod);
53                 assert (rg != null);
54                 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
55         }
56
57         public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
58                         AllocSite alloc, int paramIndex) {
59                 checkAnalysisComplete();
60                 ReachGraph rg  = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
61                 FlatMethod fm=state.getMethodFlat(taskOrMethod);
62                 assert (rg != null);
63                 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
64         }
65
66         public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
67                         AllocSite alloc1, AllocSite alloc2) {
68                 checkAnalysisComplete();
69                 ReachGraph rg  = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
70                 assert (rg != null);
71                 return rg.mayReachSharedObjects(alloc1, alloc2);
72         }
73         
74         public String prettyPrintNodeSet(Set<HeapRegionNode> s) {
75                 checkAnalysisComplete();
76
77                 String out = "{\n";
78
79                 Iterator<HeapRegionNode> i = s.iterator();
80                 while (i.hasNext()) {
81                         HeapRegionNode n = i.next();
82
83                         AllocSite as = n.getAllocSite();
84                         if (as == null) {
85                                 out += "  " + n.toString() + ",\n";
86                         } else {
87                                 out += "  " + n.toString() + ": " + as.toStringVerbose()
88                                                 + ",\n";
89                         }
90                 }
91
92                 out += "}\n";
93                 return out;
94         }
95         
96         // use the methods given above to check every possible alias
97           // between task parameters and flagged allocation sites reachable
98           // from the task
99           public void writeAllAliases(String outputFile, 
100                                       String timeReport,
101                                       String justTime,
102                                       boolean tabularOutput,
103                                       int numLines
104 )
105                         throws java.io.IOException {
106                 checkAnalysisComplete();
107
108                 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
109
110                 if (!tabularOutput) {
111                         bw.write("Conducting ownership analysis with allocation depth = "
112                                         + allocationDepth + "\n");
113                         bw.write(timeReport + "\n");
114                 }
115
116                 int numAlias = 0;
117
118                 // look through every task for potential aliases
119                 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
120                 while (taskItr.hasNext()) {
121                         TaskDescriptor td = (TaskDescriptor) taskItr.next();
122
123                         if (!tabularOutput) {
124                                 bw.write("\n---------" + td + "--------\n");
125                         }
126
127                         HashSet<AllocSite> allocSites = getFlaggedAllocationSitesReachableFromTask(td);
128
129                         Set<HeapRegionNode> common;
130
131                         // for each task parameter, check for aliases with
132                         // other task parameters and every allocation site
133                         // reachable from this task
134                         boolean foundSomeAlias = false;
135
136                         FlatMethod fm = state.getMethodFlat(td);
137                         for (int i = 0; i < fm.numParameters(); ++i) {
138
139                           // skip parameters with types that cannot reference
140                           // into the heap
141                           if( !shouldAnalysisTrack( fm.getParameter( i ).getType() ) ) {
142                             continue;
143                           }
144                           
145                                 // for the ith parameter check for aliases to all
146                                 // higher numbered parameters
147                                 for (int j = i + 1; j < fm.numParameters(); ++j) {
148
149                                   // skip parameters with types that cannot reference
150                                   // into the heap
151                                   if( !shouldAnalysisTrack( fm.getParameter( j ).getType() ) ) {
152                                     continue;
153                                   }
154
155
156                                   common = hasPotentialSharing(td, i, j);
157                                         if (!common.isEmpty()) {
158                                                 foundSomeAlias = true;
159                                                 if (!tabularOutput) {
160                                                         bw.write("Potential alias between parameters " + i
161                                                                         + " and " + j + ".\n");
162                                                         bw.write(prettyPrintNodeSet(common) + "\n");
163                                                 } else {
164                                                         ++numAlias;
165                                                 }
166                                         }
167                                 }
168
169                                 // for the ith parameter, check for aliases against
170                                 // the set of allocation sites reachable from this
171                                 // task context
172                                 Iterator allocItr = allocSites.iterator();
173                                 while (allocItr.hasNext()) {
174                                         AllocSite as = (AllocSite) allocItr.next();
175                                         common = hasPotentialSharing(td, i, as);
176                                         if (!common.isEmpty()) {
177                                                 foundSomeAlias = true;
178                                                 if (!tabularOutput) {
179                                                         bw.write("Potential alias between parameter " + i
180                                                                         + " and " + as.getFlatNew() + ".\n");
181                                                         bw.write(prettyPrintNodeSet(common) + "\n");
182                                                 } else {
183                                                         ++numAlias;
184                                                 }
185                                         }
186                                 }
187                         }
188
189                         // for each allocation site check for aliases with
190                         // other allocation sites in the context of execution
191                         // of this task
192                         HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
193                         Iterator allocItr1 = allocSites.iterator();
194                         while (allocItr1.hasNext()) {
195                                 AllocSite as1 = (AllocSite) allocItr1.next();
196
197                                 Iterator allocItr2 = allocSites.iterator();
198                                 while (allocItr2.hasNext()) {
199                                         AllocSite as2 = (AllocSite) allocItr2.next();
200
201                                         if (!outerChecked.contains(as2)) {
202                                                 common = hasPotentialSharing(td, as1, as2);
203
204                                                 if (!common.isEmpty()) {
205                                                         foundSomeAlias = true;
206                                                         if (!tabularOutput) {
207                                                                 bw.write("Potential alias between "
208                                                                                 + as1.getFlatNew() + " and "
209                                                                                 + as2.getFlatNew() + ".\n");
210                                                                 bw.write(prettyPrintNodeSet(common) + "\n");
211                                                         } else {
212                                                                 ++numAlias;
213                                                         }
214                                                 }
215                                         }
216                                 }
217
218                                 outerChecked.add(as1);
219                         }
220
221                         if (!foundSomeAlias) {
222                                 if (!tabularOutput) {
223                                         bw.write("No aliases between flagged objects in Task " + td
224                                                         + ".\n");
225                                 }
226                         }
227                 }
228
229                 /*
230                 if (!tabularOutput) {
231                         bw.write("\n" + computeAliasContextHistogram());
232                 } else {
233                         bw.write(" & " + numAlias + " & " + justTime + " & " + numLines
234                                         + " & " + numMethodsAnalyzed() + " \\\\\n");
235                 }
236                 */
237
238                 bw.close();
239         }
240         
241         // this version of writeAllAliases is for Java programs that have no tasks
242           public void writeAllAliasesJava(String outputFile, 
243                                           String timeReport,
244                                           String justTime,
245                                           boolean tabularOutput,
246                                           int numLines
247 )
248                         throws java.io.IOException {
249                 checkAnalysisComplete();
250
251                 assert !state.TASK;
252
253                 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
254
255                 bw.write("Conducting disjoint reachability analysis with allocation depth = "
256                                 + allocationDepth + "\n");
257                 bw.write(timeReport + "\n\n");
258
259                 boolean foundSomeAlias = false;
260
261                 Descriptor d = typeUtil.getMain();
262                 HashSet<AllocSite> allocSites = getFlaggedAllocationSites(d);
263
264                 // for each allocation site check for aliases with
265                 // other allocation sites in the context of execution
266                 // of this task
267                 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
268                 Iterator allocItr1 = allocSites.iterator();
269                 while (allocItr1.hasNext()) {
270                         AllocSite as1 = (AllocSite) allocItr1.next();
271
272                         Iterator allocItr2 = allocSites.iterator();
273                         while (allocItr2.hasNext()) {
274                                 AllocSite as2 = (AllocSite) allocItr2.next();
275
276                                 if (!outerChecked.contains(as2)) {
277                                         Set<HeapRegionNode> common = hasPotentialSharing(d,
278                                                         as1, as2);
279
280                                         if (!common.isEmpty()) {
281                                                 foundSomeAlias = true;
282                                                 bw.write("Potential alias between "
283                                                                 + as1.getDisjointAnalysisId() + " and "
284                                                                 + as2.getDisjointAnalysisId() + ".\n");
285                                                 bw.write(prettyPrintNodeSet(common) + "\n");
286                                         }
287                                 }
288                         }
289
290                         outerChecked.add(as1);
291                 }
292
293                 if (!foundSomeAlias) {
294                         bw.write("No aliases between flagged objects found.\n");
295                 }
296
297 //              bw.write("\n" + computeAliasContextHistogram());
298                 bw.close();
299         }
300           
301           ///////////////////////////////////////////
302           //
303           // end public interface
304           //
305           ///////////////////////////////////////////
306
307           protected void checkAnalysisComplete() {
308                     if( !analysisComplete ) {
309                       throw new Error("Warning: public interface method called while analysis is running.");
310                     }
311           } 
312
313
314   // run in faster mode, only when bugs wrung out!
315   public static boolean releaseMode;
316
317   // data from the compiler
318   public State            state;
319   public CallGraph        callGraph;
320   public Liveness         liveness;
321   public ArrayReferencees arrayReferencees;
322   public TypeUtil         typeUtil;
323   public int              allocationDepth;
324   
325   // data structure for public interface
326   private Hashtable<Descriptor,    HashSet<AllocSite> > mapDescriptorToAllocSiteSet;
327
328   
329   // for public interface methods to warn that they
330   // are grabbing results during analysis
331   private boolean analysisComplete;
332
333
334   // used to identify HeapRegionNode objects
335   // A unique ID equates an object in one
336   // ownership graph with an object in another
337   // graph that logically represents the same
338   // heap region
339   // start at 10 and increment to reserve some
340   // IDs for special purposes
341   static protected int uniqueIDcount = 10;
342
343
344   // An out-of-scope method created by the
345   // analysis that has no parameters, and
346   // appears to allocate the command line
347   // arguments, then invoke the source code's
348   // main method.  The purpose of this is to
349   // provide the analysis with an explicit
350   // top-level context with no parameters
351   protected MethodDescriptor mdAnalysisEntry;
352   protected FlatMethod       fmAnalysisEntry;
353
354   // main method defined by source program
355   protected MethodDescriptor mdSourceEntry;
356
357   // the set of task and/or method descriptors
358   // reachable in call graph
359   protected Set<Descriptor> 
360     descriptorsToAnalyze;
361
362   // current descriptors to visit in fixed-point
363   // interprocedural analysis, prioritized by
364   // dependency in the call graph
365   protected PriorityQueue<DescriptorQWrapper> 
366     descriptorsToVisitQ;
367   
368   // a duplication of the above structure, but
369   // for efficient testing of inclusion
370   protected HashSet<Descriptor> 
371     descriptorsToVisitSet;
372
373   // storage for priorities (doesn't make sense)
374   // to add it to the Descriptor class, just in
375   // this analysis
376   protected Hashtable<Descriptor, Integer> 
377     mapDescriptorToPriority;
378
379
380   // maps a descriptor to its current partial result
381   // from the intraprocedural fixed-point analysis--
382   // then the interprocedural analysis settles, this
383   // mapping will have the final results for each
384   // method descriptor
385   protected Hashtable<Descriptor, ReachGraph> 
386     mapDescriptorToCompleteReachGraph;
387
388   // maps a descriptor to its known dependents: namely
389   // methods or tasks that call the descriptor's method
390   // AND are part of this analysis (reachable from main)
391   protected Hashtable< Descriptor, Set<Descriptor> >
392     mapDescriptorToSetDependents;
393
394   // maps each flat new to one analysis abstraction
395   // allocate site object, these exist outside reach graphs
396   protected Hashtable<FlatNew, AllocSite>
397     mapFlatNewToAllocSite;
398
399   // maps intergraph heap region IDs to intergraph
400   // allocation sites that created them, a redundant
401   // structure for efficiency in some operations
402   protected Hashtable<Integer, AllocSite>
403     mapHrnIdToAllocSite;
404
405   // maps a method to its initial heap model (IHM) that
406   // is the set of reachability graphs from every caller
407   // site, all merged together.  The reason that we keep
408   // them separate is that any one call site's contribution
409   // to the IHM may changed along the path to the fixed point
410   protected Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >
411     mapDescriptorToIHMcontributions;
412
413   // TODO -- CHANGE EDGE/TYPE/FIELD storage!
414   public static final String arrayElementFieldName = "___element_";
415   static protected Hashtable<TypeDescriptor, FieldDescriptor>
416     mapTypeToArrayField;
417
418   // for controlling DOT file output
419   protected boolean writeFinalDOTs;
420   protected boolean writeAllIncrementalDOTs;
421
422   // supporting DOT output--when we want to write every
423   // partial method result, keep a tally for generating
424   // unique filenames
425   protected Hashtable<Descriptor, Integer>
426     mapDescriptorToNumUpdates;
427   
428   //map task descriptor to initial task parameter 
429   protected Hashtable<Descriptor, ReachGraph>
430   mapDescriptorToReachGraph;
431
432
433   // allocate various structures that are not local
434   // to a single class method--should be done once
435   protected void allocateStructures() {    
436     descriptorsToAnalyze = new HashSet<Descriptor>();
437
438     mapDescriptorToCompleteReachGraph =
439       new Hashtable<Descriptor, ReachGraph>();
440
441     mapDescriptorToNumUpdates =
442       new Hashtable<Descriptor, Integer>();
443
444     mapDescriptorToSetDependents =
445       new Hashtable< Descriptor, Set<Descriptor> >();
446
447     mapFlatNewToAllocSite = 
448       new Hashtable<FlatNew, AllocSite>();
449
450     mapDescriptorToIHMcontributions =
451       new Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >();
452
453     mapHrnIdToAllocSite =
454       new Hashtable<Integer, AllocSite>();
455
456     mapTypeToArrayField = 
457       new Hashtable <TypeDescriptor, FieldDescriptor>();
458
459     descriptorsToVisitQ =
460       new PriorityQueue<DescriptorQWrapper>();
461
462     descriptorsToVisitSet =
463       new HashSet<Descriptor>();
464
465     mapDescriptorToPriority =
466       new Hashtable<Descriptor, Integer>();
467     
468     mapDescriptorToAllocSiteSet =
469         new Hashtable<Descriptor,    HashSet<AllocSite> >();
470     
471     mapDescriptorToReachGraph = 
472         new Hashtable<Descriptor, ReachGraph>();
473   }
474
475
476
477   // this analysis generates a disjoint reachability
478   // graph for every reachable method in the program
479   public DisjointAnalysis( State            s,
480                            TypeUtil         tu,
481                            CallGraph        cg,
482                            Liveness         l,
483                            ArrayReferencees ar
484                            ) throws java.io.IOException {
485     init( s, tu, cg, l, ar );
486   }
487   
488   protected void init( State            state,
489                        TypeUtil         typeUtil,
490                        CallGraph        callGraph,
491                        Liveness         liveness,
492                        ArrayReferencees arrayReferencees
493                        ) throws java.io.IOException {
494           
495     analysisComplete = false;
496     
497     this.state                   = state;
498     this.typeUtil                = typeUtil;
499     this.callGraph               = callGraph;
500     this.liveness                = liveness;
501     this.arrayReferencees        = arrayReferencees;
502     this.allocationDepth         = state.DISJOINTALLOCDEPTH;
503     this.releaseMode             = state.DISJOINTRELEASEMODE;
504
505     this.writeFinalDOTs          = state.DISJOINTWRITEDOTS && !state.DISJOINTWRITEALL;
506     this.writeAllIncrementalDOTs = state.DISJOINTWRITEDOTS &&  state.DISJOINTWRITEALL;
507
508     this.takeDebugSnapshots      = state.DISJOINTSNAPSYMBOL != null;
509     this.descSymbolDebug         = state.DISJOINTSNAPSYMBOL;
510     this.visitStartCapture       = state.DISJOINTSNAPVISITTOSTART;
511     this.numVisitsToCapture      = state.DISJOINTSNAPNUMVISITS;
512     this.stopAfterCapture        = state.DISJOINTSNAPSTOPAFTER;
513     this.snapVisitCounter        = 1; // count visits from 1 (user will write 1, means 1st visit)
514     this.snapNodeCounter         = 0; // count nodes from 0
515             
516     // set some static configuration for ReachGraphs
517     ReachGraph.allocationDepth = allocationDepth;
518     ReachGraph.typeUtil        = typeUtil;
519
520     ReachGraph.debugCallSiteVisitsUntilExit = state.DISJOINTDEBUGCALLCOUNT;
521
522     allocateStructures();
523
524     double timeStartAnalysis = (double) System.nanoTime();
525
526     // start interprocedural fixed-point computation
527     analyzeMethods();
528     analysisComplete=true;
529
530     double timeEndAnalysis = (double) System.nanoTime();
531     double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
532     String treport = String.format( "The reachability analysis took %.3f sec.", dt );
533     String justtime = String.format( "%.2f", dt );
534     System.out.println( treport );
535
536     if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
537       writeFinalGraphs();      
538     }
539
540     if( state.DISJOINTWRITEIHMS ) {
541       writeFinalIHMs();
542     }
543
544     if( state.DISJOINTALIASFILE != null ) {
545       if( state.TASK ) {
546         writeAllAliases(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines);
547       } else {
548         /*
549         writeAllAliasesJava( aliasFile, 
550                              treport, 
551                              justtime, 
552                              state.DISJOINTALIASTAB, 
553                              state.lines );
554         */
555       }
556     }
557   }
558
559
560   // fixed-point computation over the call graph--when a
561   // method's callees are updated, it must be reanalyzed
562   protected void analyzeMethods() throws java.io.IOException {  
563
564     if( state.TASK ) {
565       // This analysis does not support Bamboo at the moment,
566       // but if it does in the future we would initialize the
567       // set of descriptors to analyze as the program-reachable
568       // tasks and the methods callable by them.  For Java,
569       // just methods reachable from the main method.
570       System.out.println( "Bamboo..." );
571       Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
572       
573       while (taskItr.hasNext()) {
574           TaskDescriptor td = (TaskDescriptor) taskItr.next();
575           if (!descriptorsToAnalyze.contains(td)) {           
576               descriptorsToAnalyze.add(td);
577               descriptorsToAnalyze.addAll(callGraph.getAllMethods(td));
578           }       
579       }
580
581     } else {
582       // add all methods transitively reachable from the
583       // source's main to set for analysis
584       mdSourceEntry = typeUtil.getMain();
585       descriptorsToAnalyze.add( mdSourceEntry );
586       descriptorsToAnalyze.addAll( 
587         callGraph.getAllMethods( mdSourceEntry ) 
588                                    );
589
590       // fabricate an empty calling context that will call
591       // the source's main, but call graph doesn't know
592       // about it, so explicitly add it
593       makeAnalysisEntryMethod( mdSourceEntry );
594       descriptorsToAnalyze.add( mdAnalysisEntry );
595     }
596
597     // topologically sort according to the call graph so 
598     // leaf calls are ordered first, smarter analysis order
599     // CHANGED: order leaf calls last!!
600     LinkedList<Descriptor> sortedDescriptors = 
601       topologicalSort( descriptorsToAnalyze );
602
603     // add sorted descriptors to priority queue, and duplicate
604     // the queue as a set for efficiently testing whether some
605     // method is marked for analysis
606     int p = 0;
607     Iterator<Descriptor> dItr = sortedDescriptors.iterator();
608     while( dItr.hasNext() ) {
609       Descriptor d = dItr.next();
610       mapDescriptorToPriority.put( d, new Integer( p ) );
611       descriptorsToVisitQ.add( new DescriptorQWrapper( p, d ) );
612       descriptorsToVisitSet.add( d );
613       ++p;
614     }
615
616     // analyze methods from the priority queue until it is empty
617     while( !descriptorsToVisitQ.isEmpty() ) {
618       Descriptor d = descriptorsToVisitQ.poll().getDescriptor();
619       assert descriptorsToVisitSet.contains( d );
620       descriptorsToVisitSet.remove( d );
621
622       // because the task or method descriptor just extracted
623       // was in the "to visit" set it either hasn't been analyzed
624       // yet, or some method that it depends on has been
625       // updated.  Recompute a complete reachability graph for
626       // this task/method and compare it to any previous result.
627       // If there is a change detected, add any methods/tasks
628       // that depend on this one to the "to visit" set.
629
630       System.out.println( "Analyzing " + d );
631
632       ReachGraph rg     = analyzeMethod( d );
633       ReachGraph rgPrev = getPartial( d );
634       
635       if( !rg.equals( rgPrev ) ) {
636         setPartial( d, rg );
637         
638         // results for d changed, so enqueue dependents
639         // of d for further analysis
640         Iterator<Descriptor> depsItr = getDependents( d ).iterator();
641         while( depsItr.hasNext() ) {
642           Descriptor dNext = depsItr.next();
643           enqueue( dNext );
644         }
645       }      
646     }
647   }
648
649   protected ReachGraph analyzeMethod( Descriptor d ) 
650     throws java.io.IOException {
651
652     // get the flat code for this descriptor
653     FlatMethod fm;
654     if( d == mdAnalysisEntry ) {
655       fm = fmAnalysisEntry;
656     } else {
657       fm = state.getMethodFlat( d );
658     }
659       
660     // intraprocedural work set
661     Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
662     flatNodesToVisit.add( fm );
663     
664     // mapping of current partial results
665     Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraph =
666       new Hashtable<FlatNode, ReachGraph>();
667
668     // the set of return nodes partial results that will be combined as
669     // the final, conservative approximation of the entire method
670     HashSet<FlatReturnNode> setReturns = new HashSet<FlatReturnNode>();
671
672     while( !flatNodesToVisit.isEmpty() ) {
673       FlatNode fn = (FlatNode) flatNodesToVisit.iterator().next();
674       flatNodesToVisit.remove( fn );
675
676       // effect transfer function defined by this node,
677       // then compare it to the old graph at this node
678       // to see if anything was updated.
679
680       ReachGraph rg = new ReachGraph();
681       TaskDescriptor taskDesc;
682       if(fn instanceof FlatMethod && (taskDesc=((FlatMethod)fn).getTask())!=null){
683           if(mapDescriptorToReachGraph.containsKey(taskDesc)){
684                   // retrieve existing reach graph if it is not first time
685                   rg=mapDescriptorToReachGraph.get(taskDesc);
686           }else{
687                   // create initial reach graph for a task
688                   rg=createInitialTaskReachGraph((FlatMethod)fn);
689                   rg.globalSweep();
690                   mapDescriptorToReachGraph.put(taskDesc, rg);
691           }
692       }
693
694       // start by merging all node's parents' graphs
695       for( int i = 0; i < fn.numPrev(); ++i ) {
696         FlatNode pn = fn.getPrev( i );
697         if( mapFlatNodeToReachGraph.containsKey( pn ) ) {
698           ReachGraph rgParent = mapFlatNodeToReachGraph.get( pn );
699           rg.merge( rgParent );
700         }
701       }
702
703
704       if( takeDebugSnapshots && 
705           d.getSymbol().equals( descSymbolDebug ) 
706           ) {
707         debugSnapshot( rg, fn, true );
708       }
709
710
711       // modify rg with appropriate transfer function
712       rg = analyzeFlatNode( d, fm, fn, setReturns, rg );
713
714
715       if( takeDebugSnapshots && 
716           d.getSymbol().equals( descSymbolDebug ) 
717           ) {
718         debugSnapshot( rg, fn, false );
719         ++snapNodeCounter;
720       }
721           
722
723       // if the results of the new graph are different from
724       // the current graph at this node, replace the graph
725       // with the update and enqueue the children
726       ReachGraph rgPrev = mapFlatNodeToReachGraph.get( fn );
727       if( !rg.equals( rgPrev ) ) {
728         mapFlatNodeToReachGraph.put( fn, rg );
729
730         for( int i = 0; i < fn.numNext(); i++ ) {
731           FlatNode nn = fn.getNext( i );
732           flatNodesToVisit.add( nn );
733         }
734       }
735     }
736
737     // end by merging all return nodes into a complete
738     // ownership graph that represents all possible heap
739     // states after the flat method returns
740     ReachGraph completeGraph = new ReachGraph();
741
742     assert !setReturns.isEmpty();
743     Iterator retItr = setReturns.iterator();
744     while( retItr.hasNext() ) {
745       FlatReturnNode frn = (FlatReturnNode) retItr.next();
746
747       assert mapFlatNodeToReachGraph.containsKey( frn );
748       ReachGraph rgRet = mapFlatNodeToReachGraph.get( frn );
749
750       completeGraph.merge( rgRet );
751     }
752
753
754     if( takeDebugSnapshots && 
755         d.getSymbol().equals( descSymbolDebug ) 
756         ) {
757       // increment that we've visited the debug snap
758       // method, and reset the node counter
759       System.out.println( "    @@@ debug snap at visit "+snapVisitCounter );
760       ++snapVisitCounter;
761       snapNodeCounter = 0;
762
763       if( snapVisitCounter == visitStartCapture + numVisitsToCapture && 
764           stopAfterCapture 
765           ) {
766         System.out.println( "!!! Stopping analysis after debug snap captures. !!!" );
767         System.exit( 0 );
768       }
769     }
770
771
772     return completeGraph;
773   }
774
775   
776   protected ReachGraph
777     analyzeFlatNode( Descriptor              d,
778                      FlatMethod              fmContaining,
779                      FlatNode                fn,
780                      HashSet<FlatReturnNode> setRetNodes,
781                      ReachGraph              rg
782                      ) throws java.io.IOException {
783
784     
785     // any variables that are no longer live should be
786     // nullified in the graph to reduce edges
787     //rg.nullifyDeadVars( liveness.getLiveInTemps( fmContaining, fn ) );
788
789           
790     TempDescriptor  lhs;
791     TempDescriptor  rhs;
792     FieldDescriptor fld;
793
794     // use node type to decide what transfer function
795     // to apply to the reachability graph
796     switch( fn.kind() ) {
797
798     case FKind.FlatMethod: {
799       // construct this method's initial heap model (IHM)
800       // since we're working on the FlatMethod, we know
801       // the incoming ReachGraph 'rg' is empty
802
803       Hashtable<FlatCall, ReachGraph> heapsFromCallers = 
804         getIHMcontributions( d );
805
806       Set entrySet = heapsFromCallers.entrySet();
807       Iterator itr = entrySet.iterator();
808       while( itr.hasNext() ) {
809         Map.Entry  me        = (Map.Entry)  itr.next();
810         FlatCall   fc        = (FlatCall)   me.getKey();
811         ReachGraph rgContrib = (ReachGraph) me.getValue();
812
813         assert fc.getMethod().equals( d );
814
815         // some call sites are in same method context though,
816         // and all of them should be merged together first,
817         // then heaps from different contexts should be merged
818         // THIS ASSUMES DIFFERENT CONTEXTS NEED SPECIAL CONSIDERATION!
819         // such as, do allocation sites need to be aged?
820
821         rg.merge_diffMethodContext( rgContrib );
822       }      
823     } break;
824       
825     case FKind.FlatOpNode:
826       FlatOpNode fon = (FlatOpNode) fn;
827       if( fon.getOp().getOp() == Operation.ASSIGN ) {
828         lhs = fon.getDest();
829         rhs = fon.getLeft();
830         rg.assignTempXEqualToTempY( lhs, rhs );
831       }
832       break;
833
834     case FKind.FlatCastNode:
835       FlatCastNode fcn = (FlatCastNode) fn;
836       lhs = fcn.getDst();
837       rhs = fcn.getSrc();
838
839       TypeDescriptor td = fcn.getType();
840       assert td != null;
841       
842       rg.assignTempXEqualToCastedTempY( lhs, rhs, td );
843       break;
844
845     case FKind.FlatFieldNode:
846       FlatFieldNode ffn = (FlatFieldNode) fn;
847       lhs = ffn.getDst();
848       rhs = ffn.getSrc();
849       fld = ffn.getField();
850       if( shouldAnalysisTrack( fld.getType() ) ) {
851         rg.assignTempXEqualToTempYFieldF( lhs, rhs, fld );
852       }          
853       break;
854
855     case FKind.FlatSetFieldNode:
856       FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
857       lhs = fsfn.getDst();
858       fld = fsfn.getField();
859       rhs = fsfn.getSrc();
860       if( shouldAnalysisTrack( fld.getType() ) ) {
861         rg.assignTempXFieldFEqualToTempY( lhs, fld, rhs );
862       }           
863       break;
864
865     case FKind.FlatElementNode:
866       FlatElementNode fen = (FlatElementNode) fn;
867       lhs = fen.getDst();
868       rhs = fen.getSrc();
869       if( shouldAnalysisTrack( lhs.getType() ) ) {
870
871         assert rhs.getType() != null;
872         assert rhs.getType().isArray();
873         
874         TypeDescriptor  tdElement = rhs.getType().dereference();
875         FieldDescriptor fdElement = getArrayField( tdElement );
876   
877         rg.assignTempXEqualToTempYFieldF( lhs, rhs, fdElement );
878       }
879       break;
880
881     case FKind.FlatSetElementNode:
882       FlatSetElementNode fsen = (FlatSetElementNode) fn;
883
884       if( arrayReferencees.doesNotCreateNewReaching( fsen ) ) {
885         // skip this node if it cannot create new reachability paths
886         break;
887       }
888
889       lhs = fsen.getDst();
890       rhs = fsen.getSrc();
891       if( shouldAnalysisTrack( rhs.getType() ) ) {
892
893         assert lhs.getType() != null;
894         assert lhs.getType().isArray();
895         
896         TypeDescriptor  tdElement = lhs.getType().dereference();
897         FieldDescriptor fdElement = getArrayField( tdElement );
898
899         rg.assignTempXFieldFEqualToTempY( lhs, fdElement, rhs );
900       }
901       break;
902       
903     case FKind.FlatNew:
904       FlatNew fnn = (FlatNew) fn;
905       lhs = fnn.getDst();
906       if( shouldAnalysisTrack( lhs.getType() ) ) {
907         AllocSite as = getAllocSiteFromFlatNewPRIVATE( fnn );   
908         rg.assignTempEqualToNewAlloc( lhs, as );
909       }
910       break;
911
912     case FKind.FlatCall: {
913       //TODO: temporal fix for task descriptor case
914       //MethodDescriptor mdCaller = fmContaining.getMethod();
915       Descriptor mdCaller;
916       if(fmContaining.getMethod()!=null){
917           mdCaller  = fmContaining.getMethod();
918       }else{
919           mdCaller = fmContaining.getTask();
920       }      
921       FlatCall         fc       = (FlatCall) fn;
922       MethodDescriptor mdCallee = fc.getMethod();
923       FlatMethod       fmCallee = state.getMethodFlat( mdCallee );
924
925       boolean writeDebugDOTs = 
926         mdCaller.getSymbol().equals( state.DISJOINTDEBUGCALLER ) &&
927         mdCallee.getSymbol().equals( state.DISJOINTDEBUGCALLEE );      
928
929
930       // calculate the heap this call site can reach--note this is
931       // not used for the current call site transform, we are
932       // grabbing this heap model for future analysis of the callees,
933       // so if different results emerge we will return to this site
934       ReachGraph heapForThisCall_old = 
935         getIHMcontribution( mdCallee, fc );
936
937       // the computation of the callee-reachable heap
938       // is useful for making the callee starting point
939       // and for applying the call site transfer function
940       Set<Integer> callerNodeIDsCopiedToCallee = 
941         new HashSet<Integer>();
942
943       ReachGraph heapForThisCall_cur = 
944         rg.makeCalleeView( fc, 
945                            fmCallee,
946                            callerNodeIDsCopiedToCallee,
947                            writeDebugDOTs
948                            );
949
950       if( !heapForThisCall_cur.equals( heapForThisCall_old ) ) {        
951         // if heap at call site changed, update the contribution,
952         // and reschedule the callee for analysis
953         addIHMcontribution( mdCallee, fc, heapForThisCall_cur );        
954         enqueue( mdCallee );
955       }
956
957
958
959
960       // the transformation for a call site should update the
961       // current heap abstraction with any effects from the callee,
962       // or if the method is virtual, the effects from any possible
963       // callees, so find the set of callees...
964       Set<MethodDescriptor> setPossibleCallees =
965         new HashSet<MethodDescriptor>();
966
967       if( mdCallee.isStatic() ) {        
968         setPossibleCallees.add( mdCallee );
969       } else {
970         TypeDescriptor typeDesc = fc.getThis().getType();
971         setPossibleCallees.addAll( callGraph.getMethods( mdCallee, 
972                                                          typeDesc )
973                                    );
974       }
975
976       ReachGraph rgMergeOfEffects = new ReachGraph();
977
978       Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
979       while( mdItr.hasNext() ) {
980         MethodDescriptor mdPossible = mdItr.next();
981         FlatMethod       fmPossible = state.getMethodFlat( mdPossible );
982
983         addDependent( mdPossible, // callee
984                       d );        // caller
985
986         // don't alter the working graph (rg) until we compute a 
987         // result for every possible callee, merge them all together,
988         // then set rg to that
989         ReachGraph rgCopy = new ReachGraph();
990         rgCopy.merge( rg );             
991                 
992         ReachGraph rgEffect = getPartial( mdPossible );
993
994         if( rgEffect == null ) {
995           // if this method has never been analyzed just schedule it 
996           // for analysis and skip over this call site for now
997           enqueue( mdPossible );
998         } else {
999           rgCopy.resolveMethodCall( fc, 
1000                                     fmPossible, 
1001                                     rgEffect,
1002                                     callerNodeIDsCopiedToCallee,
1003                                     writeDebugDOTs
1004                                     );
1005         }
1006         
1007         rgMergeOfEffects.merge( rgCopy );
1008       }
1009
1010
1011       // now that we've taken care of building heap models for
1012       // callee analysis, finish this transformation
1013       rg = rgMergeOfEffects;
1014     } break;
1015       
1016
1017     case FKind.FlatReturnNode:
1018       FlatReturnNode frn = (FlatReturnNode) fn;
1019       rhs = frn.getReturnTemp();
1020       if( rhs != null && shouldAnalysisTrack( rhs.getType() ) ) {
1021         rg.assignReturnEqualToTemp( rhs );
1022       }
1023       setRetNodes.add( frn );
1024       break;
1025
1026     } // end switch
1027
1028     
1029     // dead variables were removed before the above transfer function
1030     // was applied, so eliminate heap regions and edges that are no
1031     // longer part of the abstractly-live heap graph, and sweep up
1032     // and reachability effects that are altered by the reduction
1033     //rg.abstractGarbageCollect();
1034     //rg.globalSweep();
1035
1036
1037     // at this point rg should be the correct update
1038     // by an above transfer function, or untouched if
1039     // the flat node type doesn't affect the heap
1040     return rg;
1041   }
1042
1043   
1044   // this method should generate integers strictly greater than zero!
1045   // special "shadow" regions are made from a heap region by negating
1046   // the ID
1047   static public Integer generateUniqueHeapRegionNodeID() {
1048     ++uniqueIDcount;
1049     return new Integer( uniqueIDcount );
1050   }
1051
1052
1053   
1054   static public FieldDescriptor getArrayField( TypeDescriptor tdElement ) {
1055     FieldDescriptor fdElement = mapTypeToArrayField.get( tdElement );
1056     if( fdElement == null ) {
1057       fdElement = new FieldDescriptor( new Modifiers( Modifiers.PUBLIC ),
1058                                        tdElement,
1059                                        arrayElementFieldName,
1060                                        null,
1061                                        false );
1062       mapTypeToArrayField.put( tdElement, fdElement );
1063     }
1064     return fdElement;
1065   }
1066
1067   
1068   
1069   private void writeFinalGraphs() {
1070     Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
1071     Iterator itr = entrySet.iterator();
1072     while( itr.hasNext() ) {
1073       Map.Entry  me = (Map.Entry)  itr.next();
1074       Descriptor  d = (Descriptor) me.getKey();
1075       ReachGraph rg = (ReachGraph) me.getValue();
1076
1077       rg.writeGraph( "COMPLETE"+d,
1078                      true,   // write labels (variables)                
1079                      true,   // selectively hide intermediate temp vars 
1080                      true,   // prune unreachable heap regions          
1081                      false,  // hide subset reachability states         
1082                      true ); // hide edge taints                        
1083     }
1084   }
1085
1086   private void writeFinalIHMs() {
1087     Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
1088     while( d2IHMsItr.hasNext() ) {
1089       Map.Entry                        me1 = (Map.Entry)                       d2IHMsItr.next();
1090       Descriptor                         d = (Descriptor)                      me1.getKey();
1091       Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>) me1.getValue();
1092
1093       Iterator fc2rgItr = IHMs.entrySet().iterator();
1094       while( fc2rgItr.hasNext() ) {
1095         Map.Entry  me2 = (Map.Entry)  fc2rgItr.next();
1096         FlatCall   fc  = (FlatCall)   me2.getKey();
1097         ReachGraph rg  = (ReachGraph) me2.getValue();
1098                 
1099         rg.writeGraph( "IHMPARTFOR"+d+"FROM"+fc,
1100                        true,   // write labels (variables)
1101                        true,   // selectively hide intermediate temp vars
1102                        true,   // prune unreachable heap regions
1103                        false,  // hide subset reachability states
1104                        true ); // hide edge taints
1105       }
1106     }
1107   }
1108    
1109
1110   protected ReachGraph getPartial( Descriptor d ) {
1111     return mapDescriptorToCompleteReachGraph.get( d );
1112   }
1113
1114   protected void setPartial( Descriptor d, ReachGraph rg ) {
1115     mapDescriptorToCompleteReachGraph.put( d, rg );
1116
1117     // when the flag for writing out every partial
1118     // result is set, we should spit out the graph,
1119     // but in order to give it a unique name we need
1120     // to track how many partial results for this
1121     // descriptor we've already written out
1122     if( writeAllIncrementalDOTs ) {
1123       if( !mapDescriptorToNumUpdates.containsKey( d ) ) {
1124         mapDescriptorToNumUpdates.put( d, new Integer( 0 ) );
1125       }
1126       Integer n = mapDescriptorToNumUpdates.get( d );
1127       
1128       rg.writeGraph( d+"COMPLETE"+String.format( "%05d", n ),
1129                      true,   // write labels (variables)
1130                      true,   // selectively hide intermediate temp vars
1131                      true,   // prune unreachable heap regions
1132                      false,  // hide subset reachability states
1133                      true ); // hide edge taints
1134       
1135       mapDescriptorToNumUpdates.put( d, n + 1 );
1136     }
1137   }
1138
1139
1140
1141   // return just the allocation site associated with one FlatNew node
1142   protected AllocSite getAllocSiteFromFlatNewPRIVATE( FlatNew fnew ) {
1143
1144     if( !mapFlatNewToAllocSite.containsKey( fnew ) ) {
1145       AllocSite as = 
1146         (AllocSite) Canonical.makeCanonical( new AllocSite( allocationDepth, 
1147                                                             fnew, 
1148                                                             fnew.getDisjointId() 
1149                                                             )
1150                                              );
1151
1152       // the newest nodes are single objects
1153       for( int i = 0; i < allocationDepth; ++i ) {
1154         Integer id = generateUniqueHeapRegionNodeID();
1155         as.setIthOldest( i, id );
1156         mapHrnIdToAllocSite.put( id, as );
1157       }
1158
1159       // the oldest node is a summary node
1160       as.setSummary( generateUniqueHeapRegionNodeID() );
1161
1162       mapFlatNewToAllocSite.put( fnew, as );
1163     }
1164
1165     return mapFlatNewToAllocSite.get( fnew );
1166   }
1167
1168
1169   public static boolean shouldAnalysisTrack( TypeDescriptor type ) {
1170     // don't track primitive types, but an array
1171     // of primitives is heap memory
1172     if( type.isImmutable() ) {
1173       return type.isArray();
1174     }
1175
1176     // everything else is an object
1177     return true;
1178   }
1179
1180
1181   /*
1182   // return all allocation sites in the method (there is one allocation
1183   // site per FlatNew node in a method)
1184   protected HashSet<AllocSite> getAllocSiteSet(Descriptor d) {
1185     if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
1186       buildAllocSiteSet(d);
1187     }
1188
1189     return mapDescriptorToAllocSiteSet.get(d);
1190
1191   }
1192   */
1193
1194   /*
1195   protected void buildAllocSiteSet(Descriptor d) {
1196     HashSet<AllocSite> s = new HashSet<AllocSite>();
1197
1198     FlatMethod fm = state.getMethodFlat( d );
1199
1200     // visit every node in this FlatMethod's IR graph
1201     // and make a set of the allocation sites from the
1202     // FlatNew node's visited
1203     HashSet<FlatNode> visited = new HashSet<FlatNode>();
1204     HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
1205     toVisit.add( fm );
1206
1207     while( !toVisit.isEmpty() ) {
1208       FlatNode n = toVisit.iterator().next();
1209
1210       if( n instanceof FlatNew ) {
1211         s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
1212       }
1213
1214       toVisit.remove( n );
1215       visited.add( n );
1216
1217       for( int i = 0; i < n.numNext(); ++i ) {
1218         FlatNode child = n.getNext( i );
1219         if( !visited.contains( child ) ) {
1220           toVisit.add( child );
1221         }
1222       }
1223     }
1224
1225     mapDescriptorToAllocSiteSet.put( d, s );
1226   }
1227   */
1228   /*
1229   protected HashSet<AllocSite> getFlaggedAllocSites(Descriptor dIn) {
1230     
1231     HashSet<AllocSite> out     = new HashSet<AllocSite>();
1232     HashSet<Descriptor>     toVisit = new HashSet<Descriptor>();
1233     HashSet<Descriptor>     visited = new HashSet<Descriptor>();
1234
1235     toVisit.add(dIn);
1236
1237     while( !toVisit.isEmpty() ) {
1238       Descriptor d = toVisit.iterator().next();
1239       toVisit.remove(d);
1240       visited.add(d);
1241
1242       HashSet<AllocSite> asSet = getAllocSiteSet(d);
1243       Iterator asItr = asSet.iterator();
1244       while( asItr.hasNext() ) {
1245         AllocSite as = (AllocSite) asItr.next();
1246         if( as.getDisjointAnalysisId() != null ) {
1247           out.add(as);
1248         }
1249       }
1250
1251       // enqueue callees of this method to be searched for
1252       // allocation sites also
1253       Set callees = callGraph.getCalleeSet(d);
1254       if( callees != null ) {
1255         Iterator methItr = callees.iterator();
1256         while( methItr.hasNext() ) {
1257           MethodDescriptor md = (MethodDescriptor) methItr.next();
1258
1259           if( !visited.contains(md) ) {
1260             toVisit.add(md);
1261           }
1262         }
1263       }
1264     }
1265     
1266     return out;
1267   }
1268   */
1269
1270   /*
1271   protected HashSet<AllocSite>
1272   getFlaggedAllocSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
1273
1274     HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
1275     HashSet<Descriptor>     toVisit    = new HashSet<Descriptor>();
1276     HashSet<Descriptor>     visited    = new HashSet<Descriptor>();
1277
1278     toVisit.add(td);
1279
1280     // traverse this task and all methods reachable from this task
1281     while( !toVisit.isEmpty() ) {
1282       Descriptor d = toVisit.iterator().next();
1283       toVisit.remove(d);
1284       visited.add(d);
1285
1286       HashSet<AllocSite> asSet = getAllocSiteSet(d);
1287       Iterator asItr = asSet.iterator();
1288       while( asItr.hasNext() ) {
1289         AllocSite as = (AllocSite) asItr.next();
1290         TypeDescriptor typed = as.getType();
1291         if( typed != null ) {
1292           ClassDescriptor cd = typed.getClassDesc();
1293           if( cd != null && cd.hasFlags() ) {
1294             asSetTotal.add(as);
1295           }
1296         }
1297       }
1298
1299       // enqueue callees of this method to be searched for
1300       // allocation sites also
1301       Set callees = callGraph.getCalleeSet(d);
1302       if( callees != null ) {
1303         Iterator methItr = callees.iterator();
1304         while( methItr.hasNext() ) {
1305           MethodDescriptor md = (MethodDescriptor) methItr.next();
1306
1307           if( !visited.contains(md) ) {
1308             toVisit.add(md);
1309           }
1310         }
1311       }
1312     }
1313
1314
1315     return asSetTotal;
1316   }
1317   */
1318
1319
1320   /*
1321   protected String computeAliasContextHistogram() {
1322     
1323     Hashtable<Integer, Integer> mapNumContexts2NumDesc = 
1324       new Hashtable<Integer, Integer>();
1325   
1326     Iterator itr = mapDescriptorToAllDescriptors.entrySet().iterator();
1327     while( itr.hasNext() ) {
1328       Map.Entry me = (Map.Entry) itr.next();
1329       HashSet<Descriptor> s = (HashSet<Descriptor>) me.getValue();
1330       
1331       Integer i = mapNumContexts2NumDesc.get( s.size() );
1332       if( i == null ) {
1333         i = new Integer( 0 );
1334       }
1335       mapNumContexts2NumDesc.put( s.size(), i + 1 );
1336     }   
1337
1338     String s = "";
1339     int total = 0;
1340
1341     itr = mapNumContexts2NumDesc.entrySet().iterator();
1342     while( itr.hasNext() ) {
1343       Map.Entry me = (Map.Entry) itr.next();
1344       Integer c0 = (Integer) me.getKey();
1345       Integer d0 = (Integer) me.getValue();
1346       total += d0;
1347       s += String.format( "%4d methods had %4d unique alias contexts.\n", d0, c0 );
1348     }
1349
1350     s += String.format( "\n%4d total methods analayzed.\n", total );
1351
1352     return s;
1353   }
1354
1355   protected int numMethodsAnalyzed() {    
1356     return descriptorsToAnalyze.size();
1357   }
1358   */
1359
1360   
1361   
1362   
1363   // Take in source entry which is the program's compiled entry and
1364   // create a new analysis entry, a method that takes no parameters
1365   // and appears to allocate the command line arguments and call the
1366   // source entry with them.  The purpose of this analysis entry is
1367   // to provide a top-level method context with no parameters left.
1368   protected void makeAnalysisEntryMethod( MethodDescriptor mdSourceEntry ) {
1369
1370     Modifiers mods = new Modifiers();
1371     mods.addModifier( Modifiers.PUBLIC );
1372     mods.addModifier( Modifiers.STATIC );
1373
1374     TypeDescriptor returnType = 
1375       new TypeDescriptor( TypeDescriptor.VOID );
1376
1377     this.mdAnalysisEntry = 
1378       new MethodDescriptor( mods,
1379                             returnType,
1380                             "analysisEntryMethod"
1381                             );
1382
1383     TempDescriptor cmdLineArgs = 
1384       new TempDescriptor( "args",
1385                           mdSourceEntry.getParamType( 0 )
1386                           );
1387
1388     FlatNew fn = 
1389       new FlatNew( mdSourceEntry.getParamType( 0 ),
1390                    cmdLineArgs,
1391                    false // is global 
1392                    );
1393     
1394     TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
1395     sourceEntryArgs[0] = cmdLineArgs;
1396     
1397     FlatCall fc = 
1398       new FlatCall( mdSourceEntry,
1399                     null, // dst temp
1400                     null, // this temp
1401                     sourceEntryArgs
1402                     );
1403
1404     FlatReturnNode frn = new FlatReturnNode( null );
1405
1406     FlatExit fe = new FlatExit();
1407
1408     this.fmAnalysisEntry = 
1409       new FlatMethod( mdAnalysisEntry, 
1410                       fe
1411                       );
1412
1413     this.fmAnalysisEntry.addNext( fn );
1414     fn.addNext( fc );
1415     fc.addNext( frn );
1416     frn.addNext( fe );
1417   }
1418
1419
1420   protected LinkedList<Descriptor> topologicalSort( Set<Descriptor> toSort ) {
1421
1422     Set       <Descriptor> discovered = new HashSet   <Descriptor>();
1423     LinkedList<Descriptor> sorted     = new LinkedList<Descriptor>();
1424   
1425     Iterator<Descriptor> itr = toSort.iterator();
1426     while( itr.hasNext() ) {
1427       Descriptor d = itr.next();
1428           
1429       if( !discovered.contains( d ) ) {
1430         dfsVisit( d, toSort, sorted, discovered );
1431       }
1432     }
1433     
1434     return sorted;
1435   }
1436   
1437   // While we're doing DFS on call graph, remember
1438   // dependencies for efficient queuing of methods
1439   // during interprocedural analysis:
1440   //
1441   // a dependent of a method decriptor d for this analysis is:
1442   //  1) a method or task that invokes d
1443   //  2) in the descriptorsToAnalyze set
1444   protected void dfsVisit( Descriptor             d,
1445                            Set       <Descriptor> toSort,                        
1446                            LinkedList<Descriptor> sorted,
1447                            Set       <Descriptor> discovered ) {
1448     discovered.add( d );
1449     
1450     // only methods have callers, tasks never do
1451     if( d instanceof MethodDescriptor ) {
1452
1453       MethodDescriptor md = (MethodDescriptor) d;
1454
1455       // the call graph is not aware that we have a fabricated
1456       // analysis entry that calls the program source's entry
1457       if( md == mdSourceEntry ) {
1458         if( !discovered.contains( mdAnalysisEntry ) ) {
1459           addDependent( mdSourceEntry,  // callee
1460                         mdAnalysisEntry // caller
1461                         );
1462           dfsVisit( mdAnalysisEntry, toSort, sorted, discovered );
1463         }
1464       }
1465
1466       // otherwise call graph guides DFS
1467       Iterator itr = callGraph.getCallerSet( md ).iterator();
1468       while( itr.hasNext() ) {
1469         Descriptor dCaller = (Descriptor) itr.next();
1470         
1471         // only consider callers in the original set to analyze
1472         if( !toSort.contains( dCaller ) ) {
1473           continue;
1474         }
1475           
1476         if( !discovered.contains( dCaller ) ) {
1477           addDependent( md,     // callee
1478                         dCaller // caller
1479                         );
1480
1481           dfsVisit( dCaller, toSort, sorted, discovered );
1482         }
1483       }
1484     }
1485     
1486     // for leaf-nodes last now!
1487     sorted.addLast( d );
1488   }
1489
1490
1491   protected void enqueue( Descriptor d ) {
1492     if( !descriptorsToVisitSet.contains( d ) ) {
1493       Integer priority = mapDescriptorToPriority.get( d );
1494       descriptorsToVisitQ.add( new DescriptorQWrapper( priority, 
1495                                                        d ) 
1496                                );
1497       descriptorsToVisitSet.add( d );
1498     }
1499   }
1500
1501
1502   // a dependent of a method decriptor d for this analysis is:
1503   //  1) a method or task that invokes d
1504   //  2) in the descriptorsToAnalyze set
1505   protected void addDependent( Descriptor callee, Descriptor caller ) {
1506     Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1507     if( deps == null ) {
1508       deps = new HashSet<Descriptor>();
1509     }
1510     deps.add( caller );
1511     mapDescriptorToSetDependents.put( callee, deps );
1512   }
1513   
1514   protected Set<Descriptor> getDependents( Descriptor callee ) {
1515     Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1516     if( deps == null ) {
1517       deps = new HashSet<Descriptor>();
1518       mapDescriptorToSetDependents.put( callee, deps );
1519     }
1520     return deps;
1521   }
1522
1523   
1524   public Hashtable<FlatCall, ReachGraph> getIHMcontributions( Descriptor d ) {
1525
1526     Hashtable<FlatCall, ReachGraph> heapsFromCallers = 
1527       mapDescriptorToIHMcontributions.get( d );
1528     
1529     if( heapsFromCallers == null ) {
1530       heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
1531       mapDescriptorToIHMcontributions.put( d, heapsFromCallers );
1532     }
1533     
1534     return heapsFromCallers;
1535   }
1536
1537   public ReachGraph getIHMcontribution( Descriptor d, 
1538                                         FlatCall   fc
1539                                         ) {
1540     Hashtable<FlatCall, ReachGraph> heapsFromCallers = 
1541       getIHMcontributions( d );
1542
1543     if( !heapsFromCallers.containsKey( fc ) ) {
1544       heapsFromCallers.put( fc, new ReachGraph() );
1545     }
1546
1547     return heapsFromCallers.get( fc );
1548   }
1549
1550   public void addIHMcontribution( Descriptor d,
1551                                   FlatCall   fc,
1552                                   ReachGraph rg
1553                                   ) {
1554     Hashtable<FlatCall, ReachGraph> heapsFromCallers = 
1555       getIHMcontributions( d );
1556
1557     heapsFromCallers.put( fc, rg );
1558   }
1559
1560 private AllocSite createParameterAllocSite(ReachGraph rg, TempDescriptor tempDesc) {
1561     
1562     // create temp descriptor for each parameter variable
1563     FlatNew flatNew = new FlatNew(tempDesc.getType(), tempDesc, false);
1564     // create allocation site
1565     AllocSite as = (AllocSite) Canonical.makeCanonical(new AllocSite( allocationDepth, flatNew, flatNew.getDisjointId()));
1566     for (int i = 0; i < allocationDepth; ++i) {
1567         Integer id = generateUniqueHeapRegionNodeID();
1568         as.setIthOldest(i, id);
1569         mapHrnIdToAllocSite.put(id, as);
1570     }
1571     // the oldest node is a summary node
1572     as.setSummary( generateUniqueHeapRegionNodeID() );
1573     
1574     rg.age(as);
1575     
1576     return as;
1577     
1578 }
1579
1580 private Set<FieldDescriptor> getFieldSetTobeAnalyzed(TypeDescriptor typeDesc){
1581         
1582         Set<FieldDescriptor> fieldSet=new HashSet<FieldDescriptor>();
1583     if(!typeDesc.isImmutable()){
1584             ClassDescriptor classDesc = typeDesc.getClassDesc();                    
1585             for (Iterator it = classDesc.getFields(); it.hasNext();) {
1586                     FieldDescriptor field = (FieldDescriptor) it.next();
1587                     TypeDescriptor fieldType = field.getType();
1588                     if (shouldAnalysisTrack( fieldType )) {
1589                         fieldSet.add(field);                    
1590                     }
1591             }
1592     }
1593     return fieldSet;
1594         
1595 }
1596
1597   private HeapRegionNode createMultiDeimensionalArrayHRN(ReachGraph rg, AllocSite alloc, HeapRegionNode srcHRN, FieldDescriptor fd, Hashtable<HeapRegionNode, HeapRegionNode> map, Hashtable<TypeDescriptor, HeapRegionNode> mapToExistingNode, ReachSet alpha ){
1598
1599         int dimCount=fd.getType().getArrayCount();
1600         HeapRegionNode prevNode=null;
1601         HeapRegionNode arrayEntryNode=null;
1602         for(int i=dimCount;i>0;i--){
1603                 TypeDescriptor typeDesc=fd.getType().dereference();//hack to get instance of type desc
1604                 typeDesc.setArrayCount(i);
1605                 TempDescriptor tempDesc=new TempDescriptor(typeDesc.getSymbol(),typeDesc);
1606                 HeapRegionNode hrnSummary ;
1607                 if(!mapToExistingNode.containsKey(typeDesc)){
1608                         AllocSite as;
1609                         if(i==dimCount){
1610                                 as = alloc;
1611                         }else{
1612                                 as = createParameterAllocSite(rg, tempDesc);
1613                         }
1614                         // make a new reference to allocated node
1615                     hrnSummary = 
1616                                 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1617                                                            false, // single object?
1618                                                            true, // summary?
1619                                                            false, // flagged?
1620                                                            false, // out-of-context?
1621                                                            as.getType(), // type
1622                                                            as, // allocation site
1623                                                            null, // inherent reach
1624                                                            alpha, // current reach
1625                                                            ExistPredSet.factory(rg.predTrue), // predicates
1626                                                            tempDesc.toString() // description
1627                                                            );
1628                     rg.id2hrn.put(as.getSummary(),hrnSummary);
1629                     
1630                     mapToExistingNode.put(typeDesc, hrnSummary);
1631                 }else{
1632                         hrnSummary=mapToExistingNode.get(typeDesc);
1633                 }
1634             
1635             if(prevNode==null){
1636                     // make a new reference between new summary node and source
1637                     RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1638                                                         hrnSummary, // dest
1639                                                         typeDesc, // type
1640                                                         fd.getSymbol(), // field name
1641                                                         alpha, // beta
1642                                                         ExistPredSet.factory(rg.predTrue) // predicates
1643                                                         );
1644                     
1645                     rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1646                     prevNode=hrnSummary;
1647                     arrayEntryNode=hrnSummary;
1648             }else{
1649                     // make a new reference between summary nodes of array
1650                     RefEdge edgeToSummary = new RefEdge(prevNode, // source
1651                                                         hrnSummary, // dest
1652                                                         typeDesc, // type
1653                                                         arrayElementFieldName, // field name
1654                                                         alpha, // beta
1655                                                         ExistPredSet.factory(rg.predTrue) // predicates
1656                                                         );
1657                     
1658                     rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1659                     prevNode=hrnSummary;
1660             }
1661             
1662         }
1663         
1664         // create a new obj node if obj has at least one non-primitive field
1665         TypeDescriptor type=fd.getType();
1666     if(getFieldSetTobeAnalyzed(type).size()>0){
1667         TypeDescriptor typeDesc=type.dereference();
1668         typeDesc.setArrayCount(0);
1669         if(!mapToExistingNode.containsKey(typeDesc)){
1670                 TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc);
1671                 AllocSite as = createParameterAllocSite(rg, tempDesc);
1672                 // make a new reference to allocated node
1673                     HeapRegionNode hrnSummary = 
1674                                 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1675                                                            false, // single object?
1676                                                            true, // summary?
1677                                                            false, // flagged?
1678                                                            false, // out-of-context?
1679                                                            typeDesc, // type
1680                                                            as, // allocation site
1681                                                            null, // inherent reach
1682                                                            alpha, // current reach
1683                                                            ExistPredSet.factory(rg.predTrue), // predicates
1684                                                            tempDesc.toString() // description
1685                                                            );
1686                     rg.id2hrn.put(as.getSummary(),hrnSummary);
1687                     mapToExistingNode.put(typeDesc, hrnSummary);
1688                     RefEdge edgeToSummary = new RefEdge(prevNode, // source
1689                                         hrnSummary, // dest
1690                                         typeDesc, // type
1691                                         arrayElementFieldName, // field name
1692                                         alpha, // beta
1693                                         ExistPredSet.factory(rg.predTrue) // predicates
1694                                         );
1695                     rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1696                     prevNode=hrnSummary;
1697         }else{
1698                 HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc);
1699                 if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null){
1700                         RefEdge edgeToSummary = new RefEdge(prevNode, // source
1701                                         hrnSummary, // dest
1702                                         typeDesc, // type
1703                                         arrayElementFieldName, // field name
1704                                         alpha, // beta
1705                                         ExistPredSet.factory(rg.predTrue) // predicates
1706                                         );
1707                     rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1708                 }
1709                  prevNode=hrnSummary;
1710         }
1711     }
1712         
1713         map.put(arrayEntryNode, prevNode);
1714         return arrayEntryNode;
1715 }
1716
1717 private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
1718     ReachGraph rg = new ReachGraph();
1719     TaskDescriptor taskDesc = fm.getTask();
1720     
1721     for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
1722         Descriptor paramDesc = taskDesc.getParameter(idx);
1723         TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
1724         
1725         // setup data structure
1726         Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet = 
1727             new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
1728         Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode = 
1729             new Hashtable<TypeDescriptor, HeapRegionNode>();
1730         Hashtable<HeapRegionNode, HeapRegionNode> mapToFirstDimensionArrayNode = 
1731             new Hashtable<HeapRegionNode, HeapRegionNode>();
1732         Set<String> doneSet = new HashSet<String>();
1733         
1734         TempDescriptor tempDesc = fm.getParameter(idx);
1735         
1736         AllocSite as = createParameterAllocSite(rg, tempDesc);
1737         VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
1738         Integer idNewest = as.getIthOldest(0);
1739         HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
1740         // make a new reference to allocated node
1741         RefEdge edgeNew = new RefEdge(lnX, // source
1742                                       hrnNewest, // dest
1743                                       taskDesc.getParamType(idx), // type
1744                                       null, // field name
1745                                       hrnNewest.getAlpha(), // beta
1746                                       ExistPredSet.factory(rg.predTrue) // predicates
1747                                       );
1748         rg.addRefEdge(lnX, hrnNewest, edgeNew);
1749         
1750         // set-up a work set for class field
1751         ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
1752         for (Iterator it = classDesc.getFields(); it.hasNext();) {
1753             FieldDescriptor fd = (FieldDescriptor) it.next();
1754             TypeDescriptor fieldType = fd.getType();
1755             if (shouldAnalysisTrack( fieldType )) {
1756                 HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
1757                 newMap.put(hrnNewest, fd);
1758                 workSet.add(newMap);
1759             }
1760         }
1761         
1762         int uniqueIdentifier = 0;
1763         while (!workSet.isEmpty()) {
1764             HashMap<HeapRegionNode, FieldDescriptor> map = workSet
1765                 .iterator().next();
1766             workSet.remove(map);
1767             
1768             Set<HeapRegionNode> key = map.keySet();
1769             HeapRegionNode srcHRN = key.iterator().next();
1770             FieldDescriptor fd = map.get(srcHRN);
1771             TypeDescriptor type = fd.getType();
1772             String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
1773             
1774             if (!doneSet.contains(doneSetIdentifier)) {
1775                 doneSet.add(doneSetIdentifier);
1776                 if (!mapTypeToExistingSummaryNode.containsKey(type)) {
1777                     // create new summary Node
1778                     TempDescriptor td = new TempDescriptor("temp"
1779                                                            + uniqueIdentifier, type);
1780                     
1781                     AllocSite allocSite;
1782                     if(type.equals(paramTypeDesc)){
1783                     //corresponding allocsite has already been created for a parameter variable.
1784                         allocSite=as;
1785                     }else{
1786                         allocSite = createParameterAllocSite(rg, td);
1787                     }
1788                     String strDesc = allocSite.toStringForDOT()
1789                         + "\\nsummary";
1790                     TypeDescriptor allocType=allocSite.getType();
1791                     
1792                     HeapRegionNode      hrnSummary;
1793                     if(allocType.isArray() && allocType.getArrayCount()>0){
1794                       hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha());
1795                     }else{                  
1796                         hrnSummary = 
1797                                         rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
1798                                                                    false, // single object?
1799                                                                    true, // summary?
1800                                                                    false, // flagged?
1801                                                                    false, // out-of-context?
1802                                                                    allocSite.getType(), // type
1803                                                                    allocSite, // allocation site
1804                                                                    null, // inherent reach
1805                                                                    hrnNewest.getAlpha(), // current reach
1806                                                                    ExistPredSet.factory(rg.predTrue), // predicates
1807                                                                    strDesc // description
1808                                                                    );
1809                                     rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
1810                     
1811                     // make a new reference to summary node
1812                     RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1813                                                         hrnSummary, // dest
1814                                                         type, // type
1815                                                         fd.getSymbol(), // field name
1816                                                         hrnNewest.getAlpha(), // beta
1817                                                         ExistPredSet.factory(rg.predTrue) // predicates
1818                                                         );
1819                     
1820                     rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1821                     }               
1822                     uniqueIdentifier++;
1823                     
1824                     mapTypeToExistingSummaryNode.put(type, hrnSummary);
1825                     
1826                     // set-up a work set for  fields of the class
1827                     Set<FieldDescriptor> fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type);
1828                     for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator
1829                                         .hasNext();) {
1830                                 FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator
1831                                                 .next();
1832                                 HeapRegionNode newDstHRN;
1833                                 if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)){
1834                                         //related heap region node is already exsited.
1835                                         newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary);
1836                                 }else{
1837                                         newDstHRN=hrnSummary;
1838                                 }
1839                                  doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor;                                                            
1840                                  if(!doneSet.contains(doneSetIdentifier)){
1841                                  // add new work item
1842                                          HashMap<HeapRegionNode, FieldDescriptor> newMap = 
1843                                             new HashMap<HeapRegionNode, FieldDescriptor>();
1844                                          newMap.put(newDstHRN, fieldDescriptor);
1845                                          workSet.add(newMap);
1846                                   }                             
1847                         }
1848                     
1849                 }else{
1850                     // if there exists corresponding summary node
1851                     HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
1852                     
1853                     RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1854                                                         hrnDst, // dest
1855                                                         fd.getType(), // type
1856                                                         fd.getSymbol(), // field name
1857                                                         srcHRN.getAlpha(), // beta
1858                                                         ExistPredSet.factory(rg.predTrue) // predicates
1859                                                         );
1860                     rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
1861                     
1862                 }               
1863             }       
1864         }           
1865     }   
1866 //    debugSnapshot(rg, fm, true);
1867     return rg;
1868 }
1869
1870 // return all allocation sites in the method (there is one allocation
1871 // site per FlatNew node in a method)
1872 private HashSet<AllocSite> getAllocationSiteSet(Descriptor d) {
1873   if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
1874     buildAllocationSiteSet(d);
1875   }
1876
1877   return mapDescriptorToAllocSiteSet.get(d);
1878
1879 }
1880
1881 private void buildAllocationSiteSet(Descriptor d) {
1882     HashSet<AllocSite> s = new HashSet<AllocSite>();
1883
1884     FlatMethod fm;
1885     if( d instanceof MethodDescriptor ) {
1886       fm = state.getMethodFlat( (MethodDescriptor) d);
1887     } else {
1888       assert d instanceof TaskDescriptor;
1889       fm = state.getMethodFlat( (TaskDescriptor) d);
1890     }
1891
1892     // visit every node in this FlatMethod's IR graph
1893     // and make a set of the allocation sites from the
1894     // FlatNew node's visited
1895     HashSet<FlatNode> visited = new HashSet<FlatNode>();
1896     HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
1897     toVisit.add(fm);
1898
1899     while( !toVisit.isEmpty() ) {
1900       FlatNode n = toVisit.iterator().next();
1901
1902       if( n instanceof FlatNew ) {
1903         s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
1904       }
1905
1906       toVisit.remove(n);
1907       visited.add(n);
1908
1909       for( int i = 0; i < n.numNext(); ++i ) {
1910         FlatNode child = n.getNext(i);
1911         if( !visited.contains(child) ) {
1912           toVisit.add(child);
1913         }
1914       }
1915     }
1916
1917     mapDescriptorToAllocSiteSet.put(d, s);
1918   }
1919
1920         private HashSet<AllocSite> getFlaggedAllocationSites(Descriptor dIn) {
1921
1922                 HashSet<AllocSite> out = new HashSet<AllocSite>();
1923                 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1924                 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1925
1926                 toVisit.add(dIn);
1927
1928                 while (!toVisit.isEmpty()) {
1929                         Descriptor d = toVisit.iterator().next();
1930                         toVisit.remove(d);
1931                         visited.add(d);
1932
1933                         HashSet<AllocSite> asSet = getAllocationSiteSet(d);
1934                         Iterator asItr = asSet.iterator();
1935                         while (asItr.hasNext()) {
1936                                 AllocSite as = (AllocSite) asItr.next();
1937                                 if (as.getDisjointAnalysisId() != null) {
1938                                         out.add(as);
1939                                 }
1940                         }
1941
1942                         // enqueue callees of this method to be searched for
1943                         // allocation sites also
1944                         Set callees = callGraph.getCalleeSet(d);
1945                         if (callees != null) {
1946                                 Iterator methItr = callees.iterator();
1947                                 while (methItr.hasNext()) {
1948                                         MethodDescriptor md = (MethodDescriptor) methItr.next();
1949
1950                                         if (!visited.contains(md)) {
1951                                                 toVisit.add(md);
1952                                         }
1953                                 }
1954                         }
1955                 }
1956
1957                 return out;
1958         }
1959  
1960     
1961 private HashSet<AllocSite>
1962 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
1963
1964   HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
1965   HashSet<Descriptor>     toVisit    = new HashSet<Descriptor>();
1966   HashSet<Descriptor>     visited    = new HashSet<Descriptor>();
1967
1968   toVisit.add(td);
1969
1970   // traverse this task and all methods reachable from this task
1971   while( !toVisit.isEmpty() ) {
1972     Descriptor d = toVisit.iterator().next();
1973     toVisit.remove(d);
1974     visited.add(d);
1975
1976     HashSet<AllocSite> asSet = getAllocationSiteSet(d);
1977     Iterator asItr = asSet.iterator();
1978     while( asItr.hasNext() ) {
1979         AllocSite as = (AllocSite) asItr.next();
1980         TypeDescriptor typed = as.getType();
1981         if( typed != null ) {
1982           ClassDescriptor cd = typed.getClassDesc();
1983           if( cd != null && cd.hasFlags() ) {
1984             asSetTotal.add(as);
1985           }
1986         }
1987     }
1988
1989     // enqueue callees of this method to be searched for
1990     // allocation sites also
1991     Set callees = callGraph.getCalleeSet(d);
1992     if( callees != null ) {
1993         Iterator methItr = callees.iterator();
1994         while( methItr.hasNext() ) {
1995           MethodDescriptor md = (MethodDescriptor) methItr.next();
1996
1997           if( !visited.contains(md) ) {
1998             toVisit.add(md);
1999           }
2000         }
2001     }
2002   }
2003
2004   return asSetTotal;
2005 }
2006
2007
2008   
2009   
2010   // get successive captures of the analysis state, use compiler
2011   // flags to control
2012   boolean takeDebugSnapshots = false;
2013   String  descSymbolDebug    = null;
2014   boolean stopAfterCapture   = false;
2015   int     snapVisitCounter   = 0;
2016   int     snapNodeCounter    = 0;
2017   int     visitStartCapture  = 0;
2018   int     numVisitsToCapture = 0;
2019
2020
2021   void debugSnapshot( ReachGraph rg, FlatNode fn, boolean in ) {
2022     if( snapVisitCounter > visitStartCapture + numVisitsToCapture ) {
2023       return;
2024     }
2025
2026     if( in ) {
2027
2028     }
2029
2030     if( snapVisitCounter >= visitStartCapture ) {
2031       System.out.println( "    @@@ snapping visit="+snapVisitCounter+
2032                           ", node="+snapNodeCounter+
2033                           " @@@" );
2034       String graphName;
2035       if( in ) {
2036         graphName = String.format( "snap%02d_%04din",
2037                                    snapVisitCounter,
2038                                    snapNodeCounter );
2039       } else {
2040         graphName = String.format( "snap%02d_%04dout",
2041                                    snapVisitCounter,
2042                                    snapNodeCounter );
2043       }
2044       if( fn != null ) {
2045         graphName = graphName + fn;
2046       }
2047       rg.writeGraph( graphName,
2048                      true,  // write labels (variables)
2049                      true,  // selectively hide intermediate temp vars
2050                      true,  // prune unreachable heap regions
2051                      false, // hide subset reachability states
2052                      true );// hide edge taints
2053     }
2054   }
2055
2056 }