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