changes for proper handling multi-dimensional array of task parameter.
[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 IR.*;
7 import IR.Flat.*;
8 import IR.Tree.Modifiers;
9 import java.util.*;
10 import java.io.*;
11
12
13 public class DisjointAnalysis {
14         
15           ///////////////////////////////////////////
16           //
17           //  Public interface to discover possible
18           //  aliases in the program under analysis
19           //
20           ///////////////////////////////////////////
21         
22           public HashSet<AllocSite>
23           getFlaggedAllocationSitesReachableFromTask(TaskDescriptor td) {
24             checkAnalysisComplete();
25             return getFlaggedAllocationSitesReachableFromTaskPRIVATE(td);
26           }
27           
28           public AllocSite getAllocationSiteFromFlatNew(FlatNew fn) {
29                     checkAnalysisComplete();
30                     return getAllocSiteFromFlatNewPRIVATE(fn);
31            }      
32           
33           public AllocSite getAllocationSiteFromHeapRegionNodeID(Integer id) {
34                     checkAnalysisComplete();
35                     return mapHrnIdToAllocSite.get(id);
36           }
37           
38           public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
39               int paramIndex1,
40               int paramIndex2) {
41                   checkAnalysisComplete();
42                   ReachGraph rg=mapDescriptorToCompleteReachGraph.get(taskOrMethod);
43                   FlatMethod fm=state.getMethodFlat(taskOrMethod);
44                   assert(rg != null);
45                   return rg.mayReachSharedObjects(fm, paramIndex1, paramIndex2);
46           }
47           
48         public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
49                         int paramIndex, AllocSite alloc) {
50                 checkAnalysisComplete();
51                 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
52             FlatMethod fm=state.getMethodFlat(taskOrMethod);
53                 assert (rg != null);
54                 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
55         }
56
57         public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
58                         AllocSite alloc, int paramIndex) {
59                 checkAnalysisComplete();
60                 ReachGraph rg  = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
61                 FlatMethod fm=state.getMethodFlat(taskOrMethod);
62                 assert (rg != null);
63                 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
64         }
65
66         public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
67                         AllocSite alloc1, AllocSite alloc2) {
68                 checkAnalysisComplete();
69                 ReachGraph rg  = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
70                 assert (rg != null);
71                 return rg.mayReachSharedObjects(alloc1, alloc2);
72         }
73         
74         public String prettyPrintNodeSet(Set<HeapRegionNode> s) {
75                 checkAnalysisComplete();
76
77                 String out = "{\n";
78
79                 Iterator<HeapRegionNode> i = s.iterator();
80                 while (i.hasNext()) {
81                         HeapRegionNode n = i.next();
82
83                         AllocSite as = n.getAllocSite();
84                         if (as == null) {
85                                 out += "  " + n.toString() + ",\n";
86                         } else {
87                                 out += "  " + n.toString() + ": " + as.toStringVerbose()
88                                                 + ",\n";
89                         }
90                 }
91
92                 out += "}\n";
93                 return out;
94         }
95         
96         // use the methods given above to check every possible alias
97           // between task parameters and flagged allocation sites reachable
98           // from the task
99           public void writeAllAliases(String outputFile, 
100                                       String timeReport,
101                                       String justTime,
102                                       boolean tabularOutput,
103                                       int numLines
104 )
105                         throws java.io.IOException {
106                 checkAnalysisComplete();
107
108                 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
109
110                 if (!tabularOutput) {
111                         bw.write("Conducting ownership analysis with allocation depth = "
112                                         + allocationDepth + "\n");
113                         bw.write(timeReport + "\n");
114                 }
115
116                 int numAlias = 0;
117
118                 // look through every task for potential aliases
119                 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
120                 while (taskItr.hasNext()) {
121                         TaskDescriptor td = (TaskDescriptor) taskItr.next();
122
123                         if (!tabularOutput) {
124                                 bw.write("\n---------" + td + "--------\n");
125                         }
126
127                         HashSet<AllocSite> allocSites = getFlaggedAllocationSitesReachableFromTask(td);
128
129                         Set<HeapRegionNode> common;
130
131                         // for each task parameter, check for aliases with
132                         // other task parameters and every allocation site
133                         // reachable from this task
134                         boolean foundSomeAlias = false;
135
136                         FlatMethod fm = state.getMethodFlat(td);
137                         for (int i = 0; i < fm.numParameters(); ++i) {
138
139                           // skip parameters with types that cannot reference
140                           // into the heap
141                           if( !shouldAnalysisTrack( fm.getParameter( i ).getType() ) ) {
142                             continue;
143                           }
144                           
145                                 // for the ith parameter check for aliases to all
146                                 // higher numbered parameters
147                                 for (int j = i + 1; j < fm.numParameters(); ++j) {
148
149                                   // skip parameters with types that cannot reference
150                                   // into the heap
151                                   if( !shouldAnalysisTrack( fm.getParameter( j ).getType() ) ) {
152                                     continue;
153                                   }
154
155
156                                   common = hasPotentialSharing(td, i, j);
157                                         if (!common.isEmpty()) {
158                                                 foundSomeAlias = true;
159                                                 if (!tabularOutput) {
160                                                         bw.write("Potential alias between parameters " + i
161                                                                         + " and " + j + ".\n");
162                                                         bw.write(prettyPrintNodeSet(common) + "\n");
163                                                 } else {
164                                                         ++numAlias;
165                                                 }
166                                         }
167                                 }
168
169                                 // for the ith parameter, check for aliases against
170                                 // the set of allocation sites reachable from this
171                                 // task context
172                                 Iterator allocItr = allocSites.iterator();
173                                 while (allocItr.hasNext()) {
174                                         AllocSite as = (AllocSite) allocItr.next();
175                                         common = hasPotentialSharing(td, i, as);
176                                         if (!common.isEmpty()) {
177                                                 foundSomeAlias = true;
178                                                 if (!tabularOutput) {
179                                                         bw.write("Potential alias between parameter " + i
180                                                                         + " and " + as.getFlatNew() + ".\n");
181                                                         bw.write(prettyPrintNodeSet(common) + "\n");
182                                                 } else {
183                                                         ++numAlias;
184                                                 }
185                                         }
186                                 }
187                         }
188
189                         // for each allocation site check for aliases 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                                                         foundSomeAlias = true;
206                                                         if (!tabularOutput) {
207                                                                 bw.write("Potential alias between "
208                                                                                 + as1.getFlatNew() + " and "
209                                                                                 + as2.getFlatNew() + ".\n");
210                                                                 bw.write(prettyPrintNodeSet(common) + "\n");
211                                                         } else {
212                                                                 ++numAlias;
213                                                         }
214                                                 }
215                                         }
216                                 }
217
218                                 outerChecked.add(as1);
219                         }
220
221                         if (!foundSomeAlias) {
222                                 if (!tabularOutput) {
223                                         bw.write("No aliases between flagged objects in Task " + td
224                                                         + ".\n");
225                                 }
226                         }
227                 }
228
229                 /*
230                 if (!tabularOutput) {
231                         bw.write("\n" + computeAliasContextHistogram());
232                 } else {
233                         bw.write(" & " + numAlias + " & " + justTime + " & " + numLines
234                                         + " & " + numMethodsAnalyzed() + " \\\\\n");
235                 }
236                 */
237
238                 bw.close();
239         }
240         
241         // this version of writeAllAliases is for Java programs that have no tasks
242           public void writeAllAliasesJava(String outputFile, 
243                                           String timeReport,
244                                           String justTime,
245                                           boolean tabularOutput,
246                                           int numLines
247 )
248                         throws java.io.IOException {
249                 checkAnalysisComplete();
250
251                 assert !state.TASK;
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 foundSomeAlias = false;
260
261                 Descriptor d = typeUtil.getMain();
262                 HashSet<AllocSite> allocSites = getFlaggedAllocationSites(d);
263
264                 // for each allocation site check for aliases 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                                                 foundSomeAlias = true;
282                                                 bw.write("Potential alias between "
283                                                                 + as1.getDisjointAnalysisId() + " and "
284                                                                 + as2.getDisjointAnalysisId() + ".\n");
285                                                 bw.write(prettyPrintNodeSet(common) + "\n");
286                                         }
287                                 }
288                         }
289
290                         outerChecked.add(as1);
291                 }
292
293                 if (!foundSomeAlias) {
294                         bw.write("No aliases between flagged objects found.\n");
295                 }
296
297 //              bw.write("\n" + computeAliasContextHistogram());
298                 bw.close();
299         }
300           
301           ///////////////////////////////////////////
302           //
303           // end public interface
304           //
305           ///////////////////////////////////////////
306
307           protected void checkAnalysisComplete() {
308                     if( !analysisComplete ) {
309                       throw new Error("Warning: public interface method called while analysis is running.");
310                     }
311           } 
312
313
314   // data from the compiler
315   public State            state;
316   public CallGraph        callGraph;
317   public Liveness         liveness;
318   public ArrayReferencees arrayReferencees;
319   public TypeUtil         typeUtil;
320   public int              allocationDepth;
321   
322   // data structure for public interface
323   private Hashtable<Descriptor,    HashSet<AllocSite> > mapDescriptorToAllocSiteSet;
324
325   
326   // for public interface methods to warn that they
327   // are grabbing results during analysis
328   private boolean analysisComplete;
329
330
331   // used to identify HeapRegionNode objects
332   // A unique ID equates an object in one
333   // ownership graph with an object in another
334   // graph that logically represents the same
335   // heap region
336   // start at 10 and increment to reserve some
337   // IDs for special purposes
338   static protected int uniqueIDcount = 10;
339
340
341   // An out-of-scope method created by the
342   // analysis that has no parameters, and
343   // appears to allocate the command line
344   // arguments, then invoke the source code's
345   // main method.  The purpose of this is to
346   // provide the analysis with an explicit
347   // top-level context with no parameters
348   protected MethodDescriptor mdAnalysisEntry;
349   protected FlatMethod       fmAnalysisEntry;
350
351   // main method defined by source program
352   protected MethodDescriptor mdSourceEntry;
353
354   // the set of task and/or method descriptors
355   // reachable in call graph
356   protected Set<Descriptor> 
357     descriptorsToAnalyze;
358
359   // current descriptors to visit in fixed-point
360   // interprocedural analysis, prioritized by
361   // dependency in the call graph
362   protected PriorityQueue<DescriptorQWrapper> 
363     descriptorsToVisitQ;
364   
365   // a duplication of the above structure, but
366   // for efficient testing of inclusion
367   protected HashSet<Descriptor> 
368     descriptorsToVisitSet;
369
370   // storage for priorities (doesn't make sense)
371   // to add it to the Descriptor class, just in
372   // this analysis
373   protected Hashtable<Descriptor, Integer> 
374     mapDescriptorToPriority;
375
376
377   // maps a descriptor to its current partial result
378   // from the intraprocedural fixed-point analysis--
379   // then the interprocedural analysis settles, this
380   // mapping will have the final results for each
381   // method descriptor
382   protected Hashtable<Descriptor, ReachGraph> 
383     mapDescriptorToCompleteReachGraph;
384
385   // maps a descriptor to its known dependents: namely
386   // methods or tasks that call the descriptor's method
387   // AND are part of this analysis (reachable from main)
388   protected Hashtable< Descriptor, Set<Descriptor> >
389     mapDescriptorToSetDependents;
390
391   // maps each flat new to one analysis abstraction
392   // allocate site object, these exist outside reach graphs
393   protected Hashtable<FlatNew, AllocSite>
394     mapFlatNewToAllocSite;
395
396   // maps intergraph heap region IDs to intergraph
397   // allocation sites that created them, a redundant
398   // structure for efficiency in some operations
399   protected Hashtable<Integer, AllocSite>
400     mapHrnIdToAllocSite;
401
402   // maps a method to its initial heap model (IHM) that
403   // is the set of reachability graphs from every caller
404   // site, all merged together.  The reason that we keep
405   // them separate is that any one call site's contribution
406   // to the IHM may changed along the path to the fixed point
407   protected Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >
408     mapDescriptorToIHMcontributions;
409
410   // TODO -- CHANGE EDGE/TYPE/FIELD storage!
411   public static final String arrayElementFieldName = "___element_";
412   static protected Hashtable<TypeDescriptor, FieldDescriptor>
413     mapTypeToArrayField;
414
415   // for controlling DOT file output
416   protected boolean writeFinalDOTs;
417   protected boolean writeAllIncrementalDOTs;
418
419   // supporting DOT output--when we want to write every
420   // partial method result, keep a tally for generating
421   // unique filenames
422   protected Hashtable<Descriptor, Integer>
423     mapDescriptorToNumUpdates;
424   
425   //map task descriptor to initial task parameter 
426   protected Hashtable<Descriptor, ReachGraph>
427   mapDescriptorToReachGraph;
428
429
430   // allocate various structures that are not local
431   // to a single class method--should be done once
432   protected void allocateStructures() {    
433     descriptorsToAnalyze = new HashSet<Descriptor>();
434
435     mapDescriptorToCompleteReachGraph =
436       new Hashtable<Descriptor, ReachGraph>();
437
438     mapDescriptorToNumUpdates =
439       new Hashtable<Descriptor, Integer>();
440
441     mapDescriptorToSetDependents =
442       new Hashtable< Descriptor, Set<Descriptor> >();
443
444     mapFlatNewToAllocSite = 
445       new Hashtable<FlatNew, AllocSite>();
446
447     mapDescriptorToIHMcontributions =
448       new Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >();
449
450     mapHrnIdToAllocSite =
451       new Hashtable<Integer, AllocSite>();
452
453     mapTypeToArrayField = 
454       new Hashtable <TypeDescriptor, FieldDescriptor>();
455
456     descriptorsToVisitQ =
457       new PriorityQueue<DescriptorQWrapper>();
458
459     descriptorsToVisitSet =
460       new HashSet<Descriptor>();
461
462     mapDescriptorToPriority =
463       new Hashtable<Descriptor, Integer>();
464     
465     mapDescriptorToAllocSiteSet =
466         new Hashtable<Descriptor,    HashSet<AllocSite> >();
467     
468     mapDescriptorToReachGraph = 
469         new Hashtable<Descriptor, ReachGraph>();
470   }
471
472
473
474   // this analysis generates a disjoint reachability
475   // graph for every reachable method in the program
476   public DisjointAnalysis( State            s,
477                            TypeUtil         tu,
478                            CallGraph        cg,
479                            Liveness         l,
480                            ArrayReferencees ar
481                            ) throws java.io.IOException {
482     init( s, tu, cg, l, ar );
483   }
484   
485   protected void init( State            state,
486                        TypeUtil         typeUtil,
487                        CallGraph        callGraph,
488                        Liveness         liveness,
489                        ArrayReferencees arrayReferencees
490                        ) throws java.io.IOException {
491           
492         analysisComplete = false;
493     
494     this.state                   = state;
495     this.typeUtil                = typeUtil;
496     this.callGraph               = callGraph;
497     this.liveness                = liveness;
498     this.arrayReferencees        = arrayReferencees;
499     this.allocationDepth         = state.DISJOINTALLOCDEPTH;
500
501     this.writeFinalDOTs          = state.DISJOINTWRITEDOTS && !state.DISJOINTWRITEALL;
502     this.writeAllIncrementalDOTs = state.DISJOINTWRITEDOTS &&  state.DISJOINTWRITEALL;
503
504     this.takeDebugSnapshots      = state.DISJOINTSNAPSYMBOL != null;
505     this.descSymbolDebug         = state.DISJOINTSNAPSYMBOL;
506     this.visitStartCapture       = state.DISJOINTSNAPVISITTOSTART;
507     this.numVisitsToCapture      = state.DISJOINTSNAPNUMVISITS;
508     this.stopAfterCapture        = state.DISJOINTSNAPSTOPAFTER;
509     this.snapVisitCounter        = 1; // count visits from 1 (user will write 1, means 1st visit)
510     this.snapNodeCounter         = 0; // count nodes from 0
511             
512     // set some static configuration for ReachGraphs
513     ReachGraph.allocationDepth = allocationDepth;
514     ReachGraph.typeUtil        = typeUtil;
515
516     ReachGraph.debugCallSiteVisitsUntilExit = state.DISJOINTDEBUGCALLCOUNT;
517
518     allocateStructures();
519
520     double timeStartAnalysis = (double) System.nanoTime();
521
522     // start interprocedural fixed-point computation
523     analyzeMethods();
524     analysisComplete=true;
525
526     double timeEndAnalysis = (double) System.nanoTime();
527     double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
528     String treport = String.format( "The reachability analysis took %.3f sec.", dt );
529     String justtime = String.format( "%.2f", dt );
530     System.out.println( treport );
531
532     if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
533       writeFinalGraphs();      
534     }
535
536     if( state.DISJOINTWRITEIHMS ) {
537       writeFinalIHMs();
538     }
539
540     if( state.DISJOINTALIASFILE != null ) {
541       if( state.TASK ) {
542         writeAllAliases(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines);
543       } else {
544         /*
545         writeAllAliasesJava( aliasFile, 
546                              treport, 
547                              justtime, 
548                              state.DISJOINTALIASTAB, 
549                              state.lines );
550         */
551       }
552     }
553   }
554
555
556   // fixed-point computation over the call graph--when a
557   // method's callees are updated, it must be reanalyzed
558   protected void analyzeMethods() throws java.io.IOException {  
559
560     if( state.TASK ) {
561       // This analysis does not support Bamboo at the moment,
562       // but if it does in the future we would initialize the
563       // set of descriptors to analyze as the program-reachable
564       // tasks and the methods callable by them.  For Java,
565       // just methods reachable from the main method.
566       System.out.println( "Bamboo..." );
567       Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
568       
569       while (taskItr.hasNext()) {
570           TaskDescriptor td = (TaskDescriptor) taskItr.next();
571           if (!descriptorsToAnalyze.contains(td)) {           
572               descriptorsToAnalyze.add(td);
573               descriptorsToAnalyze.addAll(callGraph.getAllMethods(td));
574           }       
575       }
576
577     } else {
578       // add all methods transitively reachable from the
579       // source's main to set for analysis
580       mdSourceEntry = typeUtil.getMain();
581       descriptorsToAnalyze.add( mdSourceEntry );
582       descriptorsToAnalyze.addAll( 
583         callGraph.getAllMethods( mdSourceEntry ) 
584                                    );
585
586       // fabricate an empty calling context that will call
587       // the source's main, but call graph doesn't know
588       // about it, so explicitly add it
589       makeAnalysisEntryMethod( mdSourceEntry );
590       descriptorsToAnalyze.add( mdAnalysisEntry );
591     }
592
593     // topologically sort according to the call graph so 
594     // leaf calls are ordered first, smarter analysis order
595     // CHANGED: order leaf calls last!!
596     LinkedList<Descriptor> sortedDescriptors = 
597       topologicalSort( descriptorsToAnalyze );
598
599     // add sorted descriptors to priority queue, and duplicate
600     // the queue as a set for efficiently testing whether some
601     // method is marked for analysis
602     int p = 0;
603     Iterator<Descriptor> dItr = sortedDescriptors.iterator();
604     while( dItr.hasNext() ) {
605       Descriptor d = dItr.next();
606       mapDescriptorToPriority.put( d, new Integer( p ) );
607       descriptorsToVisitQ.add( new DescriptorQWrapper( p, d ) );
608       descriptorsToVisitSet.add( d );
609       ++p;
610     }
611
612     // analyze methods from the priority queue until it is empty
613     while( !descriptorsToVisitQ.isEmpty() ) {
614       Descriptor d = descriptorsToVisitQ.poll().getDescriptor();
615       assert descriptorsToVisitSet.contains( d );
616       descriptorsToVisitSet.remove( d );
617
618       // because the task or method descriptor just extracted
619       // was in the "to visit" set it either hasn't been analyzed
620       // yet, or some method that it depends on has been
621       // updated.  Recompute a complete reachability graph for
622       // this task/method and compare it to any previous result.
623       // If there is a change detected, add any methods/tasks
624       // that depend on this one to the "to visit" set.
625
626       System.out.println( "Analyzing " + d );
627
628       ReachGraph rg     = analyzeMethod( d );
629       ReachGraph rgPrev = getPartial( d );
630       
631       if( !rg.equals( rgPrev ) ) {
632         setPartial( d, rg );
633         
634         // results for d changed, so enqueue dependents
635         // of d for further analysis
636         Iterator<Descriptor> depsItr = getDependents( d ).iterator();
637         while( depsItr.hasNext() ) {
638           Descriptor dNext = depsItr.next();
639           enqueue( dNext );
640         }
641       }      
642     }
643   }
644
645   protected ReachGraph analyzeMethod( Descriptor d ) 
646     throws java.io.IOException {
647
648     // get the flat code for this descriptor
649     FlatMethod fm;
650     if( d == mdAnalysisEntry ) {
651       fm = fmAnalysisEntry;
652     } else {
653       fm = state.getMethodFlat( d );
654     }
655       
656     // intraprocedural work set
657     Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
658     flatNodesToVisit.add( fm );
659     
660     // mapping of current partial results
661     Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraph =
662       new Hashtable<FlatNode, ReachGraph>();
663
664     // the set of return nodes partial results that will be combined as
665     // the final, conservative approximation of the entire method
666     HashSet<FlatReturnNode> setReturns = new HashSet<FlatReturnNode>();
667
668     while( !flatNodesToVisit.isEmpty() ) {
669       FlatNode fn = (FlatNode) flatNodesToVisit.iterator().next();
670       flatNodesToVisit.remove( fn );
671
672       // effect transfer function defined by this node,
673       // then compare it to the old graph at this node
674       // to see if anything was updated.
675
676       ReachGraph rg = new ReachGraph();
677       TaskDescriptor taskDesc;
678       if(fn instanceof FlatMethod && (taskDesc=((FlatMethod)fn).getTask())!=null){
679           if(mapDescriptorToReachGraph.containsKey(taskDesc)){
680                   // retrieve existing reach graph if it is not first time
681                   rg=mapDescriptorToReachGraph.get(taskDesc);
682           }else{
683                   // create initial reach graph for a task
684                   rg=createInitialTaskReachGraph((FlatMethod)fn);
685                   rg.globalSweep();
686                   mapDescriptorToReachGraph.put(taskDesc, rg);
687           }
688       }
689
690       // start by merging all node's parents' graphs
691       for( int i = 0; i < fn.numPrev(); ++i ) {
692         FlatNode pn = fn.getPrev( i );
693         if( mapFlatNodeToReachGraph.containsKey( pn ) ) {
694           ReachGraph rgParent = mapFlatNodeToReachGraph.get( pn );
695           rg.merge( rgParent );
696         }
697       }
698
699
700       if( takeDebugSnapshots && 
701           d.getSymbol().equals( descSymbolDebug ) 
702           ) {
703         debugSnapshot( rg, fn, true );
704       }
705
706
707       // modify rg with appropriate transfer function
708       rg = analyzeFlatNode( d, fm, fn, setReturns, rg );
709
710
711       if( takeDebugSnapshots && 
712           d.getSymbol().equals( descSymbolDebug ) 
713           ) {
714         debugSnapshot( rg, fn, false );
715         ++snapNodeCounter;
716       }
717           
718
719       // if the results of the new graph are different from
720       // the current graph at this node, replace the graph
721       // with the update and enqueue the children
722       ReachGraph rgPrev = mapFlatNodeToReachGraph.get( fn );
723       if( !rg.equals( rgPrev ) ) {
724         mapFlatNodeToReachGraph.put( fn, rg );
725
726         for( int i = 0; i < fn.numNext(); i++ ) {
727           FlatNode nn = fn.getNext( i );
728           flatNodesToVisit.add( nn );
729         }
730       }
731     }
732
733     // end by merging all return nodes into a complete
734     // ownership graph that represents all possible heap
735     // states after the flat method returns
736     ReachGraph completeGraph = new ReachGraph();
737
738     assert !setReturns.isEmpty();
739     Iterator retItr = setReturns.iterator();
740     while( retItr.hasNext() ) {
741       FlatReturnNode frn = (FlatReturnNode) retItr.next();
742
743       assert mapFlatNodeToReachGraph.containsKey( frn );
744       ReachGraph rgRet = mapFlatNodeToReachGraph.get( frn );
745
746       completeGraph.merge( rgRet );
747     }
748
749
750     if( takeDebugSnapshots && 
751         d.getSymbol().equals( descSymbolDebug ) 
752         ) {
753       // increment that we've visited the debug snap
754       // method, and reset the node counter
755       System.out.println( "    @@@ debug snap at visit "+snapVisitCounter );
756       ++snapVisitCounter;
757       snapNodeCounter = 0;
758
759       if( snapVisitCounter == visitStartCapture + numVisitsToCapture && 
760           stopAfterCapture 
761           ) {
762         System.out.println( "!!! Stopping analysis after debug snap captures. !!!" );
763         System.exit( 0 );
764       }
765     }
766
767
768     return completeGraph;
769   }
770
771   
772   protected ReachGraph
773     analyzeFlatNode( Descriptor              d,
774                      FlatMethod              fmContaining,
775                      FlatNode                fn,
776                      HashSet<FlatReturnNode> setRetNodes,
777                      ReachGraph              rg
778                      ) throws java.io.IOException {
779
780     
781     // any variables that are no longer live should be
782     // nullified in the graph to reduce edges
783     //rg.nullifyDeadVars( liveness.getLiveInTemps( fmContaining, fn ) );
784
785           
786     TempDescriptor  lhs;
787     TempDescriptor  rhs;
788     FieldDescriptor fld;
789
790     // use node type to decide what transfer function
791     // to apply to the reachability graph
792     switch( fn.kind() ) {
793
794     case FKind.FlatMethod: {
795       // construct this method's initial heap model (IHM)
796       // since we're working on the FlatMethod, we know
797       // the incoming ReachGraph 'rg' is empty
798
799       Hashtable<FlatCall, ReachGraph> heapsFromCallers = 
800         getIHMcontributions( d );
801
802       Set entrySet = heapsFromCallers.entrySet();
803       Iterator itr = entrySet.iterator();
804       while( itr.hasNext() ) {
805         Map.Entry  me        = (Map.Entry)  itr.next();
806         FlatCall   fc        = (FlatCall)   me.getKey();
807         ReachGraph rgContrib = (ReachGraph) me.getValue();
808
809         assert fc.getMethod().equals( d );
810
811         // some call sites are in same method context though,
812         // and all of them should be merged together first,
813         // then heaps from different contexts should be merged
814         // THIS ASSUMES DIFFERENT CONTEXTS NEED SPECIAL CONSIDERATION!
815         // such as, do allocation sites need to be aged?
816
817         rg.merge_diffMethodContext( rgContrib );
818       }      
819     } break;
820       
821     case FKind.FlatOpNode:
822       FlatOpNode fon = (FlatOpNode) fn;
823       if( fon.getOp().getOp() == Operation.ASSIGN ) {
824         lhs = fon.getDest();
825         rhs = fon.getLeft();
826         rg.assignTempXEqualToTempY( lhs, rhs );
827       }
828       break;
829
830     case FKind.FlatCastNode:
831       FlatCastNode fcn = (FlatCastNode) fn;
832       lhs = fcn.getDst();
833       rhs = fcn.getSrc();
834
835       TypeDescriptor td = fcn.getType();
836       assert td != null;
837       
838       rg.assignTempXEqualToCastedTempY( lhs, rhs, td );
839       break;
840
841     case FKind.FlatFieldNode:
842       FlatFieldNode ffn = (FlatFieldNode) fn;
843       lhs = ffn.getDst();
844       rhs = ffn.getSrc();
845       fld = ffn.getField();
846       if( shouldAnalysisTrack( fld.getType() ) ) {
847         rg.assignTempXEqualToTempYFieldF( lhs, rhs, fld );
848       }          
849       break;
850
851     case FKind.FlatSetFieldNode:
852       FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
853       lhs = fsfn.getDst();
854       fld = fsfn.getField();
855       rhs = fsfn.getSrc();
856       if( shouldAnalysisTrack( fld.getType() ) ) {
857         rg.assignTempXFieldFEqualToTempY( lhs, fld, rhs );
858       }           
859       break;
860
861     case FKind.FlatElementNode:
862       FlatElementNode fen = (FlatElementNode) fn;
863       lhs = fen.getDst();
864       rhs = fen.getSrc();
865       if( shouldAnalysisTrack( lhs.getType() ) ) {
866
867         assert rhs.getType() != null;
868         assert rhs.getType().isArray();
869         
870         TypeDescriptor  tdElement = rhs.getType().dereference();
871         FieldDescriptor fdElement = getArrayField( tdElement );
872   
873         rg.assignTempXEqualToTempYFieldF( lhs, rhs, fdElement );
874       }
875       break;
876
877     case FKind.FlatSetElementNode:
878       FlatSetElementNode fsen = (FlatSetElementNode) fn;
879
880       if( arrayReferencees.doesNotCreateNewReaching( fsen ) ) {
881         // skip this node if it cannot create new reachability paths
882         break;
883       }
884
885       lhs = fsen.getDst();
886       rhs = fsen.getSrc();
887       if( shouldAnalysisTrack( rhs.getType() ) ) {
888
889         assert lhs.getType() != null;
890         assert lhs.getType().isArray();
891         
892         TypeDescriptor  tdElement = lhs.getType().dereference();
893         FieldDescriptor fdElement = getArrayField( tdElement );
894
895         rg.assignTempXFieldFEqualToTempY( lhs, fdElement, rhs );
896       }
897       break;
898       
899     case FKind.FlatNew:
900       FlatNew fnn = (FlatNew) fn;
901       lhs = fnn.getDst();
902       if( shouldAnalysisTrack( lhs.getType() ) ) {
903         AllocSite as = getAllocSiteFromFlatNewPRIVATE( fnn );   
904         rg.assignTempEqualToNewAlloc( lhs, as );
905       }
906       break;
907
908     case FKind.FlatCall: {
909       //TODO: temporal fix for task descriptor case
910       //MethodDescriptor mdCaller = fmContaining.getMethod();
911       Descriptor mdCaller;
912       if(fmContaining.getMethod()!=null){
913           mdCaller  = fmContaining.getMethod();
914       }else{
915           mdCaller = fmContaining.getTask();
916       }      
917       FlatCall         fc       = (FlatCall) fn;
918       MethodDescriptor mdCallee = fc.getMethod();
919       FlatMethod       fmCallee = state.getMethodFlat( mdCallee );
920
921       boolean writeDebugDOTs = 
922         mdCaller.getSymbol().equals( state.DISJOINTDEBUGCALLER ) &&
923         mdCallee.getSymbol().equals( state.DISJOINTDEBUGCALLEE );      
924
925
926       // calculate the heap this call site can reach--note this is
927       // not used for the current call site transform, we are
928       // grabbing this heap model for future analysis of the callees,
929       // so if different results emerge we will return to this site
930       ReachGraph heapForThisCall_old = 
931         getIHMcontribution( mdCallee, fc );
932
933       // the computation of the callee-reachable heap
934       // is useful for making the callee starting point
935       // and for applying the call site transfer function
936       Set<Integer> callerNodeIDsCopiedToCallee = 
937         new HashSet<Integer>();
938
939       ReachGraph heapForThisCall_cur = 
940         rg.makeCalleeView( fc, 
941                            fmCallee,
942                            callerNodeIDsCopiedToCallee,
943                            writeDebugDOTs
944                            );
945
946       if( !heapForThisCall_cur.equals( heapForThisCall_old ) ) {        
947         // if heap at call site changed, update the contribution,
948         // and reschedule the callee for analysis
949         addIHMcontribution( mdCallee, fc, heapForThisCall_cur );        
950         enqueue( mdCallee );
951       }
952
953
954
955
956       // the transformation for a call site should update the
957       // current heap abstraction with any effects from the callee,
958       // or if the method is virtual, the effects from any possible
959       // callees, so find the set of callees...
960       Set<MethodDescriptor> setPossibleCallees =
961         new HashSet<MethodDescriptor>();
962
963       if( mdCallee.isStatic() ) {        
964         setPossibleCallees.add( mdCallee );
965       } else {
966         TypeDescriptor typeDesc = fc.getThis().getType();
967         setPossibleCallees.addAll( callGraph.getMethods( mdCallee, 
968                                                          typeDesc )
969                                    );
970       }
971
972       ReachGraph rgMergeOfEffects = new ReachGraph();
973
974       Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
975       while( mdItr.hasNext() ) {
976         MethodDescriptor mdPossible = mdItr.next();
977         FlatMethod       fmPossible = state.getMethodFlat( mdPossible );
978
979         addDependent( mdPossible, // callee
980                       d );        // caller
981
982         // don't alter the working graph (rg) until we compute a 
983         // result for every possible callee, merge them all together,
984         // then set rg to that
985         ReachGraph rgCopy = new ReachGraph();
986         rgCopy.merge( rg );             
987                 
988         ReachGraph rgEffect = getPartial( mdPossible );
989
990         if( rgEffect == null ) {
991           // if this method has never been analyzed just schedule it 
992           // for analysis and skip over this call site for now
993           enqueue( mdPossible );
994         } else {
995           rgCopy.resolveMethodCall( fc, 
996                                     fmPossible, 
997                                     rgEffect,
998                                     callerNodeIDsCopiedToCallee,
999                                     writeDebugDOTs
1000                                     );
1001         }
1002         
1003         rgMergeOfEffects.merge( rgCopy );
1004       }
1005
1006
1007       // now that we've taken care of building heap models for
1008       // callee analysis, finish this transformation
1009       rg = rgMergeOfEffects;
1010     } break;
1011       
1012
1013     case FKind.FlatReturnNode:
1014       FlatReturnNode frn = (FlatReturnNode) fn;
1015       rhs = frn.getReturnTemp();
1016       if( rhs != null && shouldAnalysisTrack( rhs.getType() ) ) {
1017         rg.assignReturnEqualToTemp( rhs );
1018       }
1019       setRetNodes.add( frn );
1020       break;
1021
1022     } // end switch
1023
1024     
1025     // dead variables were removed before the above transfer function
1026     // was applied, so eliminate heap regions and edges that are no
1027     // longer part of the abstractly-live heap graph, and sweep up
1028     // and reachability effects that are altered by the reduction
1029     //rg.abstractGarbageCollect();
1030     //rg.globalSweep();
1031
1032
1033     // at this point rg should be the correct update
1034     // by an above transfer function, or untouched if
1035     // the flat node type doesn't affect the heap
1036     return rg;
1037   }
1038
1039   
1040   // this method should generate integers strictly greater than zero!
1041   // special "shadow" regions are made from a heap region by negating
1042   // the ID
1043   static public Integer generateUniqueHeapRegionNodeID() {
1044     ++uniqueIDcount;
1045     return new Integer( uniqueIDcount );
1046   }
1047
1048
1049   
1050   static public FieldDescriptor getArrayField( TypeDescriptor tdElement ) {
1051     FieldDescriptor fdElement = mapTypeToArrayField.get( tdElement );
1052     if( fdElement == null ) {
1053       fdElement = new FieldDescriptor( new Modifiers( Modifiers.PUBLIC ),
1054                                        tdElement,
1055                                        arrayElementFieldName,
1056                                        null,
1057                                        false );
1058       mapTypeToArrayField.put( tdElement, fdElement );
1059     }
1060     return fdElement;
1061   }
1062
1063   
1064   
1065   private void writeFinalGraphs() {
1066     Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
1067     Iterator itr = entrySet.iterator();
1068     while( itr.hasNext() ) {
1069       Map.Entry  me = (Map.Entry)  itr.next();
1070       Descriptor  d = (Descriptor) me.getKey();
1071       ReachGraph rg = (ReachGraph) me.getValue();
1072
1073       rg.writeGraph( "COMPLETE"+d,
1074                      true,   // write labels (variables)                
1075                      true,   // selectively hide intermediate temp vars 
1076                      true,   // prune unreachable heap regions          
1077                      false,  // hide subset reachability states         
1078                      true ); // hide edge taints                        
1079     }
1080   }
1081
1082   private void writeFinalIHMs() {
1083     Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
1084     while( d2IHMsItr.hasNext() ) {
1085       Map.Entry                        me1 = (Map.Entry)                       d2IHMsItr.next();
1086       Descriptor                         d = (Descriptor)                      me1.getKey();
1087       Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>) me1.getValue();
1088
1089       Iterator fc2rgItr = IHMs.entrySet().iterator();
1090       while( fc2rgItr.hasNext() ) {
1091         Map.Entry  me2 = (Map.Entry)  fc2rgItr.next();
1092         FlatCall   fc  = (FlatCall)   me2.getKey();
1093         ReachGraph rg  = (ReachGraph) me2.getValue();
1094                 
1095         rg.writeGraph( "IHMPARTFOR"+d+"FROM"+fc,
1096                        true,   // write labels (variables)
1097                        false,  // selectively hide intermediate temp vars
1098                        false,  // prune unreachable heap regions
1099                        false,  // hide subset reachability states
1100                        true ); // hide edge taints
1101       }
1102     }
1103   }
1104    
1105
1106   protected ReachGraph getPartial( Descriptor d ) {
1107     return mapDescriptorToCompleteReachGraph.get( d );
1108   }
1109
1110   protected void setPartial( Descriptor d, ReachGraph rg ) {
1111     mapDescriptorToCompleteReachGraph.put( d, rg );
1112
1113     // when the flag for writing out every partial
1114     // result is set, we should spit out the graph,
1115     // but in order to give it a unique name we need
1116     // to track how many partial results for this
1117     // descriptor we've already written out
1118     if( writeAllIncrementalDOTs ) {
1119       if( !mapDescriptorToNumUpdates.containsKey( d ) ) {
1120         mapDescriptorToNumUpdates.put( d, new Integer( 0 ) );
1121       }
1122       Integer n = mapDescriptorToNumUpdates.get( d );
1123       
1124       rg.writeGraph( d+"COMPLETE"+String.format( "%05d", n ),
1125                      true,   // write labels (variables)
1126                      true,   // selectively hide intermediate temp vars
1127                      false,  // prune unreachable heap regions
1128                      false,  // hide subset reachability states
1129                      true ); // hide edge taints
1130       
1131       mapDescriptorToNumUpdates.put( d, n + 1 );
1132     }
1133   }
1134
1135
1136
1137   // return just the allocation site associated with one FlatNew node
1138   protected AllocSite getAllocSiteFromFlatNewPRIVATE( FlatNew fnew ) {
1139
1140     if( !mapFlatNewToAllocSite.containsKey( fnew ) ) {
1141       AllocSite as = 
1142         (AllocSite) Canonical.makeCanonical( new AllocSite( allocationDepth, 
1143                                                             fnew, 
1144                                                             fnew.getDisjointId() 
1145                                                             )
1146                                              );
1147
1148       // the newest nodes are single objects
1149       for( int i = 0; i < allocationDepth; ++i ) {
1150         Integer id = generateUniqueHeapRegionNodeID();
1151         as.setIthOldest( i, id );
1152         mapHrnIdToAllocSite.put( id, as );
1153       }
1154
1155       // the oldest node is a summary node
1156       as.setSummary( generateUniqueHeapRegionNodeID() );
1157
1158       mapFlatNewToAllocSite.put( fnew, as );
1159     }
1160
1161     return mapFlatNewToAllocSite.get( fnew );
1162   }
1163
1164
1165   public static boolean shouldAnalysisTrack( TypeDescriptor type ) {
1166     // don't track primitive types, but an array
1167     // of primitives is heap memory
1168     if( type.isImmutable() ) {
1169       return type.isArray();
1170     }
1171
1172     // everything else is an object
1173     return true;
1174   }
1175
1176
1177   /*
1178   // return all allocation sites in the method (there is one allocation
1179   // site per FlatNew node in a method)
1180   protected HashSet<AllocSite> getAllocSiteSet(Descriptor d) {
1181     if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
1182       buildAllocSiteSet(d);
1183     }
1184
1185     return mapDescriptorToAllocSiteSet.get(d);
1186
1187   }
1188   */
1189
1190   /*
1191   protected void buildAllocSiteSet(Descriptor d) {
1192     HashSet<AllocSite> s = new HashSet<AllocSite>();
1193
1194     FlatMethod fm = state.getMethodFlat( d );
1195
1196     // visit every node in this FlatMethod's IR graph
1197     // and make a set of the allocation sites from the
1198     // FlatNew node's visited
1199     HashSet<FlatNode> visited = new HashSet<FlatNode>();
1200     HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
1201     toVisit.add( fm );
1202
1203     while( !toVisit.isEmpty() ) {
1204       FlatNode n = toVisit.iterator().next();
1205
1206       if( n instanceof FlatNew ) {
1207         s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
1208       }
1209
1210       toVisit.remove( n );
1211       visited.add( n );
1212
1213       for( int i = 0; i < n.numNext(); ++i ) {
1214         FlatNode child = n.getNext( i );
1215         if( !visited.contains( child ) ) {
1216           toVisit.add( child );
1217         }
1218       }
1219     }
1220
1221     mapDescriptorToAllocSiteSet.put( d, s );
1222   }
1223   */
1224   /*
1225   protected HashSet<AllocSite> getFlaggedAllocSites(Descriptor dIn) {
1226     
1227     HashSet<AllocSite> out     = new HashSet<AllocSite>();
1228     HashSet<Descriptor>     toVisit = new HashSet<Descriptor>();
1229     HashSet<Descriptor>     visited = new HashSet<Descriptor>();
1230
1231     toVisit.add(dIn);
1232
1233     while( !toVisit.isEmpty() ) {
1234       Descriptor d = toVisit.iterator().next();
1235       toVisit.remove(d);
1236       visited.add(d);
1237
1238       HashSet<AllocSite> asSet = getAllocSiteSet(d);
1239       Iterator asItr = asSet.iterator();
1240       while( asItr.hasNext() ) {
1241         AllocSite as = (AllocSite) asItr.next();
1242         if( as.getDisjointAnalysisId() != null ) {
1243           out.add(as);
1244         }
1245       }
1246
1247       // enqueue callees of this method to be searched for
1248       // allocation sites also
1249       Set callees = callGraph.getCalleeSet(d);
1250       if( callees != null ) {
1251         Iterator methItr = callees.iterator();
1252         while( methItr.hasNext() ) {
1253           MethodDescriptor md = (MethodDescriptor) methItr.next();
1254
1255           if( !visited.contains(md) ) {
1256             toVisit.add(md);
1257           }
1258         }
1259       }
1260     }
1261     
1262     return out;
1263   }
1264   */
1265
1266   /*
1267   protected HashSet<AllocSite>
1268   getFlaggedAllocSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
1269
1270     HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
1271     HashSet<Descriptor>     toVisit    = new HashSet<Descriptor>();
1272     HashSet<Descriptor>     visited    = new HashSet<Descriptor>();
1273
1274     toVisit.add(td);
1275
1276     // traverse this task and all methods reachable from this task
1277     while( !toVisit.isEmpty() ) {
1278       Descriptor d = toVisit.iterator().next();
1279       toVisit.remove(d);
1280       visited.add(d);
1281
1282       HashSet<AllocSite> asSet = getAllocSiteSet(d);
1283       Iterator asItr = asSet.iterator();
1284       while( asItr.hasNext() ) {
1285         AllocSite as = (AllocSite) asItr.next();
1286         TypeDescriptor typed = as.getType();
1287         if( typed != null ) {
1288           ClassDescriptor cd = typed.getClassDesc();
1289           if( cd != null && cd.hasFlags() ) {
1290             asSetTotal.add(as);
1291           }
1292         }
1293       }
1294
1295       // enqueue callees of this method to be searched for
1296       // allocation sites also
1297       Set callees = callGraph.getCalleeSet(d);
1298       if( callees != null ) {
1299         Iterator methItr = callees.iterator();
1300         while( methItr.hasNext() ) {
1301           MethodDescriptor md = (MethodDescriptor) methItr.next();
1302
1303           if( !visited.contains(md) ) {
1304             toVisit.add(md);
1305           }
1306         }
1307       }
1308     }
1309
1310
1311     return asSetTotal;
1312   }
1313   */
1314
1315
1316   /*
1317   protected String computeAliasContextHistogram() {
1318     
1319     Hashtable<Integer, Integer> mapNumContexts2NumDesc = 
1320       new Hashtable<Integer, Integer>();
1321   
1322     Iterator itr = mapDescriptorToAllDescriptors.entrySet().iterator();
1323     while( itr.hasNext() ) {
1324       Map.Entry me = (Map.Entry) itr.next();
1325       HashSet<Descriptor> s = (HashSet<Descriptor>) me.getValue();
1326       
1327       Integer i = mapNumContexts2NumDesc.get( s.size() );
1328       if( i == null ) {
1329         i = new Integer( 0 );
1330       }
1331       mapNumContexts2NumDesc.put( s.size(), i + 1 );
1332     }   
1333
1334     String s = "";
1335     int total = 0;
1336
1337     itr = mapNumContexts2NumDesc.entrySet().iterator();
1338     while( itr.hasNext() ) {
1339       Map.Entry me = (Map.Entry) itr.next();
1340       Integer c0 = (Integer) me.getKey();
1341       Integer d0 = (Integer) me.getValue();
1342       total += d0;
1343       s += String.format( "%4d methods had %4d unique alias contexts.\n", d0, c0 );
1344     }
1345
1346     s += String.format( "\n%4d total methods analayzed.\n", total );
1347
1348     return s;
1349   }
1350
1351   protected int numMethodsAnalyzed() {    
1352     return descriptorsToAnalyze.size();
1353   }
1354   */
1355
1356   
1357   
1358   
1359   // Take in source entry which is the program's compiled entry and
1360   // create a new analysis entry, a method that takes no parameters
1361   // and appears to allocate the command line arguments and call the
1362   // source entry with them.  The purpose of this analysis entry is
1363   // to provide a top-level method context with no parameters left.
1364   protected void makeAnalysisEntryMethod( MethodDescriptor mdSourceEntry ) {
1365
1366     Modifiers mods = new Modifiers();
1367     mods.addModifier( Modifiers.PUBLIC );
1368     mods.addModifier( Modifiers.STATIC );
1369
1370     TypeDescriptor returnType = 
1371       new TypeDescriptor( TypeDescriptor.VOID );
1372
1373     this.mdAnalysisEntry = 
1374       new MethodDescriptor( mods,
1375                             returnType,
1376                             "analysisEntryMethod"
1377                             );
1378
1379     TempDescriptor cmdLineArgs = 
1380       new TempDescriptor( "args",
1381                           mdSourceEntry.getParamType( 0 )
1382                           );
1383
1384     FlatNew fn = 
1385       new FlatNew( mdSourceEntry.getParamType( 0 ),
1386                    cmdLineArgs,
1387                    false // is global 
1388                    );
1389     
1390     TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
1391     sourceEntryArgs[0] = cmdLineArgs;
1392     
1393     FlatCall fc = 
1394       new FlatCall( mdSourceEntry,
1395                     null, // dst temp
1396                     null, // this temp
1397                     sourceEntryArgs
1398                     );
1399
1400     FlatReturnNode frn = new FlatReturnNode( null );
1401
1402     FlatExit fe = new FlatExit();
1403
1404     this.fmAnalysisEntry = 
1405       new FlatMethod( mdAnalysisEntry, 
1406                       fe
1407                       );
1408
1409     this.fmAnalysisEntry.addNext( fn );
1410     fn.addNext( fc );
1411     fc.addNext( frn );
1412     frn.addNext( fe );
1413   }
1414
1415
1416   protected LinkedList<Descriptor> topologicalSort( Set<Descriptor> toSort ) {
1417
1418     Set       <Descriptor> discovered = new HashSet   <Descriptor>();
1419     LinkedList<Descriptor> sorted     = new LinkedList<Descriptor>();
1420   
1421     Iterator<Descriptor> itr = toSort.iterator();
1422     while( itr.hasNext() ) {
1423       Descriptor d = itr.next();
1424           
1425       if( !discovered.contains( d ) ) {
1426         dfsVisit( d, toSort, sorted, discovered );
1427       }
1428     }
1429     
1430     return sorted;
1431   }
1432   
1433   // While we're doing DFS on call graph, remember
1434   // dependencies for efficient queuing of methods
1435   // during interprocedural analysis:
1436   //
1437   // a dependent of a method decriptor d for this analysis is:
1438   //  1) a method or task that invokes d
1439   //  2) in the descriptorsToAnalyze set
1440   protected void dfsVisit( Descriptor             d,
1441                            Set       <Descriptor> toSort,                        
1442                            LinkedList<Descriptor> sorted,
1443                            Set       <Descriptor> discovered ) {
1444     discovered.add( d );
1445     
1446     // only methods have callers, tasks never do
1447     if( d instanceof MethodDescriptor ) {
1448
1449       MethodDescriptor md = (MethodDescriptor) d;
1450
1451       // the call graph is not aware that we have a fabricated
1452       // analysis entry that calls the program source's entry
1453       if( md == mdSourceEntry ) {
1454         if( !discovered.contains( mdAnalysisEntry ) ) {
1455           addDependent( mdSourceEntry,  // callee
1456                         mdAnalysisEntry // caller
1457                         );
1458           dfsVisit( mdAnalysisEntry, toSort, sorted, discovered );
1459         }
1460       }
1461
1462       // otherwise call graph guides DFS
1463       Iterator itr = callGraph.getCallerSet( md ).iterator();
1464       while( itr.hasNext() ) {
1465         Descriptor dCaller = (Descriptor) itr.next();
1466         
1467         // only consider callers in the original set to analyze
1468         if( !toSort.contains( dCaller ) ) {
1469           continue;
1470         }
1471           
1472         if( !discovered.contains( dCaller ) ) {
1473           addDependent( md,     // callee
1474                         dCaller // caller
1475                         );
1476
1477           dfsVisit( dCaller, toSort, sorted, discovered );
1478         }
1479       }
1480     }
1481     
1482     // for leaf-nodes last now!
1483     sorted.addLast( d );
1484   }
1485
1486
1487   protected void enqueue( Descriptor d ) {
1488     if( !descriptorsToVisitSet.contains( d ) ) {
1489       Integer priority = mapDescriptorToPriority.get( d );
1490       descriptorsToVisitQ.add( new DescriptorQWrapper( priority, 
1491                                                        d ) 
1492                                );
1493       descriptorsToVisitSet.add( d );
1494     }
1495   }
1496
1497
1498   // a dependent of a method decriptor d for this analysis is:
1499   //  1) a method or task that invokes d
1500   //  2) in the descriptorsToAnalyze set
1501   protected void addDependent( Descriptor callee, Descriptor caller ) {
1502     Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1503     if( deps == null ) {
1504       deps = new HashSet<Descriptor>();
1505     }
1506     deps.add( caller );
1507     mapDescriptorToSetDependents.put( callee, deps );
1508   }
1509   
1510   protected Set<Descriptor> getDependents( Descriptor callee ) {
1511     Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1512     if( deps == null ) {
1513       deps = new HashSet<Descriptor>();
1514       mapDescriptorToSetDependents.put( callee, deps );
1515     }
1516     return deps;
1517   }
1518
1519   
1520   public Hashtable<FlatCall, ReachGraph> getIHMcontributions( Descriptor d ) {
1521
1522     Hashtable<FlatCall, ReachGraph> heapsFromCallers = 
1523       mapDescriptorToIHMcontributions.get( d );
1524     
1525     if( heapsFromCallers == null ) {
1526       heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
1527       mapDescriptorToIHMcontributions.put( d, heapsFromCallers );
1528     }
1529     
1530     return heapsFromCallers;
1531   }
1532
1533   public ReachGraph getIHMcontribution( Descriptor d, 
1534                                         FlatCall   fc
1535                                         ) {
1536     Hashtable<FlatCall, ReachGraph> heapsFromCallers = 
1537       getIHMcontributions( d );
1538
1539     if( !heapsFromCallers.containsKey( fc ) ) {
1540       heapsFromCallers.put( fc, new ReachGraph() );
1541     }
1542
1543     return heapsFromCallers.get( fc );
1544   }
1545
1546   public void addIHMcontribution( Descriptor d,
1547                                   FlatCall   fc,
1548                                   ReachGraph rg
1549                                   ) {
1550     Hashtable<FlatCall, ReachGraph> heapsFromCallers = 
1551       getIHMcontributions( d );
1552
1553     heapsFromCallers.put( fc, rg );
1554   }
1555
1556 private AllocSite createParameterAllocSite(ReachGraph rg, TempDescriptor tempDesc) {
1557     
1558     // create temp descriptor for each parameter variable
1559     FlatNew flatNew = new FlatNew(tempDesc.getType(), tempDesc, false);
1560     // create allocation site
1561     AllocSite as = (AllocSite) Canonical.makeCanonical(new AllocSite( allocationDepth, flatNew, flatNew.getDisjointId()));
1562     for (int i = 0; i < allocationDepth; ++i) {
1563         Integer id = generateUniqueHeapRegionNodeID();
1564         as.setIthOldest(i, id);
1565         mapHrnIdToAllocSite.put(id, as);
1566     }
1567     // the oldest node is a summary node
1568     as.setSummary( generateUniqueHeapRegionNodeID() );
1569     
1570     rg.age(as);
1571     
1572     return as;
1573     
1574 }
1575
1576 private HeapRegionNode createMultiDeimensionalArrayHRN(ReachGraph rg, AllocSite alloc, HeapRegionNode srcHRN, FieldDescriptor fd){
1577
1578         int dimCount=fd.getType().getArrayCount();
1579         HeapRegionNode prevNode=null;
1580         for(int i=dimCount;i>0;i--){
1581                 TempDescriptor tempDesc=new TempDescriptor("temp_");
1582                 TypeDescriptor typeDesc=fd.getType().dereference();
1583                 typeDesc.setArrayCount(i);
1584                 tempDesc.setType(typeDesc);
1585                 AllocSite as;
1586                 if(i==dimCount){
1587                         as = alloc;
1588                 }else{
1589                         as = createParameterAllocSite(rg, tempDesc);
1590                 }
1591                 // make a new reference to allocated node
1592             HeapRegionNode hrnSummary = 
1593                         rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1594                                                    false, // single object?
1595                                                    true, // summary?
1596                                                    false, // flagged?
1597                                                    false, // out-of-context?
1598                                                    typeDesc, // type
1599                                                    as, // allocation site
1600                                                    null, // inherent reach
1601                                                    null, // current reach
1602                                                    ExistPredSet.factory(), // predicates
1603                                                    tempDesc.toString() // description
1604                                                    );
1605             rg.id2hrn.put(as.getSummary(),hrnSummary);
1606             
1607             if(prevNode==null){
1608                     // make a new reference between new summary node and source
1609                     RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1610                                                         hrnSummary, // dest
1611                                                         typeDesc, // type
1612                                                         fd.getSymbol(), // field name
1613                                                         srcHRN.getAlpha(), // beta
1614                                                         ExistPredSet.factory(rg.predTrue) // predicates
1615                                                         );
1616                     
1617                     rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1618                     prevNode=hrnSummary;
1619             }else{
1620                     // make a new reference between summary nodes of array
1621                     RefEdge edgeToSummary = new RefEdge(prevNode, // source
1622                                                         hrnSummary, // dest
1623                                                         typeDesc, // type
1624                                                         fd.getSymbol(), // field name
1625                                                         srcHRN.getAlpha(), // beta
1626                                                         ExistPredSet.factory(rg.predTrue) // predicates
1627                                                         );
1628                     
1629                     rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1630                     prevNode=hrnSummary;
1631             }
1632             
1633         }
1634         
1635         return prevNode;
1636 }
1637     
1638 private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
1639     ReachGraph rg = new ReachGraph();
1640     TaskDescriptor taskDesc = fm.getTask();
1641     
1642     for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
1643         Descriptor paramDesc = taskDesc.getParameter(idx);
1644         TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
1645         
1646         // setup data structure
1647         Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet = 
1648             new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
1649         Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode = 
1650             new Hashtable<TypeDescriptor, HeapRegionNode>();
1651         Set<String> doneSet = new HashSet<String>();
1652         
1653         TempDescriptor tempDesc = fm.getParameter(idx);
1654         
1655         AllocSite as = createParameterAllocSite(rg, tempDesc);
1656         VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
1657         Integer idNewest = as.getIthOldest(0);
1658         HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
1659         // make a new reference to allocated node
1660         RefEdge edgeNew = new RefEdge(lnX, // source
1661                                       hrnNewest, // dest
1662                                       taskDesc.getParamType(idx), // type
1663                                       null, // field name
1664                                       hrnNewest.getAlpha(), // beta
1665                                       ExistPredSet.factory(rg.predTrue) // predicates
1666                                       );
1667         rg.addRefEdge(lnX, hrnNewest, edgeNew);
1668         
1669         // set-up a work set for class field
1670         ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
1671         for (Iterator it = classDesc.getFields(); it.hasNext();) {
1672             FieldDescriptor fd = (FieldDescriptor) it.next();
1673             TypeDescriptor fieldType = fd.getType();
1674             if (shouldAnalysisTrack( fieldType )) {
1675                 HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
1676                 newMap.put(hrnNewest, fd);
1677                 workSet.add(newMap);
1678             }
1679         }
1680         
1681         int uniqueIdentifier = 0;
1682         while (!workSet.isEmpty()) {
1683             HashMap<HeapRegionNode, FieldDescriptor> map = workSet
1684                 .iterator().next();
1685             workSet.remove(map);
1686             
1687             Set<HeapRegionNode> key = map.keySet();
1688             HeapRegionNode srcHRN = key.iterator().next();
1689             FieldDescriptor fd = map.get(srcHRN);
1690             TypeDescriptor type = fd.getType();
1691             String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
1692             
1693             if (!doneSet.contains(doneSetIdentifier)) {
1694                 doneSet.add(doneSetIdentifier);
1695                 if (!mapTypeToExistingSummaryNode.containsKey(type)) {
1696                     // create new summary Node
1697                     TempDescriptor td = new TempDescriptor("temp"
1698                                                            + uniqueIdentifier, type);
1699                     
1700                     AllocSite allocSite;
1701                     if(type.equals(paramTypeDesc)){
1702                     //corresponding allocsite has already been created for a parameter variable.
1703                         allocSite=as;
1704                     }else{
1705                         allocSite = createParameterAllocSite(rg, td);
1706                     }
1707                     String strDesc = allocSite.toStringForDOT()
1708                         + "\\nsummary";
1709                     TypeDescriptor allocType=allocSite.getType();
1710                     
1711                     HeapRegionNode      hrnSummary;
1712                     if(allocType.isArray() && allocType.getArrayCount()>1){
1713                         hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd);
1714                     }else{                  
1715                         hrnSummary = 
1716                                         rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
1717                                                                    false, // single object?
1718                                                                    true, // summary?
1719                                                                    false, // flagged?
1720                                                                    false, // out-of-context?
1721                                                                    allocSite.getType(), // type
1722                                                                    allocSite, // allocation site
1723                                                                    null, // inherent reach
1724                                                                    srcHRN.getAlpha(), // current reach
1725                                                                    ExistPredSet.factory(), // predicates
1726                                                                    strDesc // description
1727                                                                    );
1728                                     rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
1729                     
1730                     
1731                     // make a new reference to summary node
1732                     RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1733                                                         hrnSummary, // dest
1734                                                         type, // type
1735                                                         fd.getSymbol(), // field name
1736                                                         srcHRN.getAlpha(), // beta
1737                                                         ExistPredSet.factory(rg.predTrue) // predicates
1738                                                         );
1739                     
1740                     rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1741                     }               
1742                     uniqueIdentifier++;
1743                     
1744                     mapTypeToExistingSummaryNode.put(type, hrnSummary);
1745                     
1746                     // set-up a work set for  fields of the class
1747                     if(!type.isImmutable()){
1748                     classDesc = type.getClassDesc();                
1749                     for (Iterator it = classDesc.getFields(); it.hasNext();) {
1750                         FieldDescriptor typeFieldDesc = (FieldDescriptor) it.next();
1751                         TypeDescriptor fieldType = typeFieldDesc.getType();
1752 //                      if (!fieldType.isImmutable()) {
1753                         if (shouldAnalysisTrack( fieldType )) {
1754                             doneSetIdentifier = hrnSummary.getIDString() + "_" + typeFieldDesc;                                                          
1755                             if(!doneSet.contains(doneSetIdentifier)){
1756                                 // add new work item
1757                                 HashMap<HeapRegionNode, FieldDescriptor> newMap = 
1758                                     new HashMap<HeapRegionNode, FieldDescriptor>();
1759                                 newMap.put(hrnSummary, typeFieldDesc);
1760                                 workSet.add(newMap);
1761                             }
1762                         }
1763                     }
1764                     }
1765                     
1766                 }else{
1767                     // if there exists corresponding summary node
1768                     HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
1769                     
1770                     RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1771                                                         hrnDst, // dest
1772                                                         fd.getType(), // type
1773                                                         fd.getSymbol(), // field name
1774                                                         srcHRN.getAlpha(), // beta
1775                                                         ExistPredSet.factory(rg.predTrue) // predicates
1776                                                         );
1777                     rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
1778                     
1779                 }               
1780             }       
1781         }           
1782     }   
1783 //    debugSnapshot(rg, fm, true);
1784     return rg;
1785 }
1786
1787 // return all allocation sites in the method (there is one allocation
1788 // site per FlatNew node in a method)
1789 private HashSet<AllocSite> getAllocationSiteSet(Descriptor d) {
1790   if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
1791     buildAllocationSiteSet(d);
1792   }
1793
1794   return mapDescriptorToAllocSiteSet.get(d);
1795
1796 }
1797
1798 private void buildAllocationSiteSet(Descriptor d) {
1799     HashSet<AllocSite> s = new HashSet<AllocSite>();
1800
1801     FlatMethod fm;
1802     if( d instanceof MethodDescriptor ) {
1803       fm = state.getMethodFlat( (MethodDescriptor) d);
1804     } else {
1805       assert d instanceof TaskDescriptor;
1806       fm = state.getMethodFlat( (TaskDescriptor) d);
1807     }
1808
1809     // visit every node in this FlatMethod's IR graph
1810     // and make a set of the allocation sites from the
1811     // FlatNew node's visited
1812     HashSet<FlatNode> visited = new HashSet<FlatNode>();
1813     HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
1814     toVisit.add(fm);
1815
1816     while( !toVisit.isEmpty() ) {
1817       FlatNode n = toVisit.iterator().next();
1818
1819       if( n instanceof FlatNew ) {
1820         s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
1821       }
1822
1823       toVisit.remove(n);
1824       visited.add(n);
1825
1826       for( int i = 0; i < n.numNext(); ++i ) {
1827         FlatNode child = n.getNext(i);
1828         if( !visited.contains(child) ) {
1829           toVisit.add(child);
1830         }
1831       }
1832     }
1833
1834     mapDescriptorToAllocSiteSet.put(d, s);
1835   }
1836
1837         private HashSet<AllocSite> getFlaggedAllocationSites(Descriptor dIn) {
1838
1839                 HashSet<AllocSite> out = new HashSet<AllocSite>();
1840                 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1841                 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1842
1843                 toVisit.add(dIn);
1844
1845                 while (!toVisit.isEmpty()) {
1846                         Descriptor d = toVisit.iterator().next();
1847                         toVisit.remove(d);
1848                         visited.add(d);
1849
1850                         HashSet<AllocSite> asSet = getAllocationSiteSet(d);
1851                         Iterator asItr = asSet.iterator();
1852                         while (asItr.hasNext()) {
1853                                 AllocSite as = (AllocSite) asItr.next();
1854                                 if (as.getDisjointAnalysisId() != null) {
1855                                         out.add(as);
1856                                 }
1857                         }
1858
1859                         // enqueue callees of this method to be searched for
1860                         // allocation sites also
1861                         Set callees = callGraph.getCalleeSet(d);
1862                         if (callees != null) {
1863                                 Iterator methItr = callees.iterator();
1864                                 while (methItr.hasNext()) {
1865                                         MethodDescriptor md = (MethodDescriptor) methItr.next();
1866
1867                                         if (!visited.contains(md)) {
1868                                                 toVisit.add(md);
1869                                         }
1870                                 }
1871                         }
1872                 }
1873
1874                 return out;
1875         }
1876  
1877     
1878 private HashSet<AllocSite>
1879 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
1880
1881   HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
1882   HashSet<Descriptor>     toVisit    = new HashSet<Descriptor>();
1883   HashSet<Descriptor>     visited    = new HashSet<Descriptor>();
1884
1885   toVisit.add(td);
1886
1887   // traverse this task and all methods reachable from this task
1888   while( !toVisit.isEmpty() ) {
1889     Descriptor d = toVisit.iterator().next();
1890     toVisit.remove(d);
1891     visited.add(d);
1892
1893     HashSet<AllocSite> asSet = getAllocationSiteSet(d);
1894     Iterator asItr = asSet.iterator();
1895     while( asItr.hasNext() ) {
1896         AllocSite as = (AllocSite) asItr.next();
1897         TypeDescriptor typed = as.getType();
1898         if( typed != null ) {
1899           ClassDescriptor cd = typed.getClassDesc();
1900           if( cd != null && cd.hasFlags() ) {
1901             asSetTotal.add(as);
1902           }
1903         }
1904     }
1905
1906     // enqueue callees of this method to be searched for
1907     // allocation sites also
1908     Set callees = callGraph.getCalleeSet(d);
1909     if( callees != null ) {
1910         Iterator methItr = callees.iterator();
1911         while( methItr.hasNext() ) {
1912           MethodDescriptor md = (MethodDescriptor) methItr.next();
1913
1914           if( !visited.contains(md) ) {
1915             toVisit.add(md);
1916           }
1917         }
1918     }
1919   }
1920
1921   return asSetTotal;
1922 }
1923
1924
1925   
1926   
1927   // get successive captures of the analysis state, use compiler
1928   // flags to control
1929   boolean takeDebugSnapshots = false;
1930   String  descSymbolDebug    = null;
1931   boolean stopAfterCapture   = false;
1932   int     snapVisitCounter   = 0;
1933   int     snapNodeCounter    = 0;
1934   int     visitStartCapture  = 0;
1935   int     numVisitsToCapture = 0;
1936
1937
1938   void debugSnapshot( ReachGraph rg, FlatNode fn, boolean in ) {
1939     if( snapVisitCounter > visitStartCapture + numVisitsToCapture ) {
1940       return;
1941     }
1942
1943     if( in ) {
1944
1945     }
1946
1947     if( snapVisitCounter >= visitStartCapture ) {
1948       System.out.println( "    @@@ snapping visit="+snapVisitCounter+
1949                           ", node="+snapNodeCounter+
1950                           " @@@" );
1951       String graphName;
1952       if( in ) {
1953         graphName = String.format( "snap%02d_%04din",
1954                                    snapVisitCounter,
1955                                    snapNodeCounter );
1956       } else {
1957         graphName = String.format( "snap%02d_%04dout",
1958                                    snapVisitCounter,
1959                                    snapNodeCounter );
1960       }
1961       if( fn != null ) {
1962         graphName = graphName + fn;
1963       }
1964       rg.writeGraph( graphName,
1965                      true,  // write labels (variables)
1966                      true,  // selectively hide intermediate temp vars
1967                      false, // prune unreachable heap regions
1968                      false, // hide subset reachability states
1969                      true );// hide edge taints
1970     }
1971   }
1972
1973 }