implemented PCLOC annotation.
[IRC.git] / Robust / src / Analysis / SSJava / SSJavaAnalysis.java
1 package Analysis.SSJava;
2
3 import java.io.BufferedWriter;
4 import java.io.FileWriter;
5 import java.io.IOException;
6 import java.util.ArrayList;
7 import java.util.Collections;
8 import java.util.Comparator;
9 import java.util.HashSet;
10 import java.util.Hashtable;
11 import java.util.Iterator;
12 import java.util.LinkedList;
13 import java.util.List;
14 import java.util.Set;
15 import java.util.StringTokenizer;
16 import java.util.Vector;
17
18 import Analysis.CallGraph.CallGraph;
19 import Analysis.Loops.GlobalFieldType;
20 import Analysis.Loops.LoopFinder;
21 import Analysis.Loops.LoopOptimize;
22 import Analysis.Loops.LoopTerminate;
23 import IR.AnnotationDescriptor;
24 import IR.ClassDescriptor;
25 import IR.Descriptor;
26 import IR.FieldDescriptor;
27 import IR.MethodDescriptor;
28 import IR.State;
29 import IR.SymbolTable;
30 import IR.TypeUtil;
31 import IR.Flat.BuildFlat;
32 import IR.Flat.FlatMethod;
33 import IR.Flat.FlatNode;
34 import Util.Pair;
35
36 public class SSJavaAnalysis {
37
38   public static final String SSJAVA = "SSJAVA";
39   public static final String LATTICE = "LATTICE";
40   public static final String METHODDEFAULT = "METHODDEFAULT";
41   public static final String THISLOC = "THISLOC";
42   public static final String GLOBALLOC = "GLOBALLOC";
43   public static final String RETURNLOC = "RETURNLOC";
44   public static final String PCLOC = "PCLOC";
45   public static final String LOC = "LOC";
46   public static final String DELTA = "DELTA";
47   public static final String TERMINATE = "TERMINATE";
48   public static final String DELEGATE = "DELEGATE";
49   public static final String DELEGATETHIS = "DELEGATETHIS";
50   public static final String TRUST = "TRUST";
51
52   public static final String TOP = "_top_";
53   public static final String BOTTOM = "_bottom_";
54
55   State state;
56   TypeUtil tu;
57   FlowDownCheck flowDownChecker;
58   MethodAnnotationCheck methodAnnotationChecker;
59   BuildFlat bf;
60
61   // set containing method requires to be annoated
62   Set<MethodDescriptor> annotationRequireSet;
63
64   // class -> field lattice
65   Hashtable<ClassDescriptor, SSJavaLattice<String>> cd2lattice;
66
67   // class -> default local variable lattice
68   Hashtable<ClassDescriptor, MethodLattice<String>> cd2methodDefault;
69
70   // method -> local variable lattice
71   Hashtable<MethodDescriptor, MethodLattice<String>> md2lattice;
72
73   // method set that does not want to have loop termination analysis
74   Hashtable<MethodDescriptor, Integer> skipLoopTerminate;
75
76   // map shared location to its descriptors
77   Hashtable<Location, Set<Descriptor>> mapSharedLocation2DescriptorSet;
78
79   // set containing a class that has at least one annoated method
80   Set<ClassDescriptor> annotationRequireClassSet;
81
82   // the set of method descriptor required to check the linear type property
83   Set<MethodDescriptor> linearTypeCheckMethodSet;
84
85   // the set of method descriptors annotated as "TRUST"
86   Set<MethodDescriptor> trustWorthyMDSet;
87
88   // points to method containing SSJAVA Loop
89   private MethodDescriptor methodContainingSSJavaLoop;
90
91   private FlatNode ssjavaLoopEntrance;
92
93   // keep the field ownership from the linear type checking
94   Hashtable<MethodDescriptor, Set<FieldDescriptor>> mapMethodToOwnedFieldSet;
95
96   Set<FlatNode> sameHeightWriteFlatNodeSet;
97
98   CallGraph callgraph;
99
100   LinearTypeCheck checker;
101
102   // maps a descriptor to its known dependents: namely
103   // methods or tasks that call the descriptor's method
104   // AND are part of this analysis (reachable from main)
105   private Hashtable<Descriptor, Set<MethodDescriptor>> mapDescriptorToSetDependents;
106
107   private LinkedList<MethodDescriptor> sortedDescriptors;
108
109   public SSJavaAnalysis(State state, TypeUtil tu, BuildFlat bf, CallGraph callgraph) {
110     this.state = state;
111     this.tu = tu;
112     this.callgraph = callgraph;
113     this.cd2lattice = new Hashtable<ClassDescriptor, SSJavaLattice<String>>();
114     this.cd2methodDefault = new Hashtable<ClassDescriptor, MethodLattice<String>>();
115     this.md2lattice = new Hashtable<MethodDescriptor, MethodLattice<String>>();
116     this.annotationRequireSet = new HashSet<MethodDescriptor>();
117     this.annotationRequireClassSet = new HashSet<ClassDescriptor>();
118     this.skipLoopTerminate = new Hashtable<MethodDescriptor, Integer>();
119     this.mapSharedLocation2DescriptorSet = new Hashtable<Location, Set<Descriptor>>();
120     this.linearTypeCheckMethodSet = new HashSet<MethodDescriptor>();
121     this.bf = bf;
122     this.trustWorthyMDSet = new HashSet<MethodDescriptor>();
123     this.mapMethodToOwnedFieldSet = new Hashtable<MethodDescriptor, Set<FieldDescriptor>>();
124     this.sameHeightWriteFlatNodeSet = new HashSet<FlatNode>();
125     this.mapDescriptorToSetDependents = new Hashtable<Descriptor, Set<MethodDescriptor>>();
126     this.sortedDescriptors = new LinkedList<MethodDescriptor>();
127   }
128
129   public void doCheck() {
130     doMethodAnnotationCheck();
131     computeLinearTypeCheckMethodSet();
132     doLinearTypeCheck();
133
134     init();
135
136     if (state.SSJAVADEBUG) {
137       debug_printAnnotationRequiredSet();
138     }
139     if (state.SSJAVAINFER) {
140       inference();
141     } else {
142       parseLocationAnnotation();
143       doFlowDownCheck();
144       doDefinitelyWrittenCheck();
145       doLoopCheck();
146     }
147   }
148
149   private void init() {
150     // perform topological sort over the set of methods accessed by the main
151     // event loop
152     Set<MethodDescriptor> methodDescriptorsToAnalyze = new HashSet<MethodDescriptor>();
153     methodDescriptorsToAnalyze.addAll(getAnnotationRequireSet());
154     sortedDescriptors = topologicalSort(methodDescriptorsToAnalyze);
155   }
156
157   public LinkedList<MethodDescriptor> getSortedDescriptors() {
158     return (LinkedList<MethodDescriptor>) sortedDescriptors.clone();
159   }
160
161   private void inference() {
162     LocationInference inferEngine = new LocationInference(this, state);
163     inferEngine.inference();
164   }
165
166   private void doLoopCheck() {
167     GlobalFieldType gft = new GlobalFieldType(callgraph, state, tu.getMain());
168     LoopOptimize lo = new LoopOptimize(gft, tu);
169
170     SymbolTable classtable = state.getClassSymbolTable();
171
172     List<ClassDescriptor> toanalyzeList = new ArrayList<ClassDescriptor>();
173     List<MethodDescriptor> toanalyzeMethodList = new ArrayList<MethodDescriptor>();
174
175     toanalyzeList.addAll(classtable.getValueSet());
176     Collections.sort(toanalyzeList, new Comparator<ClassDescriptor>() {
177       public int compare(ClassDescriptor o1, ClassDescriptor o2) {
178         return o1.getClassName().compareTo(o2.getClassName());
179       }
180     });
181
182     for (int i = 0; i < toanalyzeList.size(); i++) {
183       ClassDescriptor cd = toanalyzeList.get(i);
184
185       SymbolTable methodtable = cd.getMethodTable();
186       toanalyzeMethodList.clear();
187       toanalyzeMethodList.addAll(methodtable.getValueSet());
188       Collections.sort(toanalyzeMethodList, new Comparator<MethodDescriptor>() {
189         public int compare(MethodDescriptor o1, MethodDescriptor o2) {
190           return o1.getSymbol().compareTo(o2.getSymbol());
191         }
192       });
193
194       for (int mdIdx = 0; mdIdx < toanalyzeMethodList.size(); mdIdx++) {
195         MethodDescriptor md = toanalyzeMethodList.get(mdIdx);
196         if (needTobeAnnotated(md)) {
197           lo.analyze(state.getMethodFlat(md));
198           doLoopTerminationCheck(lo, state.getMethodFlat(md));
199         }
200       }
201
202     }
203
204   }
205
206   public void addTrustMethod(MethodDescriptor md) {
207     trustWorthyMDSet.add(md);
208   }
209
210   public boolean isTrustMethod(MethodDescriptor md) {
211     return trustWorthyMDSet.contains(md);
212   }
213
214   private void computeLinearTypeCheckMethodSet() {
215
216     Set<MethodDescriptor> allCalledSet = callgraph.getMethodCalls(tu.getMain());
217     linearTypeCheckMethodSet.addAll(allCalledSet);
218
219     Set<MethodDescriptor> trustedSet = new HashSet<MethodDescriptor>();
220
221     for (Iterator iterator = trustWorthyMDSet.iterator(); iterator.hasNext();) {
222       MethodDescriptor trustMethod = (MethodDescriptor) iterator.next();
223       Set<MethodDescriptor> calledFromTrustMethodSet = callgraph.getMethodCalls(trustMethod);
224       trustedSet.add(trustMethod);
225       trustedSet.addAll(calledFromTrustMethodSet);
226     }
227
228     linearTypeCheckMethodSet.removeAll(trustedSet);
229
230     // if a method is called only by trusted method, no need to check linear
231     // type & flow down rule
232     for (Iterator iterator = trustedSet.iterator(); iterator.hasNext();) {
233       MethodDescriptor md = (MethodDescriptor) iterator.next();
234       Set<MethodDescriptor> callerSet = callgraph.getCallerSet(md);
235       if (!trustedSet.containsAll(callerSet) && !trustWorthyMDSet.contains(md)) {
236         linearTypeCheckMethodSet.add(md);
237       }
238     }
239
240   }
241
242   private void doLinearTypeCheck() {
243     LinearTypeCheck checker = new LinearTypeCheck(this, state);
244     checker.linearTypeCheck();
245   }
246
247   public void debug_printAnnotationRequiredSet() {
248     System.out.println("SSJAVA: SSJava is checking the following methods:");
249     for (Iterator<MethodDescriptor> iterator = annotationRequireSet.iterator(); iterator.hasNext();) {
250       MethodDescriptor md = iterator.next();
251       System.out.println(md);
252     }
253     System.out.println();
254   }
255
256   private void doMethodAnnotationCheck() {
257     methodAnnotationChecker = new MethodAnnotationCheck(this, state, tu);
258     methodAnnotationChecker.methodAnnoatationCheck();
259     methodAnnotationChecker.methodAnnoataionInheritanceCheck();
260     state.setAnnotationRequireSet(annotationRequireSet);
261   }
262
263   public void doFlowDownCheck() {
264     flowDownChecker = new FlowDownCheck(this, state);
265     flowDownChecker.flowDownCheck();
266   }
267
268   public void doDefinitelyWrittenCheck() {
269     DefinitelyWrittenCheck checker = new DefinitelyWrittenCheck(this, state);
270     checker.definitelyWrittenCheck();
271   }
272
273   private void parseLocationAnnotation() {
274     Iterator it = state.getClassSymbolTable().getDescriptorsIterator();
275     while (it.hasNext()) {
276       ClassDescriptor cd = (ClassDescriptor) it.next();
277       // parsing location hierarchy declaration for the class
278       Vector<AnnotationDescriptor> classAnnotations = cd.getModifier().getAnnotations();
279       for (int i = 0; i < classAnnotations.size(); i++) {
280         AnnotationDescriptor an = classAnnotations.elementAt(i);
281         String marker = an.getMarker();
282         if (marker.equals(LATTICE)) {
283           SSJavaLattice<String> locOrder =
284               new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM);
285           cd2lattice.put(cd, locOrder);
286           parseClassLatticeDefinition(cd, an.getValue(), locOrder);
287
288           if (state.SSJAVADEBUG) {
289             // generate lattice dot file
290             writeLatticeDotFile(cd, null, locOrder);
291           }
292
293         } else if (marker.equals(METHODDEFAULT)) {
294           MethodLattice<String> locOrder =
295               new MethodLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM);
296           cd2methodDefault.put(cd, locOrder);
297           parseMethodDefaultLatticeDefinition(cd, an.getValue(), locOrder);
298         }
299       }
300
301       for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
302         MethodDescriptor md = (MethodDescriptor) method_it.next();
303         // parsing location hierarchy declaration for the method
304
305         if (needTobeAnnotated(md)) {
306           Vector<AnnotationDescriptor> methodAnnotations = md.getModifiers().getAnnotations();
307           if (methodAnnotations != null) {
308             for (int i = 0; i < methodAnnotations.size(); i++) {
309               AnnotationDescriptor an = methodAnnotations.elementAt(i);
310               if (an.getMarker().equals(LATTICE)) {
311                 // developer explicitly defines method lattice
312                 MethodLattice<String> locOrder =
313                     new MethodLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM);
314                 md2lattice.put(md, locOrder);
315                 parseMethodDefaultLatticeDefinition(cd, an.getValue(), locOrder);
316               } else if (an.getMarker().equals(TERMINATE)) {
317                 // developer explicitly wants to skip loop termination analysis
318                 String value = an.getValue();
319                 int maxIteration = 0;
320                 if (value != null) {
321                   maxIteration = Integer.parseInt(value);
322                 }
323                 skipLoopTerminate.put(md, new Integer(maxIteration));
324               }
325             }
326           }
327         }
328
329       }
330
331     }
332   }
333
334   public <T> void writeLatticeDotFile(ClassDescriptor cd, MethodDescriptor md,
335       SSJavaLattice<T> locOrder) {
336
337     String fileName = "lattice_";
338     if (md != null) {
339       fileName +=
340           cd.getSymbol().replaceAll("[\\W_]", "") + "_" + md.getSymbol().replaceAll("[\\W_]", "");
341     } else {
342       fileName += cd.getSymbol().replaceAll("[\\W_]", "");
343     }
344
345     Set<Pair<T, T>> pairSet = locOrder.getOrderingPairSet();
346
347     if (pairSet.size() > 0) {
348       try {
349         BufferedWriter bw = new BufferedWriter(new FileWriter(fileName + ".dot"));
350
351         bw.write("digraph " + fileName + " {\n");
352
353         for (Iterator iterator = pairSet.iterator(); iterator.hasNext();) {
354           // pair is in the form of <higher, lower>
355           Pair<T, T> pair = (Pair<T, T>) iterator.next();
356
357           T highLocId = pair.getFirst();
358           String highLocStr, lowLocStr;
359           if (locOrder.isSharedLoc(highLocId)) {
360             highLocStr = "\"" + highLocId + "*\"";
361           } else {
362             highLocStr = highLocId.toString();
363           }
364           T lowLocId = pair.getSecond();
365           if (locOrder.isSharedLoc(lowLocId)) {
366             lowLocStr = "\"" + lowLocId + "*\"";
367           } else {
368             lowLocStr = lowLocId.toString();
369           }
370           bw.write(highLocId + " -> " + lowLocId + ";\n");
371         }
372         bw.write("}\n");
373         bw.close();
374
375       } catch (IOException e) {
376         e.printStackTrace();
377       }
378
379     }
380
381   }
382
383   private void parseMethodDefaultLatticeDefinition(ClassDescriptor cd, String value,
384       MethodLattice<String> locOrder) {
385
386     value = value.replaceAll(" ", ""); // remove all blank spaces
387
388     StringTokenizer tokenizer = new StringTokenizer(value, ",");
389
390     while (tokenizer.hasMoreTokens()) {
391       String orderElement = tokenizer.nextToken();
392       int idx = orderElement.indexOf("<");
393       if (idx > 0) {// relative order element
394         String lowerLoc = orderElement.substring(0, idx);
395         String higherLoc = orderElement.substring(idx + 1);
396         locOrder.put(higherLoc, lowerLoc);
397         if (locOrder.isIntroducingCycle(higherLoc)) {
398           throw new Error("Error: the order relation " + lowerLoc + " < " + higherLoc
399               + " introduces a cycle.");
400         }
401       } else if (orderElement.startsWith(THISLOC + "=")) {
402         String thisLoc = orderElement.substring(8);
403         locOrder.setThisLoc(thisLoc);
404       } else if (orderElement.startsWith(GLOBALLOC + "=")) {
405         String globalLoc = orderElement.substring(10);
406         locOrder.setGlobalLoc(globalLoc);
407       } else if (orderElement.startsWith(RETURNLOC + "=")) {
408         String returnLoc = orderElement.substring(10);
409         locOrder.setReturnLoc(returnLoc);
410       } else if (orderElement.startsWith(PCLOC + "=")) {
411         String pcLoc = orderElement.substring(6);
412         locOrder.setPCLoc(pcLoc);
413       } else if (orderElement.endsWith("*")) {
414         // spin loc definition
415         locOrder.addSharedLoc(orderElement.substring(0, orderElement.length() - 1));
416       } else {
417         // single element
418         locOrder.put(orderElement);
419       }
420     }
421
422     // sanity checks
423     if (locOrder.getThisLoc() != null && !locOrder.containsKey(locOrder.getThisLoc())) {
424       throw new Error("Variable 'this' location '" + locOrder.getThisLoc()
425           + "' is not defined in the local variable lattice at " + cd.getSourceFileName());
426     }
427
428     if (locOrder.getGlobalLoc() != null && !locOrder.containsKey(locOrder.getGlobalLoc())) {
429       throw new Error("Variable global location '" + locOrder.getGlobalLoc()
430           + "' is not defined in the local variable lattice at " + cd.getSourceFileName());
431     }
432   }
433
434   private void parseClassLatticeDefinition(ClassDescriptor cd, String value,
435       SSJavaLattice<String> locOrder) {
436
437     value = value.replaceAll(" ", ""); // remove all blank spaces
438
439     StringTokenizer tokenizer = new StringTokenizer(value, ",");
440
441     while (tokenizer.hasMoreTokens()) {
442       String orderElement = tokenizer.nextToken();
443       int idx = orderElement.indexOf("<");
444
445       if (idx > 0) {// relative order element
446         String lowerLoc = orderElement.substring(0, idx);
447         String higherLoc = orderElement.substring(idx + 1);
448         locOrder.put(higherLoc, lowerLoc);
449         if (locOrder.isIntroducingCycle(higherLoc)) {
450           throw new Error("Error: the order relation " + lowerLoc + " < " + higherLoc
451               + " introduces a cycle.");
452         }
453       } else if (orderElement.contains("*")) {
454         // spin loc definition
455         locOrder.addSharedLoc(orderElement.substring(0, orderElement.length() - 1));
456       } else {
457         // single element
458         locOrder.put(orderElement);
459       }
460     }
461
462     // sanity check
463     Set<String> spinLocSet = locOrder.getSharedLocSet();
464     for (Iterator iterator = spinLocSet.iterator(); iterator.hasNext();) {
465       String spinLoc = (String) iterator.next();
466       if (!locOrder.containsKey(spinLoc)) {
467         throw new Error("Spin location '" + spinLoc
468             + "' is not defined in the default local variable lattice at " + cd.getSourceFileName());
469       }
470     }
471   }
472
473   public Hashtable<ClassDescriptor, SSJavaLattice<String>> getCd2lattice() {
474     return cd2lattice;
475   }
476
477   public Hashtable<ClassDescriptor, MethodLattice<String>> getCd2methodDefault() {
478     return cd2methodDefault;
479   }
480
481   public Hashtable<MethodDescriptor, MethodLattice<String>> getMd2lattice() {
482     return md2lattice;
483   }
484
485   public SSJavaLattice<String> getClassLattice(ClassDescriptor cd) {
486     return cd2lattice.get(cd);
487   }
488
489   public MethodLattice<String> getMethodDefaultLattice(ClassDescriptor cd) {
490     return cd2methodDefault.get(cd);
491   }
492
493   public MethodLattice<String> getMethodLattice(MethodDescriptor md) {
494     if (md2lattice.containsKey(md)) {
495       return md2lattice.get(md);
496     } else {
497
498       if (cd2methodDefault.containsKey(md.getClassDesc())) {
499         return cd2methodDefault.get(md.getClassDesc());
500       } else {
501         throw new Error("Method Lattice of " + md + " is not defined.");
502       }
503
504     }
505   }
506
507   public boolean needToCheckLinearType(MethodDescriptor md) {
508     return linearTypeCheckMethodSet.contains(md);
509   }
510
511   public boolean needTobeAnnotated(MethodDescriptor md) {
512     return annotationRequireSet.contains(md);
513   }
514
515   public boolean needToBeAnnoated(ClassDescriptor cd) {
516     return annotationRequireClassSet.contains(cd);
517   }
518
519   public void addAnnotationRequire(ClassDescriptor cd) {
520     annotationRequireClassSet.add(cd);
521   }
522
523   public void addAnnotationRequire(MethodDescriptor md) {
524
525     ClassDescriptor cd = md.getClassDesc();
526     // if a method requires to be annotated, class containg that method also
527     // requires to be annotated
528     if (!isSSJavaUtil(cd)) {
529       annotationRequireClassSet.add(cd);
530       annotationRequireSet.add(md);
531     }
532   }
533
534   public Set<MethodDescriptor> getAnnotationRequireSet() {
535     return annotationRequireSet;
536   }
537
538   public void doLoopTerminationCheck(LoopOptimize lo, FlatMethod fm) {
539     LoopTerminate lt = new LoopTerminate(this, state);
540     if (needTobeAnnotated(fm.getMethod())) {
541       lt.terminateAnalysis(fm, lo.getLoopInvariant(fm));
542     }
543   }
544
545   public CallGraph getCallGraph() {
546     return callgraph;
547   }
548
549   public SSJavaLattice<String> getLattice(Descriptor d) {
550
551     if (d instanceof MethodDescriptor) {
552       return getMethodLattice((MethodDescriptor) d);
553     } else {
554       return getClassLattice((ClassDescriptor) d);
555     }
556
557   }
558
559   public boolean isSharedLocation(Location loc) {
560     SSJavaLattice<String> lattice = getLattice(loc.getDescriptor());
561     return lattice.getSharedLocSet().contains(loc.getLocIdentifier());
562   }
563
564   public void mapSharedLocation2Descriptor(Location loc, Descriptor d) {
565     Set<Descriptor> set = mapSharedLocation2DescriptorSet.get(loc);
566     if (set == null) {
567       set = new HashSet<Descriptor>();
568       mapSharedLocation2DescriptorSet.put(loc, set);
569     }
570     set.add(d);
571   }
572
573   public BuildFlat getBuildFlat() {
574     return bf;
575   }
576
577   public MethodDescriptor getMethodContainingSSJavaLoop() {
578     return methodContainingSSJavaLoop;
579   }
580
581   public void setMethodContainingSSJavaLoop(MethodDescriptor methodContainingSSJavaLoop) {
582     this.methodContainingSSJavaLoop = methodContainingSSJavaLoop;
583   }
584
585   public boolean isSSJavaUtil(ClassDescriptor cd) {
586     if (cd.getSymbol().equals("SSJAVA")) {
587       return true;
588     }
589     return false;
590   }
591
592   public void setFieldOnwership(MethodDescriptor md, FieldDescriptor field) {
593
594     Set<FieldDescriptor> fieldSet = mapMethodToOwnedFieldSet.get(md);
595     if (fieldSet == null) {
596       fieldSet = new HashSet<FieldDescriptor>();
597       mapMethodToOwnedFieldSet.put(md, fieldSet);
598     }
599     fieldSet.add(field);
600   }
601
602   public boolean isOwnedByMethod(MethodDescriptor md, FieldDescriptor field) {
603     Set<FieldDescriptor> fieldSet = mapMethodToOwnedFieldSet.get(md);
604     if (fieldSet != null) {
605       return fieldSet.contains(field);
606     }
607     return false;
608   }
609
610   public FlatNode getSSJavaLoopEntrance() {
611     return ssjavaLoopEntrance;
612   }
613
614   public void setSSJavaLoopEntrance(FlatNode ssjavaLoopEntrance) {
615     this.ssjavaLoopEntrance = ssjavaLoopEntrance;
616   }
617
618   public void addSameHeightWriteFlatNode(FlatNode fn) {
619     this.sameHeightWriteFlatNodeSet.add(fn);
620   }
621
622   public boolean isSameHeightWrite(FlatNode fn) {
623     return this.sameHeightWriteFlatNodeSet.contains(fn);
624   }
625
626   public LinkedList<MethodDescriptor> topologicalSort(Set<MethodDescriptor> toSort) {
627
628     Set<MethodDescriptor> discovered = new HashSet<MethodDescriptor>();
629
630     LinkedList<MethodDescriptor> sorted = new LinkedList<MethodDescriptor>();
631
632     Iterator<MethodDescriptor> itr = toSort.iterator();
633     while (itr.hasNext()) {
634       MethodDescriptor d = itr.next();
635
636       if (!discovered.contains(d)) {
637         dfsVisit(d, toSort, sorted, discovered);
638       }
639     }
640
641     return sorted;
642   }
643
644   // While we're doing DFS on call graph, remember
645   // dependencies for efficient queuing of methods
646   // during interprocedural analysis:
647   //
648   // a dependent of a method decriptor d for this analysis is:
649   // 1) a method or task that invokes d
650   // 2) in the descriptorsToAnalyze set
651   private void dfsVisit(MethodDescriptor md, Set<MethodDescriptor> toSort,
652       LinkedList<MethodDescriptor> sorted, Set<MethodDescriptor> discovered) {
653
654     discovered.add(md);
655
656     Iterator itr2 = callgraph.getCalleeSet(md).iterator();
657     while (itr2.hasNext()) {
658       MethodDescriptor dCallee = (MethodDescriptor) itr2.next();
659       addDependent(dCallee, md);
660     }
661
662     Iterator itr = callgraph.getCallerSet(md).iterator();
663     while (itr.hasNext()) {
664       MethodDescriptor dCaller = (MethodDescriptor) itr.next();
665       // only consider callers in the original set to analyze
666       if (!toSort.contains(dCaller)) {
667         continue;
668       }
669       if (!discovered.contains(dCaller)) {
670         addDependent(md, // callee
671             dCaller // caller
672         );
673
674         dfsVisit(dCaller, toSort, sorted, discovered);
675       }
676     }
677
678     // for leaf-nodes last now!
679     sorted.addLast(md);
680   }
681
682   public void addDependent(MethodDescriptor callee, MethodDescriptor caller) {
683     Set<MethodDescriptor> deps = mapDescriptorToSetDependents.get(callee);
684     if (deps == null) {
685       deps = new HashSet<MethodDescriptor>();
686     }
687     deps.add(caller);
688     mapDescriptorToSetDependents.put(callee, deps);
689   }
690
691   public Set<MethodDescriptor> getDependents(MethodDescriptor callee) {
692     Set<MethodDescriptor> deps = mapDescriptorToSetDependents.get(callee);
693     if (deps == null) {
694       deps = new HashSet<MethodDescriptor>();
695       mapDescriptorToSetDependents.put(callee, deps);
696     }
697     return deps;
698   }
699
700 }