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