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