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