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