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