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;
33 public class SSJavaAnalysis {
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";
50 FlowDownCheck flowDownChecker;
51 MethodAnnotationCheck methodAnnotationChecker;
54 // set containing method requires to be annoated
55 Set<MethodDescriptor> annotationRequireSet;
57 // class -> field lattice
58 Hashtable<ClassDescriptor, SSJavaLattice<String>> cd2lattice;
60 // class -> default local variable lattice
61 Hashtable<ClassDescriptor, MethodLattice<String>> cd2methodDefault;
63 // method -> local variable lattice
64 Hashtable<MethodDescriptor, MethodLattice<String>> md2lattice;
66 // method set that does not want to have loop termination analysis
67 Hashtable<MethodDescriptor, Integer> skipLoopTerminate;
69 // map shared location to its descriptors
70 Hashtable<Location, Set<Descriptor>> mapSharedLocation2DescriptorSet;
72 // set containing a class that has at least one annoated method
73 Set<ClassDescriptor> annotationRequireClassSet;
75 // the set of method descriptor required to check the linear type property
76 Set<MethodDescriptor> linearTypeCheckMethodSet;
78 // the set of method descriptors annotated as "TRUST"
79 Set<MethodDescriptor> trustWorthyMDSet;
81 // points to method containing SSJAVA Loop
82 private MethodDescriptor methodContainingSSJavaLoop;
84 // keep the field ownership from the linear type checking
85 Hashtable<MethodDescriptor, Set<FieldDescriptor>> mapMethodToOwnedFieldSet;
89 LinearTypeCheck checker;
91 public SSJavaAnalysis(State state, TypeUtil tu, BuildFlat bf, CallGraph callgraph) {
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>();
104 this.trustWorthyMDSet = new HashSet<MethodDescriptor>();
105 this.mapMethodToOwnedFieldSet = new Hashtable<MethodDescriptor, Set<FieldDescriptor>>();
108 public void doCheck() {
109 doMethodAnnotationCheck();
110 computeLinearTypeCheckMethodSet();
112 // if (state.SSJAVADEBUG) {
115 parseLocationAnnotation();
118 doDefinitelyWrittenCheck();
122 private void inference() {
123 SSJavaInferenceEngine inferEngine = new SSJavaInferenceEngine(this, state);
124 inferEngine.inference();
127 private void doLoopCheck() {
128 GlobalFieldType gft = new GlobalFieldType(callgraph, state, tu.getMain());
129 LoopOptimize lo = new LoopOptimize(gft, tu);
131 SymbolTable classtable = state.getClassSymbolTable();
133 List<ClassDescriptor> toanalyzeList = new ArrayList<ClassDescriptor>();
134 List<MethodDescriptor> toanalyzeMethodList = new ArrayList<MethodDescriptor>();
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());
143 for (int i = 0; i < toanalyzeList.size(); i++) {
144 ClassDescriptor cd = toanalyzeList.get(i);
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());
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));
167 public void addTrustMethod(MethodDescriptor md) {
168 trustWorthyMDSet.add(md);
171 public boolean isTrustMethod(MethodDescriptor md) {
172 return trustWorthyMDSet.contains(md);
175 private void computeLinearTypeCheckMethodSet() {
177 Set<MethodDescriptor> allCalledSet = callgraph.getMethodCalls(tu.getMain());
178 linearTypeCheckMethodSet.addAll(allCalledSet);
180 Set<MethodDescriptor> trustedSet = new HashSet<MethodDescriptor>();
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);
189 linearTypeCheckMethodSet.removeAll(trustedSet);
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);
203 private void doLinearTypeCheck() {
204 LinearTypeCheck checker = new LinearTypeCheck(this, state);
205 checker.linearTypeCheck();
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);
214 System.out.println();
217 private void doMethodAnnotationCheck() {
218 methodAnnotationChecker = new MethodAnnotationCheck(this, state, tu);
219 methodAnnotationChecker.methodAnnoatationCheck();
220 methodAnnotationChecker.methodAnnoataionInheritanceCheck();
223 public void doFlowDownCheck() {
224 flowDownChecker = new FlowDownCheck(this, state);
225 flowDownChecker.flowDownCheck();
228 public void doDefinitelyWrittenCheck() {
229 DefinitelyWrittenCheck checker = new DefinitelyWrittenCheck(this, state);
230 checker.definitelyWrittenCheck();
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);
248 if (state.SSJAVADEBUG) {
249 // generate lattice dot file
250 writeLatticeDotFile(cd, locOrder);
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);
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
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;
281 maxIteration = Integer.parseInt(value);
283 skipLoopTerminate.put(md, new Integer(maxIteration));
294 private void writeLatticeDotFile(ClassDescriptor cd, SSJavaLattice<String> locOrder) {
296 String className = cd.getSymbol().replaceAll("[\\W_]", "");
298 Set<Pair<String, String>> pairSet = locOrder.getOrderingPairSet();
301 BufferedWriter bw = new BufferedWriter(new FileWriter(className + ".dot"));
303 bw.write("digraph " + className + " {\n");
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();
309 String highLocId = pair.getFirst();
310 if (locOrder.isSharedLoc(highLocId)) {
311 highLocId = "\"" + highLocId + "*\"";
313 String lowLocId = pair.getSecond();
314 if (locOrder.isSharedLoc(lowLocId)) {
315 lowLocId = "\"" + lowLocId + "*\"";
317 bw.write(highLocId + " -> " + lowLocId + ";\n");
322 } catch (IOException e) {
328 private void parseMethodDefaultLatticeDefinition(ClassDescriptor cd, String value,
329 MethodLattice<String> locOrder) {
331 value = value.replaceAll(" ", ""); // remove all blank spaces
333 StringTokenizer tokenizer = new StringTokenizer(value, ",");
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.");
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));
360 locOrder.put(orderElement);
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());
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());
376 private void parseClassLatticeDefinition(ClassDescriptor cd, String value,
377 SSJavaLattice<String> locOrder) {
379 value = value.replaceAll(" ", ""); // remove all blank spaces
381 StringTokenizer tokenizer = new StringTokenizer(value, ",");
383 while (tokenizer.hasMoreTokens()) {
384 String orderElement = tokenizer.nextToken();
385 int idx = orderElement.indexOf("<");
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.");
395 } else if (orderElement.contains("*")) {
396 // spin loc definition
397 locOrder.addSharedLoc(orderElement.substring(0, orderElement.length() - 1));
400 locOrder.put(orderElement);
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());
415 public Hashtable<ClassDescriptor, SSJavaLattice<String>> getCd2lattice() {
419 public Hashtable<ClassDescriptor, MethodLattice<String>> getCd2methodDefault() {
420 return cd2methodDefault;
423 public Hashtable<MethodDescriptor, MethodLattice<String>> getMd2lattice() {
427 public SSJavaLattice<String> getClassLattice(ClassDescriptor cd) {
428 return cd2lattice.get(cd);
431 public MethodLattice<String> getMethodDefaultLattice(ClassDescriptor cd) {
432 return cd2methodDefault.get(cd);
435 public MethodLattice<String> getMethodLattice(MethodDescriptor md) {
436 if (md2lattice.containsKey(md)) {
437 return md2lattice.get(md);
440 if (cd2methodDefault.containsKey(md.getClassDesc())) {
441 return cd2methodDefault.get(md.getClassDesc());
443 throw new Error("Method Lattice of " + md + " is not defined.");
449 public boolean needToCheckLinearType(MethodDescriptor md) {
450 return linearTypeCheckMethodSet.contains(md);
453 public boolean needTobeAnnotated(MethodDescriptor md) {
454 return annotationRequireSet.contains(md);
457 public boolean needToBeAnnoated(ClassDescriptor cd) {
458 return annotationRequireClassSet.contains(cd);
461 public void addAnnotationRequire(ClassDescriptor cd) {
462 annotationRequireClassSet.add(cd);
465 public void addAnnotationRequire(MethodDescriptor md) {
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);
476 public Set<MethodDescriptor> getAnnotationRequireSet() {
477 return annotationRequireSet;
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));
487 public CallGraph getCallGraph() {
491 public SSJavaLattice<String> getLattice(Descriptor d) {
493 if (d instanceof MethodDescriptor) {
494 return getMethodLattice((MethodDescriptor) d);
496 return getClassLattice((ClassDescriptor) d);
501 public boolean isSharedLocation(Location loc) {
502 SSJavaLattice<String> lattice = getLattice(loc.getDescriptor());
503 return lattice.getSharedLocSet().contains(loc.getLocIdentifier());
506 public void mapSharedLocation2Descriptor(Location loc, Descriptor d) {
507 Set<Descriptor> set = mapSharedLocation2DescriptorSet.get(loc);
509 set = new HashSet<Descriptor>();
510 mapSharedLocation2DescriptorSet.put(loc, set);
515 public BuildFlat getBuildFlat() {
519 public MethodDescriptor getMethodContainingSSJavaLoop() {
520 return methodContainingSSJavaLoop;
523 public void setMethodContainingSSJavaLoop(MethodDescriptor methodContainingSSJavaLoop) {
524 this.methodContainingSSJavaLoop = methodContainingSSJavaLoop;
527 public boolean isSSJavaUtil(ClassDescriptor cd) {
528 if (cd.getSymbol().equals("SSJAVA")) {
534 public void setFieldOnwership(MethodDescriptor md, FieldDescriptor field) {
536 Set<FieldDescriptor> fieldSet = mapMethodToOwnedFieldSet.get(md);
537 if (fieldSet == null) {
538 fieldSet = new HashSet<FieldDescriptor>();
539 mapMethodToOwnedFieldSet.put(md, fieldSet);
544 public boolean isOwnedByMethod(MethodDescriptor md, FieldDescriptor field) {
545 Set<FieldDescriptor> fieldSet = mapMethodToOwnedFieldSet.get(md);
546 if (fieldSet != null) {
547 return fieldSet.contains(field);