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