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.LinkedList;
13 import java.util.List;
15 import java.util.StringTokenizer;
16 import java.util.Vector;
18 import Analysis.CallGraph.CallGraph;
19 import Analysis.Loops.GlobalFieldType;
20 import Analysis.Loops.LoopFinder;
21 import Analysis.Loops.LoopOptimize;
22 import Analysis.Loops.LoopTerminate;
23 import IR.AnnotationDescriptor;
24 import IR.ClassDescriptor;
26 import IR.FieldDescriptor;
27 import IR.MethodDescriptor;
29 import IR.SymbolTable;
31 import IR.Flat.BuildFlat;
32 import IR.Flat.FlatMethod;
33 import IR.Flat.FlatNode;
36 public class SSJavaAnalysis {
38 public static final String SSJAVA = "SSJAVA";
39 public static final String LATTICE = "LATTICE";
40 public static final String METHODDEFAULT = "METHODDEFAULT";
41 public static final String THISLOC = "THISLOC";
42 public static final String GLOBALLOC = "GLOBALLOC";
43 public static final String RETURNLOC = "RETURNLOC";
44 public static final String PCLOC = "PCLOC";
45 public static final String LOC = "LOC";
46 public static final String DELTA = "DELTA";
47 public static final String TERMINATE = "TERMINATE";
48 public static final String DELEGATE = "DELEGATE";
49 public static final String DELEGATETHIS = "DELEGATETHIS";
50 public static final String TRUST = "TRUST";
52 public static final String TOP = "_top_";
53 public static final String BOTTOM = "_bottom_";
57 FlowDownCheck flowDownChecker;
58 MethodAnnotationCheck methodAnnotationChecker;
61 // set containing method requires to be annoated
62 Set<MethodDescriptor> annotationRequireSet;
64 // class -> field lattice
65 Hashtable<ClassDescriptor, SSJavaLattice<String>> cd2lattice;
67 // class -> default local variable lattice
68 Hashtable<ClassDescriptor, MethodLattice<String>> cd2methodDefault;
70 // method -> local variable lattice
71 Hashtable<MethodDescriptor, MethodLattice<String>> md2lattice;
73 // method set that does not want to have loop termination analysis
74 Hashtable<MethodDescriptor, Integer> skipLoopTerminate;
76 // map shared location to its descriptors
77 Hashtable<Location, Set<Descriptor>> mapSharedLocation2DescriptorSet;
79 // set containing a class that has at least one annoated method
80 Set<ClassDescriptor> annotationRequireClassSet;
82 // the set of method descriptor required to check the linear type property
83 Set<MethodDescriptor> linearTypeCheckMethodSet;
85 // the set of method descriptors annotated as "TRUST"
86 Set<MethodDescriptor> trustWorthyMDSet;
88 // points to method containing SSJAVA Loop
89 private MethodDescriptor methodContainingSSJavaLoop;
91 private FlatNode ssjavaLoopEntrance;
93 // keep the field ownership from the linear type checking
94 Hashtable<MethodDescriptor, Set<FieldDescriptor>> mapMethodToOwnedFieldSet;
96 Set<FlatNode> sameHeightWriteFlatNodeSet;
100 LinearTypeCheck checker;
102 // maps a descriptor to its known dependents: namely
103 // methods or tasks that call the descriptor's method
104 // AND are part of this analysis (reachable from main)
105 private Hashtable<Descriptor, Set<MethodDescriptor>> mapDescriptorToSetDependents;
107 private LinkedList<MethodDescriptor> sortedDescriptors;
109 public SSJavaAnalysis(State state, TypeUtil tu, BuildFlat bf, CallGraph callgraph) {
112 this.callgraph = callgraph;
113 this.cd2lattice = new Hashtable<ClassDescriptor, SSJavaLattice<String>>();
114 this.cd2methodDefault = new Hashtable<ClassDescriptor, MethodLattice<String>>();
115 this.md2lattice = new Hashtable<MethodDescriptor, MethodLattice<String>>();
116 this.annotationRequireSet = new HashSet<MethodDescriptor>();
117 this.annotationRequireClassSet = new HashSet<ClassDescriptor>();
118 this.skipLoopTerminate = new Hashtable<MethodDescriptor, Integer>();
119 this.mapSharedLocation2DescriptorSet = new Hashtable<Location, Set<Descriptor>>();
120 this.linearTypeCheckMethodSet = new HashSet<MethodDescriptor>();
122 this.trustWorthyMDSet = new HashSet<MethodDescriptor>();
123 this.mapMethodToOwnedFieldSet = new Hashtable<MethodDescriptor, Set<FieldDescriptor>>();
124 this.sameHeightWriteFlatNodeSet = new HashSet<FlatNode>();
125 this.mapDescriptorToSetDependents = new Hashtable<Descriptor, Set<MethodDescriptor>>();
126 this.sortedDescriptors = new LinkedList<MethodDescriptor>();
129 public void doCheck() {
130 doMethodAnnotationCheck();
131 computeLinearTypeCheckMethodSet();
136 if (state.SSJAVADEBUG) {
137 debug_printAnnotationRequiredSet();
139 if (state.SSJAVAINFER) {
142 parseLocationAnnotation();
144 doDefinitelyWrittenCheck();
149 private void init() {
150 // perform topological sort over the set of methods accessed by the main
152 Set<MethodDescriptor> methodDescriptorsToAnalyze = new HashSet<MethodDescriptor>();
153 methodDescriptorsToAnalyze.addAll(getAnnotationRequireSet());
154 sortedDescriptors = topologicalSort(methodDescriptorsToAnalyze);
157 public LinkedList<MethodDescriptor> getSortedDescriptors() {
158 return (LinkedList<MethodDescriptor>) sortedDescriptors.clone();
161 private void inference() {
162 LocationInference inferEngine = new LocationInference(this, state);
163 inferEngine.inference();
166 private void doLoopCheck() {
167 GlobalFieldType gft = new GlobalFieldType(callgraph, state, tu.getMain());
168 LoopOptimize lo = new LoopOptimize(gft, tu);
170 SymbolTable classtable = state.getClassSymbolTable();
172 List<ClassDescriptor> toanalyzeList = new ArrayList<ClassDescriptor>();
173 List<MethodDescriptor> toanalyzeMethodList = new ArrayList<MethodDescriptor>();
175 toanalyzeList.addAll(classtable.getValueSet());
176 Collections.sort(toanalyzeList, new Comparator<ClassDescriptor>() {
177 public int compare(ClassDescriptor o1, ClassDescriptor o2) {
178 return o1.getClassName().compareTo(o2.getClassName());
182 for (int i = 0; i < toanalyzeList.size(); i++) {
183 ClassDescriptor cd = toanalyzeList.get(i);
185 SymbolTable methodtable = cd.getMethodTable();
186 toanalyzeMethodList.clear();
187 toanalyzeMethodList.addAll(methodtable.getValueSet());
188 Collections.sort(toanalyzeMethodList, new Comparator<MethodDescriptor>() {
189 public int compare(MethodDescriptor o1, MethodDescriptor o2) {
190 return o1.getSymbol().compareTo(o2.getSymbol());
194 for (int mdIdx = 0; mdIdx < toanalyzeMethodList.size(); mdIdx++) {
195 MethodDescriptor md = toanalyzeMethodList.get(mdIdx);
196 if (needTobeAnnotated(md)) {
197 lo.analyze(state.getMethodFlat(md));
198 doLoopTerminationCheck(lo, state.getMethodFlat(md));
206 public void addTrustMethod(MethodDescriptor md) {
207 trustWorthyMDSet.add(md);
210 public boolean isTrustMethod(MethodDescriptor md) {
211 return trustWorthyMDSet.contains(md);
214 private void computeLinearTypeCheckMethodSet() {
216 Set<MethodDescriptor> allCalledSet = callgraph.getMethodCalls(tu.getMain());
217 linearTypeCheckMethodSet.addAll(allCalledSet);
219 Set<MethodDescriptor> trustedSet = new HashSet<MethodDescriptor>();
221 for (Iterator iterator = trustWorthyMDSet.iterator(); iterator.hasNext();) {
222 MethodDescriptor trustMethod = (MethodDescriptor) iterator.next();
223 Set<MethodDescriptor> calledFromTrustMethodSet = callgraph.getMethodCalls(trustMethod);
224 trustedSet.add(trustMethod);
225 trustedSet.addAll(calledFromTrustMethodSet);
228 linearTypeCheckMethodSet.removeAll(trustedSet);
230 // if a method is called only by trusted method, no need to check linear
231 // type & flow down rule
232 for (Iterator iterator = trustedSet.iterator(); iterator.hasNext();) {
233 MethodDescriptor md = (MethodDescriptor) iterator.next();
234 Set<MethodDescriptor> callerSet = callgraph.getCallerSet(md);
235 if (!trustedSet.containsAll(callerSet) && !trustWorthyMDSet.contains(md)) {
236 linearTypeCheckMethodSet.add(md);
242 private void doLinearTypeCheck() {
243 LinearTypeCheck checker = new LinearTypeCheck(this, state);
244 checker.linearTypeCheck();
247 public void debug_printAnnotationRequiredSet() {
248 System.out.println("SSJAVA: SSJava is checking the following methods:");
249 for (Iterator<MethodDescriptor> iterator = annotationRequireSet.iterator(); iterator.hasNext();) {
250 MethodDescriptor md = iterator.next();
251 System.out.println(md);
253 System.out.println();
256 private void doMethodAnnotationCheck() {
257 methodAnnotationChecker = new MethodAnnotationCheck(this, state, tu);
258 methodAnnotationChecker.methodAnnoatationCheck();
259 methodAnnotationChecker.methodAnnoataionInheritanceCheck();
260 state.setAnnotationRequireSet(annotationRequireSet);
263 public void doFlowDownCheck() {
264 flowDownChecker = new FlowDownCheck(this, state);
265 flowDownChecker.flowDownCheck();
268 public void doDefinitelyWrittenCheck() {
269 DefinitelyWrittenCheck checker = new DefinitelyWrittenCheck(this, state);
270 checker.definitelyWrittenCheck();
273 private void parseLocationAnnotation() {
274 Iterator it = state.getClassSymbolTable().getDescriptorsIterator();
275 while (it.hasNext()) {
276 ClassDescriptor cd = (ClassDescriptor) it.next();
277 // parsing location hierarchy declaration for the class
278 Vector<AnnotationDescriptor> classAnnotations = cd.getModifier().getAnnotations();
279 for (int i = 0; i < classAnnotations.size(); i++) {
280 AnnotationDescriptor an = classAnnotations.elementAt(i);
281 String marker = an.getMarker();
282 if (marker.equals(LATTICE)) {
283 SSJavaLattice<String> locOrder =
284 new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM);
285 cd2lattice.put(cd, locOrder);
286 parseClassLatticeDefinition(cd, an.getValue(), locOrder);
288 if (state.SSJAVADEBUG) {
289 // generate lattice dot file
290 writeLatticeDotFile(cd, null, locOrder);
293 } else if (marker.equals(METHODDEFAULT)) {
294 MethodLattice<String> locOrder =
295 new MethodLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM);
296 cd2methodDefault.put(cd, locOrder);
297 parseMethodDefaultLatticeDefinition(cd, an.getValue(), locOrder);
301 for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
302 MethodDescriptor md = (MethodDescriptor) method_it.next();
303 // parsing location hierarchy declaration for the method
305 if (needTobeAnnotated(md)) {
306 Vector<AnnotationDescriptor> methodAnnotations = md.getModifiers().getAnnotations();
307 if (methodAnnotations != null) {
308 for (int i = 0; i < methodAnnotations.size(); i++) {
309 AnnotationDescriptor an = methodAnnotations.elementAt(i);
310 if (an.getMarker().equals(LATTICE)) {
311 // developer explicitly defines method lattice
312 MethodLattice<String> locOrder =
313 new MethodLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM);
314 md2lattice.put(md, locOrder);
315 parseMethodDefaultLatticeDefinition(cd, an.getValue(), locOrder);
316 } else if (an.getMarker().equals(TERMINATE)) {
317 // developer explicitly wants to skip loop termination analysis
318 String value = an.getValue();
319 int maxIteration = 0;
321 maxIteration = Integer.parseInt(value);
323 skipLoopTerminate.put(md, new Integer(maxIteration));
334 public <T> void writeLatticeDotFile(ClassDescriptor cd, MethodDescriptor md,
335 SSJavaLattice<T> locOrder) {
337 String fileName = "lattice_";
340 cd.getSymbol().replaceAll("[\\W_]", "") + "_" + md.getSymbol().replaceAll("[\\W_]", "");
342 fileName += cd.getSymbol().replaceAll("[\\W_]", "");
345 Set<Pair<T, T>> pairSet = locOrder.getOrderingPairSet();
347 if (pairSet.size() > 0) {
349 BufferedWriter bw = new BufferedWriter(new FileWriter(fileName + ".dot"));
351 bw.write("digraph " + fileName + " {\n");
353 for (Iterator iterator = pairSet.iterator(); iterator.hasNext();) {
354 // pair is in the form of <higher, lower>
355 Pair<T, T> pair = (Pair<T, T>) iterator.next();
357 T highLocId = pair.getFirst();
358 String highLocStr, lowLocStr;
359 if (locOrder.isSharedLoc(highLocId)) {
360 highLocStr = "\"" + highLocId + "*\"";
362 highLocStr = highLocId.toString();
364 T lowLocId = pair.getSecond();
365 if (locOrder.isSharedLoc(lowLocId)) {
366 lowLocStr = "\"" + lowLocId + "*\"";
368 lowLocStr = lowLocId.toString();
370 bw.write(highLocId + " -> " + lowLocId + ";\n");
375 } catch (IOException e) {
383 private void parseMethodDefaultLatticeDefinition(ClassDescriptor cd, String value,
384 MethodLattice<String> locOrder) {
386 value = value.replaceAll(" ", ""); // remove all blank spaces
388 StringTokenizer tokenizer = new StringTokenizer(value, ",");
390 while (tokenizer.hasMoreTokens()) {
391 String orderElement = tokenizer.nextToken();
392 int idx = orderElement.indexOf("<");
393 if (idx > 0) {// relative order element
394 String lowerLoc = orderElement.substring(0, idx);
395 String higherLoc = orderElement.substring(idx + 1);
396 locOrder.put(higherLoc, lowerLoc);
397 if (locOrder.isIntroducingCycle(higherLoc)) {
398 throw new Error("Error: the order relation " + lowerLoc + " < " + higherLoc
399 + " introduces a cycle.");
401 } else if (orderElement.startsWith(THISLOC + "=")) {
402 String thisLoc = orderElement.substring(8);
403 locOrder.setThisLoc(thisLoc);
404 } else if (orderElement.startsWith(GLOBALLOC + "=")) {
405 String globalLoc = orderElement.substring(10);
406 locOrder.setGlobalLoc(globalLoc);
407 } else if (orderElement.startsWith(RETURNLOC + "=")) {
408 String returnLoc = orderElement.substring(10);
409 locOrder.setReturnLoc(returnLoc);
410 } else if (orderElement.startsWith(PCLOC + "=")) {
411 String pcLoc = orderElement.substring(6);
412 locOrder.setPCLoc(pcLoc);
413 } else if (orderElement.endsWith("*")) {
414 // spin loc definition
415 locOrder.addSharedLoc(orderElement.substring(0, orderElement.length() - 1));
418 locOrder.put(orderElement);
423 if (locOrder.getThisLoc() != null && !locOrder.containsKey(locOrder.getThisLoc())) {
424 throw new Error("Variable 'this' location '" + locOrder.getThisLoc()
425 + "' is not defined in the local variable lattice at " + cd.getSourceFileName());
428 if (locOrder.getGlobalLoc() != null && !locOrder.containsKey(locOrder.getGlobalLoc())) {
429 throw new Error("Variable global location '" + locOrder.getGlobalLoc()
430 + "' is not defined in the local variable lattice at " + cd.getSourceFileName());
434 private void parseClassLatticeDefinition(ClassDescriptor cd, String value,
435 SSJavaLattice<String> locOrder) {
437 value = value.replaceAll(" ", ""); // remove all blank spaces
439 StringTokenizer tokenizer = new StringTokenizer(value, ",");
441 while (tokenizer.hasMoreTokens()) {
442 String orderElement = tokenizer.nextToken();
443 int idx = orderElement.indexOf("<");
445 if (idx > 0) {// relative order element
446 String lowerLoc = orderElement.substring(0, idx);
447 String higherLoc = orderElement.substring(idx + 1);
448 locOrder.put(higherLoc, lowerLoc);
449 if (locOrder.isIntroducingCycle(higherLoc)) {
450 throw new Error("Error: the order relation " + lowerLoc + " < " + higherLoc
451 + " introduces a cycle.");
453 } else if (orderElement.contains("*")) {
454 // spin loc definition
455 locOrder.addSharedLoc(orderElement.substring(0, orderElement.length() - 1));
458 locOrder.put(orderElement);
463 Set<String> spinLocSet = locOrder.getSharedLocSet();
464 for (Iterator iterator = spinLocSet.iterator(); iterator.hasNext();) {
465 String spinLoc = (String) iterator.next();
466 if (!locOrder.containsKey(spinLoc)) {
467 throw new Error("Spin location '" + spinLoc
468 + "' is not defined in the default local variable lattice at " + cd.getSourceFileName());
473 public Hashtable<ClassDescriptor, SSJavaLattice<String>> getCd2lattice() {
477 public Hashtable<ClassDescriptor, MethodLattice<String>> getCd2methodDefault() {
478 return cd2methodDefault;
481 public Hashtable<MethodDescriptor, MethodLattice<String>> getMd2lattice() {
485 public SSJavaLattice<String> getClassLattice(ClassDescriptor cd) {
486 return cd2lattice.get(cd);
489 public MethodLattice<String> getMethodDefaultLattice(ClassDescriptor cd) {
490 return cd2methodDefault.get(cd);
493 public MethodLattice<String> getMethodLattice(MethodDescriptor md) {
494 if (md2lattice.containsKey(md)) {
495 return md2lattice.get(md);
498 if (cd2methodDefault.containsKey(md.getClassDesc())) {
499 return cd2methodDefault.get(md.getClassDesc());
501 throw new Error("Method Lattice of " + md + " is not defined.");
507 public boolean needToCheckLinearType(MethodDescriptor md) {
508 return linearTypeCheckMethodSet.contains(md);
511 public boolean needTobeAnnotated(MethodDescriptor md) {
512 return annotationRequireSet.contains(md);
515 public boolean needToBeAnnoated(ClassDescriptor cd) {
516 return annotationRequireClassSet.contains(cd);
519 public void addAnnotationRequire(ClassDescriptor cd) {
520 annotationRequireClassSet.add(cd);
523 public void addAnnotationRequire(MethodDescriptor md) {
525 ClassDescriptor cd = md.getClassDesc();
526 // if a method requires to be annotated, class containg that method also
527 // requires to be annotated
528 if (!isSSJavaUtil(cd)) {
529 annotationRequireClassSet.add(cd);
530 annotationRequireSet.add(md);
534 public Set<MethodDescriptor> getAnnotationRequireSet() {
535 return annotationRequireSet;
538 public void doLoopTerminationCheck(LoopOptimize lo, FlatMethod fm) {
539 LoopTerminate lt = new LoopTerminate(this, state);
540 if (needTobeAnnotated(fm.getMethod())) {
541 lt.terminateAnalysis(fm, lo.getLoopInvariant(fm));
545 public CallGraph getCallGraph() {
549 public SSJavaLattice<String> getLattice(Descriptor d) {
551 if (d instanceof MethodDescriptor) {
552 return getMethodLattice((MethodDescriptor) d);
554 return getClassLattice((ClassDescriptor) d);
559 public boolean isSharedLocation(Location loc) {
560 SSJavaLattice<String> lattice = getLattice(loc.getDescriptor());
561 return lattice.getSharedLocSet().contains(loc.getLocIdentifier());
564 public void mapSharedLocation2Descriptor(Location loc, Descriptor d) {
565 Set<Descriptor> set = mapSharedLocation2DescriptorSet.get(loc);
567 set = new HashSet<Descriptor>();
568 mapSharedLocation2DescriptorSet.put(loc, set);
573 public BuildFlat getBuildFlat() {
577 public MethodDescriptor getMethodContainingSSJavaLoop() {
578 return methodContainingSSJavaLoop;
581 public void setMethodContainingSSJavaLoop(MethodDescriptor methodContainingSSJavaLoop) {
582 this.methodContainingSSJavaLoop = methodContainingSSJavaLoop;
585 public boolean isSSJavaUtil(ClassDescriptor cd) {
586 if (cd.getSymbol().equals("SSJAVA")) {
592 public void setFieldOnwership(MethodDescriptor md, FieldDescriptor field) {
594 Set<FieldDescriptor> fieldSet = mapMethodToOwnedFieldSet.get(md);
595 if (fieldSet == null) {
596 fieldSet = new HashSet<FieldDescriptor>();
597 mapMethodToOwnedFieldSet.put(md, fieldSet);
602 public boolean isOwnedByMethod(MethodDescriptor md, FieldDescriptor field) {
603 Set<FieldDescriptor> fieldSet = mapMethodToOwnedFieldSet.get(md);
604 if (fieldSet != null) {
605 return fieldSet.contains(field);
610 public FlatNode getSSJavaLoopEntrance() {
611 return ssjavaLoopEntrance;
614 public void setSSJavaLoopEntrance(FlatNode ssjavaLoopEntrance) {
615 this.ssjavaLoopEntrance = ssjavaLoopEntrance;
618 public void addSameHeightWriteFlatNode(FlatNode fn) {
619 this.sameHeightWriteFlatNodeSet.add(fn);
622 public boolean isSameHeightWrite(FlatNode fn) {
623 return this.sameHeightWriteFlatNodeSet.contains(fn);
626 public LinkedList<MethodDescriptor> topologicalSort(Set<MethodDescriptor> toSort) {
628 Set<MethodDescriptor> discovered = new HashSet<MethodDescriptor>();
630 LinkedList<MethodDescriptor> sorted = new LinkedList<MethodDescriptor>();
632 Iterator<MethodDescriptor> itr = toSort.iterator();
633 while (itr.hasNext()) {
634 MethodDescriptor d = itr.next();
636 if (!discovered.contains(d)) {
637 dfsVisit(d, toSort, sorted, discovered);
644 // While we're doing DFS on call graph, remember
645 // dependencies for efficient queuing of methods
646 // during interprocedural analysis:
648 // a dependent of a method decriptor d for this analysis is:
649 // 1) a method or task that invokes d
650 // 2) in the descriptorsToAnalyze set
651 private void dfsVisit(MethodDescriptor md, Set<MethodDescriptor> toSort,
652 LinkedList<MethodDescriptor> sorted, Set<MethodDescriptor> discovered) {
656 Iterator itr2 = callgraph.getCalleeSet(md).iterator();
657 while (itr2.hasNext()) {
658 MethodDescriptor dCallee = (MethodDescriptor) itr2.next();
659 addDependent(dCallee, md);
662 Iterator itr = callgraph.getCallerSet(md).iterator();
663 while (itr.hasNext()) {
664 MethodDescriptor dCaller = (MethodDescriptor) itr.next();
665 // only consider callers in the original set to analyze
666 if (!toSort.contains(dCaller)) {
669 if (!discovered.contains(dCaller)) {
670 addDependent(md, // callee
674 dfsVisit(dCaller, toSort, sorted, discovered);
678 // for leaf-nodes last now!
682 public void addDependent(MethodDescriptor callee, MethodDescriptor caller) {
683 Set<MethodDescriptor> deps = mapDescriptorToSetDependents.get(callee);
685 deps = new HashSet<MethodDescriptor>();
688 mapDescriptorToSetDependents.put(callee, deps);
691 public Set<MethodDescriptor> getDependents(MethodDescriptor callee) {
692 Set<MethodDescriptor> deps = mapDescriptorToSetDependents.get(callee);
694 deps = new HashSet<MethodDescriptor>();
695 mapDescriptorToSetDependents.put(callee, deps);