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