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