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.TertiaryNode;
47 import IR.Tree.TreeNode;
50 public class FlowDownCheck {
53 static SSJavaAnalysis ssjava;
57 // mapping from 'descriptor' to 'composite location'
58 Hashtable<Descriptor, CompositeLocation> d2loc;
60 Hashtable<MethodDescriptor, CompositeLocation> md2ReturnLoc;
61 Hashtable<MethodDescriptor, ReturnLocGenerator> md2ReturnLocGen;
63 // mapping from 'locID' to 'class descriptor'
64 Hashtable<String, ClassDescriptor> fieldLocName2cd;
66 public FlowDownCheck(SSJavaAnalysis ssjava, State state) {
69 this.toanalyze = new HashSet();
70 this.d2loc = new Hashtable<Descriptor, CompositeLocation>();
71 this.fieldLocName2cd = new Hashtable<String, ClassDescriptor>();
72 this.md2ReturnLoc = new Hashtable<MethodDescriptor, CompositeLocation>();
73 this.md2ReturnLocGen = new Hashtable<MethodDescriptor, ReturnLocGenerator>();
78 // construct mapping from the location name to the class descriptor
79 // assume that the location name is unique through the whole program
81 Set<ClassDescriptor> cdSet = ssjava.getCd2lattice().keySet();
82 for (Iterator iterator = cdSet.iterator(); iterator.hasNext();) {
83 ClassDescriptor cd = (ClassDescriptor) iterator.next();
84 SSJavaLattice<String> lattice = ssjava.getCd2lattice().get(cd);
85 Set<String> fieldLocNameSet = lattice.getKeySet();
87 for (Iterator iterator2 = fieldLocNameSet.iterator(); iterator2.hasNext();) {
88 String fieldLocName = (String) iterator2.next();
89 fieldLocName2cd.put(fieldLocName, cd);
96 public void flowDownCheck() {
97 SymbolTable classtable = state.getClassSymbolTable();
99 // phase 1 : checking declaration node and creating mapping of 'type
100 // desciptor' & 'location'
101 toanalyze.addAll(classtable.getValueSet());
102 toanalyze.addAll(state.getTaskSymbolTable().getValueSet());
103 while (!toanalyze.isEmpty()) {
104 Object obj = toanalyze.iterator().next();
105 ClassDescriptor cd = (ClassDescriptor) obj;
106 toanalyze.remove(cd);
108 if (ssjava.needToBeAnnoated(cd) && (!cd.isInterface())) {
110 ClassDescriptor superDesc = cd.getSuperDesc();
111 if (superDesc != null && (!superDesc.isInterface())
112 && (!superDesc.getSymbol().equals("Object"))) {
113 checkOrderingInheritance(superDesc, cd);
116 checkDeclarationInClass(cd);
117 for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
118 MethodDescriptor md = (MethodDescriptor) method_it.next();
119 if (ssjava.needTobeAnnotated(md)) {
120 checkDeclarationInMethodBody(cd, md);
127 // phase2 : checking assignments
128 toanalyze.addAll(classtable.getValueSet());
129 toanalyze.addAll(state.getTaskSymbolTable().getValueSet());
130 while (!toanalyze.isEmpty()) {
131 Object obj = toanalyze.iterator().next();
132 ClassDescriptor cd = (ClassDescriptor) obj;
133 toanalyze.remove(cd);
136 for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
137 MethodDescriptor md = (MethodDescriptor) method_it.next();
138 if (ssjava.needTobeAnnotated(md)) {
139 checkMethodBody(cd, md);
146 private void checkOrderingInheritance(ClassDescriptor superCd, ClassDescriptor cd) {
147 // here, we're going to check that sub class keeps same relative orderings
148 // in respect to super class
150 SSJavaLattice<String> superLattice = ssjava.getClassLattice(superCd);
151 SSJavaLattice<String> subLattice = ssjava.getClassLattice(cd);
153 if (superLattice != null) {
155 if (subLattice == null) {
156 throw new Error("If a parent class '" + superCd
157 + "' has a ordering lattice, its subclass '" + cd + "' should have one.");
160 Set<Pair<String, String>> superPairSet = superLattice.getOrderingPairSet();
161 Set<Pair<String, String>> subPairSet = subLattice.getOrderingPairSet();
163 for (Iterator iterator = superPairSet.iterator(); iterator.hasNext();) {
164 Pair<String, String> pair = (Pair<String, String>) iterator.next();
166 if (!subPairSet.contains(pair)) {
167 throw new Error("Subclass '" + cd + "' does not have the relative ordering '"
168 + pair.getSecond() + " < " + pair.getFirst()
169 + "' that is defined by its superclass '" + superCd + "'.");
174 // if super class doesn't define lattice, then we don't need to check its
179 public Hashtable getMap() {
183 private void checkDeclarationInMethodBody(ClassDescriptor cd, MethodDescriptor md) {
184 BlockNode bn = state.getMethodBody(md);
186 // parsing returnloc annotation
187 if (ssjava.needTobeAnnotated(md)) {
189 Vector<AnnotationDescriptor> methodAnnotations = md.getModifiers().getAnnotations();
190 if (methodAnnotations != null) {
191 for (int i = 0; i < methodAnnotations.size(); i++) {
192 AnnotationDescriptor an = methodAnnotations.elementAt(i);
193 if (an.getMarker().equals(ssjava.RETURNLOC)) {
194 // developer explicitly defines method lattice
195 String returnLocDeclaration = an.getValue();
196 CompositeLocation returnLocComp =
197 parseLocationDeclaration(md, null, returnLocDeclaration);
198 md2ReturnLoc.put(md, returnLocComp);
202 if (!md.getReturnType().isVoid() && !md2ReturnLoc.containsKey(md)) {
203 throw new Error("Return location is not specified for the method " + md + " at "
204 + cd.getSourceFileName());
210 List<CompositeLocation> paramList = new ArrayList<CompositeLocation>();
212 boolean hasReturnValue = (!md.getReturnType().isVoid());
213 if (hasReturnValue) {
214 MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
215 String thisLocId = methodLattice.getThisLoc();
216 if (thisLocId == null) {
217 throw new Error("Method '" + md + "' does not have the definition of 'this' location at "
218 + md.getClassDesc().getSourceFileName());
220 CompositeLocation thisLoc = new CompositeLocation(new Location(md, thisLocId));
221 paramList.add(thisLoc);
224 for (int i = 0; i < md.numParameters(); i++) {
225 // process annotations on method parameters
226 VarDescriptor vd = (VarDescriptor) md.getParameter(i);
227 assignLocationOfVarDescriptor(vd, md, md.getParameterTable(), bn);
228 if (hasReturnValue) {
229 paramList.add(d2loc.get(vd));
233 if (hasReturnValue) {
234 md2ReturnLocGen.put(md, new ReturnLocGenerator(md2ReturnLoc.get(md), paramList,
235 generateErrorMessage(cd, null)));
238 checkDeclarationInBlockNode(md, md.getParameterTable(), bn);
241 private void checkDeclarationInBlockNode(MethodDescriptor md, SymbolTable nametable, BlockNode bn) {
242 bn.getVarTable().setParent(nametable);
243 for (int i = 0; i < bn.size(); i++) {
244 BlockStatementNode bsn = bn.get(i);
245 checkDeclarationInBlockStatementNode(md, bn.getVarTable(), bsn);
249 private void checkDeclarationInBlockStatementNode(MethodDescriptor md, SymbolTable nametable,
250 BlockStatementNode bsn) {
252 switch (bsn.kind()) {
253 case Kind.SubBlockNode:
254 checkDeclarationInSubBlockNode(md, nametable, (SubBlockNode) bsn);
257 case Kind.DeclarationNode:
258 checkDeclarationNode(md, nametable, (DeclarationNode) bsn);
262 checkDeclarationInLoopNode(md, nametable, (LoopNode) bsn);
267 private void checkDeclarationInLoopNode(MethodDescriptor md, SymbolTable nametable, LoopNode ln) {
269 if (ln.getType() == LoopNode.FORLOOP) {
270 // check for loop case
271 ClassDescriptor cd = md.getClassDesc();
272 BlockNode bn = ln.getInitializer();
273 for (int i = 0; i < bn.size(); i++) {
274 BlockStatementNode bsn = bn.get(i);
275 checkDeclarationInBlockStatementNode(md, nametable, bsn);
280 checkDeclarationInBlockNode(md, nametable, ln.getBody());
283 private void checkMethodBody(ClassDescriptor cd, MethodDescriptor md) {
284 BlockNode bn = state.getMethodBody(md);
285 checkLocationFromBlockNode(md, md.getParameterTable(), bn);
288 private String generateErrorMessage(ClassDescriptor cd, TreeNode tn) {
290 return cd.getSourceFileName() + "::" + tn.getNumLine();
292 return cd.getSourceFileName();
297 private CompositeLocation checkLocationFromBlockNode(MethodDescriptor md, SymbolTable nametable,
300 bn.getVarTable().setParent(nametable);
301 // it will return the lowest location in the block node
302 CompositeLocation lowestLoc = null;
304 for (int i = 0; i < bn.size(); i++) {
305 BlockStatementNode bsn = bn.get(i);
306 CompositeLocation bLoc = checkLocationFromBlockStatementNode(md, bn.getVarTable(), bsn);
307 if (!bLoc.isEmpty()) {
308 if (lowestLoc == null) {
311 if (CompositeLattice.isGreaterThan(lowestLoc, bLoc,
312 generateErrorMessage(md.getClassDesc(), bn))) {
320 if (lowestLoc == null) {
321 lowestLoc = new CompositeLocation(Location.createBottomLocation(md));
327 private CompositeLocation checkLocationFromBlockStatementNode(MethodDescriptor md,
328 SymbolTable nametable, BlockStatementNode bsn) {
330 CompositeLocation compLoc = null;
331 switch (bsn.kind()) {
332 case Kind.BlockExpressionNode:
333 compLoc = checkLocationFromBlockExpressionNode(md, nametable, (BlockExpressionNode) bsn);
336 case Kind.DeclarationNode:
337 compLoc = checkLocationFromDeclarationNode(md, nametable, (DeclarationNode) bsn);
340 case Kind.IfStatementNode:
341 compLoc = checkLocationFromIfStatementNode(md, nametable, (IfStatementNode) bsn);
345 compLoc = checkLocationFromLoopNode(md, nametable, (LoopNode) bsn);
348 case Kind.ReturnNode:
349 compLoc = checkLocationFromReturnNode(md, nametable, (ReturnNode) bsn);
352 case Kind.SubBlockNode:
353 compLoc = checkLocationFromSubBlockNode(md, nametable, (SubBlockNode) bsn);
356 case Kind.ContinueBreakNode:
357 compLoc = new CompositeLocation();
360 case Kind.SwitchStatementNode:
361 compLoc = checkLocationFromSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn);
367 private CompositeLocation checkLocationFromSwitchStatementNode(MethodDescriptor md,
368 SymbolTable nametable, SwitchStatementNode ssn) {
370 ClassDescriptor cd = md.getClassDesc();
371 CompositeLocation condLoc =
372 checkLocationFromExpressionNode(md, nametable, ssn.getCondition(), new CompositeLocation());
373 BlockNode sbn = ssn.getSwitchBody();
375 Set<CompositeLocation> blockLocSet = new HashSet<CompositeLocation>();
376 for (int i = 0; i < sbn.size(); i++) {
377 CompositeLocation blockLoc =
378 checkLocationFromSwitchBlockNode(md, nametable, (SwitchBlockNode) sbn.get(i));
379 if (!CompositeLattice.isGreaterThan(condLoc, blockLoc,
380 generateErrorMessage(cd, ssn.getCondition()))) {
382 "The location of the switch-condition statement is lower than the conditional body at "
383 + cd.getSourceFileName() + ":" + ssn.getCondition().getNumLine());
386 blockLocSet.add(blockLoc);
388 return CompositeLattice.calculateGLB(blockLocSet);
391 private CompositeLocation checkLocationFromSwitchBlockNode(MethodDescriptor md,
392 SymbolTable nametable, SwitchBlockNode sbn) {
394 CompositeLocation blockLoc =
395 checkLocationFromBlockNode(md, nametable, sbn.getSwitchBlockStatement());
401 private CompositeLocation checkLocationFromReturnNode(MethodDescriptor md, SymbolTable nametable,
404 ExpressionNode returnExp = rn.getReturnExpression();
406 CompositeLocation expLoc;
407 if (returnExp != null) {
408 expLoc = checkLocationFromExpressionNode(md, nametable, returnExp, new CompositeLocation());
409 // check if return value is equal or higher than RETRUNLOC of method
410 // declaration annotation
411 CompositeLocation returnLocAt = md2ReturnLoc.get(md);
414 .compare(returnLocAt, expLoc, generateErrorMessage(md.getClassDesc(), rn)) != ComparisonResult.LESS) {
416 "Return value location is not equal or higher than the declaraed return location at "
417 + md.getClassDesc().getSourceFileName() + "::" + rn.getNumLine());
421 return new CompositeLocation();
424 private boolean hasOnlyLiteralValue(ExpressionNode en) {
425 if (en.kind() == Kind.LiteralNode) {
432 private CompositeLocation checkLocationFromLoopNode(MethodDescriptor md, SymbolTable nametable,
435 ClassDescriptor cd = md.getClassDesc();
436 if (ln.getType() == LoopNode.WHILELOOP || ln.getType() == LoopNode.DOWHILELOOP) {
438 CompositeLocation condLoc =
439 checkLocationFromExpressionNode(md, nametable, ln.getCondition(), new CompositeLocation());
440 addLocationType(ln.getCondition().getType(), (condLoc));
442 CompositeLocation bodyLoc = checkLocationFromBlockNode(md, nametable, ln.getBody());
444 if (!CompositeLattice.isGreaterThan(condLoc, bodyLoc, generateErrorMessage(cd, ln))) {
445 // loop condition should be higher than loop body
447 "The location of the while-condition statement is lower than the loop body at "
448 + cd.getSourceFileName() + ":" + ln.getCondition().getNumLine());
454 // check for loop case
455 BlockNode bn = ln.getInitializer();
456 bn.getVarTable().setParent(nametable);
458 // calculate glb location of condition and update statements
459 CompositeLocation condLoc =
460 checkLocationFromExpressionNode(md, bn.getVarTable(), ln.getCondition(),
461 new CompositeLocation());
462 addLocationType(ln.getCondition().getType(), condLoc);
464 CompositeLocation updateLoc =
465 checkLocationFromBlockNode(md, bn.getVarTable(), ln.getUpdate());
467 Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
468 glbInputSet.add(condLoc);
469 // glbInputSet.add(updateLoc);
471 CompositeLocation glbLocOfForLoopCond = CompositeLattice.calculateGLB(glbInputSet);
473 // check location of 'forloop' body
474 CompositeLocation blockLoc = checkLocationFromBlockNode(md, bn.getVarTable(), ln.getBody());
476 // compute glb of body including loop body and update statement
479 if (blockLoc == null) {
480 // when there is no statement in the loop body
482 if (updateLoc == null) {
483 // also there is no update statement in the loop body
484 return glbLocOfForLoopCond;
486 glbInputSet.add(updateLoc);
489 glbInputSet.add(blockLoc);
490 glbInputSet.add(updateLoc);
493 CompositeLocation loopBodyLoc = CompositeLattice.calculateGLB(glbInputSet);
495 if (!CompositeLattice.isGreaterThan(glbLocOfForLoopCond, loopBodyLoc,
496 generateErrorMessage(cd, ln))) {
498 "The location of the for-condition statement is lower than the for-loop body at "
499 + cd.getSourceFileName() + ":" + ln.getCondition().getNumLine());
506 private CompositeLocation checkLocationFromSubBlockNode(MethodDescriptor md,
507 SymbolTable nametable, SubBlockNode sbn) {
508 CompositeLocation compLoc = checkLocationFromBlockNode(md, nametable, sbn.getBlockNode());
512 private CompositeLocation checkLocationFromIfStatementNode(MethodDescriptor md,
513 SymbolTable nametable, IfStatementNode isn) {
515 ClassDescriptor localCD = md.getClassDesc();
516 Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
518 CompositeLocation condLoc =
519 checkLocationFromExpressionNode(md, nametable, isn.getCondition(), new CompositeLocation());
521 addLocationType(isn.getCondition().getType(), condLoc);
522 glbInputSet.add(condLoc);
524 CompositeLocation locTrueBlock = checkLocationFromBlockNode(md, nametable, isn.getTrueBlock());
525 if (locTrueBlock != null) {
526 glbInputSet.add(locTrueBlock);
527 // here, the location of conditional block should be higher than the
528 // location of true/false blocks
529 if (locTrueBlock != null
530 && !CompositeLattice.isGreaterThan(condLoc, locTrueBlock,
531 generateErrorMessage(localCD, isn.getCondition()))) {
534 "The location of the if-condition statement is lower than the conditional block at "
535 + localCD.getSourceFileName() + ":" + isn.getCondition().getNumLine());
539 if (isn.getFalseBlock() != null) {
540 CompositeLocation locFalseBlock =
541 checkLocationFromBlockNode(md, nametable, isn.getFalseBlock());
543 if (locFalseBlock != null) {
544 glbInputSet.add(locFalseBlock);
546 if (!CompositeLattice.isGreaterThan(condLoc, locFalseBlock,
547 generateErrorMessage(localCD, isn.getCondition()))) {
550 "The location of the if-condition statement is lower than the conditional block at "
551 + localCD.getSourceFileName() + ":" + isn.getCondition().getNumLine());
557 // return GLB location of condition, true, and false block
558 CompositeLocation glbLoc = CompositeLattice.calculateGLB(glbInputSet);
563 private CompositeLocation checkLocationFromDeclarationNode(MethodDescriptor md,
564 SymbolTable nametable, DeclarationNode dn) {
566 System.out.println("DeclarationNode=" + dn.printNode(0) + " "
567 + generateErrorMessage(md.getClassDesc(), dn));
569 VarDescriptor vd = dn.getVarDescriptor();
571 CompositeLocation destLoc = d2loc.get(vd);
573 if (dn.getExpression() != null) {
574 CompositeLocation expressionLoc =
575 checkLocationFromExpressionNode(md, nametable, dn.getExpression(),
576 new CompositeLocation());
577 // addTypeLocation(dn.getExpression().getType(), expressionLoc);
579 if (expressionLoc != null) {
580 // checking location order
581 if (!CompositeLattice.isGreaterThan(expressionLoc, destLoc,
582 generateErrorMessage(md.getClassDesc(), dn))) {
583 throw new Error("The value flow from " + expressionLoc + " to " + destLoc
584 + " does not respect location hierarchy on the assignment " + dn.printNode(0)
585 + " at " + md.getClassDesc().getSourceFileName() + "::" + dn.getNumLine());
588 return expressionLoc;
592 return new CompositeLocation();
598 private void checkDeclarationInSubBlockNode(MethodDescriptor md, SymbolTable nametable,
600 checkDeclarationInBlockNode(md, nametable.getParent(), sbn.getBlockNode());
603 private CompositeLocation checkLocationFromBlockExpressionNode(MethodDescriptor md,
604 SymbolTable nametable, BlockExpressionNode ben) {
605 CompositeLocation compLoc =
606 checkLocationFromExpressionNode(md, nametable, ben.getExpression(), null);
607 // addTypeLocation(ben.getExpression().getType(), compLoc);
611 private CompositeLocation checkLocationFromExpressionNode(MethodDescriptor md,
612 SymbolTable nametable, ExpressionNode en, CompositeLocation loc) {
614 CompositeLocation compLoc = null;
617 case Kind.AssignmentNode:
618 compLoc = checkLocationFromAssignmentNode(md, nametable, (AssignmentNode) en, loc);
621 case Kind.FieldAccessNode:
622 compLoc = checkLocationFromFieldAccessNode(md, nametable, (FieldAccessNode) en, loc);
626 compLoc = checkLocationFromNameNode(md, nametable, (NameNode) en, loc);
630 compLoc = checkLocationFromOpNode(md, nametable, (OpNode) en);
633 case Kind.CreateObjectNode:
634 compLoc = checkLocationFromCreateObjectNode(md, nametable, (CreateObjectNode) en);
637 case Kind.ArrayAccessNode:
638 compLoc = checkLocationFromArrayAccessNode(md, nametable, (ArrayAccessNode) en);
641 case Kind.LiteralNode:
642 compLoc = checkLocationFromLiteralNode(md, nametable, (LiteralNode) en, loc);
645 case Kind.MethodInvokeNode:
646 compLoc = checkLocationFromMethodInvokeNode(md, nametable, (MethodInvokeNode) en, loc);
649 case Kind.TertiaryNode:
650 compLoc = checkLocationFromTertiaryNode(md, nametable, (TertiaryNode) en);
654 compLoc = checkLocationFromCastNode(md, nametable, (CastNode) en);
657 // case Kind.InstanceOfNode:
658 // checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
661 // case Kind.ArrayInitializerNode:
662 // checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en,
666 // case Kind.ClassTypeNode:
667 // checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
670 // case Kind.OffsetNode:
671 // checkOffsetNode(md, nametable, (OffsetNode)en, td);
678 // addTypeLocation(en.getType(), compLoc);
683 private CompositeLocation checkLocationFromCastNode(MethodDescriptor md, SymbolTable nametable,
686 ExpressionNode en = cn.getExpression();
687 return checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation());
691 private CompositeLocation checkLocationFromTertiaryNode(MethodDescriptor md,
692 SymbolTable nametable, TertiaryNode tn) {
693 ClassDescriptor cd = md.getClassDesc();
695 CompositeLocation condLoc =
696 checkLocationFromExpressionNode(md, nametable, tn.getCond(), new CompositeLocation());
697 addLocationType(tn.getCond().getType(), condLoc);
698 CompositeLocation trueLoc =
699 checkLocationFromExpressionNode(md, nametable, tn.getTrueExpr(), new CompositeLocation());
700 addLocationType(tn.getTrueExpr().getType(), trueLoc);
701 CompositeLocation falseLoc =
702 checkLocationFromExpressionNode(md, nametable, tn.getFalseExpr(), new CompositeLocation());
703 addLocationType(tn.getFalseExpr().getType(), falseLoc);
705 // locations from true/false branches can be TOP when there are only literal
707 // in this case, we don't need to check flow down rule!
709 // check if condLoc is higher than trueLoc & falseLoc
710 if (!trueLoc.get(0).isTop()
711 && !CompositeLattice.isGreaterThan(condLoc, trueLoc, generateErrorMessage(cd, tn))) {
713 "The location of the condition expression is lower than the true expression at "
714 + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
717 if (!falseLoc.get(0).isTop()
718 && !CompositeLattice.isGreaterThan(condLoc, falseLoc,
719 generateErrorMessage(cd, tn.getCond()))) {
721 "The location of the condition expression is lower than the true expression at "
722 + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
725 // then, return glb of trueLoc & falseLoc
726 Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
727 glbInputSet.add(trueLoc);
728 glbInputSet.add(falseLoc);
730 return CompositeLattice.calculateGLB(glbInputSet);
733 private CompositeLocation checkLocationFromMethodInvokeNode(MethodDescriptor md,
734 SymbolTable nametable, MethodInvokeNode min, CompositeLocation loc) {
736 checkCalleeConstraints(md, nametable, min);
738 CompositeLocation baseLocation = null;
739 if (min.getExpression() != null) {
741 checkLocationFromExpressionNode(md, nametable, min.getExpression(),
742 new CompositeLocation());
744 String thisLocId = ssjava.getMethodLattice(md).getThisLoc();
745 baseLocation = new CompositeLocation(new Location(md, thisLocId));
748 if (!min.getMethod().getReturnType().isVoid()) {
749 // If method has a return value, compute the highest possible return
750 // location in the caller's perspective
751 CompositeLocation ceilingLoc =
752 computeCeilingLocationForCaller(md, nametable, min, baseLocation);
756 return new CompositeLocation();
760 private CompositeLocation computeCeilingLocationForCaller(MethodDescriptor md,
761 SymbolTable nametable, MethodInvokeNode min, CompositeLocation baseLocation) {
762 List<CompositeLocation> argList = new ArrayList<CompositeLocation>();
764 // by default, method has a THIS parameter
765 argList.add(baseLocation);
767 for (int i = 0; i < min.numArgs(); i++) {
768 ExpressionNode en = min.getArg(i);
769 CompositeLocation callerArg =
770 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation());
771 argList.add(callerArg);
774 System.out.println("##");
775 System.out.println("min.getMethod()=" + min.getMethod());
776 System.out.println("md2ReturnLocGen.get(min.getMethod())="
777 + md2ReturnLocGen.get(min.getMethod()));
779 return md2ReturnLocGen.get(min.getMethod()).computeReturnLocation(argList);
783 private void checkCalleeConstraints(MethodDescriptor md, SymbolTable nametable,
784 MethodInvokeNode min) {
786 if (min.numArgs() > 1) {
787 // caller needs to guarantee that it passes arguments in regarding to
788 // callee's hierarchy
789 for (int i = 0; i < min.numArgs(); i++) {
790 ExpressionNode en = min.getArg(i);
791 CompositeLocation callerArg1 =
792 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation());
794 ClassDescriptor calleecd = min.getMethod().getClassDesc();
795 VarDescriptor calleevd = (VarDescriptor) min.getMethod().getParameter(i);
796 CompositeLocation calleeLoc1 = d2loc.get(calleevd);
798 if (!callerArg1.get(0).isTop()) {
799 // here, check if ordering relations among caller's args respect
800 // ordering relations in-between callee's args
801 for (int currentIdx = 0; currentIdx < min.numArgs(); currentIdx++) {
802 if (currentIdx != i) { // skip itself
803 ExpressionNode argExp = min.getArg(currentIdx);
805 CompositeLocation callerArg2 =
806 checkLocationFromExpressionNode(md, nametable, argExp, new CompositeLocation());
808 VarDescriptor calleevd2 = (VarDescriptor) min.getMethod().getParameter(currentIdx);
809 CompositeLocation calleeLoc2 = d2loc.get(calleevd2);
812 CompositeLattice.compare(callerArg1, callerArg2,
813 generateErrorMessage(md.getClassDesc(), min));
815 CompositeLattice.compare(calleeLoc1, calleeLoc2,
816 generateErrorMessage(md.getClassDesc(), min));
817 if (calleeResult == ComparisonResult.GREATER
818 && callerResult != ComparisonResult.GREATER) {
819 // If calleeLoc1 is higher than calleeLoc2
820 // then, caller should have same ordering relation in-bet
821 // callerLoc1 & callerLoc2
823 throw new Error("Caller doesn't respect ordering relations among method arguments:"
824 + md.getClassDesc().getSourceFileName() + ":" + min.getNumLine());
837 private CompositeLocation checkLocationFromArrayAccessNode(MethodDescriptor md,
838 SymbolTable nametable, ArrayAccessNode aan) {
840 // return glb location of array itself and index
842 ClassDescriptor cd = md.getClassDesc();
844 Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
846 CompositeLocation arrayLoc =
847 checkLocationFromExpressionNode(md, nametable, aan.getExpression(), new CompositeLocation());
848 // addTypeLocation(aan.getExpression().getType(), arrayLoc);
849 glbInputSet.add(arrayLoc);
850 CompositeLocation indexLoc =
851 checkLocationFromExpressionNode(md, nametable, aan.getIndex(), new CompositeLocation());
852 glbInputSet.add(indexLoc);
853 // addTypeLocation(aan.getIndex().getType(), indexLoc);
855 CompositeLocation glbLoc = CompositeLattice.calculateGLB(glbInputSet);
859 private CompositeLocation checkLocationFromCreateObjectNode(MethodDescriptor md,
860 SymbolTable nametable, CreateObjectNode con) {
862 ClassDescriptor cd = md.getClassDesc();
865 Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
866 for (int i = 0; i < con.numArgs(); i++) {
867 ExpressionNode en = con.getArg(i);
868 CompositeLocation argLoc =
869 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation());
870 glbInputSet.add(argLoc);
871 addLocationType(en.getType(), argLoc);
874 // check array initializers
875 // if ((con.getArrayInitializer() != null)) {
876 // checkLocationFromArrayInitializerNode(md, nametable,
877 // con.getArrayInitializer());
880 if (glbInputSet.size() > 0) {
881 return CompositeLattice.calculateGLB(glbInputSet);
884 CompositeLocation compLoc = new CompositeLocation();
885 compLoc.addLocation(Location.createTopLocation(md));
890 private CompositeLocation checkLocationFromOpNode(MethodDescriptor md, SymbolTable nametable,
893 ClassDescriptor cd = md.getClassDesc();
894 CompositeLocation leftLoc = new CompositeLocation();
895 leftLoc = checkLocationFromExpressionNode(md, nametable, on.getLeft(), leftLoc);
896 // addTypeLocation(on.getLeft().getType(), leftLoc);
898 CompositeLocation rightLoc = new CompositeLocation();
899 if (on.getRight() != null) {
900 rightLoc = checkLocationFromExpressionNode(md, nametable, on.getRight(), rightLoc);
901 // addTypeLocation(on.getRight().getType(), rightLoc);
904 System.out.println("checking op node=" + on.printNode(0)
905 + generateErrorMessage(md.getClassDesc(), on));
906 System.out.println("left loc=" + leftLoc + " from " + on.getLeft().getClass());
907 if (on.getRight() != null) {
908 System.out.println("right loc=" + rightLoc + " from " + on.getRight().kind());
911 Operation op = on.getOp();
913 switch (op.getOp()) {
915 case Operation.UNARYPLUS:
916 case Operation.UNARYMINUS:
917 case Operation.LOGIC_NOT:
921 case Operation.LOGIC_OR:
922 case Operation.LOGIC_AND:
924 case Operation.BIT_OR:
925 case Operation.BIT_XOR:
926 case Operation.BIT_AND:
927 case Operation.ISAVAILABLE:
928 case Operation.EQUAL:
929 case Operation.NOTEQUAL:
939 case Operation.LEFTSHIFT:
940 case Operation.RIGHTSHIFT:
941 case Operation.URIGHTSHIFT:
943 Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
944 inputSet.add(leftLoc);
945 inputSet.add(rightLoc);
946 CompositeLocation glbCompLoc = CompositeLattice.calculateGLB(inputSet);
950 throw new Error(op.toString());
955 private CompositeLocation checkLocationFromLiteralNode(MethodDescriptor md,
956 SymbolTable nametable, LiteralNode en, CompositeLocation loc) {
958 // literal value has the top location so that value can be flowed into any
960 Location literalLoc = Location.createTopLocation(md);
961 loc.addLocation(literalLoc);
966 private CompositeLocation checkLocationFromNameNode(MethodDescriptor md, SymbolTable nametable,
967 NameNode nn, CompositeLocation loc) {
969 NameDescriptor nd = nn.getName();
970 if (nd.getBase() != null) {
971 loc = checkLocationFromExpressionNode(md, nametable, nn.getExpression(), loc);
973 String varname = nd.toString();
974 if (varname.equals("this")) {
976 MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
977 String thisLocId = methodLattice.getThisLoc();
978 if (thisLocId == null) {
979 throw new Error("The location for 'this' is not defined at "
980 + md.getClassDesc().getSourceFileName() + "::" + nn.getNumLine());
982 Location locElement = new Location(md, thisLocId);
983 loc.addLocation(locElement);
986 Descriptor d = (Descriptor) nametable.get(varname);
988 // CompositeLocation localLoc = null;
989 if (d instanceof VarDescriptor) {
990 VarDescriptor vd = (VarDescriptor) d;
991 // localLoc = d2loc.get(vd);
992 // the type of var descriptor has a composite location!
993 loc = ((CompositeLocation) vd.getType().getExtension()).clone();
994 } else if (d instanceof FieldDescriptor) {
995 // the type of field descriptor has a location!
996 FieldDescriptor fd = (FieldDescriptor) d;
999 // if it is 'static final', the location has TOP since no one can
1001 loc.addLocation(Location.createTopLocation(md));
1003 // if 'static', the location has pre-assigned global loc
1004 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1005 String globalLocId = localLattice.getGlobalLoc();
1006 if (globalLocId == null) {
1007 throw new Error("Global location element is not defined in the method " + md);
1009 Location globalLoc = new Location(md, globalLocId);
1011 loc.addLocation(globalLoc);
1014 // the location of field access starts from this, followed by field
1016 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1017 Location thisLoc = new Location(md, localLattice.getThisLoc());
1018 loc.addLocation(thisLoc);
1021 Location fieldLoc = (Location) fd.getType().getExtension();
1022 loc.addLocation(fieldLoc);
1028 private CompositeLocation checkLocationFromFieldAccessNode(MethodDescriptor md,
1029 SymbolTable nametable, FieldAccessNode fan, CompositeLocation loc) {
1031 ExpressionNode left = fan.getExpression();
1032 TypeDescriptor ltd = left.getType();
1034 FieldDescriptor fd = fan.getField();
1036 if (ltd.isClassNameRef()) {
1037 // using a class name directly
1038 if (fd.isStatic() && fd.isFinal()) {
1039 loc.addLocation(Location.createTopLocation(md));
1044 loc = checkLocationFromExpressionNode(md, nametable, left, loc);
1045 if (!left.getType().isPrimitive()) {
1046 Location fieldLoc = getFieldLocation(fd);
1047 loc.addLocation(fieldLoc);
1053 private Location getFieldLocation(FieldDescriptor fd) {
1055 Location fieldLoc = (Location) fd.getType().getExtension();
1057 // handle the case that method annotation checking skips checking field
1059 if (fieldLoc == null) {
1060 fieldLoc = checkFieldDeclaration(fd.getClassDescriptor(), fd);
1067 private CompositeLocation checkLocationFromAssignmentNode(MethodDescriptor md,
1068 SymbolTable nametable, AssignmentNode an, CompositeLocation loc) {
1070 ClassDescriptor cd = md.getClassDesc();
1072 boolean postinc = true;
1073 if (an.getOperation().getBaseOp() == null
1074 || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
1075 .getBaseOp().getOp() != Operation.POSTDEC))
1078 CompositeLocation destLocation =
1079 checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation());
1081 CompositeLocation srcLocation = new CompositeLocation();
1084 if (hasOnlyLiteralValue(an.getSrc())) {
1085 // if source is literal value, src location is TOP. so do not need to
1087 return destLocation;
1089 srcLocation = new CompositeLocation();
1090 srcLocation = checkLocationFromExpressionNode(md, nametable, an.getSrc(), srcLocation);
1092 // System.out.println(" an= " + an.printNode(0) + " an.getSrc()=" + an.getSrc().getClass()
1093 // + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1094 // System.out.println("srcLocation=" + srcLocation);
1095 // System.out.println("dstLocation=" + destLocation);
1097 if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1098 throw new Error("The value flow from " + srcLocation + " to " + destLocation
1099 + " does not respect location hierarchy on the assignment " + an.printNode(0) + " at "
1100 + cd.getSourceFileName() + "::" + an.getNumLine());
1104 srcLocation = checkLocationFromExpressionNode(md, nametable, an.getDest(), srcLocation);
1106 if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1107 throw new Error("Location " + destLocation
1108 + " is not allowed to have the value flow that moves within the same location at "
1109 + cd.getSourceFileName() + "::" + an.getNumLine());
1114 return destLocation;
1117 private void assignLocationOfVarDescriptor(VarDescriptor vd, MethodDescriptor md,
1118 SymbolTable nametable, TreeNode n) {
1120 ClassDescriptor cd = md.getClassDesc();
1121 Vector<AnnotationDescriptor> annotationVec = vd.getType().getAnnotationMarkers();
1123 if (!md.getModifiers().isAbstract()) {
1124 // currently enforce every variable to have corresponding location
1125 if (annotationVec.size() == 0) {
1126 throw new Error("Location is not assigned to variable " + vd.getSymbol()
1127 + " in the method " + md.getSymbol() + " of the class " + cd.getSymbol());
1130 if (annotationVec.size() > 1) { // variable can have at most one location
1131 throw new Error(vd.getSymbol() + " has more than one location.");
1134 AnnotationDescriptor ad = annotationVec.elementAt(0);
1136 if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1138 if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1139 String locDec = ad.getValue(); // check if location is defined
1141 if (locDec.startsWith(SSJavaAnalysis.DELTA)) {
1142 DeltaLocation deltaLoc = parseDeltaDeclaration(md, n, locDec);
1143 d2loc.put(vd, deltaLoc);
1144 addLocationType(vd.getType(), deltaLoc);
1146 CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1148 Location lastElement = compLoc.get(compLoc.getSize() - 1);
1149 if (ssjava.isSharedLocation(lastElement)) {
1150 ssjava.mapSharedLocation2Descriptor(lastElement, vd);
1153 d2loc.put(vd, compLoc);
1154 addLocationType(vd.getType(), compLoc);
1163 private DeltaLocation parseDeltaDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1166 int dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1169 int beginIdx = dIdx + 6;
1170 locDec = locDec.substring(beginIdx, locDec.length() - 1);
1171 dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1174 CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1175 DeltaLocation deltaLoc = new DeltaLocation(compLoc, deltaCount);
1180 private Location parseFieldLocDeclaraton(String decl, String msg) {
1182 int idx = decl.indexOf(".");
1183 String className = decl.substring(0, idx);
1184 String fieldName = decl.substring(idx + 1);
1186 className.replaceAll(" ", "");
1187 fieldName.replaceAll(" ", "");
1189 Descriptor d = state.getClassSymbolTable().get(className);
1192 throw new Error("The class in the location declaration '" + decl + "' does not exist at "
1196 assert (d instanceof ClassDescriptor);
1197 SSJavaLattice<String> lattice = ssjava.getClassLattice((ClassDescriptor) d);
1198 if (!lattice.containsKey(fieldName)) {
1199 throw new Error("The location " + fieldName + " is not defined in the field lattice of '"
1200 + className + "' at " + msg);
1203 return new Location(d, fieldName);
1206 private CompositeLocation parseLocationDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1208 CompositeLocation compLoc = new CompositeLocation();
1210 StringTokenizer tokenizer = new StringTokenizer(locDec, ",");
1211 List<String> locIdList = new ArrayList<String>();
1212 while (tokenizer.hasMoreTokens()) {
1213 String locId = tokenizer.nextToken();
1214 locIdList.add(locId);
1217 // at least,one location element needs to be here!
1218 assert (locIdList.size() > 0);
1220 // assume that loc with idx 0 comes from the local lattice
1221 // loc with idx 1 comes from the field lattice
1223 String localLocId = locIdList.get(0);
1224 SSJavaLattice<String> localLattice = CompositeLattice.getLatticeByDescriptor(md);
1225 Location localLoc = new Location(md, localLocId);
1226 if (localLattice == null || (!localLattice.containsKey(localLocId))) {
1227 throw new Error("Location " + localLocId
1228 + " is not defined in the local variable lattice at "
1229 + md.getClassDesc().getSourceFileName() + "::" + (n != null ? n.getNumLine() : "") + ".");
1231 compLoc.addLocation(localLoc);
1233 for (int i = 1; i < locIdList.size(); i++) {
1234 String locName = locIdList.get(i);
1237 parseFieldLocDeclaraton(locName, generateErrorMessage(md.getClassDesc(), n));
1238 // ClassDescriptor cd = fieldLocName2cd.get(locName);
1239 // SSJavaLattice<String> fieldLattice =
1240 // CompositeLattice.getLatticeByDescriptor(cd);
1242 // if (fieldLattice == null || (!fieldLattice.containsKey(locName))) {
1243 // throw new Error("Location " + locName +
1244 // " is not defined in the field lattice at "
1245 // + cd.getSourceFileName() + ".");
1247 // Location fieldLoc = new Location(cd, locName);
1248 compLoc.addLocation(fieldLoc);
1255 private void checkDeclarationNode(MethodDescriptor md, SymbolTable nametable, DeclarationNode dn) {
1256 VarDescriptor vd = dn.getVarDescriptor();
1257 assignLocationOfVarDescriptor(vd, md, nametable, dn);
1260 private void checkClass(ClassDescriptor cd) {
1261 // Check to see that methods respects ss property
1262 for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
1263 MethodDescriptor md = (MethodDescriptor) method_it.next();
1264 checkMethodDeclaration(cd, md);
1268 private void checkDeclarationInClass(ClassDescriptor cd) {
1269 // Check to see that fields are okay
1270 for (Iterator field_it = cd.getFields(); field_it.hasNext();) {
1271 FieldDescriptor fd = (FieldDescriptor) field_it.next();
1273 if (!(fd.isFinal() && fd.isStatic())) {
1274 checkFieldDeclaration(cd, fd);
1276 // for static final, assign top location by default
1277 Location loc = Location.createTopLocation(cd);
1278 addLocationType(fd.getType(), loc);
1283 private void checkMethodDeclaration(ClassDescriptor cd, MethodDescriptor md) {
1287 private Location checkFieldDeclaration(ClassDescriptor cd, FieldDescriptor fd) {
1289 Vector<AnnotationDescriptor> annotationVec = fd.getType().getAnnotationMarkers();
1291 // currently enforce every field to have corresponding location
1292 if (annotationVec.size() == 0) {
1293 throw new Error("Location is not assigned to the field '" + fd.getSymbol()
1294 + "' of the class " + cd.getSymbol() + " at " + cd.getSourceFileName());
1297 if (annotationVec.size() > 1) {
1298 // variable can have at most one location
1299 throw new Error("Field " + fd.getSymbol() + " of class " + cd
1300 + " has more than one location.");
1303 AnnotationDescriptor ad = annotationVec.elementAt(0);
1304 Location loc = null;
1306 if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1307 if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1308 String locationID = ad.getValue();
1309 // check if location is defined
1310 SSJavaLattice<String> lattice = ssjava.getClassLattice(cd);
1311 if (lattice == null || (!lattice.containsKey(locationID))) {
1312 throw new Error("Location " + locationID
1313 + " is not defined in the field lattice of class " + cd.getSymbol() + " at"
1314 + cd.getSourceFileName() + ".");
1316 loc = new Location(cd, locationID);
1318 if (ssjava.isSharedLocation(loc)) {
1319 ssjava.mapSharedLocation2Descriptor(loc, fd);
1322 addLocationType(fd.getType(), loc);
1330 private void addLocationType(TypeDescriptor type, CompositeLocation loc) {
1332 type.setExtension(loc);
1336 private void addLocationType(TypeDescriptor type, Location loc) {
1338 type.setExtension(loc);
1342 static class CompositeLattice {
1344 public static boolean isGreaterThan(CompositeLocation loc1, CompositeLocation loc2, String msg) {
1346 System.out.println("isGreaterThan=" + loc1 + " " + loc2 + " msg=" + msg);
1347 int baseCompareResult = compareBaseLocationSet(loc1, loc2, true, msg);
1348 if (baseCompareResult == ComparisonResult.EQUAL) {
1349 if (compareDelta(loc1, loc2) == ComparisonResult.GREATER) {
1354 } else if (baseCompareResult == ComparisonResult.GREATER) {
1362 public static int compare(CompositeLocation loc1, CompositeLocation loc2, String msg) {
1364 // System.out.println("compare=" + loc1 + " " + loc2);
1365 int baseCompareResult = compareBaseLocationSet(loc1, loc2, false, msg);
1367 if (baseCompareResult == ComparisonResult.EQUAL) {
1368 return compareDelta(loc1, loc2);
1370 return baseCompareResult;
1375 private static int compareDelta(CompositeLocation dLoc1, CompositeLocation dLoc2) {
1377 int deltaCount1 = 0;
1378 int deltaCount2 = 0;
1379 if (dLoc1 instanceof DeltaLocation) {
1380 deltaCount1 = ((DeltaLocation) dLoc1).getNumDelta();
1383 if (dLoc2 instanceof DeltaLocation) {
1384 deltaCount2 = ((DeltaLocation) dLoc2).getNumDelta();
1386 if (deltaCount1 < deltaCount2) {
1387 return ComparisonResult.GREATER;
1388 } else if (deltaCount1 == deltaCount2) {
1389 return ComparisonResult.EQUAL;
1391 return ComparisonResult.LESS;
1396 private static int compareBaseLocationSet(CompositeLocation compLoc1,
1397 CompositeLocation compLoc2, boolean awareSharedLoc, String msg) {
1399 // if compLoc1 is greater than compLoc2, return true
1400 // else return false;
1402 // compare one by one in according to the order of the tuple
1404 for (int i = 0; i < compLoc1.getSize(); i++) {
1405 Location loc1 = compLoc1.get(i);
1406 if (i >= compLoc2.getSize()) {
1407 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1408 + " because they are not comparable.");
1410 Location loc2 = compLoc2.get(i);
1412 if (!loc1.getDescriptor().equals(loc2.getDescriptor())) {
1413 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1414 + " because they are not comparable at " + msg);
1417 Descriptor d1 = loc1.getDescriptor();
1418 Descriptor d2 = loc2.getDescriptor();
1420 SSJavaLattice<String> lattice1 = getLatticeByDescriptor(d1);
1421 SSJavaLattice<String> lattice2 = getLatticeByDescriptor(d2);
1423 // check if the spin location is appeared only at the end of the
1424 // composite location
1425 if (lattice1.getSpinLocSet().contains(loc1.getLocIdentifier())) {
1426 if (i != (compLoc1.getSize() - 1)) {
1427 throw new Error("The spin location " + loc1.getLocIdentifier()
1428 + " cannot be appeared in the middle of composite location at" + msg);
1432 if (lattice2.getSpinLocSet().contains(loc2.getLocIdentifier())) {
1433 if (i != (compLoc2.getSize() - 1)) {
1434 throw new Error("The spin location " + loc2.getLocIdentifier()
1435 + " cannot be appeared in the middle of composite location at " + msg);
1439 if (!lattice1.equals(lattice2)) {
1440 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1441 + " because they are not comparable at " + msg);
1444 if (loc1.getLocIdentifier().equals(loc2.getLocIdentifier())) {
1446 // check if the current location is the spinning location
1447 // note that the spinning location only can be appeared in the last
1448 // part of the composite location
1449 if (awareSharedLoc && numOfTie == compLoc1.getSize()
1450 && lattice1.getSpinLocSet().contains(loc1.getLocIdentifier())) {
1451 return ComparisonResult.GREATER;
1454 } else if (lattice1.isGreaterThan(loc1.getLocIdentifier(), loc2.getLocIdentifier())) {
1455 return ComparisonResult.GREATER;
1457 return ComparisonResult.LESS;
1462 if (numOfTie == compLoc1.getSize()) {
1464 if (numOfTie != compLoc2.getSize()) {
1465 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1466 + " because they are not comparable at " + msg);
1469 return ComparisonResult.EQUAL;
1472 return ComparisonResult.LESS;
1476 public static CompositeLocation calculateGLB(Set<CompositeLocation> inputSet) {
1478 // System.out.println("Calculating GLB=" + inputSet);
1479 CompositeLocation glbCompLoc = new CompositeLocation();
1481 // calculate GLB of the first(priority) element
1482 Set<String> priorityLocIdentifierSet = new HashSet<String>();
1483 Descriptor priorityDescriptor = null;
1485 Hashtable<String, Set<CompositeLocation>> locId2CompLocSet =
1486 new Hashtable<String, Set<CompositeLocation>>();
1487 // mapping from the priority loc ID to its full representation by the
1488 // composite location
1490 int maxTupleSize = 0;
1491 CompositeLocation maxCompLoc = null;
1493 for (Iterator iterator = inputSet.iterator(); iterator.hasNext();) {
1494 CompositeLocation compLoc = (CompositeLocation) iterator.next();
1495 if (compLoc.getSize() > maxTupleSize) {
1496 maxTupleSize = compLoc.getSize();
1497 maxCompLoc = compLoc;
1499 Location priorityLoc = compLoc.get(0);
1500 String priorityLocId = priorityLoc.getLocIdentifier();
1501 priorityLocIdentifierSet.add(priorityLocId);
1503 if (locId2CompLocSet.containsKey(priorityLocId)) {
1504 locId2CompLocSet.get(priorityLocId).add(compLoc);
1506 Set<CompositeLocation> newSet = new HashSet<CompositeLocation>();
1507 newSet.add(compLoc);
1508 locId2CompLocSet.put(priorityLocId, newSet);
1511 // check if priority location are coming from the same lattice
1512 if (priorityDescriptor == null) {
1513 priorityDescriptor = priorityLoc.getDescriptor();
1514 } else if (!priorityDescriptor.equals(priorityLoc.getDescriptor())) {
1515 throw new Error("Failed to calculate GLB of " + inputSet
1516 + " because they are from different lattices.");
1520 SSJavaLattice<String> locOrder = getLatticeByDescriptor(priorityDescriptor);
1521 String glbOfPriorityLoc = locOrder.getGLB(priorityLocIdentifierSet);
1523 glbCompLoc.addLocation(new Location(priorityDescriptor, glbOfPriorityLoc));
1524 Set<CompositeLocation> compSet = locId2CompLocSet.get(glbOfPriorityLoc);
1526 if (compSet == null) {
1527 // when GLB(x1,x2)!=x1 and !=x2 : GLB case 4
1528 // mean that the result is already lower than <x1,y1> and <x2,y2>
1529 // assign TOP to the rest of the location elements
1531 // in this case, do not take care about delta
1532 // CompositeLocation inputComp = inputSet.iterator().next();
1533 for (int i = 1; i < maxTupleSize; i++) {
1534 glbCompLoc.addLocation(Location.createTopLocation(maxCompLoc.get(i).getDescriptor()));
1538 // here find out composite location that has a maximum length tuple
1539 // if we have three input set: [A], [A,B], [A,B,C]
1540 // maximum length tuple will be [A,B,C]
1542 CompositeLocation maxFromCompSet = null;
1543 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1544 CompositeLocation c = (CompositeLocation) iterator.next();
1545 if (c.getSize() > max) {
1551 if (compSet.size() == 1) {
1553 // if GLB(x1,x2)==x1 or x2 : GLB case 2,3
1554 CompositeLocation comp = compSet.iterator().next();
1555 for (int i = 1; i < comp.getSize(); i++) {
1556 glbCompLoc.addLocation(comp.get(i));
1559 // if input location corresponding to glb is a delta, need to apply
1560 // delta to glb result
1561 if (comp instanceof DeltaLocation) {
1562 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1566 // when GLB(x1,x2)==x1 and x2 : GLB case 1
1567 // if more than one location shares the same priority GLB
1568 // need to calculate the rest of GLB loc
1570 // int compositeLocSize = compSet.iterator().next().getSize();
1571 int compositeLocSize = maxFromCompSet.getSize();
1573 Set<String> glbInputSet = new HashSet<String>();
1574 Descriptor currentD = null;
1575 for (int i = 1; i < compositeLocSize; i++) {
1576 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1577 CompositeLocation compositeLocation = (CompositeLocation) iterator.next();
1578 if (compositeLocation.getSize() > i) {
1579 Location currentLoc = compositeLocation.get(i);
1580 currentD = currentLoc.getDescriptor();
1581 // making set of the current location sharing the same idx
1582 glbInputSet.add(currentLoc.getLocIdentifier());
1585 // calculate glb for the current lattice
1587 SSJavaLattice<String> currentLattice = getLatticeByDescriptor(currentD);
1588 String currentGLBLocId = currentLattice.getGLB(glbInputSet);
1589 glbCompLoc.addLocation(new Location(currentD, currentGLBLocId));
1592 // if input location corresponding to glb is a delta, need to apply
1593 // delta to glb result
1595 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1596 CompositeLocation compLoc = (CompositeLocation) iterator.next();
1597 if (compLoc instanceof DeltaLocation) {
1598 if (glbCompLoc.equals(compLoc)) {
1599 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1612 static SSJavaLattice<String> getLatticeByDescriptor(Descriptor d) {
1614 SSJavaLattice<String> lattice = null;
1616 if (d instanceof ClassDescriptor) {
1617 lattice = ssjava.getCd2lattice().get(d);
1618 } else if (d instanceof MethodDescriptor) {
1619 if (ssjava.getMd2lattice().containsKey(d)) {
1620 lattice = ssjava.getMd2lattice().get(d);
1622 // use default lattice for the method
1623 lattice = ssjava.getCd2methodDefault().get(((MethodDescriptor) d).getClassDesc());
1632 class ComparisonResult {
1634 public static final int GREATER = 0;
1635 public static final int EQUAL = 1;
1636 public static final int LESS = 2;
1637 public static final int INCOMPARABLE = 3;
1644 class ReturnLocGenerator {
1646 public static final int PARAMISHIGHER = 0;
1647 public static final int PARAMISSAME = 1;
1648 public static final int IGNORE = 2;
1650 Hashtable<Integer, Integer> paramIdx2paramType;
1652 public ReturnLocGenerator(CompositeLocation returnLoc, List<CompositeLocation> params, String msg) {
1653 // creating mappings
1654 paramIdx2paramType = new Hashtable<Integer, Integer>();
1655 for (int i = 0; i < params.size(); i++) {
1656 CompositeLocation param = params.get(i);
1657 int compareResult = CompositeLattice.compare(param, returnLoc, msg);
1660 if (compareResult == ComparisonResult.GREATER) {
1662 } else if (compareResult == ComparisonResult.EQUAL) {
1667 paramIdx2paramType.put(new Integer(i), new Integer(type));
1672 public CompositeLocation computeReturnLocation(List<CompositeLocation> args) {
1674 // compute the highest possible location in caller's side
1675 assert paramIdx2paramType.keySet().size() == args.size();
1677 Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
1678 for (int i = 0; i < args.size(); i++) {
1679 int type = (paramIdx2paramType.get(new Integer(i))).intValue();
1680 CompositeLocation argLoc = args.get(i);
1681 if (type == PARAMISHIGHER) {
1682 // return loc is lower than param
1683 DeltaLocation delta = new DeltaLocation(argLoc, 1);
1684 inputGLB.add(delta);
1685 } else if (type == PARAMISSAME) {
1686 // return loc is equal or lower than param
1687 inputGLB.add(argLoc);
1691 // compute GLB of arguments subset that are same or higher than return
1693 CompositeLocation glb = CompositeLattice.calculateGLB(inputGLB);