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