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;
92 LinearTypeCheck checker;
94 public SSJavaAnalysis(State state, TypeUtil tu, BuildFlat bf, CallGraph callgraph) {
97 this.callgraph = callgraph;
98 this.cd2lattice = new Hashtable<ClassDescriptor, SSJavaLattice<String>>();
99 this.cd2methodDefault = new Hashtable<ClassDescriptor, MethodLattice<String>>();
100 this.md2lattice = new Hashtable<MethodDescriptor, MethodLattice<String>>();
101 this.annotationRequireSet = new HashSet<MethodDescriptor>();
102 this.annotationRequireClassSet = new HashSet<ClassDescriptor>();
103 this.skipLoopTerminate = new Hashtable<MethodDescriptor, Integer>();
104 this.mapSharedLocation2DescriptorSet = new Hashtable<Location, Set<Descriptor>>();
105 this.linearTypeCheckMethodSet = new HashSet<MethodDescriptor>();
107 this.trustWorthyMDSet = new HashSet<MethodDescriptor>();
108 this.mapMethodToOwnedFieldSet = new Hashtable<MethodDescriptor, Set<FieldDescriptor>>();
111 public void doCheck() {
112 doMethodAnnotationCheck();
113 computeLinearTypeCheckMethodSet();
115 // if (state.SSJAVADEBUG) {
118 parseLocationAnnotation();
121 doDefinitelyWrittenCheck();
125 private void inference() {
126 SSJavaInferenceEngine inferEngine = new SSJavaInferenceEngine(this, state);
127 inferEngine.inference();
130 private void doLoopCheck() {
131 GlobalFieldType gft = new GlobalFieldType(callgraph, state, tu.getMain());
132 LoopOptimize lo = new LoopOptimize(gft, tu);
134 SymbolTable classtable = state.getClassSymbolTable();
136 List<ClassDescriptor> toanalyzeList = new ArrayList<ClassDescriptor>();
137 List<MethodDescriptor> toanalyzeMethodList = new ArrayList<MethodDescriptor>();
139 toanalyzeList.addAll(classtable.getValueSet());
140 Collections.sort(toanalyzeList, new Comparator<ClassDescriptor>() {
141 public int compare(ClassDescriptor o1, ClassDescriptor o2) {
142 return o1.getClassName().compareTo(o2.getClassName());
146 for (int i = 0; i < toanalyzeList.size(); i++) {
147 ClassDescriptor cd = toanalyzeList.get(i);
149 SymbolTable methodtable = cd.getMethodTable();
150 toanalyzeMethodList.clear();
151 toanalyzeMethodList.addAll(methodtable.getValueSet());
152 Collections.sort(toanalyzeMethodList, new Comparator<MethodDescriptor>() {
153 public int compare(MethodDescriptor o1, MethodDescriptor o2) {
154 return o1.getSymbol().compareTo(o2.getSymbol());
158 for (int mdIdx = 0; mdIdx < toanalyzeMethodList.size(); mdIdx++) {
159 MethodDescriptor md = toanalyzeMethodList.get(mdIdx);
160 if (needTobeAnnotated(md)) {
161 lo.analyze(state.getMethodFlat(md));
162 doLoopTerminationCheck(lo, state.getMethodFlat(md));
170 public void addTrustMethod(MethodDescriptor md) {
171 trustWorthyMDSet.add(md);
174 public boolean isTrustMethod(MethodDescriptor md) {
175 return trustWorthyMDSet.contains(md);
178 private void computeLinearTypeCheckMethodSet() {
180 Set<MethodDescriptor> allCalledSet = callgraph.getMethodCalls(tu.getMain());
181 linearTypeCheckMethodSet.addAll(allCalledSet);
183 Set<MethodDescriptor> trustedSet = new HashSet<MethodDescriptor>();
185 for (Iterator iterator = trustWorthyMDSet.iterator(); iterator.hasNext();) {
186 MethodDescriptor trustMethod = (MethodDescriptor) iterator.next();
187 Set<MethodDescriptor> calledFromTrustMethodSet = callgraph.getMethodCalls(trustMethod);
188 trustedSet.add(trustMethod);
189 trustedSet.addAll(calledFromTrustMethodSet);
192 linearTypeCheckMethodSet.removeAll(trustedSet);
194 // if a method is called only by trusted method, no need to check linear
195 // type & flow down rule
196 for (Iterator iterator = trustedSet.iterator(); iterator.hasNext();) {
197 MethodDescriptor md = (MethodDescriptor) iterator.next();
198 Set<MethodDescriptor> callerSet = callgraph.getCallerSet(md);
199 if (!trustedSet.containsAll(callerSet) && !trustWorthyMDSet.contains(md)) {
200 linearTypeCheckMethodSet.add(md);
206 private void doLinearTypeCheck() {
207 LinearTypeCheck checker = new LinearTypeCheck(this, state);
208 checker.linearTypeCheck();
211 public void debugPrint() {
212 System.out.println("SSJAVA: SSJava is checking the following methods:");
213 for (Iterator<MethodDescriptor> iterator = annotationRequireSet.iterator(); iterator.hasNext();) {
214 MethodDescriptor md = iterator.next();
215 System.out.print(" " + md);
217 System.out.println();
220 private void doMethodAnnotationCheck() {
221 methodAnnotationChecker = new MethodAnnotationCheck(this, state, tu);
222 methodAnnotationChecker.methodAnnoatationCheck();
223 methodAnnotationChecker.methodAnnoataionInheritanceCheck();
226 public void doFlowDownCheck() {
227 flowDownChecker = new FlowDownCheck(this, state);
228 flowDownChecker.flowDownCheck();
231 public void doDefinitelyWrittenCheck() {
232 DefinitelyWrittenCheck checker = new DefinitelyWrittenCheck(this, state);
233 checker.definitelyWrittenCheck();
236 private void parseLocationAnnotation() {
237 Iterator it = state.getClassSymbolTable().getDescriptorsIterator();
238 while (it.hasNext()) {
239 ClassDescriptor cd = (ClassDescriptor) it.next();
240 // parsing location hierarchy declaration for the class
241 Vector<AnnotationDescriptor> classAnnotations = cd.getModifier().getAnnotations();
242 for (int i = 0; i < classAnnotations.size(); i++) {
243 AnnotationDescriptor an = classAnnotations.elementAt(i);
244 String marker = an.getMarker();
245 if (marker.equals(LATTICE)) {
246 SSJavaLattice<String> locOrder =
247 new SSJavaLattice<String>(SSJavaLattice.TOP, SSJavaLattice.BOTTOM);
248 cd2lattice.put(cd, locOrder);
249 parseClassLatticeDefinition(cd, an.getValue(), locOrder);
251 if (state.SSJAVADEBUG) {
252 // generate lattice dot file
253 writeLatticeDotFile(cd, locOrder);
256 } else if (marker.equals(METHODDEFAULT)) {
257 MethodLattice<String> locOrder =
258 new MethodLattice<String>(SSJavaLattice.TOP, SSJavaLattice.BOTTOM);
259 cd2methodDefault.put(cd, locOrder);
260 parseMethodDefaultLatticeDefinition(cd, an.getValue(), locOrder);
264 for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
265 MethodDescriptor md = (MethodDescriptor) method_it.next();
266 // parsing location hierarchy declaration for the method
268 if (needTobeAnnotated(md)) {
269 Vector<AnnotationDescriptor> methodAnnotations = md.getModifiers().getAnnotations();
270 if (methodAnnotations != null) {
271 for (int i = 0; i < methodAnnotations.size(); i++) {
272 AnnotationDescriptor an = methodAnnotations.elementAt(i);
273 if (an.getMarker().equals(LATTICE)) {
274 // developer explicitly defines method lattice
275 MethodLattice<String> locOrder =
276 new MethodLattice<String>(SSJavaLattice.TOP, SSJavaLattice.BOTTOM);
277 md2lattice.put(md, locOrder);
278 parseMethodDefaultLatticeDefinition(cd, an.getValue(), locOrder);
279 } else if (an.getMarker().equals(TERMINATE)) {
280 // developer explicitly wants to skip loop termination analysis
281 String value = an.getValue();
282 int maxIteration = 0;
284 maxIteration = Integer.parseInt(value);
286 skipLoopTerminate.put(md, new Integer(maxIteration));
297 private void writeLatticeDotFile(ClassDescriptor cd, SSJavaLattice<String> locOrder) {
299 String className = cd.getSymbol().replaceAll("[\\W_]", "");
301 Set<Pair<String, String>> pairSet = locOrder.getOrderingPairSet();
304 BufferedWriter bw = new BufferedWriter(new FileWriter(className + ".dot"));
306 bw.write("digraph " + className + " {\n");
308 for (Iterator iterator = pairSet.iterator(); iterator.hasNext();) {
309 // pair is in the form of <higher, lower>
310 Pair<String, String> pair = (Pair<String, String>) iterator.next();
312 String highLocId = pair.getFirst();
313 if (locOrder.isSharedLoc(highLocId)) {
314 highLocId = "\"" + highLocId + "*\"";
316 String lowLocId = pair.getSecond();
317 if (locOrder.isSharedLoc(lowLocId)) {
318 lowLocId = "\"" + lowLocId + "*\"";
320 bw.write(highLocId + " -> " + lowLocId + ";\n");
325 } catch (IOException e) {
331 private void parseMethodDefaultLatticeDefinition(ClassDescriptor cd, String value,
332 MethodLattice<String> locOrder) {
334 value = value.replaceAll(" ", ""); // remove all blank spaces
336 StringTokenizer tokenizer = new StringTokenizer(value, ",");
338 while (tokenizer.hasMoreTokens()) {
339 String orderElement = tokenizer.nextToken();
340 int idx = orderElement.indexOf("<");
341 if (idx > 0) {// relative order element
342 String lowerLoc = orderElement.substring(0, idx);
343 String higherLoc = orderElement.substring(idx + 1);
344 locOrder.put(higherLoc, lowerLoc);
345 if (locOrder.isIntroducingCycle(higherLoc)) {
346 throw new Error("Error: the order relation " + lowerLoc + " < " + higherLoc
347 + " introduces a cycle.");
349 } else if (orderElement.startsWith(THISLOC + "=")) {
350 String thisLoc = orderElement.substring(8);
351 locOrder.setThisLoc(thisLoc);
352 } else if (orderElement.startsWith(GLOBALLOC + "=")) {
353 String globalLoc = orderElement.substring(10);
354 locOrder.setGlobalLoc(globalLoc);
355 } else if (orderElement.startsWith(RETURNLOC + "=")) {
356 String returnLoc = orderElement.substring(10);
357 locOrder.setReturnLoc(returnLoc);
358 } else if (orderElement.endsWith("*")) {
359 // spin loc definition
360 locOrder.addSharedLoc(orderElement.substring(0, orderElement.length() - 1));
363 locOrder.put(orderElement);
368 if (locOrder.getThisLoc() != null && !locOrder.containsKey(locOrder.getThisLoc())) {
369 throw new Error("Variable 'this' location '" + locOrder.getThisLoc()
370 + "' is not defined in the local variable lattice at " + cd.getSourceFileName());
373 if (locOrder.getGlobalLoc() != null && !locOrder.containsKey(locOrder.getGlobalLoc())) {
374 throw new Error("Variable global location '" + locOrder.getGlobalLoc()
375 + "' is not defined in the local variable lattice at " + cd.getSourceFileName());
379 private void parseClassLatticeDefinition(ClassDescriptor cd, String value,
380 SSJavaLattice<String> locOrder) {
382 value = value.replaceAll(" ", ""); // remove all blank spaces
384 StringTokenizer tokenizer = new StringTokenizer(value, ",");
386 while (tokenizer.hasMoreTokens()) {
387 String orderElement = tokenizer.nextToken();
388 int idx = orderElement.indexOf("<");
390 if (idx > 0) {// relative order element
391 String lowerLoc = orderElement.substring(0, idx);
392 String higherLoc = orderElement.substring(idx + 1);
393 locOrder.put(higherLoc, lowerLoc);
394 if (locOrder.isIntroducingCycle(higherLoc)) {
395 throw new Error("Error: the order relation " + lowerLoc + " < " + higherLoc
396 + " introduces a cycle.");
398 } else if (orderElement.contains("*")) {
399 // spin loc definition
400 locOrder.addSharedLoc(orderElement.substring(0, orderElement.length() - 1));
403 locOrder.put(orderElement);
408 Set<String> spinLocSet = locOrder.getSharedLocSet();
409 for (Iterator iterator = spinLocSet.iterator(); iterator.hasNext();) {
410 String spinLoc = (String) iterator.next();
411 if (!locOrder.containsKey(spinLoc)) {
412 throw new Error("Spin location '" + spinLoc
413 + "' is not defined in the default local variable lattice at " + cd.getSourceFileName());
418 public Hashtable<ClassDescriptor, SSJavaLattice<String>> getCd2lattice() {
422 public Hashtable<ClassDescriptor, MethodLattice<String>> getCd2methodDefault() {
423 return cd2methodDefault;
426 public Hashtable<MethodDescriptor, MethodLattice<String>> getMd2lattice() {
430 public SSJavaLattice<String> getClassLattice(ClassDescriptor cd) {
431 return cd2lattice.get(cd);
434 public MethodLattice<String> getMethodDefaultLattice(ClassDescriptor cd) {
435 return cd2methodDefault.get(cd);
438 public MethodLattice<String> getMethodLattice(MethodDescriptor md) {
439 if (md2lattice.containsKey(md)) {
440 return md2lattice.get(md);
443 if (cd2methodDefault.containsKey(md.getClassDesc())) {
444 return cd2methodDefault.get(md.getClassDesc());
446 throw new Error("Method Lattice of " + md + " is not defined.");
452 public boolean needToCheckLinearType(MethodDescriptor md) {
453 return linearTypeCheckMethodSet.contains(md);
456 public boolean needTobeAnnotated(MethodDescriptor md) {
457 return annotationRequireSet.contains(md);
460 public boolean needToBeAnnoated(ClassDescriptor cd) {
461 return annotationRequireClassSet.contains(cd);
464 public void addAnnotationRequire(ClassDescriptor cd) {
465 annotationRequireClassSet.add(cd);
468 public void addAnnotationRequire(MethodDescriptor md) {
470 ClassDescriptor cd = md.getClassDesc();
471 // if a method requires to be annotated, class containg that method also
472 // requires to be annotated
473 if (!isSSJavaUtil(cd)) {
474 annotationRequireClassSet.add(cd);
475 annotationRequireSet.add(md);
479 public Set<MethodDescriptor> getAnnotationRequireSet() {
480 return annotationRequireSet;
483 public void doLoopTerminationCheck(LoopOptimize lo, FlatMethod fm) {
484 LoopTerminate lt = new LoopTerminate(this, state);
485 if (needTobeAnnotated(fm.getMethod())) {
486 lt.terminateAnalysis(fm, lo.getLoopInvariant(fm));
490 public CallGraph getCallGraph() {
494 public SSJavaLattice<String> getLattice(Descriptor d) {
496 if (d instanceof MethodDescriptor) {
497 return getMethodLattice((MethodDescriptor) d);
499 return getClassLattice((ClassDescriptor) d);
504 public boolean isSharedLocation(Location loc) {
505 SSJavaLattice<String> lattice = getLattice(loc.getDescriptor());
506 return lattice.getSharedLocSet().contains(loc.getLocIdentifier());
509 public void mapSharedLocation2Descriptor(Location loc, Descriptor d) {
510 Set<Descriptor> set = mapSharedLocation2DescriptorSet.get(loc);
512 set = new HashSet<Descriptor>();
513 mapSharedLocation2DescriptorSet.put(loc, set);
518 public BuildFlat getBuildFlat() {
522 public MethodDescriptor getMethodContainingSSJavaLoop() {
523 return methodContainingSSJavaLoop;
526 public void setMethodContainingSSJavaLoop(MethodDescriptor methodContainingSSJavaLoop) {
527 this.methodContainingSSJavaLoop = methodContainingSSJavaLoop;
530 public boolean isSSJavaUtil(ClassDescriptor cd) {
531 if (cd.getSymbol().equals("SSJAVA")) {
537 public void setFieldOnwership(MethodDescriptor md, FieldDescriptor field) {
539 Set<FieldDescriptor> fieldSet = mapMethodToOwnedFieldSet.get(md);
540 if (fieldSet == null) {
541 fieldSet = new HashSet<FieldDescriptor>();
542 mapMethodToOwnedFieldSet.put(md, fieldSet);
547 public boolean isOwnedByMethod(MethodDescriptor md, FieldDescriptor field) {
548 Set<FieldDescriptor> fieldSet = mapMethodToOwnedFieldSet.get(md);
549 if (fieldSet != null) {
550 return fieldSet.contains(field);
555 public FlatNode getSSJavaLoopEntrance() {
556 return ssjavaLoopEntrance;
559 public void setSSJavaLoopEntrance(FlatNode ssjavaLoopEntrance) {
560 this.ssjavaLoopEntrance = ssjavaLoopEntrance;