1 package Analysis.SSJava;
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;
14 import java.util.StringTokenizer;
15 import java.util.Vector;
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;
24 import IR.FieldDescriptor;
25 import IR.MethodDescriptor;
27 import IR.SymbolTable;
29 import IR.Flat.BuildFlat;
30 import IR.Flat.FlatMethod;
31 import IR.Flat.FlatNode;
34 public class SSJavaAnalysis {
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";
51 FlowDownCheck flowDownChecker;
52 MethodAnnotationCheck methodAnnotationChecker;
55 // set containing method requires to be annoated
56 Set<MethodDescriptor> annotationRequireSet;
58 // class -> field lattice
59 Hashtable<ClassDescriptor, SSJavaLattice<String>> cd2lattice;
61 // class -> default local variable lattice
62 Hashtable<ClassDescriptor, MethodLattice<String>> cd2methodDefault;
64 // method -> local variable lattice
65 Hashtable<MethodDescriptor, MethodLattice<String>> md2lattice;
67 // method set that does not want to have loop termination analysis
68 Hashtable<MethodDescriptor, Integer> skipLoopTerminate;
70 // map shared location to its descriptors
71 Hashtable<Location, Set<Descriptor>> mapSharedLocation2DescriptorSet;
73 // set containing a class that has at least one annoated method
74 Set<ClassDescriptor> annotationRequireClassSet;
76 // the set of method descriptor required to check the linear type property
77 Set<MethodDescriptor> linearTypeCheckMethodSet;
79 // the set of method descriptors annotated as "TRUST"
80 Set<MethodDescriptor> trustWorthyMDSet;
82 // points to method containing SSJAVA Loop
83 private MethodDescriptor methodContainingSSJavaLoop;
85 private FlatNode ssjavaLoopEntrance;
87 // keep the field ownership from the linear type checking
88 Hashtable<MethodDescriptor, Set<FieldDescriptor>> mapMethodToOwnedFieldSet;
90 Set<FlatNode> sameHeightWriteFlatNodeSet;
94 LinearTypeCheck checker;
96 public SSJavaAnalysis(State state, TypeUtil tu, BuildFlat bf, CallGraph callgraph) {
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>();
109 this.trustWorthyMDSet = new HashSet<MethodDescriptor>();
110 this.mapMethodToOwnedFieldSet = new Hashtable<MethodDescriptor, Set<FieldDescriptor>>();
111 this.sameHeightWriteFlatNodeSet = new HashSet<FlatNode>();
114 public void doCheck() {
115 doMethodAnnotationCheck();
116 computeLinearTypeCheckMethodSet();
118 // if (state.SSJAVADEBUG) {
121 if (state.SSJAVAINFER) {
124 parseLocationAnnotation();
126 doDefinitelyWrittenCheck();
131 private void inference() {
132 LocationInference inferEngine = new LocationInference(this, state);
133 inferEngine.inference();
136 private void doLoopCheck() {
137 GlobalFieldType gft = new GlobalFieldType(callgraph, state, tu.getMain());
138 LoopOptimize lo = new LoopOptimize(gft, tu);
140 SymbolTable classtable = state.getClassSymbolTable();
142 List<ClassDescriptor> toanalyzeList = new ArrayList<ClassDescriptor>();
143 List<MethodDescriptor> toanalyzeMethodList = new ArrayList<MethodDescriptor>();
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());
152 for (int i = 0; i < toanalyzeList.size(); i++) {
153 ClassDescriptor cd = toanalyzeList.get(i);
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());
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));
176 public void addTrustMethod(MethodDescriptor md) {
177 trustWorthyMDSet.add(md);
180 public boolean isTrustMethod(MethodDescriptor md) {
181 return trustWorthyMDSet.contains(md);
184 private void computeLinearTypeCheckMethodSet() {
186 Set<MethodDescriptor> allCalledSet = callgraph.getMethodCalls(tu.getMain());
187 linearTypeCheckMethodSet.addAll(allCalledSet);
189 Set<MethodDescriptor> trustedSet = new HashSet<MethodDescriptor>();
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);
198 linearTypeCheckMethodSet.removeAll(trustedSet);
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);
212 private void doLinearTypeCheck() {
213 LinearTypeCheck checker = new LinearTypeCheck(this, state);
214 checker.linearTypeCheck();
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);
223 System.out.println();
226 private void doMethodAnnotationCheck() {
227 methodAnnotationChecker = new MethodAnnotationCheck(this, state, tu);
228 methodAnnotationChecker.methodAnnoatationCheck();
229 methodAnnotationChecker.methodAnnoataionInheritanceCheck();
232 public void doFlowDownCheck() {
233 flowDownChecker = new FlowDownCheck(this, state);
234 flowDownChecker.flowDownCheck();
237 public void doDefinitelyWrittenCheck() {
238 DefinitelyWrittenCheck checker = new DefinitelyWrittenCheck(this, state);
239 checker.definitelyWrittenCheck();
242 private void parseLocationAnnotation() {
243 Iterator it = state.getClassSymbolTable().getDescriptorsIterator();
244 while (it.hasNext()) {
245 ClassDescriptor cd = (ClassDescriptor) it.next();
246 // parsing location hierarchy declaration for the class
247 Vector<AnnotationDescriptor> classAnnotations = cd.getModifier().getAnnotations();
248 for (int i = 0; i < classAnnotations.size(); i++) {
249 AnnotationDescriptor an = classAnnotations.elementAt(i);
250 String marker = an.getMarker();
251 if (marker.equals(LATTICE)) {
252 SSJavaLattice<String> locOrder =
253 new SSJavaLattice<String>(SSJavaLattice.TOP, SSJavaLattice.BOTTOM);
254 cd2lattice.put(cd, locOrder);
255 parseClassLatticeDefinition(cd, an.getValue(), locOrder);
257 if (state.SSJAVADEBUG) {
258 // generate lattice dot file
259 writeLatticeDotFile(cd, locOrder);
262 } else if (marker.equals(METHODDEFAULT)) {
263 MethodLattice<String> locOrder =
264 new MethodLattice<String>(SSJavaLattice.TOP, SSJavaLattice.BOTTOM);
265 cd2methodDefault.put(cd, locOrder);
266 parseMethodDefaultLatticeDefinition(cd, an.getValue(), locOrder);
270 for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
271 MethodDescriptor md = (MethodDescriptor) method_it.next();
272 // parsing location hierarchy declaration for the method
274 if (needTobeAnnotated(md)) {
275 Vector<AnnotationDescriptor> methodAnnotations = md.getModifiers().getAnnotations();
276 if (methodAnnotations != null) {
277 for (int i = 0; i < methodAnnotations.size(); i++) {
278 AnnotationDescriptor an = methodAnnotations.elementAt(i);
279 if (an.getMarker().equals(LATTICE)) {
280 // developer explicitly defines method lattice
281 MethodLattice<String> locOrder =
282 new MethodLattice<String>(SSJavaLattice.TOP, SSJavaLattice.BOTTOM);
283 md2lattice.put(md, locOrder);
284 parseMethodDefaultLatticeDefinition(cd, an.getValue(), locOrder);
285 } else if (an.getMarker().equals(TERMINATE)) {
286 // developer explicitly wants to skip loop termination analysis
287 String value = an.getValue();
288 int maxIteration = 0;
290 maxIteration = Integer.parseInt(value);
292 skipLoopTerminate.put(md, new Integer(maxIteration));
303 private void writeLatticeDotFile(ClassDescriptor cd, SSJavaLattice<String> locOrder) {
305 String className = cd.getSymbol().replaceAll("[\\W_]", "");
307 Set<Pair<String, String>> pairSet = locOrder.getOrderingPairSet();
310 BufferedWriter bw = new BufferedWriter(new FileWriter(className + ".dot"));
312 bw.write("digraph " + className + " {\n");
314 for (Iterator iterator = pairSet.iterator(); iterator.hasNext();) {
315 // pair is in the form of <higher, lower>
316 Pair<String, String> pair = (Pair<String, String>) iterator.next();
318 String highLocId = pair.getFirst();
319 if (locOrder.isSharedLoc(highLocId)) {
320 highLocId = "\"" + highLocId + "*\"";
322 String lowLocId = pair.getSecond();
323 if (locOrder.isSharedLoc(lowLocId)) {
324 lowLocId = "\"" + lowLocId + "*\"";
326 bw.write(highLocId + " -> " + lowLocId + ";\n");
331 } catch (IOException e) {
337 private void parseMethodDefaultLatticeDefinition(ClassDescriptor cd, String value,
338 MethodLattice<String> locOrder) {
340 value = value.replaceAll(" ", ""); // remove all blank spaces
342 StringTokenizer tokenizer = new StringTokenizer(value, ",");
344 while (tokenizer.hasMoreTokens()) {
345 String orderElement = tokenizer.nextToken();
346 int idx = orderElement.indexOf("<");
347 if (idx > 0) {// relative order element
348 String lowerLoc = orderElement.substring(0, idx);
349 String higherLoc = orderElement.substring(idx + 1);
350 locOrder.put(higherLoc, lowerLoc);
351 if (locOrder.isIntroducingCycle(higherLoc)) {
352 throw new Error("Error: the order relation " + lowerLoc + " < " + higherLoc
353 + " introduces a cycle.");
355 } else if (orderElement.startsWith(THISLOC + "=")) {
356 String thisLoc = orderElement.substring(8);
357 locOrder.setThisLoc(thisLoc);
358 } else if (orderElement.startsWith(GLOBALLOC + "=")) {
359 String globalLoc = orderElement.substring(10);
360 locOrder.setGlobalLoc(globalLoc);
361 } else if (orderElement.startsWith(RETURNLOC + "=")) {
362 String returnLoc = orderElement.substring(10);
363 locOrder.setReturnLoc(returnLoc);
364 } else if (orderElement.endsWith("*")) {
365 // spin loc definition
366 locOrder.addSharedLoc(orderElement.substring(0, orderElement.length() - 1));
369 locOrder.put(orderElement);
374 if (locOrder.getThisLoc() != null && !locOrder.containsKey(locOrder.getThisLoc())) {
375 throw new Error("Variable 'this' location '" + locOrder.getThisLoc()
376 + "' is not defined in the local variable lattice at " + cd.getSourceFileName());
379 if (locOrder.getGlobalLoc() != null && !locOrder.containsKey(locOrder.getGlobalLoc())) {
380 throw new Error("Variable global location '" + locOrder.getGlobalLoc()
381 + "' is not defined in the local variable lattice at " + cd.getSourceFileName());
385 private void parseClassLatticeDefinition(ClassDescriptor cd, String value,
386 SSJavaLattice<String> locOrder) {
388 value = value.replaceAll(" ", ""); // remove all blank spaces
390 StringTokenizer tokenizer = new StringTokenizer(value, ",");
392 while (tokenizer.hasMoreTokens()) {
393 String orderElement = tokenizer.nextToken();
394 int idx = orderElement.indexOf("<");
396 if (idx > 0) {// relative order element
397 String lowerLoc = orderElement.substring(0, idx);
398 String higherLoc = orderElement.substring(idx + 1);
399 locOrder.put(higherLoc, lowerLoc);
400 if (locOrder.isIntroducingCycle(higherLoc)) {
401 throw new Error("Error: the order relation " + lowerLoc + " < " + higherLoc
402 + " introduces a cycle.");
404 } else if (orderElement.contains("*")) {
405 // spin loc definition
406 locOrder.addSharedLoc(orderElement.substring(0, orderElement.length() - 1));
409 locOrder.put(orderElement);
414 Set<String> spinLocSet = locOrder.getSharedLocSet();
415 for (Iterator iterator = spinLocSet.iterator(); iterator.hasNext();) {
416 String spinLoc = (String) iterator.next();
417 if (!locOrder.containsKey(spinLoc)) {
418 throw new Error("Spin location '" + spinLoc
419 + "' is not defined in the default local variable lattice at " + cd.getSourceFileName());
424 public Hashtable<ClassDescriptor, SSJavaLattice<String>> getCd2lattice() {
428 public Hashtable<ClassDescriptor, MethodLattice<String>> getCd2methodDefault() {
429 return cd2methodDefault;
432 public Hashtable<MethodDescriptor, MethodLattice<String>> getMd2lattice() {
436 public SSJavaLattice<String> getClassLattice(ClassDescriptor cd) {
437 return cd2lattice.get(cd);
440 public MethodLattice<String> getMethodDefaultLattice(ClassDescriptor cd) {
441 return cd2methodDefault.get(cd);
444 public MethodLattice<String> getMethodLattice(MethodDescriptor md) {
445 if (md2lattice.containsKey(md)) {
446 return md2lattice.get(md);
449 if (cd2methodDefault.containsKey(md.getClassDesc())) {
450 return cd2methodDefault.get(md.getClassDesc());
452 throw new Error("Method Lattice of " + md + " is not defined.");
458 public boolean needToCheckLinearType(MethodDescriptor md) {
459 return linearTypeCheckMethodSet.contains(md);
462 public boolean needTobeAnnotated(MethodDescriptor md) {
463 return annotationRequireSet.contains(md);
466 public boolean needToBeAnnoated(ClassDescriptor cd) {
467 return annotationRequireClassSet.contains(cd);
470 public void addAnnotationRequire(ClassDescriptor cd) {
471 annotationRequireClassSet.add(cd);
474 public void addAnnotationRequire(MethodDescriptor md) {
476 ClassDescriptor cd = md.getClassDesc();
477 // if a method requires to be annotated, class containg that method also
478 // requires to be annotated
479 if (!isSSJavaUtil(cd)) {
480 annotationRequireClassSet.add(cd);
481 annotationRequireSet.add(md);
485 public Set<MethodDescriptor> getAnnotationRequireSet() {
486 return annotationRequireSet;
489 public void doLoopTerminationCheck(LoopOptimize lo, FlatMethod fm) {
490 LoopTerminate lt = new LoopTerminate(this, state);
491 if (needTobeAnnotated(fm.getMethod())) {
492 lt.terminateAnalysis(fm, lo.getLoopInvariant(fm));
496 public CallGraph getCallGraph() {
500 public SSJavaLattice<String> getLattice(Descriptor d) {
502 if (d instanceof MethodDescriptor) {
503 return getMethodLattice((MethodDescriptor) d);
505 return getClassLattice((ClassDescriptor) d);
510 public boolean isSharedLocation(Location loc) {
511 SSJavaLattice<String> lattice = getLattice(loc.getDescriptor());
512 return lattice.getSharedLocSet().contains(loc.getLocIdentifier());
515 public void mapSharedLocation2Descriptor(Location loc, Descriptor d) {
516 Set<Descriptor> set = mapSharedLocation2DescriptorSet.get(loc);
518 set = new HashSet<Descriptor>();
519 mapSharedLocation2DescriptorSet.put(loc, set);
524 public BuildFlat getBuildFlat() {
528 public MethodDescriptor getMethodContainingSSJavaLoop() {
529 return methodContainingSSJavaLoop;
532 public void setMethodContainingSSJavaLoop(MethodDescriptor methodContainingSSJavaLoop) {
533 this.methodContainingSSJavaLoop = methodContainingSSJavaLoop;
536 public boolean isSSJavaUtil(ClassDescriptor cd) {
537 if (cd.getSymbol().equals("SSJAVA")) {
543 public void setFieldOnwership(MethodDescriptor md, FieldDescriptor field) {
545 Set<FieldDescriptor> fieldSet = mapMethodToOwnedFieldSet.get(md);
546 if (fieldSet == null) {
547 fieldSet = new HashSet<FieldDescriptor>();
548 mapMethodToOwnedFieldSet.put(md, fieldSet);
553 public boolean isOwnedByMethod(MethodDescriptor md, FieldDescriptor field) {
554 Set<FieldDescriptor> fieldSet = mapMethodToOwnedFieldSet.get(md);
555 if (fieldSet != null) {
556 return fieldSet.contains(field);
561 public FlatNode getSSJavaLoopEntrance() {
562 return ssjavaLoopEntrance;
565 public void setSSJavaLoopEntrance(FlatNode ssjavaLoopEntrance) {
566 this.ssjavaLoopEntrance = ssjavaLoopEntrance;
569 public void addSameHeightWriteFlatNode(FlatNode fn) {
570 this.sameHeightWriteFlatNodeSet.add(fn);
573 public boolean isSameHeightWrite(FlatNode fn) {
574 return this.sameHeightWriteFlatNodeSet.contains(fn);