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