bug fixes
[IRC.git] / Robust / src / Analysis / SSJava / FlowDownCheck.java
1 package Analysis.SSJava;
2
3 import java.util.ArrayList;
4 import java.util.HashSet;
5 import java.util.Hashtable;
6 import java.util.Iterator;
7 import java.util.List;
8 import java.util.Set;
9 import java.util.StringTokenizer;
10 import java.util.Vector;
11
12 import Analysis.SSJava.FlowDownCheck.ComparisonResult;
13 import Analysis.SSJava.FlowDownCheck.CompositeLattice;
14 import IR.AnnotationDescriptor;
15 import IR.ClassDescriptor;
16 import IR.Descriptor;
17 import IR.FieldDescriptor;
18 import IR.MethodDescriptor;
19 import IR.NameDescriptor;
20 import IR.Operation;
21 import IR.State;
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;
36 import IR.Tree.Kind;
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.TertiaryNode;
45 import IR.Tree.TreeNode;
46 import Util.Pair;
47
48 public class FlowDownCheck {
49
50   State state;
51   static SSJavaAnalysis ssjava;
52
53   HashSet toanalyze;
54
55   // mapping from 'descriptor' to 'composite location'
56   Hashtable<Descriptor, CompositeLocation> d2loc;
57
58   Hashtable<MethodDescriptor, CompositeLocation> md2ReturnLoc;
59   Hashtable<MethodDescriptor, ReturnLocGenerator> md2ReturnLocGen;
60
61   // mapping from 'locID' to 'class descriptor'
62   Hashtable<String, ClassDescriptor> fieldLocName2cd;
63
64   public FlowDownCheck(SSJavaAnalysis ssjava, State state) {
65     this.ssjava = ssjava;
66     this.state = state;
67     this.toanalyze = new HashSet();
68     this.d2loc = new Hashtable<Descriptor, CompositeLocation>();
69     this.fieldLocName2cd = new Hashtable<String, ClassDescriptor>();
70     this.md2ReturnLoc = new Hashtable<MethodDescriptor, CompositeLocation>();
71     this.md2ReturnLocGen = new Hashtable<MethodDescriptor, ReturnLocGenerator>();
72   }
73
74   public void init() {
75
76     // construct mapping from the location name to the class descriptor
77     // assume that the location name is unique through the whole program
78
79     Set<ClassDescriptor> cdSet = ssjava.getCd2lattice().keySet();
80     for (Iterator iterator = cdSet.iterator(); iterator.hasNext();) {
81       ClassDescriptor cd = (ClassDescriptor) iterator.next();
82       SSJavaLattice<String> lattice = ssjava.getCd2lattice().get(cd);
83       Set<String> fieldLocNameSet = lattice.getKeySet();
84
85       for (Iterator iterator2 = fieldLocNameSet.iterator(); iterator2.hasNext();) {
86         String fieldLocName = (String) iterator2.next();
87         fieldLocName2cd.put(fieldLocName, cd);
88       }
89
90     }
91
92   }
93
94   public void flowDownCheck() {
95     SymbolTable classtable = state.getClassSymbolTable();
96
97     // phase 1 : checking declaration node and creating mapping of 'type
98     // desciptor' & 'location'
99     toanalyze.addAll(classtable.getValueSet());
100     toanalyze.addAll(state.getTaskSymbolTable().getValueSet());
101     while (!toanalyze.isEmpty()) {
102       Object obj = toanalyze.iterator().next();
103       ClassDescriptor cd = (ClassDescriptor) obj;
104       toanalyze.remove(cd);
105
106       if (!cd.isInterface()) {
107
108         ClassDescriptor superDesc = cd.getSuperDesc();
109         if (superDesc != null && (!superDesc.isInterface())
110             && (!superDesc.getSymbol().equals("Object"))) {
111           checkOrderingInheritance(superDesc, cd);
112         }
113
114         checkDeclarationInClass(cd);
115         for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
116           MethodDescriptor md = (MethodDescriptor) method_it.next();
117           if (ssjava.needTobeAnnotated(md)) {
118             checkDeclarationInMethodBody(cd, md);
119           }
120         }
121       }
122
123     }
124
125     // phase2 : checking assignments
126     toanalyze.addAll(classtable.getValueSet());
127     toanalyze.addAll(state.getTaskSymbolTable().getValueSet());
128     while (!toanalyze.isEmpty()) {
129       Object obj = toanalyze.iterator().next();
130       ClassDescriptor cd = (ClassDescriptor) obj;
131       toanalyze.remove(cd);
132
133       checkClass(cd);
134       for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
135         MethodDescriptor md = (MethodDescriptor) method_it.next();
136         if (ssjava.needTobeAnnotated(md)) {
137           checkMethodBody(cd, md);
138         }
139       }
140     }
141
142   }
143
144   private void checkOrderingInheritance(ClassDescriptor superCd, ClassDescriptor cd) {
145     // here, we're going to check that sub class keeps same relative orderings
146     // in respect to super class
147
148     SSJavaLattice<String> superLattice = ssjava.getClassLattice(superCd);
149     SSJavaLattice<String> subLattice = ssjava.getClassLattice(cd);
150
151     if (superLattice != null && subLattice == null) {
152       throw new Error("If a parent class '" + superCd + "' has a ordering lattice, its subclass '"
153           + cd + "' should have one.");
154     }
155
156     Set<Pair<String, String>> superPairSet = superLattice.getOrderingPairSet();
157     Set<Pair<String, String>> subPairSet = subLattice.getOrderingPairSet();
158
159     for (Iterator iterator = superPairSet.iterator(); iterator.hasNext();) {
160       Pair<String, String> pair = (Pair<String, String>) iterator.next();
161
162       if (!subPairSet.contains(pair)) {
163         throw new Error("Subclass '" + cd + "' does not have the relative ordering '"
164             + pair.getSecond() + " < " + pair.getFirst() + "' that is defined by its superclass '"
165             + superCd + "'.");
166       }
167     }
168
169   }
170
171   public Hashtable getMap() {
172     return d2loc;
173   }
174
175   private void checkDeclarationInMethodBody(ClassDescriptor cd, MethodDescriptor md) {
176     BlockNode bn = state.getMethodBody(md);
177
178     // parsing returnloc annotation
179     if (ssjava.needTobeAnnotated(md)) {
180
181       Vector<AnnotationDescriptor> methodAnnotations = md.getModifiers().getAnnotations();
182       if (methodAnnotations != null) {
183         for (int i = 0; i < methodAnnotations.size(); i++) {
184           AnnotationDescriptor an = methodAnnotations.elementAt(i);
185           if (an.getMarker().equals(ssjava.RETURNLOC)) {
186             // developer explicitly defines method lattice
187             String returnLocDeclaration = an.getValue();
188             CompositeLocation returnLocComp =
189                 parseLocationDeclaration(md, null, returnLocDeclaration);
190             md2ReturnLoc.put(md, returnLocComp);
191           }
192         }
193
194         if (!md.getReturnType().isVoid() && !md2ReturnLoc.containsKey(md)) {
195           throw new Error("Return location is not specified for the method " + md + " at "
196               + cd.getSourceFileName());
197         }
198
199       }
200     }
201
202     List<CompositeLocation> paramList = new ArrayList<CompositeLocation>();
203
204     boolean hasReturnValue = (!md.getReturnType().isVoid());
205     if (hasReturnValue) {
206       MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
207       String thisLocId = methodLattice.getThisLoc();
208       CompositeLocation thisLoc = new CompositeLocation(new Location(md, thisLocId));
209       paramList.add(thisLoc);
210     }
211
212     for (int i = 0; i < md.numParameters(); i++) {
213       // process annotations on method parameters
214       VarDescriptor vd = (VarDescriptor) md.getParameter(i);
215       assignLocationOfVarDescriptor(vd, md, md.getParameterTable(), bn);
216       if (hasReturnValue) {
217         paramList.add(d2loc.get(vd));
218       }
219     }
220
221     if (hasReturnValue) {
222       md2ReturnLocGen.put(md, new ReturnLocGenerator(md2ReturnLoc.get(md), paramList));
223     }
224
225     checkDeclarationInBlockNode(md, md.getParameterTable(), bn);
226   }
227
228   private void checkDeclarationInBlockNode(MethodDescriptor md, SymbolTable nametable, BlockNode bn) {
229     bn.getVarTable().setParent(nametable);
230     for (int i = 0; i < bn.size(); i++) {
231       BlockStatementNode bsn = bn.get(i);
232       checkDeclarationInBlockStatementNode(md, bn.getVarTable(), bsn);
233     }
234   }
235
236   private void checkDeclarationInBlockStatementNode(MethodDescriptor md, SymbolTable nametable,
237       BlockStatementNode bsn) {
238
239     switch (bsn.kind()) {
240     case Kind.SubBlockNode:
241       checkDeclarationInSubBlockNode(md, nametable, (SubBlockNode) bsn);
242       return;
243
244     case Kind.DeclarationNode:
245       checkDeclarationNode(md, nametable, (DeclarationNode) bsn);
246       break;
247
248     case Kind.LoopNode:
249       checkDeclarationInLoopNode(md, nametable, (LoopNode) bsn);
250       break;
251     }
252   }
253
254   private void checkDeclarationInLoopNode(MethodDescriptor md, SymbolTable nametable, LoopNode ln) {
255
256     if (ln.getType() == LoopNode.FORLOOP) {
257       // check for loop case
258       ClassDescriptor cd = md.getClassDesc();
259       BlockNode bn = ln.getInitializer();
260       for (int i = 0; i < bn.size(); i++) {
261         BlockStatementNode bsn = bn.get(i);
262         checkDeclarationInBlockStatementNode(md, nametable, bsn);
263       }
264     }
265
266     // check loop body
267     checkDeclarationInBlockNode(md, nametable, ln.getBody());
268   }
269
270   private void checkMethodBody(ClassDescriptor cd, MethodDescriptor md) {
271     BlockNode bn = state.getMethodBody(md);
272     checkLocationFromBlockNode(md, md.getParameterTable(), bn);
273   }
274
275   private CompositeLocation checkLocationFromBlockNode(MethodDescriptor md, SymbolTable nametable,
276       BlockNode bn) {
277
278     bn.getVarTable().setParent(nametable);
279     // it will return the lowest location in the block node
280     CompositeLocation lowestLoc = null;
281
282     for (int i = 0; i < bn.size(); i++) {
283       BlockStatementNode bsn = bn.get(i);
284       CompositeLocation bLoc = checkLocationFromBlockStatementNode(md, bn.getVarTable(), bsn);
285       if (!bLoc.isEmpty()) {
286         if (lowestLoc == null) {
287           lowestLoc = bLoc;
288         } else {
289           if (CompositeLattice.isGreaterThan(lowestLoc, bLoc)) {
290             lowestLoc = bLoc;
291           }
292         }
293       }
294
295     }
296
297     if (lowestLoc == null) {
298       lowestLoc = new CompositeLocation(Location.createBottomLocation(md));
299     }
300
301     return lowestLoc;
302   }
303
304   private CompositeLocation checkLocationFromBlockStatementNode(MethodDescriptor md,
305       SymbolTable nametable, BlockStatementNode bsn) {
306
307     CompositeLocation compLoc = null;
308     switch (bsn.kind()) {
309     case Kind.BlockExpressionNode:
310       compLoc = checkLocationFromBlockExpressionNode(md, nametable, (BlockExpressionNode) bsn);
311       break;
312
313     case Kind.DeclarationNode:
314       compLoc = checkLocationFromDeclarationNode(md, nametable, (DeclarationNode) bsn);
315       break;
316
317     case Kind.IfStatementNode:
318       compLoc = checkLocationFromIfStatementNode(md, nametable, (IfStatementNode) bsn);
319       break;
320
321     case Kind.LoopNode:
322       compLoc = checkLocationFromLoopNode(md, nametable, (LoopNode) bsn);
323       break;
324
325     case Kind.ReturnNode:
326       compLoc = checkLocationFromReturnNode(md, nametable, (ReturnNode) bsn);
327       break;
328
329     case Kind.SubBlockNode:
330       compLoc = checkLocationFromSubBlockNode(md, nametable, (SubBlockNode) bsn);
331       break;
332
333     case Kind.ContinueBreakNode:
334       compLoc = new CompositeLocation();
335       break;
336
337     }
338     return compLoc;
339   }
340
341   private CompositeLocation checkLocationFromReturnNode(MethodDescriptor md, SymbolTable nametable,
342       ReturnNode rn) {
343
344     ExpressionNode returnExp = rn.getReturnExpression();
345
346     CompositeLocation expLoc;
347     if (returnExp != null) {
348       expLoc = checkLocationFromExpressionNode(md, nametable, returnExp, new CompositeLocation());
349       // check if return value is equal or higher than RETRUNLOC of method
350       // declaration annotation
351       CompositeLocation returnLocAt = md2ReturnLoc.get(md);
352
353       if (CompositeLattice.isGreaterThan(returnLocAt, expLoc)) {
354         throw new Error(
355             "Return value location is not equal or higher than the declaraed return location at "
356                 + md.getClassDesc().getSourceFileName() + "::" + rn.getNumLine());
357       }
358     }
359
360     return new CompositeLocation();
361   }
362
363   private boolean hasOnlyLiteralValue(ExpressionNode en) {
364     if (en.kind() == Kind.LiteralNode) {
365       return true;
366     } else {
367       return false;
368     }
369   }
370
371   private CompositeLocation checkLocationFromLoopNode(MethodDescriptor md, SymbolTable nametable,
372       LoopNode ln) {
373
374     ClassDescriptor cd = md.getClassDesc();
375     if (ln.getType() == LoopNode.WHILELOOP || ln.getType() == LoopNode.DOWHILELOOP) {
376
377       CompositeLocation condLoc =
378           checkLocationFromExpressionNode(md, nametable, ln.getCondition(), new CompositeLocation());
379       addTypeLocation(ln.getCondition().getType(), (condLoc));
380
381       CompositeLocation bodyLoc = checkLocationFromBlockNode(md, nametable, ln.getBody());
382
383       if (!CompositeLattice.isGreaterThan(condLoc, bodyLoc)) {
384         // loop condition should be higher than loop body
385         throw new Error(
386             "The location of the while-condition statement is lower than the loop body at "
387                 + cd.getSourceFileName() + ":" + ln.getCondition().getNumLine());
388       }
389
390       return bodyLoc;
391
392     } else {
393       // check for loop case
394       BlockNode bn = ln.getInitializer();
395       bn.getVarTable().setParent(nametable);
396
397       // calculate glb location of condition and update statements
398       CompositeLocation condLoc =
399           checkLocationFromExpressionNode(md, bn.getVarTable(), ln.getCondition(),
400               new CompositeLocation());
401       addTypeLocation(ln.getCondition().getType(), condLoc);
402
403       CompositeLocation updateLoc =
404           checkLocationFromBlockNode(md, bn.getVarTable(), ln.getUpdate());
405
406       Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
407       glbInputSet.add(condLoc);
408       glbInputSet.add(updateLoc);
409
410       CompositeLocation glbLocOfForLoopCond = CompositeLattice.calculateGLB(glbInputSet);
411
412       // check location of 'forloop' body
413       CompositeLocation blockLoc = checkLocationFromBlockNode(md, bn.getVarTable(), ln.getBody());
414
415       if (blockLoc == null) {
416         // when there is no statement in the loop body
417         return glbLocOfForLoopCond;
418       }
419
420       if (!CompositeLattice.isGreaterThan(glbLocOfForLoopCond, blockLoc)) {
421         throw new Error(
422             "The location of the for-condition statement is lower than the for-loop body at "
423                 + cd.getSourceFileName() + ":" + ln.getCondition().getNumLine());
424       }
425       return blockLoc;
426     }
427
428   }
429
430   private CompositeLocation checkLocationFromSubBlockNode(MethodDescriptor md,
431       SymbolTable nametable, SubBlockNode sbn) {
432     CompositeLocation compLoc = checkLocationFromBlockNode(md, nametable, sbn.getBlockNode());
433     return compLoc;
434   }
435
436   private CompositeLocation checkLocationFromIfStatementNode(MethodDescriptor md,
437       SymbolTable nametable, IfStatementNode isn) {
438
439     ClassDescriptor localCD = md.getClassDesc();
440     Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
441
442     CompositeLocation condLoc =
443         checkLocationFromExpressionNode(md, nametable, isn.getCondition(), new CompositeLocation());
444
445     addTypeLocation(isn.getCondition().getType(), condLoc);
446     glbInputSet.add(condLoc);
447
448     CompositeLocation locTrueBlock = checkLocationFromBlockNode(md, nametable, isn.getTrueBlock());
449     if (locTrueBlock != null) {
450       glbInputSet.add(locTrueBlock);
451       // here, the location of conditional block should be higher than the
452       // location of true/false blocks
453       if (locTrueBlock != null && !CompositeLattice.isGreaterThan(condLoc, locTrueBlock)) {
454         // error
455         throw new Error(
456             "The location of the if-condition statement is lower than the conditional block at "
457                 + localCD.getSourceFileName() + ":" + isn.getCondition().getNumLine());
458       }
459     }
460
461     if (isn.getFalseBlock() != null) {
462       CompositeLocation locFalseBlock =
463           checkLocationFromBlockNode(md, nametable, isn.getFalseBlock());
464
465       if (locFalseBlock != null) {
466         glbInputSet.add(locFalseBlock);
467
468         if (!CompositeLattice.isGreaterThan(condLoc, locFalseBlock)) {
469           // error
470           throw new Error(
471               "The location of the if-condition statement is lower than the conditional block at "
472                   + localCD.getSourceFileName() + ":" + isn.getCondition().getNumLine());
473         }
474       }
475
476     }
477
478     // return GLB location of condition, true, and false block
479     CompositeLocation glbLoc = CompositeLattice.calculateGLB(glbInputSet);
480
481     return glbLoc;
482   }
483
484   private CompositeLocation checkLocationFromDeclarationNode(MethodDescriptor md,
485       SymbolTable nametable, DeclarationNode dn) {
486
487     VarDescriptor vd = dn.getVarDescriptor();
488
489     CompositeLocation destLoc = d2loc.get(vd);
490
491     if (dn.getExpression() != null) {
492       CompositeLocation expressionLoc =
493           checkLocationFromExpressionNode(md, nametable, dn.getExpression(),
494               new CompositeLocation());
495       // addTypeLocation(dn.getExpression().getType(), expressionLoc);
496
497       if (expressionLoc != null) {
498         // checking location order
499         if (!CompositeLattice.isGreaterThan(expressionLoc, destLoc)) {
500           throw new Error("The value flow from " + expressionLoc + " to " + destLoc
501               + " does not respect location hierarchy on the assignment " + dn.printNode(0)
502               + " at " + md.getClassDesc().getSourceFileName() + "::" + dn.getNumLine());
503         }
504       }
505       return expressionLoc;
506
507     } else {
508
509       return new CompositeLocation();
510
511     }
512
513   }
514
515   private void checkDeclarationInSubBlockNode(MethodDescriptor md, SymbolTable nametable,
516       SubBlockNode sbn) {
517     checkDeclarationInBlockNode(md, nametable.getParent(), sbn.getBlockNode());
518   }
519
520   private CompositeLocation checkLocationFromBlockExpressionNode(MethodDescriptor md,
521       SymbolTable nametable, BlockExpressionNode ben) {
522     CompositeLocation compLoc =
523         checkLocationFromExpressionNode(md, nametable, ben.getExpression(), null);
524     // addTypeLocation(ben.getExpression().getType(), compLoc);
525     return compLoc;
526   }
527
528   private CompositeLocation checkLocationFromExpressionNode(MethodDescriptor md,
529       SymbolTable nametable, ExpressionNode en, CompositeLocation loc) {
530
531     CompositeLocation compLoc = null;
532     switch (en.kind()) {
533
534     case Kind.AssignmentNode:
535       compLoc = checkLocationFromAssignmentNode(md, nametable, (AssignmentNode) en, loc);
536       break;
537
538     case Kind.FieldAccessNode:
539       compLoc = checkLocationFromFieldAccessNode(md, nametable, (FieldAccessNode) en, loc);
540       break;
541
542     case Kind.NameNode:
543       compLoc = checkLocationFromNameNode(md, nametable, (NameNode) en, loc);
544       break;
545
546     case Kind.OpNode:
547       compLoc = checkLocationFromOpNode(md, nametable, (OpNode) en);
548       break;
549
550     case Kind.CreateObjectNode:
551       compLoc = checkLocationFromCreateObjectNode(md, nametable, (CreateObjectNode) en);
552       break;
553
554     case Kind.ArrayAccessNode:
555       compLoc = checkLocationFromArrayAccessNode(md, nametable, (ArrayAccessNode) en);
556       break;
557
558     case Kind.LiteralNode:
559       compLoc = checkLocationFromLiteralNode(md, nametable, (LiteralNode) en, loc);
560       break;
561
562     case Kind.MethodInvokeNode:
563       compLoc = checkLocationFromMethodInvokeNode(md, nametable, (MethodInvokeNode) en, loc);
564       break;
565
566     case Kind.TertiaryNode:
567       compLoc = checkLocationFromTertiaryNode(md, nametable, (TertiaryNode) en);
568       break;
569
570     case Kind.CastNode:
571       compLoc = checkLocationFromCastNode(md, nametable, (CastNode) en);
572       break;
573
574     // case Kind.InstanceOfNode:
575     // checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
576     // return null;
577
578     // case Kind.ArrayInitializerNode:
579     // checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en,
580     // td);
581     // return null;
582
583     // case Kind.ClassTypeNode:
584     // checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
585     // return null;
586
587     // case Kind.OffsetNode:
588     // checkOffsetNode(md, nametable, (OffsetNode)en, td);
589     // return null;
590
591     default:
592       return null;
593
594     }
595     // addTypeLocation(en.getType(), compLoc);
596     return compLoc;
597
598   }
599
600   private CompositeLocation checkLocationFromCastNode(MethodDescriptor md, SymbolTable nametable,
601       CastNode cn) {
602
603     ExpressionNode en = cn.getExpression();
604     return checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation());
605
606   }
607
608   private CompositeLocation checkLocationFromTertiaryNode(MethodDescriptor md,
609       SymbolTable nametable, TertiaryNode tn) {
610     ClassDescriptor cd = md.getClassDesc();
611
612     CompositeLocation condLoc =
613         checkLocationFromExpressionNode(md, nametable, tn.getCond(), new CompositeLocation());
614     addTypeLocation(tn.getCond().getType(), condLoc);
615     CompositeLocation trueLoc =
616         checkLocationFromExpressionNode(md, nametable, tn.getTrueExpr(), new CompositeLocation());
617     addTypeLocation(tn.getTrueExpr().getType(), trueLoc);
618     CompositeLocation falseLoc =
619         checkLocationFromExpressionNode(md, nametable, tn.getFalseExpr(), new CompositeLocation());
620     addTypeLocation(tn.getFalseExpr().getType(), falseLoc);
621
622     // check if condLoc is higher than trueLoc & falseLoc
623     if (!CompositeLattice.isGreaterThan(condLoc, trueLoc)) {
624       throw new Error(
625           "The location of the condition expression is lower than the true expression at "
626               + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
627     }
628
629     if (!CompositeLattice.isGreaterThan(condLoc, falseLoc)) {
630       throw new Error(
631           "The location of the condition expression is lower than the true expression at "
632               + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
633     }
634
635     // then, return glb of trueLoc & falseLoc
636     Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
637     glbInputSet.add(trueLoc);
638     glbInputSet.add(falseLoc);
639
640     return CompositeLattice.calculateGLB(glbInputSet);
641   }
642
643   private CompositeLocation checkLocationFromMethodInvokeNode(MethodDescriptor md,
644       SymbolTable nametable, MethodInvokeNode min, CompositeLocation loc) {
645
646     checkCalleeConstraints(md, nametable, min);
647
648     CompositeLocation baseLocation = null;
649     if (min.getExpression() != null) {
650       baseLocation =
651           checkLocationFromExpressionNode(md, nametable, min.getExpression(),
652               new CompositeLocation());
653     } else {
654       String thisLocId = ssjava.getMethodLattice(md).getThisLoc();
655       baseLocation = new CompositeLocation(new Location(md, thisLocId));
656     }
657
658     if (!min.getMethod().getReturnType().isVoid()) {
659       // If method has a return value, compute the highest possible return
660       // location in the caller's perspective
661       CompositeLocation ceilingLoc =
662           computeCeilingLocationForCaller(md, nametable, min, baseLocation);
663       return ceilingLoc;
664     }
665
666     return new CompositeLocation();
667
668   }
669
670   private CompositeLocation computeCeilingLocationForCaller(MethodDescriptor md,
671       SymbolTable nametable, MethodInvokeNode min, CompositeLocation baseLocation) {
672     List<CompositeLocation> argList = new ArrayList<CompositeLocation>();
673
674     // by default, method has a THIS parameter
675     argList.add(baseLocation);
676
677     for (int i = 0; i < min.numArgs(); i++) {
678       ExpressionNode en = min.getArg(i);
679       CompositeLocation callerArg =
680           checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation());
681       argList.add(callerArg);
682     }
683
684     return md2ReturnLocGen.get(min.getMethod()).computeReturnLocation(argList);
685
686   }
687
688   private void checkCalleeConstraints(MethodDescriptor md, SymbolTable nametable,
689       MethodInvokeNode min) {
690
691     if (min.numArgs() > 1) {
692       // caller needs to guarantee that it passes arguments in regarding to
693       // callee's hierarchy
694       for (int i = 0; i < min.numArgs(); i++) {
695         ExpressionNode en = min.getArg(i);
696         CompositeLocation callerArg1 =
697             checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation());
698
699         ClassDescriptor calleecd = min.getMethod().getClassDesc();
700         VarDescriptor calleevd = (VarDescriptor) min.getMethod().getParameter(i);
701         CompositeLocation calleeLoc1 = d2loc.get(calleevd);
702
703         if (!callerArg1.get(0).isTop()) {
704           // here, check if ordering relations among caller's args respect
705           // ordering relations in-between callee's args
706           for (int currentIdx = 0; currentIdx < min.numArgs(); currentIdx++) {
707             if (currentIdx != i) { // skip itself
708               ExpressionNode argExp = min.getArg(currentIdx);
709
710               CompositeLocation callerArg2 =
711                   checkLocationFromExpressionNode(md, nametable, argExp, new CompositeLocation());
712
713               VarDescriptor calleevd2 = (VarDescriptor) min.getMethod().getParameter(currentIdx);
714               CompositeLocation calleeLoc2 = d2loc.get(calleevd2);
715
716               int callerResult = CompositeLattice.compare(callerArg1, callerArg2);
717               int calleeResult = CompositeLattice.compare(calleeLoc1, calleeLoc2);
718               if (calleeResult == ComparisonResult.GREATER
719                   && callerResult != ComparisonResult.GREATER) {
720                 // If calleeLoc1 is higher than calleeLoc2
721                 // then, caller should have same ordering relation in-bet
722                 // callerLoc1 & callerLoc2
723
724                 throw new Error("Caller doesn't respect ordering relations among method arguments:"
725                     + md.getClassDesc().getSourceFileName() + ":" + min.getNumLine());
726               }
727
728             }
729           }
730         }
731
732       }
733
734     }
735
736   }
737
738   private CompositeLocation checkLocationFromArrayAccessNode(MethodDescriptor md,
739       SymbolTable nametable, ArrayAccessNode aan) {
740
741     // return glb location of array itself and index
742
743     ClassDescriptor cd = md.getClassDesc();
744
745     Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
746
747     CompositeLocation arrayLoc =
748         checkLocationFromExpressionNode(md, nametable, aan.getExpression(), new CompositeLocation());
749     // addTypeLocation(aan.getExpression().getType(), arrayLoc);
750     glbInputSet.add(arrayLoc);
751     CompositeLocation indexLoc =
752         checkLocationFromExpressionNode(md, nametable, aan.getIndex(), new CompositeLocation());
753     glbInputSet.add(indexLoc);
754     // addTypeLocation(aan.getIndex().getType(), indexLoc);
755
756     CompositeLocation glbLoc = CompositeLattice.calculateGLB(glbInputSet);
757     return glbLoc;
758   }
759
760   private CompositeLocation checkLocationFromCreateObjectNode(MethodDescriptor md,
761       SymbolTable nametable, CreateObjectNode con) {
762
763     ClassDescriptor cd = md.getClassDesc();
764
765     // check arguments
766     Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
767     for (int i = 0; i < con.numArgs(); i++) {
768       ExpressionNode en = con.getArg(i);
769       CompositeLocation argLoc =
770           checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation());
771       glbInputSet.add(argLoc);
772       addTypeLocation(en.getType(), argLoc);
773     }
774
775     // check array initializers
776     // if ((con.getArrayInitializer() != null)) {
777     // checkLocationFromArrayInitializerNode(md, nametable,
778     // con.getArrayInitializer());
779     // }
780
781     if (glbInputSet.size() > 0) {
782       return CompositeLattice.calculateGLB(glbInputSet);
783     }
784
785     CompositeLocation compLoc = new CompositeLocation();
786     compLoc.addLocation(Location.createTopLocation(md));
787     return compLoc;
788
789   }
790
791   private CompositeLocation checkLocationFromOpNode(MethodDescriptor md, SymbolTable nametable,
792       OpNode on) {
793
794     ClassDescriptor cd = md.getClassDesc();
795     CompositeLocation leftLoc = new CompositeLocation();
796     leftLoc = checkLocationFromExpressionNode(md, nametable, on.getLeft(), leftLoc);
797     // addTypeLocation(on.getLeft().getType(), leftLoc);
798
799     CompositeLocation rightLoc = new CompositeLocation();
800     if (on.getRight() != null) {
801       rightLoc = checkLocationFromExpressionNode(md, nametable, on.getRight(), rightLoc);
802       // addTypeLocation(on.getRight().getType(), rightLoc);
803     }
804
805     // System.out.println("checking op node=" + on.printNode(0));
806     // System.out.println("left loc=" + leftLoc + " from " +
807     // on.getLeft().getClass());
808     // System.out.println("right loc=" + rightLoc + " from " +
809     // on.getRight().getClass());
810
811     Operation op = on.getOp();
812
813     switch (op.getOp()) {
814
815     case Operation.UNARYPLUS:
816     case Operation.UNARYMINUS:
817     case Operation.LOGIC_NOT:
818       // single operand
819       return leftLoc;
820
821     case Operation.LOGIC_OR:
822     case Operation.LOGIC_AND:
823     case Operation.COMP:
824     case Operation.BIT_OR:
825     case Operation.BIT_XOR:
826     case Operation.BIT_AND:
827     case Operation.ISAVAILABLE:
828     case Operation.EQUAL:
829     case Operation.NOTEQUAL:
830     case Operation.LT:
831     case Operation.GT:
832     case Operation.LTE:
833     case Operation.GTE:
834     case Operation.ADD:
835     case Operation.SUB:
836     case Operation.MULT:
837     case Operation.DIV:
838     case Operation.MOD:
839     case Operation.LEFTSHIFT:
840     case Operation.RIGHTSHIFT:
841     case Operation.URIGHTSHIFT:
842
843       Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
844       inputSet.add(leftLoc);
845       inputSet.add(rightLoc);
846       CompositeLocation glbCompLoc = CompositeLattice.calculateGLB(inputSet);
847       return glbCompLoc;
848
849     default:
850       throw new Error(op.toString());
851     }
852
853   }
854
855   private CompositeLocation checkLocationFromLiteralNode(MethodDescriptor md,
856       SymbolTable nametable, LiteralNode en, CompositeLocation loc) {
857
858     // literal value has the top location so that value can be flowed into any
859     // location
860     Location literalLoc = Location.createTopLocation(md);
861     loc.addLocation(literalLoc);
862     return loc;
863
864   }
865
866   private CompositeLocation checkLocationFromNameNode(MethodDescriptor md, SymbolTable nametable,
867       NameNode nn, CompositeLocation loc) {
868
869     NameDescriptor nd = nn.getName();
870     if (nd.getBase() != null) {
871
872       loc = checkLocationFromExpressionNode(md, nametable, nn.getExpression(), loc);
873       // addTypeLocation(nn.getExpression().getType(), loc);
874     } else {
875       String varname = nd.toString();
876
877       if (varname.equals("this")) {
878         // 'this' itself!
879         MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
880         String thisLocId = methodLattice.getThisLoc();
881         if (thisLocId == null) {
882           throw new Error("The location for 'this' is not defined at "
883               + md.getClassDesc().getSourceFileName() + "::" + nn.getNumLine());
884         }
885         Location locElement = new Location(md, thisLocId);
886         loc.addLocation(locElement);
887         return loc;
888       }
889       Descriptor d = (Descriptor) nametable.get(varname);
890
891       // CompositeLocation localLoc = null;
892       if (d instanceof VarDescriptor) {
893         VarDescriptor vd = (VarDescriptor) d;
894         // localLoc = d2loc.get(vd);
895         // the type of var descriptor has a composite location!
896         loc = ((CompositeLocation) vd.getType().getExtension()).clone();
897       } else if (d instanceof FieldDescriptor) {
898         // the type of field descriptor has a location!
899         FieldDescriptor fd = (FieldDescriptor) d;
900
901         if (fd.isStatic()) {
902           if (fd.isFinal()) {
903             // if it is 'static final', the location has TOP since no one can
904             // change its value
905             loc.addLocation(Location.createTopLocation(md));
906           } else {
907             // if 'static', the location has pre-assigned global loc
908             MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
909             String globalLocId = localLattice.getGlobalLoc();
910             if (globalLocId == null) {
911               throw new Error("Global location element is not defined in the method " + md);
912             }
913             Location globalLoc = new Location(md, globalLocId);
914
915             loc.addLocation(globalLoc);
916           }
917         } else {
918           // the location of field access starts from this, followed by field
919           // location
920           MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
921           Location thisLoc = new Location(md, localLattice.getThisLoc());
922           loc.addLocation(thisLoc);
923         }
924
925         Location fieldLoc = (Location) fd.getType().getExtension();
926         loc.addLocation(fieldLoc);
927       }
928     }
929     return loc;
930   }
931
932   private CompositeLocation checkLocationFromFieldAccessNode(MethodDescriptor md,
933       SymbolTable nametable, FieldAccessNode fan, CompositeLocation loc) {
934
935     ExpressionNode left = fan.getExpression();
936     loc = checkLocationFromExpressionNode(md, nametable, left, loc);
937     // addTypeLocation(left.getType(), loc);
938
939     if (!left.getType().isPrimitive()) {
940       FieldDescriptor fd = fan.getField();
941       Location fieldLoc = (Location) fd.getType().getExtension();
942       loc.addLocation(fieldLoc);
943     }
944
945     return loc;
946   }
947
948   private CompositeLocation checkLocationFromAssignmentNode(MethodDescriptor md,
949       SymbolTable nametable, AssignmentNode an, CompositeLocation loc) {
950
951     ClassDescriptor cd = md.getClassDesc();
952
953     boolean postinc = true;
954     if (an.getOperation().getBaseOp() == null
955         || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
956             .getBaseOp().getOp() != Operation.POSTDEC))
957       postinc = false;
958
959     CompositeLocation destLocation =
960         checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation());
961
962     CompositeLocation srcLocation = new CompositeLocation();
963
964     if (!postinc) {
965       if (hasOnlyLiteralValue(an.getSrc())) {
966         // if source is literal value, src location is TOP. so do not need to
967         // compare!
968         return destLocation;
969       }
970       srcLocation = new CompositeLocation();
971       srcLocation = checkLocationFromExpressionNode(md, nametable, an.getSrc(), srcLocation);
972       // System.out.println(" an= " + an.printNode(0) + " an.getSrc()=" +
973       // an.getSrc().getClass()
974       // + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
975       // System.out.println("srcLocation=" + srcLocation);
976       // System.out.println("dstLocation=" + destLocation);
977       if (!CompositeLattice.isGreaterThan(srcLocation, destLocation)) {
978         throw new Error("The value flow from " + srcLocation + " to " + destLocation
979             + " does not respect location hierarchy on the assignment " + an.printNode(0) + " at "
980             + cd.getSourceFileName() + "::" + an.getNumLine());
981       }
982     } else {
983       destLocation =
984           srcLocation = checkLocationFromExpressionNode(md, nametable, an.getDest(), srcLocation);
985
986       if (!CompositeLattice.isGreaterThan(srcLocation, destLocation)) {
987         throw new Error("Location " + destLocation
988             + " is not allowed to have the value flow that moves within the same location at "
989             + cd.getSourceFileName() + "::" + an.getNumLine());
990       }
991
992     }
993
994     return destLocation;
995   }
996
997   private void assignLocationOfVarDescriptor(VarDescriptor vd, MethodDescriptor md,
998       SymbolTable nametable, TreeNode n) {
999
1000     ClassDescriptor cd = md.getClassDesc();
1001     Vector<AnnotationDescriptor> annotationVec = vd.getType().getAnnotationMarkers();
1002
1003     // currently enforce every variable to have corresponding location
1004     if (annotationVec.size() == 0) {
1005       throw new Error("Location is not assigned to variable " + vd.getSymbol() + " in the method "
1006           + md.getSymbol() + " of the class " + cd.getSymbol());
1007     }
1008
1009     if (annotationVec.size() > 1) { // variable can have at most one location
1010       throw new Error(vd.getSymbol() + " has more than one location.");
1011     }
1012
1013     AnnotationDescriptor ad = annotationVec.elementAt(0);
1014
1015     if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1016
1017       if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1018         String locDec = ad.getValue(); // check if location is defined
1019
1020         if (locDec.startsWith(SSJavaAnalysis.DELTA)) {
1021           DeltaLocation deltaLoc = parseDeltaDeclaration(md, n, locDec);
1022           d2loc.put(vd, deltaLoc);
1023           addTypeLocation(vd.getType(), deltaLoc);
1024         } else {
1025           CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1026           d2loc.put(vd, compLoc);
1027           addTypeLocation(vd.getType(), compLoc);
1028         }
1029
1030       }
1031     }
1032
1033   }
1034
1035   private DeltaLocation parseDeltaDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1036
1037     int deltaCount = 0;
1038     int dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1039     while (dIdx >= 0) {
1040       deltaCount++;
1041       int beginIdx = dIdx + 6;
1042       locDec = locDec.substring(beginIdx, locDec.length() - 1);
1043       dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1044     }
1045
1046     CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1047     DeltaLocation deltaLoc = new DeltaLocation(compLoc, deltaCount);
1048
1049     return deltaLoc;
1050   }
1051
1052   private Location parseFieldLocDeclaraton(String decl) {
1053
1054     int idx = decl.indexOf(".");
1055     String className = decl.substring(0, idx);
1056     String fieldName = decl.substring(idx + 1);
1057
1058     Descriptor d = state.getClassSymbolTable().get(className);
1059
1060     assert (d instanceof ClassDescriptor);
1061     SSJavaLattice<String> lattice = ssjava.getClassLattice((ClassDescriptor) d);
1062     if (!lattice.containsKey(fieldName)) {
1063       throw new Error("The location " + fieldName + " is not defined in the field lattice of '"
1064           + className + "'.");
1065     }
1066
1067     return new Location(d, fieldName);
1068   }
1069
1070   private CompositeLocation parseLocationDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1071
1072     CompositeLocation compLoc = new CompositeLocation();
1073
1074     StringTokenizer tokenizer = new StringTokenizer(locDec, ",");
1075     List<String> locIdList = new ArrayList<String>();
1076     while (tokenizer.hasMoreTokens()) {
1077       String locId = tokenizer.nextToken();
1078       locIdList.add(locId);
1079     }
1080
1081     // at least,one location element needs to be here!
1082     assert (locIdList.size() > 0);
1083
1084     // assume that loc with idx 0 comes from the local lattice
1085     // loc with idx 1 comes from the field lattice
1086
1087     String localLocId = locIdList.get(0);
1088     SSJavaLattice<String> localLattice = CompositeLattice.getLatticeByDescriptor(md);
1089     Location localLoc = new Location(md, localLocId);
1090     if (localLattice == null || (!localLattice.containsKey(localLocId))) {
1091       throw new Error("Location " + localLocId
1092           + " is not defined in the local variable lattice at "
1093           + md.getClassDesc().getSourceFileName() + "::" + (n != null ? n.getNumLine() : "") + ".");
1094     }
1095     compLoc.addLocation(localLoc);
1096
1097     for (int i = 1; i < locIdList.size(); i++) {
1098       String locName = locIdList.get(i);
1099
1100       Location fieldLoc = parseFieldLocDeclaraton(locName);
1101       // ClassDescriptor cd = fieldLocName2cd.get(locName);
1102       // SSJavaLattice<String> fieldLattice =
1103       // CompositeLattice.getLatticeByDescriptor(cd);
1104       //
1105       // if (fieldLattice == null || (!fieldLattice.containsKey(locName))) {
1106       // throw new Error("Location " + locName +
1107       // " is not defined in the field lattice at "
1108       // + cd.getSourceFileName() + ".");
1109       // }
1110       // Location fieldLoc = new Location(cd, locName);
1111       compLoc.addLocation(fieldLoc);
1112     }
1113
1114     return compLoc;
1115
1116   }
1117
1118   private void checkDeclarationNode(MethodDescriptor md, SymbolTable nametable, DeclarationNode dn) {
1119     VarDescriptor vd = dn.getVarDescriptor();
1120     assignLocationOfVarDescriptor(vd, md, nametable, dn);
1121   }
1122
1123   private void checkClass(ClassDescriptor cd) {
1124     // Check to see that methods respects ss property
1125     for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
1126       MethodDescriptor md = (MethodDescriptor) method_it.next();
1127       checkMethodDeclaration(cd, md);
1128     }
1129   }
1130
1131   private void checkDeclarationInClass(ClassDescriptor cd) {
1132     // Check to see that fields are okay
1133     for (Iterator field_it = cd.getFields(); field_it.hasNext();) {
1134       FieldDescriptor fd = (FieldDescriptor) field_it.next();
1135       checkFieldDeclaration(cd, fd);
1136     }
1137   }
1138
1139   private void checkMethodDeclaration(ClassDescriptor cd, MethodDescriptor md) {
1140     // TODO
1141   }
1142
1143   private void checkFieldDeclaration(ClassDescriptor cd, FieldDescriptor fd) {
1144
1145     Vector<AnnotationDescriptor> annotationVec = fd.getType().getAnnotationMarkers();
1146
1147     // currently enforce every field to have corresponding location
1148     if (annotationVec.size() == 0) {
1149       throw new Error("Location is not assigned to the field '" + fd.getSymbol()
1150           + "' of the class " + cd.getSymbol() + " at " + cd.getSourceFileName());
1151     }
1152
1153     if (annotationVec.size() > 1) {
1154       // variable can have at most one location
1155       throw new Error("Field " + fd.getSymbol() + " of class " + cd
1156           + " has more than one location.");
1157     }
1158
1159     AnnotationDescriptor ad = annotationVec.elementAt(0);
1160
1161     if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1162
1163       if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1164         String locationID = ad.getValue();
1165         // check if location is defined
1166         SSJavaLattice<String> lattice = ssjava.getClassLattice(cd);
1167         if (lattice == null || (!lattice.containsKey(locationID))) {
1168           throw new Error("Location " + locationID
1169               + " is not defined in the field lattice of class " + cd.getSymbol() + " at"
1170               + cd.getSourceFileName() + ".");
1171         }
1172         Location loc = new Location(cd, locationID);
1173         // d2loc.put(fd, loc);
1174         addTypeLocation(fd.getType(), loc);
1175
1176       }
1177     }
1178
1179   }
1180
1181   private void addTypeLocation(TypeDescriptor type, CompositeLocation loc) {
1182     if (type != null) {
1183       type.setExtension(loc);
1184     }
1185   }
1186
1187   private void addTypeLocation(TypeDescriptor type, Location loc) {
1188     if (type != null) {
1189       type.setExtension(loc);
1190     }
1191   }
1192
1193   static class CompositeLattice {
1194
1195     public static boolean isGreaterThan(CompositeLocation loc1, CompositeLocation loc2) {
1196
1197       int baseCompareResult = compareBaseLocationSet(loc1, loc2, true);
1198       if (baseCompareResult == ComparisonResult.EQUAL) {
1199         if (compareDelta(loc1, loc2) == ComparisonResult.GREATER) {
1200           return true;
1201         } else {
1202           return false;
1203         }
1204       } else if (baseCompareResult == ComparisonResult.GREATER) {
1205         return true;
1206       } else {
1207         return false;
1208       }
1209
1210     }
1211
1212     public static int compare(CompositeLocation loc1, CompositeLocation loc2) {
1213
1214       // System.out.println("compare=" + loc1 + " " + loc2);
1215       int baseCompareResult = compareBaseLocationSet(loc1, loc2, false);
1216
1217       if (baseCompareResult == ComparisonResult.EQUAL) {
1218         return compareDelta(loc1, loc2);
1219       } else {
1220         return baseCompareResult;
1221       }
1222
1223     }
1224
1225     private static int compareDelta(CompositeLocation dLoc1, CompositeLocation dLoc2) {
1226
1227       int deltaCount1 = 0;
1228       int deltaCount2 = 0;
1229       if (dLoc1 instanceof DeltaLocation) {
1230         deltaCount1 = ((DeltaLocation) dLoc1).getNumDelta();
1231       }
1232
1233       if (dLoc2 instanceof DeltaLocation) {
1234         deltaCount2 = ((DeltaLocation) dLoc2).getNumDelta();
1235       }
1236       if (deltaCount1 < deltaCount2) {
1237         return ComparisonResult.GREATER;
1238       } else if (deltaCount1 == deltaCount2) {
1239         return ComparisonResult.EQUAL;
1240       } else {
1241         return ComparisonResult.LESS;
1242       }
1243
1244     }
1245
1246     private static int compareBaseLocationSet(CompositeLocation compLoc1,
1247         CompositeLocation compLoc2, boolean awareSharedLoc) {
1248
1249       // if compLoc1 is greater than compLoc2, return true
1250       // else return false;
1251
1252       // compare one by one in according to the order of the tuple
1253       int numOfTie = 0;
1254       for (int i = 0; i < compLoc1.getSize(); i++) {
1255         Location loc1 = compLoc1.get(i);
1256         if (i >= compLoc2.getSize()) {
1257           throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1258               + " because they are not comparable.");
1259         }
1260         Location loc2 = compLoc2.get(i);
1261
1262         if (!loc1.getDescriptor().equals(loc2.getDescriptor())) {
1263           throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1264               + " because they are not comparable.");
1265         }
1266
1267         Descriptor d1 = loc1.getDescriptor();
1268         Descriptor d2 = loc2.getDescriptor();
1269
1270         SSJavaLattice<String> lattice1 = getLatticeByDescriptor(d1);
1271         SSJavaLattice<String> lattice2 = getLatticeByDescriptor(d2);
1272
1273         // check if the spin location is appeared only at the end of the
1274         // composite location
1275         if (lattice1.getSpinLocSet().contains(loc1.getLocIdentifier())) {
1276           if (i != (compLoc1.getSize() - 1)) {
1277             throw new Error("The spin location " + loc1.getLocIdentifier()
1278                 + " cannot be appeared in the middle of composite location.");
1279           }
1280         }
1281
1282         if (lattice2.getSpinLocSet().contains(loc2.getLocIdentifier())) {
1283           if (i != (compLoc2.getSize() - 1)) {
1284             throw new Error("The spin location " + loc2.getLocIdentifier()
1285                 + " cannot be appeared in the middle of composite location.");
1286           }
1287         }
1288
1289         if (!lattice1.equals(lattice2)) {
1290           throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1291               + " because they are not comparable.");
1292         }
1293
1294         if (loc1.getLocIdentifier().equals(loc2.getLocIdentifier())) {
1295           numOfTie++;
1296           // check if the current location is the spinning location
1297           // note that the spinning location only can be appeared in the last
1298           // part of the composite location
1299           if (awareSharedLoc && numOfTie == compLoc1.getSize()
1300               && lattice1.getSpinLocSet().contains(loc1.getLocIdentifier())) {
1301             return ComparisonResult.GREATER;
1302           }
1303           continue;
1304         } else if (lattice1.isGreaterThan(loc1.getLocIdentifier(), loc2.getLocIdentifier())) {
1305           return ComparisonResult.GREATER;
1306         } else {
1307           return ComparisonResult.LESS;
1308         }
1309
1310       }
1311
1312       if (numOfTie == compLoc1.getSize()) {
1313
1314         if (numOfTie != compLoc2.getSize()) {
1315           throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1316               + " because they are not comparable.");
1317         }
1318
1319         return ComparisonResult.EQUAL;
1320       }
1321
1322       return ComparisonResult.LESS;
1323
1324     }
1325
1326     public static CompositeLocation calculateGLB(Set<CompositeLocation> inputSet) {
1327
1328       // System.out.println("Calculating GLB=" + inputSet);
1329       CompositeLocation glbCompLoc = new CompositeLocation();
1330
1331       // calculate GLB of the first(priority) element
1332       Set<String> priorityLocIdentifierSet = new HashSet<String>();
1333       Descriptor priorityDescriptor = null;
1334
1335       Hashtable<String, Set<CompositeLocation>> locId2CompLocSet =
1336           new Hashtable<String, Set<CompositeLocation>>();
1337       // mapping from the priority loc ID to its full representation by the
1338       // composite location
1339
1340       int maxTupleSize = 0;
1341       CompositeLocation maxCompLoc = null;
1342
1343       for (Iterator iterator = inputSet.iterator(); iterator.hasNext();) {
1344         CompositeLocation compLoc = (CompositeLocation) iterator.next();
1345         if (compLoc.getSize() > maxTupleSize) {
1346           maxTupleSize = compLoc.getSize();
1347           maxCompLoc = compLoc;
1348         }
1349         Location priorityLoc = compLoc.get(0);
1350         String priorityLocId = priorityLoc.getLocIdentifier();
1351         priorityLocIdentifierSet.add(priorityLocId);
1352
1353         if (locId2CompLocSet.containsKey(priorityLocId)) {
1354           locId2CompLocSet.get(priorityLocId).add(compLoc);
1355         } else {
1356           Set<CompositeLocation> newSet = new HashSet<CompositeLocation>();
1357           newSet.add(compLoc);
1358           locId2CompLocSet.put(priorityLocId, newSet);
1359         }
1360
1361         // check if priority location are coming from the same lattice
1362         if (priorityDescriptor == null) {
1363           priorityDescriptor = priorityLoc.getDescriptor();
1364         } else if (!priorityDescriptor.equals(priorityLoc.getDescriptor())) {
1365           throw new Error("Failed to calculate GLB of " + inputSet
1366               + " because they are from different lattices.");
1367         }
1368       }
1369
1370       SSJavaLattice<String> locOrder = getLatticeByDescriptor(priorityDescriptor);
1371       String glbOfPriorityLoc = locOrder.getGLB(priorityLocIdentifierSet);
1372
1373       glbCompLoc.addLocation(new Location(priorityDescriptor, glbOfPriorityLoc));
1374       Set<CompositeLocation> compSet = locId2CompLocSet.get(glbOfPriorityLoc);
1375
1376       // here find out composite location that has a maximum length tuple
1377       // if we have three input set: [A], [A,B], [A,B,C]
1378       // maximum length tuple will be [A,B,C]
1379       int max = 0;
1380       CompositeLocation maxFromCompSet = null;
1381       for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1382         CompositeLocation c = (CompositeLocation) iterator.next();
1383         if (c.getSize() > max) {
1384           max = c.getSize();
1385           maxFromCompSet = c;
1386         }
1387       }
1388
1389       if (compSet == null) {
1390         // when GLB(x1,x2)!=x1 and !=x2 : GLB case 4
1391         // mean that the result is already lower than <x1,y1> and <x2,y2>
1392         // assign TOP to the rest of the location elements
1393
1394         // in this case, do not take care about delta
1395         // CompositeLocation inputComp = inputSet.iterator().next();
1396         CompositeLocation inputComp = maxCompLoc;
1397         for (int i = 1; i < inputComp.getSize(); i++) {
1398           glbCompLoc.addLocation(Location.createTopLocation(inputComp.get(i).getDescriptor()));
1399         }
1400       } else {
1401         if (compSet.size() == 1) {
1402
1403           // if GLB(x1,x2)==x1 or x2 : GLB case 2,3
1404           CompositeLocation comp = compSet.iterator().next();
1405           for (int i = 1; i < comp.getSize(); i++) {
1406             glbCompLoc.addLocation(comp.get(i));
1407           }
1408
1409           // if input location corresponding to glb is a delta, need to apply
1410           // delta to glb result
1411           if (comp instanceof DeltaLocation) {
1412             glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1413           }
1414
1415         } else {
1416           // when GLB(x1,x2)==x1 and x2 : GLB case 1
1417           // if more than one location shares the same priority GLB
1418           // need to calculate the rest of GLB loc
1419
1420           // int compositeLocSize = compSet.iterator().next().getSize();
1421           int compositeLocSize = maxFromCompSet.getSize();
1422
1423           Set<String> glbInputSet = new HashSet<String>();
1424           Descriptor currentD = null;
1425           for (int i = 1; i < compositeLocSize; i++) {
1426             for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1427               CompositeLocation compositeLocation = (CompositeLocation) iterator.next();
1428               if (compositeLocation.getSize() > i) {
1429                 Location currentLoc = compositeLocation.get(i);
1430                 currentD = currentLoc.getDescriptor();
1431                 // making set of the current location sharing the same idx
1432                 glbInputSet.add(currentLoc.getLocIdentifier());
1433               }
1434             }
1435             // calculate glb for the current lattice
1436
1437             SSJavaLattice<String> currentLattice = getLatticeByDescriptor(currentD);
1438             String currentGLBLocId = currentLattice.getGLB(glbInputSet);
1439             glbCompLoc.addLocation(new Location(currentD, currentGLBLocId));
1440           }
1441
1442           // if input location corresponding to glb is a delta, need to apply
1443           // delta to glb result
1444
1445           for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1446             CompositeLocation compLoc = (CompositeLocation) iterator.next();
1447             if (compLoc instanceof DeltaLocation) {
1448               if (glbCompLoc.equals(compLoc)) {
1449                 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1450                 break;
1451               }
1452             }
1453           }
1454
1455         }
1456       }
1457
1458       return glbCompLoc;
1459
1460     }
1461
1462     static SSJavaLattice<String> getLatticeByDescriptor(Descriptor d) {
1463
1464       SSJavaLattice<String> lattice = null;
1465
1466       if (d instanceof ClassDescriptor) {
1467         lattice = ssjava.getCd2lattice().get(d);
1468       } else if (d instanceof MethodDescriptor) {
1469         if (ssjava.getMd2lattice().containsKey(d)) {
1470           lattice = ssjava.getMd2lattice().get(d);
1471         } else {
1472           // use default lattice for the method
1473           lattice = ssjava.getCd2methodDefault().get(((MethodDescriptor) d).getClassDesc());
1474         }
1475       }
1476
1477       return lattice;
1478     }
1479
1480   }
1481
1482   class ComparisonResult {
1483
1484     public static final int GREATER = 0;
1485     public static final int EQUAL = 1;
1486     public static final int LESS = 2;
1487     public static final int INCOMPARABLE = 3;
1488     int result;
1489
1490   }
1491
1492 }
1493
1494 class ReturnLocGenerator {
1495
1496   public static final int PARAMISHIGHER = 0;
1497   public static final int PARAMISSAME = 1;
1498   public static final int IGNORE = 2;
1499
1500   Hashtable<Integer, Integer> paramIdx2paramType;
1501
1502   public ReturnLocGenerator(CompositeLocation returnLoc, List<CompositeLocation> params) {
1503     // creating mappings
1504
1505     paramIdx2paramType = new Hashtable<Integer, Integer>();
1506     for (int i = 0; i < params.size(); i++) {
1507       CompositeLocation param = params.get(i);
1508       int compareResult = CompositeLattice.compare(param, returnLoc);
1509
1510       int type;
1511       if (compareResult == ComparisonResult.GREATER) {
1512         type = 0;
1513       } else if (compareResult == ComparisonResult.EQUAL) {
1514         type = 1;
1515       } else {
1516         type = 2;
1517       }
1518       paramIdx2paramType.put(new Integer(i), new Integer(type));
1519     }
1520
1521   }
1522
1523   public CompositeLocation computeReturnLocation(List<CompositeLocation> args) {
1524
1525     // compute the highest possible location in caller's side
1526     assert paramIdx2paramType.keySet().size() == args.size();
1527
1528     Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
1529     for (int i = 0; i < args.size(); i++) {
1530       int type = (paramIdx2paramType.get(new Integer(i))).intValue();
1531       CompositeLocation argLoc = args.get(i);
1532       if (type == PARAMISHIGHER) {
1533         // return loc is lower than param
1534         DeltaLocation delta = new DeltaLocation(argLoc, 1);
1535         inputGLB.add(delta);
1536       } else if (type == PARAMISSAME) {
1537         // return loc is equal or lower than param
1538         inputGLB.add(argLoc);
1539       }
1540     }
1541
1542     // compute GLB of arguments subset that are same or higher than return
1543     // location
1544     CompositeLocation glb = CompositeLattice.calculateGLB(inputGLB);
1545     return glb;
1546   }
1547 }