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