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