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