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