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