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