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