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