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