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