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