1 package Analysis.SSJava;
3 import java.util.ArrayList;
4 import java.util.HashSet;
5 import java.util.Hashtable;
6 import java.util.Iterator;
9 import java.util.StringTokenizer;
10 import java.util.Vector;
12 import Analysis.SSJava.FlowDownCheck.ComparisonResult;
13 import Analysis.SSJava.FlowDownCheck.CompositeLattice;
14 import IR.AnnotationDescriptor;
15 import IR.ClassDescriptor;
17 import IR.FieldDescriptor;
18 import IR.MethodDescriptor;
19 import IR.NameDescriptor;
22 import IR.SymbolTable;
23 import IR.TypeDescriptor;
24 import IR.VarDescriptor;
25 import IR.Tree.ArrayAccessNode;
26 import IR.Tree.AssignmentNode;
27 import IR.Tree.BlockExpressionNode;
28 import IR.Tree.BlockNode;
29 import IR.Tree.BlockStatementNode;
30 import IR.Tree.CastNode;
31 import IR.Tree.CreateObjectNode;
32 import IR.Tree.DeclarationNode;
33 import IR.Tree.ExpressionNode;
34 import IR.Tree.FieldAccessNode;
35 import IR.Tree.IfStatementNode;
37 import IR.Tree.LiteralNode;
38 import IR.Tree.LoopNode;
39 import IR.Tree.MethodInvokeNode;
40 import IR.Tree.NameNode;
41 import IR.Tree.OpNode;
42 import IR.Tree.ReturnNode;
43 import IR.Tree.SubBlockNode;
44 import IR.Tree.SwitchBlockNode;
45 import IR.Tree.SwitchStatementNode;
46 import IR.Tree.SynchronizedNode;
47 import IR.Tree.TertiaryNode;
48 import IR.Tree.TreeNode;
51 public class FlowDownCheck {
54 static SSJavaAnalysis ssjava;
58 // mapping from 'descriptor' to 'composite location'
59 Hashtable<Descriptor, CompositeLocation> d2loc;
61 Hashtable<MethodDescriptor, CompositeLocation> md2ReturnLoc;
62 Hashtable<MethodDescriptor, ReturnLocGenerator> md2ReturnLocGen;
64 // mapping from 'locID' to 'class descriptor'
65 Hashtable<String, ClassDescriptor> fieldLocName2cd;
67 public FlowDownCheck(SSJavaAnalysis ssjava, State state) {
70 this.toanalyze = new HashSet();
71 this.d2loc = new Hashtable<Descriptor, CompositeLocation>();
72 this.fieldLocName2cd = new Hashtable<String, ClassDescriptor>();
73 this.md2ReturnLoc = new Hashtable<MethodDescriptor, CompositeLocation>();
74 this.md2ReturnLocGen = new Hashtable<MethodDescriptor, ReturnLocGenerator>();
79 // construct mapping from the location name to the class descriptor
80 // assume that the location name is unique through the whole program
82 Set<ClassDescriptor> cdSet = ssjava.getCd2lattice().keySet();
83 for (Iterator iterator = cdSet.iterator(); iterator.hasNext();) {
84 ClassDescriptor cd = (ClassDescriptor) iterator.next();
85 SSJavaLattice<String> lattice = ssjava.getCd2lattice().get(cd);
86 Set<String> fieldLocNameSet = lattice.getKeySet();
88 for (Iterator iterator2 = fieldLocNameSet.iterator(); iterator2.hasNext();) {
89 String fieldLocName = (String) iterator2.next();
90 fieldLocName2cd.put(fieldLocName, cd);
97 public void flowDownCheck() {
98 SymbolTable classtable = state.getClassSymbolTable();
100 // phase 1 : checking declaration node and creating mapping of 'type
101 // desciptor' & 'location'
102 toanalyze.addAll(classtable.getValueSet());
103 toanalyze.addAll(state.getTaskSymbolTable().getValueSet());
105 while (!toanalyze.isEmpty()) {
106 Object obj = toanalyze.iterator().next();
107 ClassDescriptor cd = (ClassDescriptor) obj;
108 toanalyze.remove(cd);
110 if (ssjava.needToBeAnnoated(cd)) {
112 ClassDescriptor superDesc = cd.getSuperDesc();
114 if (superDesc != null && (!superDesc.getSymbol().equals("Object"))) {
115 checkOrderingInheritance(superDesc, cd);
118 checkDeclarationInClass(cd);
119 for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
120 MethodDescriptor md = (MethodDescriptor) method_it.next();
121 if (ssjava.needTobeAnnotated(md)) {
122 checkDeclarationInMethodBody(cd, md);
129 // phase2 : checking assignments
130 toanalyze.addAll(classtable.getValueSet());
131 toanalyze.addAll(state.getTaskSymbolTable().getValueSet());
132 while (!toanalyze.isEmpty()) {
133 Object obj = toanalyze.iterator().next();
134 ClassDescriptor cd = (ClassDescriptor) obj;
135 toanalyze.remove(cd);
138 for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
139 MethodDescriptor md = (MethodDescriptor) method_it.next();
140 if (ssjava.needTobeAnnotated(md)) {
141 checkMethodBody(cd, md);
148 private void checkOrderingInheritance(ClassDescriptor superCd, ClassDescriptor cd) {
149 // here, we're going to check that sub class keeps same relative orderings
150 // in respect to super class
152 SSJavaLattice<String> superLattice = ssjava.getClassLattice(superCd);
153 SSJavaLattice<String> subLattice = ssjava.getClassLattice(cd);
155 if (superLattice != null) {
156 // if super class doesn't define lattice, then we don't need to check its
158 if (subLattice == null) {
159 throw new Error("If a parent class '" + superCd
160 + "' has a ordering lattice, its subclass '" + cd + "' should have one.");
163 Set<Pair<String, String>> superPairSet = superLattice.getOrderingPairSet();
164 Set<Pair<String, String>> subPairSet = subLattice.getOrderingPairSet();
166 for (Iterator iterator = superPairSet.iterator(); iterator.hasNext();) {
167 Pair<String, String> pair = (Pair<String, String>) iterator.next();
169 if (!subPairSet.contains(pair)) {
170 throw new Error("Subclass '" + cd + "' does not have the relative ordering '"
171 + pair.getSecond() + " < " + pair.getFirst()
172 + "' that is defined by its superclass '" + superCd + "'.");
177 MethodLattice<String> superMethodDefaultLattice = ssjava.getMethodDefaultLattice(superCd);
178 MethodLattice<String> subMethodDefaultLattice = ssjava.getMethodDefaultLattice(cd);
180 if (superMethodDefaultLattice != null) {
181 if (subMethodDefaultLattice == null) {
182 throw new Error("When a parent class '" + superCd
183 + "' defines a default method lattice, its subclass '" + cd + "' should define one.");
186 Set<Pair<String, String>> superPairSet = superMethodDefaultLattice.getOrderingPairSet();
187 Set<Pair<String, String>> subPairSet = subMethodDefaultLattice.getOrderingPairSet();
189 for (Iterator iterator = superPairSet.iterator(); iterator.hasNext();) {
190 Pair<String, String> pair = (Pair<String, String>) iterator.next();
192 if (!subPairSet.contains(pair)) {
193 throw new Error("Subclass '" + cd + "' does not have the relative ordering '"
194 + pair.getSecond() + " < " + pair.getFirst()
195 + "' that is defined by its superclass '" + superCd
196 + "' in the method default lattice.");
204 public Hashtable getMap() {
208 private void checkDeclarationInMethodBody(ClassDescriptor cd, MethodDescriptor md) {
209 BlockNode bn = state.getMethodBody(md);
211 if (ssjava.needTobeAnnotated(md)) {
213 // parsing returnloc annotation
214 Vector<AnnotationDescriptor> methodAnnotations = md.getModifiers().getAnnotations();
215 if (methodAnnotations != null) {
216 for (int i = 0; i < methodAnnotations.size(); i++) {
217 AnnotationDescriptor an = methodAnnotations.elementAt(i);
218 if (an.getMarker().equals(ssjava.RETURNLOC)) {
219 // developer explicitly defines method lattice
220 String returnLocDeclaration = an.getValue();
221 CompositeLocation returnLocComp =
222 parseLocationDeclaration(md, null, returnLocDeclaration);
223 md2ReturnLoc.put(md, returnLocComp);
226 if (!md.getReturnType().isVoid() && !md2ReturnLoc.containsKey(md)) {
227 throw new Error("Return location is not specified for the method " + md + " at "
228 + cd.getSourceFileName());
232 List<CompositeLocation> paramList = new ArrayList<CompositeLocation>();
234 boolean hasReturnValue = (!md.getReturnType().isVoid());
235 if (hasReturnValue) {
236 MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
237 String thisLocId = methodLattice.getThisLoc();
238 if (thisLocId == null) {
239 throw new Error("Method '" + md + "' does not have the definition of 'this' location at "
240 + md.getClassDesc().getSourceFileName());
242 CompositeLocation thisLoc = new CompositeLocation(new Location(md, thisLocId));
243 paramList.add(thisLoc);
246 for (int i = 0; i < md.numParameters(); i++) {
247 // process annotations on method parameters
248 VarDescriptor vd = (VarDescriptor) md.getParameter(i);
249 assignLocationOfVarDescriptor(vd, md, md.getParameterTable(), bn);
250 if (hasReturnValue) {
251 paramList.add(d2loc.get(vd));
255 if (hasReturnValue) {
256 md2ReturnLocGen.put(md, new ReturnLocGenerator(md2ReturnLoc.get(md), paramList,
257 generateErrorMessage(cd, null)));
259 checkDeclarationInBlockNode(md, md.getParameterTable(), bn);
264 private void checkDeclarationInBlockNode(MethodDescriptor md, SymbolTable nametable, BlockNode bn) {
265 bn.getVarTable().setParent(nametable);
266 for (int i = 0; i < bn.size(); i++) {
267 BlockStatementNode bsn = bn.get(i);
268 checkDeclarationInBlockStatementNode(md, bn.getVarTable(), bsn);
272 private void checkDeclarationInBlockStatementNode(MethodDescriptor md, SymbolTable nametable,
273 BlockStatementNode bsn) {
275 switch (bsn.kind()) {
276 case Kind.SubBlockNode:
277 checkDeclarationInSubBlockNode(md, nametable, (SubBlockNode) bsn);
280 case Kind.DeclarationNode:
281 checkDeclarationNode(md, nametable, (DeclarationNode) bsn);
285 checkDeclarationInLoopNode(md, nametable, (LoopNode) bsn);
288 case Kind.IfStatementNode:
289 checkDeclarationInIfStatementNode(md, nametable, (IfStatementNode) bsn);
292 case Kind.SwitchStatementNode:
293 checkDeclarationInSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn);
296 case Kind.SynchronizedNode:
297 checkDeclarationInSynchronizedNode(md, nametable, (SynchronizedNode) bsn);
303 private void checkDeclarationInSynchronizedNode(MethodDescriptor md, SymbolTable nametable,
304 SynchronizedNode sbn) {
305 checkDeclarationInBlockNode(md, nametable, sbn.getBlockNode());
308 private void checkDeclarationInSwitchStatementNode(MethodDescriptor md, SymbolTable nametable,
309 SwitchStatementNode ssn) {
310 BlockNode sbn = ssn.getSwitchBody();
311 for (int i = 0; i < sbn.size(); i++) {
312 SwitchBlockNode node = (SwitchBlockNode) sbn.get(i);
313 checkDeclarationInBlockNode(md, nametable, node.getSwitchBlockStatement());
317 private void checkDeclarationInIfStatementNode(MethodDescriptor md, SymbolTable nametable,
318 IfStatementNode isn) {
319 checkDeclarationInBlockNode(md, nametable, isn.getTrueBlock());
320 if (isn.getFalseBlock() != null)
321 checkDeclarationInBlockNode(md, nametable, isn.getFalseBlock());
324 private void checkDeclarationInLoopNode(MethodDescriptor md, SymbolTable nametable, LoopNode ln) {
326 if (ln.getType() == LoopNode.FORLOOP) {
327 // check for loop case
328 ClassDescriptor cd = md.getClassDesc();
329 BlockNode bn = ln.getInitializer();
330 for (int i = 0; i < bn.size(); i++) {
331 BlockStatementNode bsn = bn.get(i);
332 checkDeclarationInBlockStatementNode(md, nametable, bsn);
337 checkDeclarationInBlockNode(md, nametable, ln.getBody());
340 private void checkMethodBody(ClassDescriptor cd, MethodDescriptor md) {
341 BlockNode bn = state.getMethodBody(md);
342 checkLocationFromBlockNode(md, md.getParameterTable(), bn);
345 private String generateErrorMessage(ClassDescriptor cd, TreeNode tn) {
347 return cd.getSourceFileName() + "::" + tn.getNumLine();
349 return cd.getSourceFileName();
354 private CompositeLocation checkLocationFromBlockNode(MethodDescriptor md, SymbolTable nametable,
357 bn.getVarTable().setParent(nametable);
358 // it will return the lowest location in the block node
359 CompositeLocation lowestLoc = null;
361 for (int i = 0; i < bn.size(); i++) {
362 BlockStatementNode bsn = bn.get(i);
363 CompositeLocation bLoc = checkLocationFromBlockStatementNode(md, bn.getVarTable(), bsn);
364 if (!bLoc.isEmpty()) {
365 if (lowestLoc == null) {
368 if (CompositeLattice.isGreaterThan(lowestLoc, bLoc,
369 generateErrorMessage(md.getClassDesc(), bn))) {
377 if (lowestLoc == null) {
378 lowestLoc = new CompositeLocation(Location.createBottomLocation(md));
384 private CompositeLocation checkLocationFromBlockStatementNode(MethodDescriptor md,
385 SymbolTable nametable, BlockStatementNode bsn) {
387 CompositeLocation compLoc = null;
388 switch (bsn.kind()) {
389 case Kind.BlockExpressionNode:
390 compLoc = checkLocationFromBlockExpressionNode(md, nametable, (BlockExpressionNode) bsn);
393 case Kind.DeclarationNode:
394 compLoc = checkLocationFromDeclarationNode(md, nametable, (DeclarationNode) bsn);
397 case Kind.IfStatementNode:
398 compLoc = checkLocationFromIfStatementNode(md, nametable, (IfStatementNode) bsn);
402 compLoc = checkLocationFromLoopNode(md, nametable, (LoopNode) bsn);
405 case Kind.ReturnNode:
406 compLoc = checkLocationFromReturnNode(md, nametable, (ReturnNode) bsn);
409 case Kind.SubBlockNode:
410 compLoc = checkLocationFromSubBlockNode(md, nametable, (SubBlockNode) bsn);
413 case Kind.ContinueBreakNode:
414 compLoc = new CompositeLocation();
417 case Kind.SwitchStatementNode:
418 compLoc = checkLocationFromSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn);
424 private CompositeLocation checkLocationFromSwitchStatementNode(MethodDescriptor md,
425 SymbolTable nametable, SwitchStatementNode ssn) {
427 ClassDescriptor cd = md.getClassDesc();
428 CompositeLocation condLoc =
429 checkLocationFromExpressionNode(md, nametable, ssn.getCondition(), new CompositeLocation());
430 BlockNode sbn = ssn.getSwitchBody();
432 Set<CompositeLocation> blockLocSet = new HashSet<CompositeLocation>();
433 for (int i = 0; i < sbn.size(); i++) {
434 CompositeLocation blockLoc =
435 checkLocationFromSwitchBlockNode(md, nametable, (SwitchBlockNode) sbn.get(i));
436 if (!CompositeLattice.isGreaterThan(condLoc, blockLoc,
437 generateErrorMessage(cd, ssn.getCondition()))) {
439 "The location of the switch-condition statement is lower than the conditional body at "
440 + cd.getSourceFileName() + ":" + ssn.getCondition().getNumLine());
443 blockLocSet.add(blockLoc);
445 return CompositeLattice.calculateGLB(blockLocSet);
448 private CompositeLocation checkLocationFromSwitchBlockNode(MethodDescriptor md,
449 SymbolTable nametable, SwitchBlockNode sbn) {
451 CompositeLocation blockLoc =
452 checkLocationFromBlockNode(md, nametable, sbn.getSwitchBlockStatement());
458 private CompositeLocation checkLocationFromReturnNode(MethodDescriptor md, SymbolTable nametable,
461 ExpressionNode returnExp = rn.getReturnExpression();
463 CompositeLocation returnValueLoc;
464 if (returnExp != null) {
466 checkLocationFromExpressionNode(md, nametable, returnExp, new CompositeLocation());
468 // check if return value is equal or higher than RETRUNLOC of method
469 // declaration annotation
470 CompositeLocation declaredReturnLoc = md2ReturnLoc.get(md);
473 CompositeLattice.compare(returnValueLoc, declaredReturnLoc,
474 generateErrorMessage(md.getClassDesc(), rn));
476 if (compareResult == ComparisonResult.LESS || compareResult == ComparisonResult.INCOMPARABLE) {
478 "Return value location is not equal or higher than the declaraed return location at "
479 + md.getClassDesc().getSourceFileName() + "::" + rn.getNumLine());
483 return new CompositeLocation();
486 private boolean hasOnlyLiteralValue(ExpressionNode en) {
487 if (en.kind() == Kind.LiteralNode) {
494 private CompositeLocation checkLocationFromLoopNode(MethodDescriptor md, SymbolTable nametable,
497 ClassDescriptor cd = md.getClassDesc();
498 if (ln.getType() == LoopNode.WHILELOOP || ln.getType() == LoopNode.DOWHILELOOP) {
500 CompositeLocation condLoc =
501 checkLocationFromExpressionNode(md, nametable, ln.getCondition(), new CompositeLocation());
502 addLocationType(ln.getCondition().getType(), (condLoc));
504 CompositeLocation bodyLoc = checkLocationFromBlockNode(md, nametable, ln.getBody());
506 if (!CompositeLattice.isGreaterThan(condLoc, bodyLoc, generateErrorMessage(cd, ln))) {
507 // loop condition should be higher than loop body
509 "The location of the while-condition statement is lower than the loop body at "
510 + cd.getSourceFileName() + ":" + ln.getCondition().getNumLine());
516 // check for loop case
517 BlockNode bn = ln.getInitializer();
518 bn.getVarTable().setParent(nametable);
520 // calculate glb location of condition and update statements
521 CompositeLocation condLoc =
522 checkLocationFromExpressionNode(md, bn.getVarTable(), ln.getCondition(),
523 new CompositeLocation());
524 addLocationType(ln.getCondition().getType(), condLoc);
526 CompositeLocation updateLoc =
527 checkLocationFromBlockNode(md, bn.getVarTable(), ln.getUpdate());
529 Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
530 glbInputSet.add(condLoc);
531 // glbInputSet.add(updateLoc);
533 CompositeLocation glbLocOfForLoopCond = CompositeLattice.calculateGLB(glbInputSet);
535 // check location of 'forloop' body
536 CompositeLocation blockLoc = checkLocationFromBlockNode(md, bn.getVarTable(), ln.getBody());
538 // compute glb of body including loop body and update statement
541 if (blockLoc == null) {
542 // when there is no statement in the loop body
544 if (updateLoc == null) {
545 // also there is no update statement in the loop body
546 return glbLocOfForLoopCond;
548 glbInputSet.add(updateLoc);
551 glbInputSet.add(blockLoc);
552 glbInputSet.add(updateLoc);
555 CompositeLocation loopBodyLoc = CompositeLattice.calculateGLB(glbInputSet);
557 if (!CompositeLattice.isGreaterThan(glbLocOfForLoopCond, loopBodyLoc,
558 generateErrorMessage(cd, ln))) {
560 "The location of the for-condition statement is lower than the for-loop body at "
561 + cd.getSourceFileName() + ":" + ln.getCondition().getNumLine());
568 private CompositeLocation checkLocationFromSubBlockNode(MethodDescriptor md,
569 SymbolTable nametable, SubBlockNode sbn) {
570 CompositeLocation compLoc = checkLocationFromBlockNode(md, nametable, sbn.getBlockNode());
574 private CompositeLocation checkLocationFromIfStatementNode(MethodDescriptor md,
575 SymbolTable nametable, IfStatementNode isn) {
577 ClassDescriptor localCD = md.getClassDesc();
578 Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
580 CompositeLocation condLoc =
581 checkLocationFromExpressionNode(md, nametable, isn.getCondition(), new CompositeLocation());
583 addLocationType(isn.getCondition().getType(), condLoc);
584 glbInputSet.add(condLoc);
586 CompositeLocation locTrueBlock = checkLocationFromBlockNode(md, nametable, isn.getTrueBlock());
587 if (locTrueBlock != null) {
588 glbInputSet.add(locTrueBlock);
589 // here, the location of conditional block should be higher than the
590 // location of true/false blocks
591 if (locTrueBlock != null
592 && !CompositeLattice.isGreaterThan(condLoc, locTrueBlock,
593 generateErrorMessage(localCD, isn.getCondition()))) {
596 "The location of the if-condition statement is lower than the conditional block at "
597 + localCD.getSourceFileName() + ":" + isn.getCondition().getNumLine());
601 if (isn.getFalseBlock() != null) {
602 CompositeLocation locFalseBlock =
603 checkLocationFromBlockNode(md, nametable, isn.getFalseBlock());
605 if (locFalseBlock != null) {
606 glbInputSet.add(locFalseBlock);
608 if (!CompositeLattice.isGreaterThan(condLoc, locFalseBlock,
609 generateErrorMessage(localCD, isn.getCondition()))) {
612 "The location of the if-condition statement is lower than the conditional block at "
613 + localCD.getSourceFileName() + ":" + isn.getCondition().getNumLine());
619 // return GLB location of condition, true, and false block
620 CompositeLocation glbLoc = CompositeLattice.calculateGLB(glbInputSet);
625 private CompositeLocation checkLocationFromDeclarationNode(MethodDescriptor md,
626 SymbolTable nametable, DeclarationNode dn) {
628 VarDescriptor vd = dn.getVarDescriptor();
630 CompositeLocation destLoc = d2loc.get(vd);
632 if (dn.getExpression() != null) {
633 CompositeLocation expressionLoc =
634 checkLocationFromExpressionNode(md, nametable, dn.getExpression(),
635 new CompositeLocation());
636 // addTypeLocation(dn.getExpression().getType(), expressionLoc);
638 if (expressionLoc != null) {
639 // checking location order
640 if (!CompositeLattice.isGreaterThan(expressionLoc, destLoc,
641 generateErrorMessage(md.getClassDesc(), dn))) {
642 throw new Error("The value flow from " + expressionLoc + " to " + destLoc
643 + " does not respect location hierarchy on the assignment " + dn.printNode(0)
644 + " at " + md.getClassDesc().getSourceFileName() + "::" + dn.getNumLine());
647 return expressionLoc;
651 return new CompositeLocation();
657 private void checkDeclarationInSubBlockNode(MethodDescriptor md, SymbolTable nametable,
659 checkDeclarationInBlockNode(md, nametable.getParent(), sbn.getBlockNode());
662 private CompositeLocation checkLocationFromBlockExpressionNode(MethodDescriptor md,
663 SymbolTable nametable, BlockExpressionNode ben) {
664 CompositeLocation compLoc =
665 checkLocationFromExpressionNode(md, nametable, ben.getExpression(), null);
666 // addTypeLocation(ben.getExpression().getType(), compLoc);
670 private CompositeLocation checkLocationFromExpressionNode(MethodDescriptor md,
671 SymbolTable nametable, ExpressionNode en, CompositeLocation loc) {
673 CompositeLocation compLoc = null;
676 case Kind.AssignmentNode:
677 compLoc = checkLocationFromAssignmentNode(md, nametable, (AssignmentNode) en, loc);
680 case Kind.FieldAccessNode:
681 compLoc = checkLocationFromFieldAccessNode(md, nametable, (FieldAccessNode) en, loc);
685 compLoc = checkLocationFromNameNode(md, nametable, (NameNode) en, loc);
689 compLoc = checkLocationFromOpNode(md, nametable, (OpNode) en);
692 case Kind.CreateObjectNode:
693 compLoc = checkLocationFromCreateObjectNode(md, nametable, (CreateObjectNode) en);
696 case Kind.ArrayAccessNode:
697 compLoc = checkLocationFromArrayAccessNode(md, nametable, (ArrayAccessNode) en);
700 case Kind.LiteralNode:
701 compLoc = checkLocationFromLiteralNode(md, nametable, (LiteralNode) en, loc);
704 case Kind.MethodInvokeNode:
705 compLoc = checkLocationFromMethodInvokeNode(md, nametable, (MethodInvokeNode) en, loc);
708 case Kind.TertiaryNode:
709 compLoc = checkLocationFromTertiaryNode(md, nametable, (TertiaryNode) en);
713 compLoc = checkLocationFromCastNode(md, nametable, (CastNode) en);
716 // case Kind.InstanceOfNode:
717 // checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
720 // case Kind.ArrayInitializerNode:
721 // checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en,
725 // case Kind.ClassTypeNode:
726 // checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
729 // case Kind.OffsetNode:
730 // checkOffsetNode(md, nametable, (OffsetNode)en, td);
737 // addTypeLocation(en.getType(), compLoc);
742 private CompositeLocation checkLocationFromCastNode(MethodDescriptor md, SymbolTable nametable,
745 ExpressionNode en = cn.getExpression();
746 return checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation());
750 private CompositeLocation checkLocationFromTertiaryNode(MethodDescriptor md,
751 SymbolTable nametable, TertiaryNode tn) {
752 ClassDescriptor cd = md.getClassDesc();
754 CompositeLocation condLoc =
755 checkLocationFromExpressionNode(md, nametable, tn.getCond(), new CompositeLocation());
756 addLocationType(tn.getCond().getType(), condLoc);
757 CompositeLocation trueLoc =
758 checkLocationFromExpressionNode(md, nametable, tn.getTrueExpr(), new CompositeLocation());
759 addLocationType(tn.getTrueExpr().getType(), trueLoc);
760 CompositeLocation falseLoc =
761 checkLocationFromExpressionNode(md, nametable, tn.getFalseExpr(), new CompositeLocation());
762 addLocationType(tn.getFalseExpr().getType(), falseLoc);
764 // locations from true/false branches can be TOP when there are only literal
766 // in this case, we don't need to check flow down rule!
768 // check if condLoc is higher than trueLoc & falseLoc
769 if (!trueLoc.get(0).isTop()
770 && !CompositeLattice.isGreaterThan(condLoc, trueLoc, generateErrorMessage(cd, tn))) {
772 "The location of the condition expression is lower than the true expression at "
773 + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
776 if (!falseLoc.get(0).isTop()
777 && !CompositeLattice.isGreaterThan(condLoc, falseLoc,
778 generateErrorMessage(cd, tn.getCond()))) {
780 "The location of the condition expression is lower than the true expression at "
781 + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
784 // then, return glb of trueLoc & falseLoc
785 Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
786 glbInputSet.add(trueLoc);
787 glbInputSet.add(falseLoc);
789 return CompositeLattice.calculateGLB(glbInputSet);
792 private CompositeLocation checkLocationFromMethodInvokeNode(MethodDescriptor md,
793 SymbolTable nametable, MethodInvokeNode min, CompositeLocation loc) {
795 checkCalleeConstraints(md, nametable, min);
797 CompositeLocation baseLocation = null;
798 if (min.getExpression() != null) {
800 checkLocationFromExpressionNode(md, nametable, min.getExpression(),
801 new CompositeLocation());
803 String thisLocId = ssjava.getMethodLattice(md).getThisLoc();
804 baseLocation = new CompositeLocation(new Location(md, thisLocId));
807 if (!min.getMethod().getReturnType().isVoid()) {
808 // If method has a return value, compute the highest possible return
809 // location in the caller's perspective
810 CompositeLocation ceilingLoc =
811 computeCeilingLocationForCaller(md, nametable, min, baseLocation);
815 return new CompositeLocation();
819 private CompositeLocation computeCeilingLocationForCaller(MethodDescriptor md,
820 SymbolTable nametable, MethodInvokeNode min, CompositeLocation baseLocation) {
821 List<CompositeLocation> argList = new ArrayList<CompositeLocation>();
823 // by default, method has a THIS parameter
824 argList.add(baseLocation);
826 for (int i = 0; i < min.numArgs(); i++) {
827 ExpressionNode en = min.getArg(i);
828 CompositeLocation callerArg =
829 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation());
830 argList.add(callerArg);
833 System.out.println("\n## computeReturnLocation=" + min.getMethod() + " argList=" + argList);
834 CompositeLocation compLoc = md2ReturnLocGen.get(min.getMethod()).computeReturnLocation(argList);
835 DeltaLocation delta = new DeltaLocation(compLoc, 1);
836 System.out.println("##computeReturnLocation=" + delta);
842 private void checkCalleeConstraints(MethodDescriptor md, SymbolTable nametable,
843 MethodInvokeNode min) {
845 if (min.numArgs() > 1) {
846 // caller needs to guarantee that it passes arguments in regarding to
847 // callee's hierarchy
848 for (int i = 0; i < min.numArgs(); i++) {
849 ExpressionNode en = min.getArg(i);
850 CompositeLocation callerArg1 =
851 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation());
853 VarDescriptor calleevd = (VarDescriptor) min.getMethod().getParameter(i);
854 CompositeLocation calleeLoc1 = d2loc.get(calleevd);
856 if (!callerArg1.get(0).isTop()) {
857 // here, check if ordering relations among caller's args respect
858 // ordering relations in-between callee's args
859 for (int currentIdx = 0; currentIdx < min.numArgs(); currentIdx++) {
860 if (currentIdx != i) { // skip itself
861 ExpressionNode argExp = min.getArg(currentIdx);
863 CompositeLocation callerArg2 =
864 checkLocationFromExpressionNode(md, nametable, argExp, new CompositeLocation());
866 VarDescriptor calleevd2 = (VarDescriptor) min.getMethod().getParameter(currentIdx);
867 CompositeLocation calleeLoc2 = d2loc.get(calleevd2);
870 CompositeLattice.compare(callerArg1, callerArg2,
871 generateErrorMessage(md.getClassDesc(), min));
873 CompositeLattice.compare(calleeLoc1, calleeLoc2,
874 generateErrorMessage(md.getClassDesc(), min));
876 if (calleeResult == ComparisonResult.GREATER
877 && callerResult != ComparisonResult.GREATER) {
878 // If calleeLoc1 is higher than calleeLoc2
879 // then, caller should have same ordering relation in-bet
880 // callerLoc1 & callerLoc2
882 throw new Error("Caller doesn't respect ordering relations among method arguments:"
883 + md.getClassDesc().getSourceFileName() + ":" + min.getNumLine());
896 private CompositeLocation checkLocationFromArrayAccessNode(MethodDescriptor md,
897 SymbolTable nametable, ArrayAccessNode aan) {
899 // return glb location of array itself and index
901 ClassDescriptor cd = md.getClassDesc();
903 Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
905 CompositeLocation arrayLoc =
906 checkLocationFromExpressionNode(md, nametable, aan.getExpression(), new CompositeLocation());
907 // addTypeLocation(aan.getExpression().getType(), arrayLoc);
908 glbInputSet.add(arrayLoc);
909 CompositeLocation indexLoc =
910 checkLocationFromExpressionNode(md, nametable, aan.getIndex(), new CompositeLocation());
911 glbInputSet.add(indexLoc);
912 // addTypeLocation(aan.getIndex().getType(), indexLoc);
914 CompositeLocation glbLoc = CompositeLattice.calculateGLB(glbInputSet);
918 private CompositeLocation checkLocationFromCreateObjectNode(MethodDescriptor md,
919 SymbolTable nametable, CreateObjectNode con) {
921 ClassDescriptor cd = md.getClassDesc();
923 CompositeLocation compLoc = new CompositeLocation();
924 compLoc.addLocation(Location.createTopLocation(md));
929 private CompositeLocation checkLocationFromOpNode(MethodDescriptor md, SymbolTable nametable,
932 ClassDescriptor cd = md.getClassDesc();
933 CompositeLocation leftLoc = new CompositeLocation();
934 leftLoc = checkLocationFromExpressionNode(md, nametable, on.getLeft(), leftLoc);
935 // addTypeLocation(on.getLeft().getType(), leftLoc);
937 CompositeLocation rightLoc = new CompositeLocation();
938 if (on.getRight() != null) {
939 rightLoc = checkLocationFromExpressionNode(md, nametable, on.getRight(), rightLoc);
940 // addTypeLocation(on.getRight().getType(), rightLoc);
943 System.out.println("checking op node=" + on.printNode(0)
944 + generateErrorMessage(md.getClassDesc(), on));
945 System.out.println("# op node=" + on.printNode(0));
946 System.out.println("left loc=" + leftLoc + " from " + on.getLeft().getClass());
947 if (on.getRight() != null) {
948 System.out.println("right loc=" + rightLoc + " from " + on.getRight().kind());
951 Operation op = on.getOp();
953 switch (op.getOp()) {
955 case Operation.UNARYPLUS:
956 case Operation.UNARYMINUS:
957 case Operation.LOGIC_NOT:
961 case Operation.LOGIC_OR:
962 case Operation.LOGIC_AND:
964 case Operation.BIT_OR:
965 case Operation.BIT_XOR:
966 case Operation.BIT_AND:
967 case Operation.ISAVAILABLE:
968 case Operation.EQUAL:
969 case Operation.NOTEQUAL:
979 case Operation.LEFTSHIFT:
980 case Operation.RIGHTSHIFT:
981 case Operation.URIGHTSHIFT:
983 Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
984 inputSet.add(leftLoc);
985 inputSet.add(rightLoc);
986 CompositeLocation glbCompLoc = CompositeLattice.calculateGLB(inputSet);
990 throw new Error(op.toString());
995 private CompositeLocation checkLocationFromLiteralNode(MethodDescriptor md,
996 SymbolTable nametable, LiteralNode en, CompositeLocation loc) {
998 // literal value has the top location so that value can be flowed into any
1000 Location literalLoc = Location.createTopLocation(md);
1001 loc.addLocation(literalLoc);
1006 private CompositeLocation checkLocationFromNameNode(MethodDescriptor md, SymbolTable nametable,
1007 NameNode nn, CompositeLocation loc) {
1009 NameDescriptor nd = nn.getName();
1010 if (nd.getBase() != null) {
1011 loc = checkLocationFromExpressionNode(md, nametable, nn.getExpression(), loc);
1013 String varname = nd.toString();
1014 if (varname.equals("this")) {
1016 MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
1017 String thisLocId = methodLattice.getThisLoc();
1018 if (thisLocId == null) {
1019 throw new Error("The location for 'this' is not defined at "
1020 + md.getClassDesc().getSourceFileName() + "::" + nn.getNumLine());
1022 Location locElement = new Location(md, thisLocId);
1023 loc.addLocation(locElement);
1027 Descriptor d = (Descriptor) nametable.get(varname);
1029 // CompositeLocation localLoc = null;
1030 if (d instanceof VarDescriptor) {
1031 VarDescriptor vd = (VarDescriptor) d;
1032 // localLoc = d2loc.get(vd);
1033 // the type of var descriptor has a composite location!
1034 loc = ((CompositeLocation) vd.getType().getExtension()).clone();
1035 } else if (d instanceof FieldDescriptor) {
1036 // the type of field descriptor has a location!
1037 FieldDescriptor fd = (FieldDescriptor) d;
1038 if (fd.isStatic()) {
1040 // if it is 'static final', the location has TOP since no one can
1042 loc.addLocation(Location.createTopLocation(md));
1045 // if 'static', the location has pre-assigned global loc
1046 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1047 String globalLocId = localLattice.getGlobalLoc();
1048 if (globalLocId == null) {
1049 throw new Error("Global location element is not defined in the method " + md);
1051 Location globalLoc = new Location(md, globalLocId);
1053 loc.addLocation(globalLoc);
1056 // the location of field access starts from this, followed by field
1058 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1059 Location thisLoc = new Location(md, localLattice.getThisLoc());
1060 loc.addLocation(thisLoc);
1063 Location fieldLoc = (Location) fd.getType().getExtension();
1064 loc.addLocation(fieldLoc);
1065 } else if (d == null) {
1067 // check if the var is a static field of the class
1068 FieldDescriptor fd = nn.getField();
1069 ClassDescriptor cd = nn.getClassDesc();
1071 if (fd != null && cd != null) {
1073 if (fd.isStatic() && fd.isFinal()) {
1074 loc.addLocation(Location.createTopLocation(md));
1077 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1078 Location fieldLoc = new Location(md, localLattice.getThisLoc());
1079 loc.addLocation(fieldLoc);
1088 private CompositeLocation checkLocationFromFieldAccessNode(MethodDescriptor md,
1089 SymbolTable nametable, FieldAccessNode fan, CompositeLocation loc) {
1091 ExpressionNode left = fan.getExpression();
1092 TypeDescriptor ltd = left.getType();
1094 FieldDescriptor fd = fan.getField();
1096 String varName = null;
1097 if (left.kind() == Kind.NameNode) {
1098 NameDescriptor nd = ((NameNode) left).getName();
1099 varName = nd.toString();
1102 if (ltd.isClassNameRef() || (varName != null && varName.equals("this"))) {
1103 // using a class name directly or access using this
1104 if (fd.isStatic() && fd.isFinal()) {
1105 loc.addLocation(Location.createTopLocation(md));
1110 loc = checkLocationFromExpressionNode(md, nametable, left, loc);
1111 if (!left.getType().isPrimitive()) {
1112 Location fieldLoc = getFieldLocation(fd);
1113 loc.addLocation(fieldLoc);
1119 private Location getFieldLocation(FieldDescriptor fd) {
1121 Location fieldLoc = (Location) fd.getType().getExtension();
1123 // handle the case that method annotation checking skips checking field
1125 if (fieldLoc == null) {
1126 fieldLoc = checkFieldDeclaration(fd.getClassDescriptor(), fd);
1133 private CompositeLocation checkLocationFromAssignmentNode(MethodDescriptor md,
1134 SymbolTable nametable, AssignmentNode an, CompositeLocation loc) {
1136 ClassDescriptor cd = md.getClassDesc();
1138 boolean postinc = true;
1139 if (an.getOperation().getBaseOp() == null
1140 || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
1141 .getBaseOp().getOp() != Operation.POSTDEC))
1144 CompositeLocation destLocation =
1145 checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation());
1147 CompositeLocation srcLocation = new CompositeLocation();
1150 if (hasOnlyLiteralValue(an.getSrc())) {
1151 // if source is literal value, src location is TOP. so do not need to
1153 return destLocation;
1155 srcLocation = new CompositeLocation();
1156 srcLocation = checkLocationFromExpressionNode(md, nametable, an.getSrc(), srcLocation);
1158 System.out.println("\n an= " + an.printNode(0) + " an.getSrc()=" +
1159 an.getSrc().getClass()
1160 + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1161 System.out.println("srcLocation=" + srcLocation);
1162 System.out.println("dstLocation=" + destLocation);
1164 if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1165 throw new Error("The value flow from " + srcLocation + " to " + destLocation
1166 + " does not respect location hierarchy on the assignment " + an.printNode(0) + " at "
1167 + cd.getSourceFileName() + "::" + an.getNumLine());
1171 srcLocation = checkLocationFromExpressionNode(md, nametable, an.getDest(), srcLocation);
1173 if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1174 throw new Error("Location " + destLocation
1175 + " is not allowed to have the value flow that moves within the same location at "
1176 + cd.getSourceFileName() + "::" + an.getNumLine());
1181 return destLocation;
1184 private void assignLocationOfVarDescriptor(VarDescriptor vd, MethodDescriptor md,
1185 SymbolTable nametable, TreeNode n) {
1187 ClassDescriptor cd = md.getClassDesc();
1188 Vector<AnnotationDescriptor> annotationVec = vd.getType().getAnnotationMarkers();
1190 // currently enforce every variable to have corresponding location
1191 if (annotationVec.size() == 0) {
1192 throw new Error("Location is not assigned to variable " + vd.getSymbol() + " in the method "
1193 + md.getSymbol() + " of the class " + cd.getSymbol());
1196 if (annotationVec.size() > 1) { // variable can have at most one location
1197 throw new Error(vd.getSymbol() + " has more than one location.");
1200 AnnotationDescriptor ad = annotationVec.elementAt(0);
1202 if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1204 if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1205 String locDec = ad.getValue(); // check if location is defined
1207 if (locDec.startsWith(SSJavaAnalysis.DELTA)) {
1208 DeltaLocation deltaLoc = parseDeltaDeclaration(md, n, locDec);
1209 d2loc.put(vd, deltaLoc);
1210 addLocationType(vd.getType(), deltaLoc);
1212 CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1214 Location lastElement = compLoc.get(compLoc.getSize() - 1);
1215 if (ssjava.isSharedLocation(lastElement)) {
1216 ssjava.mapSharedLocation2Descriptor(lastElement, vd);
1219 d2loc.put(vd, compLoc);
1220 addLocationType(vd.getType(), compLoc);
1228 private DeltaLocation parseDeltaDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1231 int dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1234 int beginIdx = dIdx + 6;
1235 locDec = locDec.substring(beginIdx, locDec.length() - 1);
1236 dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1239 CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1240 DeltaLocation deltaLoc = new DeltaLocation(compLoc, deltaCount);
1245 private Location parseFieldLocDeclaraton(String decl, String msg) {
1247 int idx = decl.indexOf(".");
1248 String className = decl.substring(0, idx);
1249 String fieldName = decl.substring(idx + 1);
1251 className.replaceAll(" ", "");
1252 fieldName.replaceAll(" ", "");
1254 Descriptor d = state.getClassSymbolTable().get(className);
1257 throw new Error("The class in the location declaration '" + decl + "' does not exist at "
1261 assert (d instanceof ClassDescriptor);
1262 SSJavaLattice<String> lattice = ssjava.getClassLattice((ClassDescriptor) d);
1263 if (!lattice.containsKey(fieldName)) {
1264 throw new Error("The location " + fieldName + " is not defined in the field lattice of '"
1265 + className + "' at " + msg);
1268 return new Location(d, fieldName);
1271 private CompositeLocation parseLocationDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1273 CompositeLocation compLoc = new CompositeLocation();
1275 StringTokenizer tokenizer = new StringTokenizer(locDec, ",");
1276 List<String> locIdList = new ArrayList<String>();
1277 while (tokenizer.hasMoreTokens()) {
1278 String locId = tokenizer.nextToken();
1279 locIdList.add(locId);
1282 // at least,one location element needs to be here!
1283 assert (locIdList.size() > 0);
1285 // assume that loc with idx 0 comes from the local lattice
1286 // loc with idx 1 comes from the field lattice
1288 String localLocId = locIdList.get(0);
1289 SSJavaLattice<String> localLattice = CompositeLattice.getLatticeByDescriptor(md);
1290 Location localLoc = new Location(md, localLocId);
1291 if (localLattice == null || (!localLattice.containsKey(localLocId))) {
1292 throw new Error("Location " + localLocId
1293 + " is not defined in the local variable lattice at "
1294 + md.getClassDesc().getSourceFileName() + "::" + (n != null ? n.getNumLine() : "") + ".");
1296 compLoc.addLocation(localLoc);
1298 for (int i = 1; i < locIdList.size(); i++) {
1299 String locName = locIdList.get(i);
1302 parseFieldLocDeclaraton(locName, generateErrorMessage(md.getClassDesc(), n));
1303 // ClassDescriptor cd = fieldLocName2cd.get(locName);
1304 // SSJavaLattice<String> fieldLattice =
1305 // CompositeLattice.getLatticeByDescriptor(cd);
1307 // if (fieldLattice == null || (!fieldLattice.containsKey(locName))) {
1308 // throw new Error("Location " + locName +
1309 // " is not defined in the field lattice at "
1310 // + cd.getSourceFileName() + ".");
1312 // Location fieldLoc = new Location(cd, locName);
1313 compLoc.addLocation(fieldLoc);
1320 private void checkDeclarationNode(MethodDescriptor md, SymbolTable nametable, DeclarationNode dn) {
1321 VarDescriptor vd = dn.getVarDescriptor();
1322 assignLocationOfVarDescriptor(vd, md, nametable, dn);
1325 private void checkClass(ClassDescriptor cd) {
1326 // Check to see that methods respects ss property
1327 for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
1328 MethodDescriptor md = (MethodDescriptor) method_it.next();
1329 checkMethodDeclaration(cd, md);
1333 private void checkDeclarationInClass(ClassDescriptor cd) {
1334 // Check to see that fields are okay
1335 for (Iterator field_it = cd.getFields(); field_it.hasNext();) {
1336 FieldDescriptor fd = (FieldDescriptor) field_it.next();
1338 if (!(fd.isFinal() && fd.isStatic())) {
1339 checkFieldDeclaration(cd, fd);
1341 // for static final, assign top location by default
1342 Location loc = Location.createTopLocation(cd);
1343 addLocationType(fd.getType(), loc);
1348 private void checkMethodDeclaration(ClassDescriptor cd, MethodDescriptor md) {
1352 private Location checkFieldDeclaration(ClassDescriptor cd, FieldDescriptor fd) {
1354 Vector<AnnotationDescriptor> annotationVec = fd.getType().getAnnotationMarkers();
1356 // currently enforce every field to have corresponding location
1357 if (annotationVec.size() == 0) {
1358 throw new Error("Location is not assigned to the field '" + fd.getSymbol()
1359 + "' of the class " + cd.getSymbol() + " at " + cd.getSourceFileName());
1362 if (annotationVec.size() > 1) {
1363 // variable can have at most one location
1364 throw new Error("Field " + fd.getSymbol() + " of class " + cd
1365 + " has more than one location.");
1368 AnnotationDescriptor ad = annotationVec.elementAt(0);
1369 Location loc = null;
1371 if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1372 if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1373 String locationID = ad.getValue();
1374 // check if location is defined
1375 SSJavaLattice<String> lattice = ssjava.getClassLattice(cd);
1376 if (lattice == null || (!lattice.containsKey(locationID))) {
1377 throw new Error("Location " + locationID
1378 + " is not defined in the field lattice of class " + cd.getSymbol() + " at"
1379 + cd.getSourceFileName() + ".");
1381 loc = new Location(cd, locationID);
1383 if (ssjava.isSharedLocation(loc)) {
1384 ssjava.mapSharedLocation2Descriptor(loc, fd);
1387 addLocationType(fd.getType(), loc);
1395 private void addLocationType(TypeDescriptor type, CompositeLocation loc) {
1397 type.setExtension(loc);
1401 private void addLocationType(TypeDescriptor type, Location loc) {
1403 type.setExtension(loc);
1407 static class CompositeLattice {
1409 public static boolean isGreaterThan(CompositeLocation loc1, CompositeLocation loc2, String msg) {
1411 System.out.println("isGreaterThan=" + loc1 + " " + loc2 + " msg=" + msg);
1412 int baseCompareResult = compareBaseLocationSet(loc1, loc2, true, msg);
1413 if (baseCompareResult == ComparisonResult.EQUAL) {
1414 if (compareDelta(loc1, loc2) == ComparisonResult.GREATER) {
1419 } else if (baseCompareResult == ComparisonResult.GREATER) {
1427 public static int compare(CompositeLocation loc1, CompositeLocation loc2, String msg) {
1429 System.out.println("compare=" + loc1 + " " + loc2);
1430 int baseCompareResult = compareBaseLocationSet(loc1, loc2, false, msg);
1432 if (baseCompareResult == ComparisonResult.EQUAL) {
1433 return compareDelta(loc1, loc2);
1435 return baseCompareResult;
1440 private static int compareDelta(CompositeLocation dLoc1, CompositeLocation dLoc2) {
1442 int deltaCount1 = 0;
1443 int deltaCount2 = 0;
1444 if (dLoc1 instanceof DeltaLocation) {
1445 deltaCount1 = ((DeltaLocation) dLoc1).getNumDelta();
1448 if (dLoc2 instanceof DeltaLocation) {
1449 deltaCount2 = ((DeltaLocation) dLoc2).getNumDelta();
1451 if (deltaCount1 < deltaCount2) {
1452 return ComparisonResult.GREATER;
1453 } else if (deltaCount1 == deltaCount2) {
1454 return ComparisonResult.EQUAL;
1456 return ComparisonResult.LESS;
1461 private static int compareBaseLocationSet(CompositeLocation compLoc1,
1462 CompositeLocation compLoc2, boolean awareSharedLoc, String msg) {
1464 // if compLoc1 is greater than compLoc2, return true
1465 // else return false;
1467 // compare one by one in according to the order of the tuple
1469 for (int i = 0; i < compLoc1.getSize(); i++) {
1470 Location loc1 = compLoc1.get(i);
1471 if (i >= compLoc2.getSize()) {
1472 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1473 + " because they are not comparable.");
1475 Location loc2 = compLoc2.get(i);
1477 Descriptor d1 = loc1.getDescriptor();
1478 Descriptor d2 = loc2.getDescriptor();
1480 Descriptor descriptor;
1482 if (d1 instanceof ClassDescriptor && d2 instanceof ClassDescriptor) {
1484 if (d1.equals(d2)) {
1487 // identifying which one is parent class
1488 Set<Descriptor> d1SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d1);
1489 Set<Descriptor> d2SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d2);
1491 if (d1 == null && d2 == null) {
1492 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1493 + " because they are not comparable at " + msg);
1494 } else if (d1 != null && d1SubClassesSet.contains(d2)) {
1496 } else if (d2 != null && d2SubClassesSet.contains(d1)) {
1499 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1500 + " because they are not comparable at " + msg);
1504 } else if (d1 instanceof MethodDescriptor && d2 instanceof MethodDescriptor) {
1506 if (d1.equals(d2)) {
1510 // identifying which one is parent class
1511 MethodDescriptor md1 = (MethodDescriptor) d1;
1512 MethodDescriptor md2 = (MethodDescriptor) d2;
1514 if (!md1.matches(md2)) {
1515 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1516 + " because they are not comparable at " + msg);
1519 Set<Descriptor> d1SubClassesSet =
1520 ssjava.tu.getSubClasses(((MethodDescriptor) d1).getClassDesc());
1521 Set<Descriptor> d2SubClassesSet =
1522 ssjava.tu.getSubClasses(((MethodDescriptor) d2).getClassDesc());
1524 if (d1 == null && d2 == null) {
1525 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1526 + " because they are not comparable at " + msg);
1527 } else if (d1 != null && d1SubClassesSet.contains(d2)) {
1529 } else if (d2 != null && d2SubClassesSet.contains(d1)) {
1532 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1533 + " because they are not comparable at " + msg);
1538 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1539 + " because they are not comparable at " + msg);
1542 // SSJavaLattice<String> lattice1 = getLatticeByDescriptor(d1);
1543 // SSJavaLattice<String> lattice2 = getLatticeByDescriptor(d2);
1545 SSJavaLattice<String> lattice = getLatticeByDescriptor(descriptor);
1547 // check if the spin location is appeared only at the end of the
1548 // composite location
1549 if (lattice.getSpinLocSet().contains(loc1.getLocIdentifier())) {
1550 if (i != (compLoc1.getSize() - 1)) {
1551 throw new Error("The shared location " + loc1.getLocIdentifier()
1552 + " cannot be appeared in the middle of composite location at" + msg);
1556 if (lattice.getSpinLocSet().contains(loc2.getLocIdentifier())) {
1557 if (i != (compLoc2.getSize() - 1)) {
1558 throw new Error("The spin location " + loc2.getLocIdentifier()
1559 + " cannot be appeared in the middle of composite location at " + msg);
1563 // if (!lattice1.equals(lattice2)) {
1564 // throw new Error("Failed to compare two locations of " + compLoc1 +
1565 // " and " + compLoc2
1566 // + " because they are not comparable at " + msg);
1569 if (loc1.getLocIdentifier().equals(loc2.getLocIdentifier())) {
1571 // check if the current location is the spinning location
1572 // note that the spinning location only can be appeared in the last
1573 // part of the composite location
1574 if (awareSharedLoc && numOfTie == compLoc1.getSize()
1575 && lattice.getSpinLocSet().contains(loc1.getLocIdentifier())) {
1576 return ComparisonResult.GREATER;
1579 } else if (lattice.isGreaterThan(loc1.getLocIdentifier(), loc2.getLocIdentifier())) {
1580 return ComparisonResult.GREATER;
1582 return ComparisonResult.LESS;
1587 if (numOfTie == compLoc1.getSize()) {
1589 if (numOfTie != compLoc2.getSize()) {
1590 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1591 + " because they are not comparable at " + msg);
1594 return ComparisonResult.EQUAL;
1597 return ComparisonResult.LESS;
1601 public static CompositeLocation calculateGLB(Set<CompositeLocation> inputSet) {
1603 // System.out.println("Calculating GLB=" + inputSet);
1604 CompositeLocation glbCompLoc = new CompositeLocation();
1606 // calculate GLB of the first(priority) element
1607 Set<String> priorityLocIdentifierSet = new HashSet<String>();
1608 Descriptor priorityDescriptor = null;
1610 Hashtable<String, Set<CompositeLocation>> locId2CompLocSet =
1611 new Hashtable<String, Set<CompositeLocation>>();
1612 // mapping from the priority loc ID to its full representation by the
1613 // composite location
1615 int maxTupleSize = 0;
1616 CompositeLocation maxCompLoc = null;
1618 for (Iterator iterator = inputSet.iterator(); iterator.hasNext();) {
1619 CompositeLocation compLoc = (CompositeLocation) iterator.next();
1620 if (compLoc.getSize() > maxTupleSize) {
1621 maxTupleSize = compLoc.getSize();
1622 maxCompLoc = compLoc;
1624 Location priorityLoc = compLoc.get(0);
1625 String priorityLocId = priorityLoc.getLocIdentifier();
1626 priorityLocIdentifierSet.add(priorityLocId);
1628 if (locId2CompLocSet.containsKey(priorityLocId)) {
1629 locId2CompLocSet.get(priorityLocId).add(compLoc);
1631 Set<CompositeLocation> newSet = new HashSet<CompositeLocation>();
1632 newSet.add(compLoc);
1633 locId2CompLocSet.put(priorityLocId, newSet);
1636 // check if priority location are coming from the same lattice
1637 if (priorityDescriptor == null) {
1638 priorityDescriptor = priorityLoc.getDescriptor();
1639 } else if (!priorityDescriptor.equals(priorityLoc.getDescriptor())) {
1640 throw new Error("Failed to calculate GLB of " + inputSet
1641 + " because they are from different lattices.");
1645 SSJavaLattice<String> locOrder = getLatticeByDescriptor(priorityDescriptor);
1646 String glbOfPriorityLoc = locOrder.getGLB(priorityLocIdentifierSet);
1648 glbCompLoc.addLocation(new Location(priorityDescriptor, glbOfPriorityLoc));
1649 Set<CompositeLocation> compSet = locId2CompLocSet.get(glbOfPriorityLoc);
1651 if (compSet == null) {
1652 // when GLB(x1,x2)!=x1 and !=x2 : GLB case 4
1653 // mean that the result is already lower than <x1,y1> and <x2,y2>
1654 // assign TOP to the rest of the location elements
1656 // in this case, do not take care about delta
1657 // CompositeLocation inputComp = inputSet.iterator().next();
1658 for (int i = 1; i < maxTupleSize; i++) {
1659 glbCompLoc.addLocation(Location.createTopLocation(maxCompLoc.get(i).getDescriptor()));
1663 // here find out composite location that has a maximum length tuple
1664 // if we have three input set: [A], [A,B], [A,B,C]
1665 // maximum length tuple will be [A,B,C]
1667 CompositeLocation maxFromCompSet = null;
1668 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1669 CompositeLocation c = (CompositeLocation) iterator.next();
1670 if (c.getSize() > max) {
1676 if (compSet.size() == 1) {
1678 // if GLB(x1,x2)==x1 or x2 : GLB case 2,3
1679 CompositeLocation comp = compSet.iterator().next();
1680 for (int i = 1; i < comp.getSize(); i++) {
1681 glbCompLoc.addLocation(comp.get(i));
1684 // if input location corresponding to glb is a delta, need to apply
1685 // delta to glb result
1686 if (comp instanceof DeltaLocation) {
1687 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1691 // when GLB(x1,x2)==x1 and x2 : GLB case 1
1692 // if more than one location shares the same priority GLB
1693 // need to calculate the rest of GLB loc
1695 // int compositeLocSize = compSet.iterator().next().getSize();
1696 int compositeLocSize = maxFromCompSet.getSize();
1698 Set<String> glbInputSet = new HashSet<String>();
1699 Descriptor currentD = null;
1700 for (int i = 1; i < compositeLocSize; i++) {
1701 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1702 CompositeLocation compositeLocation = (CompositeLocation) iterator.next();
1703 if (compositeLocation.getSize() > i) {
1704 Location currentLoc = compositeLocation.get(i);
1705 currentD = currentLoc.getDescriptor();
1706 // making set of the current location sharing the same idx
1707 glbInputSet.add(currentLoc.getLocIdentifier());
1710 // calculate glb for the current lattice
1712 SSJavaLattice<String> currentLattice = getLatticeByDescriptor(currentD);
1713 String currentGLBLocId = currentLattice.getGLB(glbInputSet);
1714 glbCompLoc.addLocation(new Location(currentD, currentGLBLocId));
1717 // if input location corresponding to glb is a delta, need to apply
1718 // delta to glb result
1720 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1721 CompositeLocation compLoc = (CompositeLocation) iterator.next();
1722 if (compLoc instanceof DeltaLocation) {
1723 if (glbCompLoc.equals(compLoc)) {
1724 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1737 static SSJavaLattice<String> getLatticeByDescriptor(Descriptor d) {
1739 SSJavaLattice<String> lattice = null;
1741 if (d instanceof ClassDescriptor) {
1742 lattice = ssjava.getCd2lattice().get(d);
1743 } else if (d instanceof MethodDescriptor) {
1744 if (ssjava.getMd2lattice().containsKey(d)) {
1745 lattice = ssjava.getMd2lattice().get(d);
1747 // use default lattice for the method
1748 lattice = ssjava.getCd2methodDefault().get(((MethodDescriptor) d).getClassDesc());
1757 class ComparisonResult {
1759 public static final int GREATER = 0;
1760 public static final int EQUAL = 1;
1761 public static final int LESS = 2;
1762 public static final int INCOMPARABLE = 3;
1769 class ReturnLocGenerator {
1771 public static final int PARAMISHIGHER = 0;
1772 public static final int PARAMISSAME = 1;
1773 public static final int IGNORE = 2;
1775 Hashtable<Integer, Integer> paramIdx2paramType;
1777 public ReturnLocGenerator(CompositeLocation returnLoc, List<CompositeLocation> params, String msg) {
1778 // creating mappings
1779 paramIdx2paramType = new Hashtable<Integer, Integer>();
1780 for (int i = 0; i < params.size(); i++) {
1781 CompositeLocation param = params.get(i);
1782 int compareResult = CompositeLattice.compare(param, returnLoc, msg);
1785 if (compareResult == ComparisonResult.GREATER) {
1787 } else if (compareResult == ComparisonResult.EQUAL) {
1792 paramIdx2paramType.put(new Integer(i), new Integer(type));
1797 public CompositeLocation computeReturnLocation(List<CompositeLocation> args) {
1799 // compute the highest possible location in caller's side
1800 assert paramIdx2paramType.keySet().size() == args.size();
1802 Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
1803 for (int i = 0; i < args.size(); i++) {
1804 int type = (paramIdx2paramType.get(new Integer(i))).intValue();
1805 CompositeLocation argLoc = args.get(i);
1806 if (type == PARAMISHIGHER) {
1807 // return loc is lower than param
1808 DeltaLocation delta = new DeltaLocation(argLoc, 1);
1809 inputGLB.add(delta);
1810 } else if (type == PARAMISSAME) {
1811 // return loc is equal or lower than param
1812 inputGLB.add(argLoc);
1816 // compute GLB of arguments subset that are same or higher than return
1818 CompositeLocation glb = CompositeLattice.calculateGLB(inputGLB);