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