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