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