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