146af4e6215a5bc2b8696df6c15177c10a15a79f
[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     state.setAnnotationRequireSet(annotationRequireSet);
231   }
232
233   public void doFlowDownCheck() {
234     flowDownChecker = new FlowDownCheck(this, state);
235     flowDownChecker.flowDownCheck();
236   }
237
238   public void doDefinitelyWrittenCheck() {
239     DefinitelyWrittenCheck checker = new DefinitelyWrittenCheck(this, state);
240     checker.definitelyWrittenCheck();
241   }
242
243   private void parseLocationAnnotation() {
244     Iterator it = state.getClassSymbolTable().getDescriptorsIterator();
245     while (it.hasNext()) {
246       ClassDescriptor cd = (ClassDescriptor) it.next();
247       // parsing location hierarchy declaration for the class
248       Vector<AnnotationDescriptor> classAnnotations = cd.getModifier().getAnnotations();
249       for (int i = 0; i < classAnnotations.size(); i++) {
250         AnnotationDescriptor an = classAnnotations.elementAt(i);
251         String marker = an.getMarker();
252         if (marker.equals(LATTICE)) {
253           SSJavaLattice<String> locOrder =
254               new SSJavaLattice<String>(SSJavaLattice.TOP, SSJavaLattice.BOTTOM);
255           cd2lattice.put(cd, locOrder);
256           parseClassLatticeDefinition(cd, an.getValue(), locOrder);
257
258           if (state.SSJAVADEBUG) {
259             // generate lattice dot file
260             writeLatticeDotFile(cd, locOrder);
261           }
262
263         } else if (marker.equals(METHODDEFAULT)) {
264           MethodLattice<String> locOrder =
265               new MethodLattice<String>(SSJavaLattice.TOP, SSJavaLattice.BOTTOM);
266           cd2methodDefault.put(cd, locOrder);
267           parseMethodDefaultLatticeDefinition(cd, an.getValue(), locOrder);
268         }
269       }
270
271       for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
272         MethodDescriptor md = (MethodDescriptor) method_it.next();
273         // parsing location hierarchy declaration for the method
274
275         if (needTobeAnnotated(md)) {
276           Vector<AnnotationDescriptor> methodAnnotations = md.getModifiers().getAnnotations();
277           if (methodAnnotations != null) {
278             for (int i = 0; i < methodAnnotations.size(); i++) {
279               AnnotationDescriptor an = methodAnnotations.elementAt(i);
280               if (an.getMarker().equals(LATTICE)) {
281                 // developer explicitly defines method lattice
282                 MethodLattice<String> locOrder =
283                     new MethodLattice<String>(SSJavaLattice.TOP, SSJavaLattice.BOTTOM);
284                 md2lattice.put(md, locOrder);
285                 parseMethodDefaultLatticeDefinition(cd, an.getValue(), locOrder);
286               } else if (an.getMarker().equals(TERMINATE)) {
287                 // developer explicitly wants to skip loop termination analysis
288                 String value = an.getValue();
289                 int maxIteration = 0;
290                 if (value != null) {
291                   maxIteration = Integer.parseInt(value);
292                 }
293                 skipLoopTerminate.put(md, new Integer(maxIteration));
294               }
295             }
296           }
297         }
298
299       }
300
301     }
302   }
303
304   private void writeLatticeDotFile(ClassDescriptor cd, SSJavaLattice<String> locOrder) {
305
306     String className = cd.getSymbol().replaceAll("[\\W_]", "");
307
308     Set<Pair<String, String>> pairSet = locOrder.getOrderingPairSet();
309
310     try {
311       BufferedWriter bw = new BufferedWriter(new FileWriter(className + ".dot"));
312
313       bw.write("digraph " + className + " {\n");
314
315       for (Iterator iterator = pairSet.iterator(); iterator.hasNext();) {
316         // pair is in the form of <higher, lower>
317         Pair<String, String> pair = (Pair<String, String>) iterator.next();
318
319         String highLocId = pair.getFirst();
320         if (locOrder.isSharedLoc(highLocId)) {
321           highLocId = "\"" + highLocId + "*\"";
322         }
323         String lowLocId = pair.getSecond();
324         if (locOrder.isSharedLoc(lowLocId)) {
325           lowLocId = "\"" + lowLocId + "*\"";
326         }
327         bw.write(highLocId + " -> " + lowLocId + ";\n");
328       }
329       bw.write("}\n");
330       bw.close();
331
332     } catch (IOException e) {
333       e.printStackTrace();
334     }
335
336   }
337
338   private void parseMethodDefaultLatticeDefinition(ClassDescriptor cd, String value,
339       MethodLattice<String> locOrder) {
340
341     value = value.replaceAll(" ", ""); // remove all blank spaces
342
343     StringTokenizer tokenizer = new StringTokenizer(value, ",");
344
345     while (tokenizer.hasMoreTokens()) {
346       String orderElement = tokenizer.nextToken();
347       int idx = orderElement.indexOf("<");
348       if (idx > 0) {// relative order element
349         String lowerLoc = orderElement.substring(0, idx);
350         String higherLoc = orderElement.substring(idx + 1);
351         locOrder.put(higherLoc, lowerLoc);
352         if (locOrder.isIntroducingCycle(higherLoc)) {
353           throw new Error("Error: the order relation " + lowerLoc + " < " + higherLoc
354               + " introduces a cycle.");
355         }
356       } else if (orderElement.startsWith(THISLOC + "=")) {
357         String thisLoc = orderElement.substring(8);
358         locOrder.setThisLoc(thisLoc);
359       } else if (orderElement.startsWith(GLOBALLOC + "=")) {
360         String globalLoc = orderElement.substring(10);
361         locOrder.setGlobalLoc(globalLoc);
362       } else if (orderElement.startsWith(RETURNLOC + "=")) {
363         String returnLoc = orderElement.substring(10);
364         locOrder.setReturnLoc(returnLoc);
365       } else if (orderElement.endsWith("*")) {
366         // spin loc definition
367         locOrder.addSharedLoc(orderElement.substring(0, orderElement.length() - 1));
368       } else {
369         // single element
370         locOrder.put(orderElement);
371       }
372     }
373
374     // sanity checks
375     if (locOrder.getThisLoc() != null && !locOrder.containsKey(locOrder.getThisLoc())) {
376       throw new Error("Variable 'this' location '" + locOrder.getThisLoc()
377           + "' is not defined in the local variable lattice at " + cd.getSourceFileName());
378     }
379
380     if (locOrder.getGlobalLoc() != null && !locOrder.containsKey(locOrder.getGlobalLoc())) {
381       throw new Error("Variable global location '" + locOrder.getGlobalLoc()
382           + "' is not defined in the local variable lattice at " + cd.getSourceFileName());
383     }
384   }
385
386   private void parseClassLatticeDefinition(ClassDescriptor cd, String value,
387       SSJavaLattice<String> locOrder) {
388
389     value = value.replaceAll(" ", ""); // remove all blank spaces
390
391     StringTokenizer tokenizer = new StringTokenizer(value, ",");
392
393     while (tokenizer.hasMoreTokens()) {
394       String orderElement = tokenizer.nextToken();
395       int idx = orderElement.indexOf("<");
396
397       if (idx > 0) {// relative order element
398         String lowerLoc = orderElement.substring(0, idx);
399         String higherLoc = orderElement.substring(idx + 1);
400         locOrder.put(higherLoc, lowerLoc);
401         if (locOrder.isIntroducingCycle(higherLoc)) {
402           throw new Error("Error: the order relation " + lowerLoc + " < " + higherLoc
403               + " introduces a cycle.");
404         }
405       } else if (orderElement.contains("*")) {
406         // spin loc definition
407         locOrder.addSharedLoc(orderElement.substring(0, orderElement.length() - 1));
408       } else {
409         // single element
410         locOrder.put(orderElement);
411       }
412     }
413
414     // sanity check
415     Set<String> spinLocSet = locOrder.getSharedLocSet();
416     for (Iterator iterator = spinLocSet.iterator(); iterator.hasNext();) {
417       String spinLoc = (String) iterator.next();
418       if (!locOrder.containsKey(spinLoc)) {
419         throw new Error("Spin location '" + spinLoc
420             + "' is not defined in the default local variable lattice at " + cd.getSourceFileName());
421       }
422     }
423   }
424
425   public Hashtable<ClassDescriptor, SSJavaLattice<String>> getCd2lattice() {
426     return cd2lattice;
427   }
428
429   public Hashtable<ClassDescriptor, MethodLattice<String>> getCd2methodDefault() {
430     return cd2methodDefault;
431   }
432
433   public Hashtable<MethodDescriptor, MethodLattice<String>> getMd2lattice() {
434     return md2lattice;
435   }
436
437   public SSJavaLattice<String> getClassLattice(ClassDescriptor cd) {
438     return cd2lattice.get(cd);
439   }
440
441   public MethodLattice<String> getMethodDefaultLattice(ClassDescriptor cd) {
442     return cd2methodDefault.get(cd);
443   }
444
445   public MethodLattice<String> getMethodLattice(MethodDescriptor md) {
446     if (md2lattice.containsKey(md)) {
447       return md2lattice.get(md);
448     } else {
449
450       if (cd2methodDefault.containsKey(md.getClassDesc())) {
451         return cd2methodDefault.get(md.getClassDesc());
452       } else {
453         throw new Error("Method Lattice of " + md + " is not defined.");
454       }
455
456     }
457   }
458
459   public boolean needToCheckLinearType(MethodDescriptor md) {
460     return linearTypeCheckMethodSet.contains(md);
461   }
462
463   public boolean needTobeAnnotated(MethodDescriptor md) {
464     return annotationRequireSet.contains(md);
465   }
466
467   public boolean needToBeAnnoated(ClassDescriptor cd) {
468     return annotationRequireClassSet.contains(cd);
469   }
470
471   public void addAnnotationRequire(ClassDescriptor cd) {
472     annotationRequireClassSet.add(cd);
473   }
474
475   public void addAnnotationRequire(MethodDescriptor md) {
476
477     ClassDescriptor cd = md.getClassDesc();
478     // if a method requires to be annotated, class containg that method also
479     // requires to be annotated
480     if (!isSSJavaUtil(cd)) {
481       annotationRequireClassSet.add(cd);
482       annotationRequireSet.add(md);
483     }
484   }
485
486   public Set<MethodDescriptor> getAnnotationRequireSet() {
487     return annotationRequireSet;
488   }
489
490   public void doLoopTerminationCheck(LoopOptimize lo, FlatMethod fm) {
491     LoopTerminate lt = new LoopTerminate(this, state);
492     if (needTobeAnnotated(fm.getMethod())) {
493       lt.terminateAnalysis(fm, lo.getLoopInvariant(fm));
494     }
495   }
496
497   public CallGraph getCallGraph() {
498     return callgraph;
499   }
500
501   public SSJavaLattice<String> getLattice(Descriptor d) {
502
503     if (d instanceof MethodDescriptor) {
504       return getMethodLattice((MethodDescriptor) d);
505     } else {
506       return getClassLattice((ClassDescriptor) d);
507     }
508
509   }
510
511   public boolean isSharedLocation(Location loc) {
512     SSJavaLattice<String> lattice = getLattice(loc.getDescriptor());
513     return lattice.getSharedLocSet().contains(loc.getLocIdentifier());
514   }
515
516   public void mapSharedLocation2Descriptor(Location loc, Descriptor d) {
517     Set<Descriptor> set = mapSharedLocation2DescriptorSet.get(loc);
518     if (set == null) {
519       set = new HashSet<Descriptor>();
520       mapSharedLocation2DescriptorSet.put(loc, set);
521     }
522     set.add(d);
523   }
524
525   public BuildFlat getBuildFlat() {
526     return bf;
527   }
528
529   public MethodDescriptor getMethodContainingSSJavaLoop() {
530     return methodContainingSSJavaLoop;
531   }
532
533   public void setMethodContainingSSJavaLoop(MethodDescriptor methodContainingSSJavaLoop) {
534     this.methodContainingSSJavaLoop = methodContainingSSJavaLoop;
535   }
536
537   public boolean isSSJavaUtil(ClassDescriptor cd) {
538     if (cd.getSymbol().equals("SSJAVA")) {
539       return true;
540     }
541     return false;
542   }
543
544   public void setFieldOnwership(MethodDescriptor md, FieldDescriptor field) {
545
546     Set<FieldDescriptor> fieldSet = mapMethodToOwnedFieldSet.get(md);
547     if (fieldSet == null) {
548       fieldSet = new HashSet<FieldDescriptor>();
549       mapMethodToOwnedFieldSet.put(md, fieldSet);
550     }
551     fieldSet.add(field);
552   }
553
554   public boolean isOwnedByMethod(MethodDescriptor md, FieldDescriptor field) {
555     Set<FieldDescriptor> fieldSet = mapMethodToOwnedFieldSet.get(md);
556     if (fieldSet != null) {
557       return fieldSet.contains(field);
558     }
559     return false;
560   }
561
562   public FlatNode getSSJavaLoopEntrance() {
563     return ssjavaLoopEntrance;
564   }
565
566   public void setSSJavaLoopEntrance(FlatNode ssjavaLoopEntrance) {
567     this.ssjavaLoopEntrance = ssjavaLoopEntrance;
568   }
569
570   public void addSameHeightWriteFlatNode(FlatNode fn) {
571     this.sameHeightWriteFlatNodeSet.add(fn);
572   }
573
574   public boolean isSameHeightWrite(FlatNode fn) {
575     return this.sameHeightWriteFlatNodeSet.contains(fn);
576   }
577
578 }