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