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