0dfd8892705f417e8fcaa73e615b361ac67a91d5
[IRC.git] / Robust / src / Analysis / SSJava / FlowDownCheck.java
1 package Analysis.SSJava;
2
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.Comparator;
6 import java.util.HashSet;
7 import java.util.Hashtable;
8 import java.util.Iterator;
9 import java.util.List;
10 import java.util.Set;
11 import java.util.StringTokenizer;
12 import java.util.Vector;
13
14 import Analysis.SSJava.FlowDownCheck.ComparisonResult;
15 import Analysis.SSJava.FlowDownCheck.CompositeLattice;
16 import IR.AnnotationDescriptor;
17 import IR.ClassDescriptor;
18 import IR.Descriptor;
19 import IR.FieldDescriptor;
20 import IR.MethodDescriptor;
21 import IR.NameDescriptor;
22 import IR.Operation;
23 import IR.State;
24 import IR.SymbolTable;
25 import IR.TypeDescriptor;
26 import IR.VarDescriptor;
27 import IR.Tree.ArrayAccessNode;
28 import IR.Tree.AssignmentNode;
29 import IR.Tree.BlockExpressionNode;
30 import IR.Tree.BlockNode;
31 import IR.Tree.BlockStatementNode;
32 import IR.Tree.CastNode;
33 import IR.Tree.CreateObjectNode;
34 import IR.Tree.DeclarationNode;
35 import IR.Tree.ExpressionNode;
36 import IR.Tree.FieldAccessNode;
37 import IR.Tree.IfStatementNode;
38 import IR.Tree.Kind;
39 import IR.Tree.LiteralNode;
40 import IR.Tree.LoopNode;
41 import IR.Tree.MethodInvokeNode;
42 import IR.Tree.NameNode;
43 import IR.Tree.OpNode;
44 import IR.Tree.ReturnNode;
45 import IR.Tree.SubBlockNode;
46 import IR.Tree.SwitchBlockNode;
47 import IR.Tree.SwitchStatementNode;
48 import IR.Tree.SynchronizedNode;
49 import IR.Tree.TertiaryNode;
50 import IR.Tree.TreeNode;
51 import Util.Pair;
52
53 public class FlowDownCheck {
54
55   State state;
56   static SSJavaAnalysis ssjava;
57
58   Set<ClassDescriptor> toanalyze;
59   List<ClassDescriptor> toanalyzeList;
60
61   Set<MethodDescriptor> toanalyzeMethod;
62   List<MethodDescriptor> toanalyzeMethodList;
63
64   // mapping from 'descriptor' to 'composite location'
65   Hashtable<Descriptor, CompositeLocation> d2loc;
66
67   Hashtable<MethodDescriptor, CompositeLocation> md2ReturnLoc;
68   Hashtable<MethodDescriptor, ReturnLocGenerator> md2ReturnLocGen;
69
70   // mapping from 'locID' to 'class descriptor'
71   Hashtable<String, ClassDescriptor> fieldLocName2cd;
72
73   boolean deterministic = true;
74
75   public FlowDownCheck(SSJavaAnalysis ssjava, State state) {
76     this.ssjava = ssjava;
77     this.state = state;
78     if (deterministic) {
79       this.toanalyzeList = new ArrayList<ClassDescriptor>();
80     } else {
81       this.toanalyze = new HashSet<ClassDescriptor>();
82     }
83     if (deterministic) {
84       this.toanalyzeMethodList = new ArrayList<MethodDescriptor>();
85     } else {
86       this.toanalyzeMethod = new HashSet<MethodDescriptor>();
87     }
88     this.d2loc = new Hashtable<Descriptor, CompositeLocation>();
89     this.fieldLocName2cd = new Hashtable<String, ClassDescriptor>();
90     this.md2ReturnLoc = new Hashtable<MethodDescriptor, CompositeLocation>();
91     this.md2ReturnLocGen = new Hashtable<MethodDescriptor, ReturnLocGenerator>();
92   }
93
94   public void init() {
95
96     // construct mapping from the location name to the class descriptor
97     // assume that the location name is unique through the whole program
98
99     Set<ClassDescriptor> cdSet = ssjava.getCd2lattice().keySet();
100     for (Iterator iterator = cdSet.iterator(); iterator.hasNext();) {
101       ClassDescriptor cd = (ClassDescriptor) iterator.next();
102       SSJavaLattice<String> lattice = ssjava.getCd2lattice().get(cd);
103       Set<String> fieldLocNameSet = lattice.getKeySet();
104
105       for (Iterator iterator2 = fieldLocNameSet.iterator(); iterator2.hasNext();) {
106         String fieldLocName = (String) iterator2.next();
107         fieldLocName2cd.put(fieldLocName, cd);
108       }
109
110     }
111
112   }
113
114   public boolean toAnalyzeIsEmpty() {
115     if (deterministic) {
116       return toanalyzeList.isEmpty();
117     } else {
118       return toanalyze.isEmpty();
119     }
120   }
121
122   public ClassDescriptor toAnalyzeNext() {
123     if (deterministic) {
124       return toanalyzeList.remove(0);
125     } else {
126       ClassDescriptor cd = toanalyze.iterator().next();
127       toanalyze.remove(cd);
128       return cd;
129     }
130   }
131
132   public void setupToAnalyze() {
133     SymbolTable classtable = state.getClassSymbolTable();
134     if (deterministic) {
135       toanalyzeList.clear();
136       toanalyzeList.addAll(classtable.getValueSet());
137       Collections.sort(toanalyzeList, new Comparator<ClassDescriptor>() {
138         public int compare(ClassDescriptor o1, ClassDescriptor o2) {
139           return o1.getClassName().compareTo(o2.getClassName());
140         }
141       });
142     } else {
143       toanalyze.clear();
144       toanalyze.addAll(classtable.getValueSet());
145     }
146   }
147
148   public void setupToAnalazeMethod(ClassDescriptor cd) {
149
150     SymbolTable methodtable = cd.getMethodTable();
151     if (deterministic) {
152       toanalyzeMethodList.clear();
153       toanalyzeMethodList.addAll(methodtable.getValueSet());
154       Collections.sort(toanalyzeMethodList, new Comparator<MethodDescriptor>() {
155         public int compare(MethodDescriptor o1, MethodDescriptor o2) {
156           return o1.getSymbol().compareTo(o2.getSymbol());
157         }
158       });
159     } else {
160       toanalyzeMethod.clear();
161       toanalyzeMethod.addAll(methodtable.getValueSet());
162     }
163   }
164
165   public boolean toAnalyzeMethodIsEmpty() {
166     if (deterministic) {
167       return toanalyzeMethodList.isEmpty();
168     } else {
169       return toanalyzeMethod.isEmpty();
170     }
171   }
172
173   public MethodDescriptor toAnalyzeMethodNext() {
174     if (deterministic) {
175       return toanalyzeMethodList.remove(0);
176     } else {
177       MethodDescriptor md = toanalyzeMethod.iterator().next();
178       toanalyzeMethod.remove(md);
179       return md;
180     }
181   }
182
183   public void flowDownCheck() {
184
185     // phase 1 : checking declaration node and creating mapping of 'type
186     // desciptor' & 'location'
187     setupToAnalyze();
188
189     while (!toAnalyzeIsEmpty()) {
190       ClassDescriptor cd = toAnalyzeNext();
191
192       if (ssjava.needToBeAnnoated(cd)) {
193
194         ClassDescriptor superDesc = cd.getSuperDesc();
195
196         if (superDesc != null && (!superDesc.getSymbol().equals("Object"))) {
197           checkOrderingInheritance(superDesc, cd);
198         }
199
200         checkDeclarationInClass(cd);
201
202         setupToAnalazeMethod(cd);
203         while (!toAnalyzeMethodIsEmpty()) {
204           MethodDescriptor md = toAnalyzeMethodNext();
205           if (ssjava.needTobeAnnotated(md)) {
206             checkDeclarationInMethodBody(cd, md);
207           }
208         }
209
210       }
211
212     }
213
214     // phase2 : checking assignments
215     setupToAnalyze();
216
217     while (!toAnalyzeIsEmpty()) {
218       ClassDescriptor cd = toAnalyzeNext();
219
220       setupToAnalazeMethod(cd);
221       while (!toAnalyzeMethodIsEmpty()) {
222         MethodDescriptor md = toAnalyzeMethodNext();
223         if (ssjava.needTobeAnnotated(md)) {
224           System.out.println("SSJAVA: Checking assignments: " + md);
225           checkMethodBody(cd, md);
226         }
227       }
228     }
229
230   }
231
232   private void checkOrderingInheritance(ClassDescriptor superCd, ClassDescriptor cd) {
233     // here, we're going to check that sub class keeps same relative orderings
234     // in respect to super class
235
236     SSJavaLattice<String> superLattice = ssjava.getClassLattice(superCd);
237     SSJavaLattice<String> subLattice = ssjava.getClassLattice(cd);
238
239     if (superLattice != null) {
240       // if super class doesn't define lattice, then we don't need to check its
241       // subclass
242       if (subLattice == null) {
243         throw new Error("If a parent class '" + superCd
244             + "' has a ordering lattice, its subclass '" + cd + "' should have one.");
245       }
246
247       Set<Pair<String, String>> superPairSet = superLattice.getOrderingPairSet();
248       Set<Pair<String, String>> subPairSet = subLattice.getOrderingPairSet();
249
250       for (Iterator iterator = superPairSet.iterator(); iterator.hasNext();) {
251         Pair<String, String> pair = (Pair<String, String>) iterator.next();
252
253         if (!subPairSet.contains(pair)) {
254           throw new Error("Subclass '" + cd + "' does not have the relative ordering '"
255               + pair.getSecond() + " < " + pair.getFirst()
256               + "' that is defined by its superclass '" + superCd + "'.");
257         }
258       }
259     }
260
261     MethodLattice<String> superMethodDefaultLattice = ssjava.getMethodDefaultLattice(superCd);
262     MethodLattice<String> subMethodDefaultLattice = ssjava.getMethodDefaultLattice(cd);
263
264     if (superMethodDefaultLattice != null) {
265       if (subMethodDefaultLattice == null) {
266         throw new Error("When a parent class '" + superCd
267             + "' defines a default method lattice, its subclass '" + cd + "' should define one.");
268       }
269
270       Set<Pair<String, String>> superPairSet = superMethodDefaultLattice.getOrderingPairSet();
271       Set<Pair<String, String>> subPairSet = subMethodDefaultLattice.getOrderingPairSet();
272
273       for (Iterator iterator = superPairSet.iterator(); iterator.hasNext();) {
274         Pair<String, String> pair = (Pair<String, String>) iterator.next();
275
276         if (!subPairSet.contains(pair)) {
277           throw new Error("Subclass '" + cd + "' does not have the relative ordering '"
278               + pair.getSecond() + " < " + pair.getFirst()
279               + "' that is defined by its superclass '" + superCd
280               + "' in the method default lattice.");
281         }
282       }
283
284     }
285
286   }
287
288   public Hashtable getMap() {
289     return d2loc;
290   }
291
292   private void checkDeclarationInMethodBody(ClassDescriptor cd, MethodDescriptor md) {
293     BlockNode bn = state.getMethodBody(md);
294
295     // first, check annotations on method parameters
296     List<CompositeLocation> paramList = new ArrayList<CompositeLocation>();
297     for (int i = 0; i < md.numParameters(); i++) {
298       // process annotations on method parameters
299       VarDescriptor vd = (VarDescriptor) md.getParameter(i);
300       assignLocationOfVarDescriptor(vd, md, md.getParameterTable(), bn);
301       paramList.add(d2loc.get(vd));
302     }
303     Vector<AnnotationDescriptor> methodAnnotations = md.getModifiers().getAnnotations();
304
305     // second, check return location annotation
306     if (!md.getReturnType().isVoid()) {
307       CompositeLocation returnLocComp = null;
308
309       boolean hasReturnLocDeclaration = false;
310       if (methodAnnotations != null) {
311         for (int i = 0; i < methodAnnotations.size(); i++) {
312           AnnotationDescriptor an = methodAnnotations.elementAt(i);
313           if (an.getMarker().equals(ssjava.RETURNLOC)) {
314             // this case, developer explicitly defines method lattice
315             String returnLocDeclaration = an.getValue();
316             returnLocComp = parseLocationDeclaration(md, null, returnLocDeclaration);
317             hasReturnLocDeclaration = true;
318           }
319         }
320       }
321
322       if (!hasReturnLocDeclaration) {
323         // if developer does not define method lattice
324         // search return location in the method default lattice
325         String rtrStr = ssjava.getMethodLattice(md).getReturnLoc();
326         returnLocComp = new CompositeLocation(new Location(md, rtrStr));
327       }
328
329       if (returnLocComp == null) {
330         throw new Error("Return location is not specified for the method " + md + " at "
331             + cd.getSourceFileName());
332       }
333
334       md2ReturnLoc.put(md, returnLocComp);
335
336       // check this location
337       MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
338       String thisLocId = methodLattice.getThisLoc();
339       if (thisLocId == null) {
340         throw new Error("Method '" + md + "' does not have the definition of 'this' location at "
341             + md.getClassDesc().getSourceFileName());
342       }
343       CompositeLocation thisLoc = new CompositeLocation(new Location(md, thisLocId));
344       paramList.add(0, thisLoc);
345
346       System.out.println("### ReturnLocGenerator=" + md);
347       System.out.println("### md2ReturnLoc.get(md)=" + md2ReturnLoc.get(md));
348       md2ReturnLocGen.put(md, new ReturnLocGenerator(md2ReturnLoc.get(md), md, paramList, md
349           + " of " + cd.getSourceFileName()));
350     }
351
352     // fourth, check declarations inside of method
353
354     checkDeclarationInBlockNode(md, md.getParameterTable(), bn);
355
356   }
357
358   private void checkDeclarationInBlockNode(MethodDescriptor md, SymbolTable nametable, BlockNode bn) {
359     bn.getVarTable().setParent(nametable);
360     for (int i = 0; i < bn.size(); i++) {
361       BlockStatementNode bsn = bn.get(i);
362       checkDeclarationInBlockStatementNode(md, bn.getVarTable(), bsn);
363     }
364   }
365
366   private void checkDeclarationInBlockStatementNode(MethodDescriptor md, SymbolTable nametable,
367       BlockStatementNode bsn) {
368
369     switch (bsn.kind()) {
370     case Kind.SubBlockNode:
371       checkDeclarationInSubBlockNode(md, nametable, (SubBlockNode) bsn);
372       return;
373
374     case Kind.DeclarationNode:
375       checkDeclarationNode(md, nametable, (DeclarationNode) bsn);
376       break;
377
378     case Kind.LoopNode:
379       checkDeclarationInLoopNode(md, nametable, (LoopNode) bsn);
380       break;
381
382     case Kind.IfStatementNode:
383       checkDeclarationInIfStatementNode(md, nametable, (IfStatementNode) bsn);
384       return;
385
386     case Kind.SwitchStatementNode:
387       checkDeclarationInSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn);
388       return;
389
390     case Kind.SynchronizedNode:
391       checkDeclarationInSynchronizedNode(md, nametable, (SynchronizedNode) bsn);
392       return;
393
394     }
395   }
396
397   private void checkDeclarationInSynchronizedNode(MethodDescriptor md, SymbolTable nametable,
398       SynchronizedNode sbn) {
399     checkDeclarationInBlockNode(md, nametable, sbn.getBlockNode());
400   }
401
402   private void checkDeclarationInSwitchStatementNode(MethodDescriptor md, SymbolTable nametable,
403       SwitchStatementNode ssn) {
404     BlockNode sbn = ssn.getSwitchBody();
405     for (int i = 0; i < sbn.size(); i++) {
406       SwitchBlockNode node = (SwitchBlockNode) sbn.get(i);
407       checkDeclarationInBlockNode(md, nametable, node.getSwitchBlockStatement());
408     }
409   }
410
411   private void checkDeclarationInIfStatementNode(MethodDescriptor md, SymbolTable nametable,
412       IfStatementNode isn) {
413     checkDeclarationInBlockNode(md, nametable, isn.getTrueBlock());
414     if (isn.getFalseBlock() != null)
415       checkDeclarationInBlockNode(md, nametable, isn.getFalseBlock());
416   }
417
418   private void checkDeclarationInLoopNode(MethodDescriptor md, SymbolTable nametable, LoopNode ln) {
419
420     if (ln.getType() == LoopNode.FORLOOP) {
421       // check for loop case
422       ClassDescriptor cd = md.getClassDesc();
423       BlockNode bn = ln.getInitializer();
424       for (int i = 0; i < bn.size(); i++) {
425         BlockStatementNode bsn = bn.get(i);
426         checkDeclarationInBlockStatementNode(md, nametable, bsn);
427       }
428     }
429
430     // check loop body
431     checkDeclarationInBlockNode(md, nametable, ln.getBody());
432   }
433
434   private void checkMethodBody(ClassDescriptor cd, MethodDescriptor md) {
435     BlockNode bn = state.getMethodBody(md);
436     checkLocationFromBlockNode(md, md.getParameterTable(), bn, null);
437   }
438
439   private String generateErrorMessage(ClassDescriptor cd, TreeNode tn) {
440     if (tn != null) {
441       return cd.getSourceFileName() + "::" + tn.getNumLine();
442     } else {
443       return cd.getSourceFileName();
444     }
445
446   }
447
448   private CompositeLocation checkLocationFromBlockNode(MethodDescriptor md, SymbolTable nametable,
449       BlockNode bn, CompositeLocation constraint) {
450
451     bn.getVarTable().setParent(nametable);
452     for (int i = 0; i < bn.size(); i++) {
453       BlockStatementNode bsn = bn.get(i);
454       checkLocationFromBlockStatementNode(md, bn.getVarTable(), bsn, constraint);
455     }
456     return new CompositeLocation();
457
458   }
459
460   private CompositeLocation checkLocationFromBlockStatementNode(MethodDescriptor md,
461       SymbolTable nametable, BlockStatementNode bsn, CompositeLocation constraint) {
462
463     CompositeLocation compLoc = null;
464     switch (bsn.kind()) {
465     case Kind.BlockExpressionNode:
466       compLoc =
467           checkLocationFromBlockExpressionNode(md, nametable, (BlockExpressionNode) bsn, constraint);
468       break;
469
470     case Kind.DeclarationNode:
471       compLoc = checkLocationFromDeclarationNode(md, nametable, (DeclarationNode) bsn, constraint);
472       break;
473
474     case Kind.IfStatementNode:
475       compLoc = checkLocationFromIfStatementNode(md, nametable, (IfStatementNode) bsn, constraint);
476       break;
477
478     case Kind.LoopNode:
479       compLoc = checkLocationFromLoopNode(md, nametable, (LoopNode) bsn, constraint);
480       break;
481
482     case Kind.ReturnNode:
483       compLoc = checkLocationFromReturnNode(md, nametable, (ReturnNode) bsn, constraint);
484       break;
485
486     case Kind.SubBlockNode:
487       compLoc = checkLocationFromSubBlockNode(md, nametable, (SubBlockNode) bsn, constraint);
488       break;
489
490     case Kind.ContinueBreakNode:
491       compLoc = new CompositeLocation();
492       break;
493
494     case Kind.SwitchStatementNode:
495       compLoc =
496           checkLocationFromSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn, constraint);
497
498     }
499     return compLoc;
500   }
501
502   private CompositeLocation checkLocationFromSwitchStatementNode(MethodDescriptor md,
503       SymbolTable nametable, SwitchStatementNode ssn, CompositeLocation constraint) {
504
505     ClassDescriptor cd = md.getClassDesc();
506     CompositeLocation condLoc =
507         checkLocationFromExpressionNode(md, nametable, ssn.getCondition(), new CompositeLocation(),
508             constraint, false);
509     BlockNode sbn = ssn.getSwitchBody();
510
511     constraint = generateNewConstraint(constraint, condLoc);
512
513     for (int i = 0; i < sbn.size(); i++) {
514       checkLocationFromSwitchBlockNode(md, nametable, (SwitchBlockNode) sbn.get(i), constraint);
515     }
516     return new CompositeLocation();
517   }
518
519   private CompositeLocation checkLocationFromSwitchBlockNode(MethodDescriptor md,
520       SymbolTable nametable, SwitchBlockNode sbn, CompositeLocation constraint) {
521
522     CompositeLocation blockLoc =
523         checkLocationFromBlockNode(md, nametable, sbn.getSwitchBlockStatement(), constraint);
524
525     return blockLoc;
526
527   }
528
529   private CompositeLocation checkLocationFromReturnNode(MethodDescriptor md, SymbolTable nametable,
530       ReturnNode rn, CompositeLocation constraint) {
531
532     ExpressionNode returnExp = rn.getReturnExpression();
533
534     CompositeLocation returnValueLoc;
535     if (returnExp != null) {
536       returnValueLoc =
537           checkLocationFromExpressionNode(md, nametable, returnExp, new CompositeLocation(),
538               constraint, false);
539
540       // if this return statement is inside branch, return value has an implicit
541       // flow from conditional location
542       if (constraint != null) {
543         Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
544         inputGLB.add(returnValueLoc);
545         inputGLB.add(constraint);
546         returnValueLoc =
547             CompositeLattice.calculateGLB(inputGLB, generateErrorMessage(md.getClassDesc(), rn));
548       }
549
550       // check if return value is equal or higher than RETRUNLOC of method
551       // declaration annotation
552       CompositeLocation declaredReturnLoc = md2ReturnLoc.get(md);
553
554       int compareResult =
555           CompositeLattice.compare(returnValueLoc, declaredReturnLoc, false,
556               generateErrorMessage(md.getClassDesc(), rn));
557
558       if (compareResult == ComparisonResult.LESS || compareResult == ComparisonResult.INCOMPARABLE) {
559         throw new Error(
560             "Return value location is not equal or higher than the declaraed return location at "
561                 + md.getClassDesc().getSourceFileName() + "::" + rn.getNumLine());
562       }
563     }
564
565     return new CompositeLocation();
566   }
567
568   private boolean hasOnlyLiteralValue(ExpressionNode en) {
569     if (en.kind() == Kind.LiteralNode) {
570       return true;
571     } else {
572       return false;
573     }
574   }
575
576   private CompositeLocation checkLocationFromLoopNode(MethodDescriptor md, SymbolTable nametable,
577       LoopNode ln, CompositeLocation constraint) {
578
579     ClassDescriptor cd = md.getClassDesc();
580     if (ln.getType() == LoopNode.WHILELOOP || ln.getType() == LoopNode.DOWHILELOOP) {
581
582       CompositeLocation condLoc =
583           checkLocationFromExpressionNode(md, nametable, ln.getCondition(),
584               new CompositeLocation(), constraint, false);
585       // addLocationType(ln.getCondition().getType(), (condLoc));
586
587       constraint = generateNewConstraint(constraint, condLoc);
588       checkLocationFromBlockNode(md, nametable, ln.getBody(), constraint);
589
590       return new CompositeLocation();
591
592     } else {
593       // check 'for loop' case
594       BlockNode bn = ln.getInitializer();
595       bn.getVarTable().setParent(nametable);
596
597       // calculate glb location of condition and update statements
598       CompositeLocation condLoc =
599           checkLocationFromExpressionNode(md, bn.getVarTable(), ln.getCondition(),
600               new CompositeLocation(), constraint, false);
601       // addLocationType(ln.getCondition().getType(), condLoc);
602
603       constraint = generateNewConstraint(constraint, condLoc);
604
605       checkLocationFromBlockNode(md, bn.getVarTable(), ln.getUpdate(), constraint);
606       checkLocationFromBlockNode(md, bn.getVarTable(), ln.getBody(), constraint);
607
608       return new CompositeLocation();
609
610     }
611
612   }
613
614   private CompositeLocation checkLocationFromSubBlockNode(MethodDescriptor md,
615       SymbolTable nametable, SubBlockNode sbn, CompositeLocation constraint) {
616     CompositeLocation compLoc =
617         checkLocationFromBlockNode(md, nametable, sbn.getBlockNode(), constraint);
618     return compLoc;
619   }
620
621   private CompositeLocation generateNewConstraint(CompositeLocation currentCon,
622       CompositeLocation newCon) {
623
624     if (currentCon == null) {
625       return newCon;
626     } else {
627       // compute GLB of current constraint and new constraint
628       Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
629       inputSet.add(currentCon);
630       inputSet.add(newCon);
631       return CompositeLattice.calculateGLB(inputSet, "");
632     }
633
634   }
635
636   private CompositeLocation checkLocationFromIfStatementNode(MethodDescriptor md,
637       SymbolTable nametable, IfStatementNode isn, CompositeLocation constraint) {
638
639     CompositeLocation condLoc =
640         checkLocationFromExpressionNode(md, nametable, isn.getCondition(), new CompositeLocation(),
641             constraint, false);
642
643     // addLocationType(isn.getCondition().getType(), condLoc);
644
645     constraint = generateNewConstraint(constraint, condLoc);
646     checkLocationFromBlockNode(md, nametable, isn.getTrueBlock(), constraint);
647
648     if (isn.getFalseBlock() != null) {
649       checkLocationFromBlockNode(md, nametable, isn.getFalseBlock(), constraint);
650     }
651
652     return new CompositeLocation();
653   }
654
655   private CompositeLocation checkLocationFromDeclarationNode(MethodDescriptor md,
656       SymbolTable nametable, DeclarationNode dn, CompositeLocation constraint) {
657
658     VarDescriptor vd = dn.getVarDescriptor();
659
660     CompositeLocation destLoc = d2loc.get(vd);
661
662     if (dn.getExpression() != null) {
663       CompositeLocation expressionLoc =
664           checkLocationFromExpressionNode(md, nametable, dn.getExpression(),
665               new CompositeLocation(), constraint, false);
666       // addTypeLocation(dn.getExpression().getType(), expressionLoc);
667
668       if (expressionLoc != null) {
669         // checking location order
670         if (!CompositeLattice.isGreaterThan(expressionLoc, destLoc,
671             generateErrorMessage(md.getClassDesc(), dn))) {
672           throw new Error("The value flow from " + expressionLoc + " to " + destLoc
673               + " does not respect location hierarchy on the assignment " + dn.printNode(0)
674               + " at " + md.getClassDesc().getSourceFileName() + "::" + dn.getNumLine());
675         }
676       }
677       return expressionLoc;
678
679     } else {
680
681       return new CompositeLocation();
682
683     }
684
685   }
686
687   private void checkDeclarationInSubBlockNode(MethodDescriptor md, SymbolTable nametable,
688       SubBlockNode sbn) {
689     checkDeclarationInBlockNode(md, nametable.getParent(), sbn.getBlockNode());
690   }
691
692   private CompositeLocation checkLocationFromBlockExpressionNode(MethodDescriptor md,
693       SymbolTable nametable, BlockExpressionNode ben, CompositeLocation constraint) {
694     CompositeLocation compLoc =
695         checkLocationFromExpressionNode(md, nametable, ben.getExpression(), null, constraint, false);
696     // addTypeLocation(ben.getExpression().getType(), compLoc);
697     return compLoc;
698   }
699
700   private CompositeLocation checkLocationFromExpressionNode(MethodDescriptor md,
701       SymbolTable nametable, ExpressionNode en, CompositeLocation loc,
702       CompositeLocation constraint, boolean isLHS) {
703
704     CompositeLocation compLoc = null;
705     switch (en.kind()) {
706
707     case Kind.AssignmentNode:
708       compLoc =
709           checkLocationFromAssignmentNode(md, nametable, (AssignmentNode) en, loc, constraint);
710       break;
711
712     case Kind.FieldAccessNode:
713       compLoc =
714           checkLocationFromFieldAccessNode(md, nametable, (FieldAccessNode) en, loc, constraint);
715       break;
716
717     case Kind.NameNode:
718       compLoc = checkLocationFromNameNode(md, nametable, (NameNode) en, loc, constraint);
719       break;
720
721     case Kind.OpNode:
722       compLoc = checkLocationFromOpNode(md, nametable, (OpNode) en, constraint);
723       break;
724
725     case Kind.CreateObjectNode:
726       compLoc = checkLocationFromCreateObjectNode(md, nametable, (CreateObjectNode) en);
727       break;
728
729     case Kind.ArrayAccessNode:
730       compLoc =
731           checkLocationFromArrayAccessNode(md, nametable, (ArrayAccessNode) en, constraint, isLHS);
732       break;
733
734     case Kind.LiteralNode:
735       compLoc = checkLocationFromLiteralNode(md, nametable, (LiteralNode) en, loc);
736       break;
737
738     case Kind.MethodInvokeNode:
739       compLoc =
740           checkLocationFromMethodInvokeNode(md, nametable, (MethodInvokeNode) en, loc, constraint);
741       break;
742
743     case Kind.TertiaryNode:
744       compLoc = checkLocationFromTertiaryNode(md, nametable, (TertiaryNode) en, constraint);
745       break;
746
747     case Kind.CastNode:
748       compLoc = checkLocationFromCastNode(md, nametable, (CastNode) en, constraint);
749       break;
750
751     // case Kind.InstanceOfNode:
752     // checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
753     // return null;
754
755     // case Kind.ArrayInitializerNode:
756     // checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en,
757     // td);
758     // return null;
759
760     // case Kind.ClassTypeNode:
761     // checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
762     // return null;
763
764     // case Kind.OffsetNode:
765     // checkOffsetNode(md, nametable, (OffsetNode)en, td);
766     // return null;
767
768     default:
769       return null;
770
771     }
772     // addTypeLocation(en.getType(), compLoc);
773     return compLoc;
774
775   }
776
777   private CompositeLocation checkLocationFromCastNode(MethodDescriptor md, SymbolTable nametable,
778       CastNode cn, CompositeLocation constraint) {
779
780     ExpressionNode en = cn.getExpression();
781     return checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
782         false);
783
784   }
785
786   private CompositeLocation checkLocationFromTertiaryNode(MethodDescriptor md,
787       SymbolTable nametable, TertiaryNode tn, CompositeLocation constraint) {
788     ClassDescriptor cd = md.getClassDesc();
789
790     CompositeLocation condLoc =
791         checkLocationFromExpressionNode(md, nametable, tn.getCond(), new CompositeLocation(),
792             constraint, false);
793     // addLocationType(tn.getCond().getType(), condLoc);
794     CompositeLocation trueLoc =
795         checkLocationFromExpressionNode(md, nametable, tn.getTrueExpr(), new CompositeLocation(),
796             constraint, false);
797     // addLocationType(tn.getTrueExpr().getType(), trueLoc);
798     CompositeLocation falseLoc =
799         checkLocationFromExpressionNode(md, nametable, tn.getFalseExpr(), new CompositeLocation(),
800             constraint, false);
801     // addLocationType(tn.getFalseExpr().getType(), falseLoc);
802
803     // locations from true/false branches can be TOP when there are only literal
804     // values
805     // in this case, we don't need to check flow down rule!
806
807     // check if condLoc is higher than trueLoc & falseLoc
808     if (!trueLoc.get(0).isTop()
809         && !CompositeLattice.isGreaterThan(condLoc, trueLoc, generateErrorMessage(cd, tn))) {
810       throw new Error(
811           "The location of the condition expression is lower than the true expression at "
812               + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
813     }
814
815     if (!falseLoc.get(0).isTop()
816         && !CompositeLattice.isGreaterThan(condLoc, falseLoc,
817             generateErrorMessage(cd, tn.getCond()))) {
818       throw new Error(
819           "The location of the condition expression is lower than the true expression at "
820               + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
821     }
822
823     // then, return glb of trueLoc & falseLoc
824     Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
825     glbInputSet.add(trueLoc);
826     glbInputSet.add(falseLoc);
827
828     return CompositeLattice.calculateGLB(glbInputSet, generateErrorMessage(cd, tn));
829   }
830
831   private CompositeLocation checkLocationFromMethodInvokeNode(MethodDescriptor md,
832       SymbolTable nametable, MethodInvokeNode min, CompositeLocation loc,
833       CompositeLocation constraint) {
834
835     CompositeLocation baseLocation = null;
836     if (min.getExpression() != null) {
837       baseLocation =
838           checkLocationFromExpressionNode(md, nametable, min.getExpression(),
839               new CompositeLocation(), constraint, false);
840     } else {
841
842       if (min.getMethod().isStatic()) {
843         String globalLocId = ssjava.getMethodLattice(md).getGlobalLoc();
844         if (globalLocId == null) {
845           throw new Error("Method lattice does not define global variable location at "
846               + generateErrorMessage(md.getClassDesc(), min));
847         }
848         baseLocation = new CompositeLocation(new Location(md, globalLocId));
849       } else {
850         String thisLocId = ssjava.getMethodLattice(md).getThisLoc();
851         baseLocation = new CompositeLocation(new Location(md, thisLocId));
852       }
853     }
854
855     checkCalleeConstraints(md, nametable, min, baseLocation, constraint);
856
857     checkCallerArgumentLocationConstraints(md, nametable, min, baseLocation, constraint);
858
859     if (!min.getMethod().getReturnType().isVoid()) {
860       // If method has a return value, compute the highest possible return
861       // location in the caller's perspective
862       CompositeLocation ceilingLoc =
863           computeCeilingLocationForCaller(md, nametable, min, baseLocation, constraint);
864       return ceilingLoc;
865     }
866
867     return new CompositeLocation();
868
869   }
870
871   private void checkCallerArgumentLocationConstraints(MethodDescriptor md, SymbolTable nametable,
872       MethodInvokeNode min, CompositeLocation callerBaseLoc, CompositeLocation constraint) {
873     // if parameter location consists of THIS and FIELD location,
874     // caller should pass an argument that is comparable to the declared
875     // parameter location
876     // and is not lower than the declared parameter location in the field
877     // lattice.
878
879     MethodDescriptor calleemd = min.getMethod();
880
881     List<CompositeLocation> callerArgList = new ArrayList<CompositeLocation>();
882     List<CompositeLocation> calleeParamList = new ArrayList<CompositeLocation>();
883
884     MethodLattice<String> calleeLattice = ssjava.getMethodLattice(calleemd);
885     Location calleeThisLoc = new Location(calleemd, calleeLattice.getThisLoc());
886
887     for (int i = 0; i < min.numArgs(); i++) {
888       ExpressionNode en = min.getArg(i);
889       CompositeLocation callerArgLoc =
890           checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
891               false);
892       callerArgList.add(callerArgLoc);
893     }
894
895     // setup callee params set
896     for (int i = 0; i < calleemd.numParameters(); i++) {
897       VarDescriptor calleevd = (VarDescriptor) calleemd.getParameter(i);
898       CompositeLocation calleeLoc = d2loc.get(calleevd);
899       calleeParamList.add(calleeLoc);
900     }
901
902     String errorMsg = generateErrorMessage(md.getClassDesc(), min);
903
904     System.out.println("checkCallerArgumentLocationConstraints=" + min.printNode(0));
905     System.out.println("base location=" + callerBaseLoc);
906
907     for (int i = 0; i < calleeParamList.size(); i++) {
908       CompositeLocation calleeParamLoc = calleeParamList.get(i);
909       if (calleeParamLoc.get(0).equals(calleeThisLoc) && calleeParamLoc.getSize() > 1) {
910
911         // callee parameter location has field information
912         CompositeLocation callerArgLoc = callerArgList.get(i);
913
914         CompositeLocation paramLocation =
915             translateCalleeParamLocToCaller(md, calleeParamLoc, callerBaseLoc, errorMsg);
916
917         Set<CompositeLocation> inputGLBSet = new HashSet<CompositeLocation>();
918         if (constraint != null) {
919           inputGLBSet.add(callerArgLoc);
920           inputGLBSet.add(constraint);
921           callerArgLoc =
922               CompositeLattice.calculateGLB(inputGLBSet,
923                   generateErrorMessage(md.getClassDesc(), min));
924         }
925
926         if (!CompositeLattice.isGreaterThan(callerArgLoc, paramLocation, errorMsg)) {
927           throw new Error("Caller argument '" + min.getArg(i).printNode(0) + " : " + callerArgLoc
928               + "' should be higher than corresponding callee's parameter : " + paramLocation
929               + " at " + errorMsg);
930         }
931
932       }
933     }
934
935   }
936
937   private CompositeLocation translateCalleeParamLocToCaller(MethodDescriptor md,
938       CompositeLocation calleeParamLoc, CompositeLocation callerBaseLocation, String errorMsg) {
939
940     CompositeLocation translate = new CompositeLocation();
941
942     for (int i = 0; i < callerBaseLocation.getSize(); i++) {
943       translate.addLocation(callerBaseLocation.get(i));
944     }
945
946     for (int i = 1; i < calleeParamLoc.getSize(); i++) {
947       translate.addLocation(calleeParamLoc.get(i));
948     }
949
950     System.out.println("TRANSLATED=" + translate + " from calleeParamLoc=" + calleeParamLoc);
951
952     return translate;
953   }
954
955   private CompositeLocation computeCeilingLocationForCaller(MethodDescriptor md,
956       SymbolTable nametable, MethodInvokeNode min, CompositeLocation baseLocation,
957       CompositeLocation constraint) {
958     List<CompositeLocation> argList = new ArrayList<CompositeLocation>();
959
960     // by default, method has a THIS parameter
961     argList.add(baseLocation);
962
963     for (int i = 0; i < min.numArgs(); i++) {
964       ExpressionNode en = min.getArg(i);
965       CompositeLocation callerArg =
966           checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
967               false);
968       argList.add(callerArg);
969     }
970
971     System.out.println("\n## computeReturnLocation=" + min.getMethod() + " argList=" + argList);
972     CompositeLocation compLoc = md2ReturnLocGen.get(min.getMethod()).computeReturnLocation(argList);
973     DeltaLocation delta = new DeltaLocation(compLoc, 1);
974     System.out.println("##computeReturnLocation=" + delta);
975
976     return delta;
977
978   }
979
980   private void checkCalleeConstraints(MethodDescriptor md, SymbolTable nametable,
981       MethodInvokeNode min, CompositeLocation callerBaseLoc, CompositeLocation constraint) {
982     
983     System.out.println("checkCalleeConstraints="+min.printNode(0));
984
985     MethodDescriptor calleemd = min.getMethod();
986
987     MethodLattice<String> calleeLattice = ssjava.getMethodLattice(calleemd);
988     CompositeLocation calleeThisLoc =
989         new CompositeLocation(new Location(calleemd, calleeLattice.getThisLoc()));
990
991     List<CompositeLocation> callerArgList = new ArrayList<CompositeLocation>();
992     List<CompositeLocation> calleeParamList = new ArrayList<CompositeLocation>();
993
994     if (min.numArgs() > 0) {
995       // caller needs to guarantee that it passes arguments in regarding to
996       // callee's hierarchy
997
998       // setup caller args set
999       // first, add caller's base(this) location
1000       callerArgList.add(callerBaseLoc);
1001       // second, add caller's arguments
1002       for (int i = 0; i < min.numArgs(); i++) {
1003         ExpressionNode en = min.getArg(i);
1004         CompositeLocation callerArgLoc =
1005             checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
1006                 false);
1007         callerArgList.add(callerArgLoc);
1008       }
1009
1010       // setup callee params set
1011       // first, add callee's this location
1012       calleeParamList.add(calleeThisLoc);
1013       // second, add callee's parameters
1014       for (int i = 0; i < calleemd.numParameters(); i++) {
1015         VarDescriptor calleevd = (VarDescriptor) calleemd.getParameter(i);
1016         CompositeLocation calleeLoc = d2loc.get(calleevd);
1017         System.out.println("calleevd="+calleevd+" loc="+calleeLoc);
1018         calleeParamList.add(calleeLoc);
1019       }
1020
1021       // here, check if ordering relations among caller's args respect
1022       // ordering relations in-between callee's args
1023       CHECK: for (int i = 0; i < calleeParamList.size(); i++) {
1024         CompositeLocation calleeLoc1 = calleeParamList.get(i);
1025         CompositeLocation callerLoc1 = callerArgList.get(i);
1026
1027         for (int j = 0; j < calleeParamList.size(); j++) {
1028           if (i != j) {
1029             CompositeLocation calleeLoc2 = calleeParamList.get(j);
1030             CompositeLocation callerLoc2 = callerArgList.get(j);
1031
1032             if (callerLoc1.get(callerLoc1.getSize() - 1).isTop()
1033                 || callerLoc2.get(callerLoc2.getSize() - 1).isTop()) {
1034               continue CHECK;
1035             }
1036             
1037             System.out.println("calleeLoc1="+calleeLoc1);
1038             System.out.println("calleeLoc2="+calleeLoc2+"calleeParamList="+calleeParamList);
1039
1040             int callerResult =
1041                 CompositeLattice.compare(callerLoc1, callerLoc2, true,
1042                     generateErrorMessage(md.getClassDesc(), min));
1043             int calleeResult =
1044                 CompositeLattice.compare(calleeLoc1, calleeLoc2, true,
1045                     generateErrorMessage(md.getClassDesc(), min));
1046
1047             if (calleeResult == ComparisonResult.GREATER
1048                 && callerResult != ComparisonResult.GREATER) {
1049               // If calleeLoc1 is higher than calleeLoc2
1050               // then, caller should have same ordering relation in-bet
1051               // callerLoc1 & callerLoc2
1052
1053               String paramName1, paramName2;
1054
1055               if (i == 0) {
1056                 paramName1 = "'THIS'";
1057               } else {
1058                 paramName1 = "'parameter " + calleemd.getParamName(i - 1) + "'";
1059               }
1060
1061               if (j == 0) {
1062                 paramName2 = "'THIS'";
1063               } else {
1064                 paramName2 = "'parameter " + calleemd.getParamName(j - 1) + "'";
1065               }
1066
1067               throw new Error(
1068                   "Caller doesn't respect an ordering relation among method arguments: callee expects that "
1069                       + paramName1 + " should be higher than " + paramName2 + " in " + calleemd
1070                       + " at " + md.getClassDesc().getSourceFileName() + ":" + min.getNumLine());
1071             }
1072           }
1073
1074         }
1075       }
1076
1077     }
1078
1079   }
1080
1081   private CompositeLocation checkLocationFromArrayAccessNode(MethodDescriptor md,
1082       SymbolTable nametable, ArrayAccessNode aan, CompositeLocation constraint, boolean isLHS) {
1083
1084     ClassDescriptor cd = md.getClassDesc();
1085
1086     CompositeLocation arrayLoc =
1087         checkLocationFromExpressionNode(md, nametable, aan.getExpression(),
1088             new CompositeLocation(), constraint, isLHS);
1089     // addTypeLocation(aan.getExpression().getType(), arrayLoc);
1090     CompositeLocation indexLoc =
1091         checkLocationFromExpressionNode(md, nametable, aan.getIndex(), new CompositeLocation(),
1092             constraint, isLHS);
1093     // addTypeLocation(aan.getIndex().getType(), indexLoc);
1094
1095     if (isLHS) {
1096       if (!CompositeLattice.isGreaterThan(indexLoc, arrayLoc, generateErrorMessage(cd, aan))) {
1097         throw new Error("Array index value is not higher than array location at "
1098             + generateErrorMessage(cd, aan));
1099       }
1100       return arrayLoc;
1101     } else {
1102       Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
1103       inputGLB.add(arrayLoc);
1104       inputGLB.add(indexLoc);
1105       return CompositeLattice.calculateGLB(inputGLB, generateErrorMessage(cd, aan));
1106     }
1107
1108   }
1109
1110   private CompositeLocation checkLocationFromCreateObjectNode(MethodDescriptor md,
1111       SymbolTable nametable, CreateObjectNode con) {
1112
1113     ClassDescriptor cd = md.getClassDesc();
1114
1115     CompositeLocation compLoc = new CompositeLocation();
1116     compLoc.addLocation(Location.createTopLocation(md));
1117     return compLoc;
1118
1119   }
1120
1121   private CompositeLocation checkLocationFromOpNode(MethodDescriptor md, SymbolTable nametable,
1122       OpNode on, CompositeLocation constraint) {
1123
1124     ClassDescriptor cd = md.getClassDesc();
1125     CompositeLocation leftLoc = new CompositeLocation();
1126     leftLoc =
1127         checkLocationFromExpressionNode(md, nametable, on.getLeft(), leftLoc, constraint, false);
1128     // addTypeLocation(on.getLeft().getType(), leftLoc);
1129
1130     CompositeLocation rightLoc = new CompositeLocation();
1131     if (on.getRight() != null) {
1132       rightLoc =
1133           checkLocationFromExpressionNode(md, nametable, on.getRight(), rightLoc, constraint, false);
1134       // addTypeLocation(on.getRight().getType(), rightLoc);
1135     }
1136
1137     System.out.println("\n# OP NODE=" + on.printNode(0));
1138     System.out.println("# left loc=" + leftLoc + " from " + on.getLeft().getClass());
1139     if (on.getRight() != null) {
1140       System.out.println("# right loc=" + rightLoc + " from " + on.getRight().getClass());
1141     }
1142
1143     Operation op = on.getOp();
1144
1145     switch (op.getOp()) {
1146
1147     case Operation.UNARYPLUS:
1148     case Operation.UNARYMINUS:
1149     case Operation.LOGIC_NOT:
1150       // single operand
1151       return leftLoc;
1152
1153     case Operation.LOGIC_OR:
1154     case Operation.LOGIC_AND:
1155     case Operation.COMP:
1156     case Operation.BIT_OR:
1157     case Operation.BIT_XOR:
1158     case Operation.BIT_AND:
1159     case Operation.ISAVAILABLE:
1160     case Operation.EQUAL:
1161     case Operation.NOTEQUAL:
1162     case Operation.LT:
1163     case Operation.GT:
1164     case Operation.LTE:
1165     case Operation.GTE:
1166     case Operation.ADD:
1167     case Operation.SUB:
1168     case Operation.MULT:
1169     case Operation.DIV:
1170     case Operation.MOD:
1171     case Operation.LEFTSHIFT:
1172     case Operation.RIGHTSHIFT:
1173     case Operation.URIGHTSHIFT:
1174
1175       Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
1176       inputSet.add(leftLoc);
1177       inputSet.add(rightLoc);
1178       CompositeLocation glbCompLoc =
1179           CompositeLattice.calculateGLB(inputSet, generateErrorMessage(cd, on));
1180       System.out.println("# glbCompLoc=" + glbCompLoc);
1181       return glbCompLoc;
1182
1183     default:
1184       throw new Error(op.toString());
1185     }
1186
1187   }
1188
1189   private CompositeLocation checkLocationFromLiteralNode(MethodDescriptor md,
1190       SymbolTable nametable, LiteralNode en, CompositeLocation loc) {
1191
1192     // literal value has the top location so that value can be flowed into any
1193     // location
1194     Location literalLoc = Location.createTopLocation(md);
1195     loc.addLocation(literalLoc);
1196     return loc;
1197
1198   }
1199
1200   private CompositeLocation checkLocationFromNameNode(MethodDescriptor md, SymbolTable nametable,
1201       NameNode nn, CompositeLocation loc, CompositeLocation constraint) {
1202
1203     NameDescriptor nd = nn.getName();
1204     if (nd.getBase() != null) {
1205       loc =
1206           checkLocationFromExpressionNode(md, nametable, nn.getExpression(), loc, constraint, false);
1207     } else {
1208       String varname = nd.toString();
1209       if (varname.equals("this")) {
1210         // 'this' itself!
1211         MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
1212         String thisLocId = methodLattice.getThisLoc();
1213         if (thisLocId == null) {
1214           throw new Error("The location for 'this' is not defined at "
1215               + md.getClassDesc().getSourceFileName() + "::" + nn.getNumLine());
1216         }
1217         Location locElement = new Location(md, thisLocId);
1218         loc.addLocation(locElement);
1219         return loc;
1220
1221       }
1222
1223       Descriptor d = (Descriptor) nametable.get(varname);
1224
1225       // CompositeLocation localLoc = null;
1226       if (d instanceof VarDescriptor) {
1227         VarDescriptor vd = (VarDescriptor) d;
1228         // localLoc = d2loc.get(vd);
1229         // the type of var descriptor has a composite location!
1230         loc = ((CompositeLocation) vd.getType().getExtension()).clone();
1231       } else if (d instanceof FieldDescriptor) {
1232         // the type of field descriptor has a location!
1233         FieldDescriptor fd = (FieldDescriptor) d;
1234         if (fd.isStatic()) {
1235           if (fd.isFinal()) {
1236             // if it is 'static final', the location has TOP since no one can
1237             // change its value
1238             loc.addLocation(Location.createTopLocation(md));
1239             return loc;
1240           } else {
1241             // if 'static', the location has pre-assigned global loc
1242             MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1243             String globalLocId = localLattice.getGlobalLoc();
1244             if (globalLocId == null) {
1245               throw new Error("Global location element is not defined in the method " + md);
1246             }
1247             Location globalLoc = new Location(md, globalLocId);
1248
1249             loc.addLocation(globalLoc);
1250           }
1251         } else {
1252           // the location of field access starts from this, followed by field
1253           // location
1254           MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1255           Location thisLoc = new Location(md, localLattice.getThisLoc());
1256           loc.addLocation(thisLoc);
1257         }
1258
1259         Location fieldLoc = (Location) fd.getType().getExtension();
1260         loc.addLocation(fieldLoc);
1261       } else if (d == null) {
1262         // access static field
1263         ClassDescriptor cd = nn.getClassDesc();
1264
1265         MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1266         String globalLocId = localLattice.getGlobalLoc();
1267         if (globalLocId == null) {
1268           throw new Error("Method lattice does not define global variable location at "
1269               + generateErrorMessage(md.getClassDesc(), nn));
1270         }
1271         loc.addLocation(new Location(md, globalLocId));
1272         return loc;
1273
1274       }
1275     }
1276     return loc;
1277   }
1278
1279   private CompositeLocation checkLocationFromFieldAccessNode(MethodDescriptor md,
1280       SymbolTable nametable, FieldAccessNode fan, CompositeLocation loc,
1281       CompositeLocation constraint) {
1282
1283     ExpressionNode left = fan.getExpression();
1284     TypeDescriptor ltd = left.getType();
1285
1286     FieldDescriptor fd = fan.getField();
1287
1288     String varName = null;
1289     if (left.kind() == Kind.NameNode) {
1290       NameDescriptor nd = ((NameNode) left).getName();
1291       varName = nd.toString();
1292     }
1293
1294     if (ltd.isClassNameRef() || (varName != null && varName.equals("this"))) {
1295       // using a class name directly or access using this
1296       if (fd.isStatic() && fd.isFinal()) {
1297         loc.addLocation(Location.createTopLocation(md));
1298         return loc;
1299       }
1300     }
1301
1302     loc = checkLocationFromExpressionNode(md, nametable, left, loc, constraint, false);
1303     System.out.println("### checkLocationFromFieldAccessNode=" + fan.printNode(0));
1304     System.out.println("### left=" + left.printNode(0));
1305     if (!left.getType().isPrimitive()) {
1306       Location fieldLoc = getFieldLocation(fd);
1307       loc.addLocation(fieldLoc);
1308     }
1309
1310     return loc;
1311   }
1312
1313   private Location getFieldLocation(FieldDescriptor fd) {
1314
1315     System.out.println("### getFieldLocation=" + fd);
1316     System.out.println("### fd.getType().getExtension()=" + fd.getType().getExtension());
1317
1318     Location fieldLoc = (Location) fd.getType().getExtension();
1319
1320     // handle the case that method annotation checking skips checking field
1321     // declaration
1322     if (fieldLoc == null) {
1323       fieldLoc = checkFieldDeclaration(fd.getClassDescriptor(), fd);
1324     }
1325
1326     return fieldLoc;
1327
1328   }
1329
1330   private CompositeLocation checkLocationFromAssignmentNode(MethodDescriptor md,
1331       SymbolTable nametable, AssignmentNode an, CompositeLocation loc, CompositeLocation constraint) {
1332
1333     System.out.println("\n# ASSIGNMENTNODE=" + an.printNode(0));
1334
1335     ClassDescriptor cd = md.getClassDesc();
1336
1337     Set<CompositeLocation> inputGLBSet = new HashSet<CompositeLocation>();
1338
1339     boolean postinc = true;
1340     if (an.getOperation().getBaseOp() == null
1341         || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
1342             .getBaseOp().getOp() != Operation.POSTDEC))
1343       postinc = false;
1344
1345     // if LHS is array access node, need to check if array index is higher
1346     // than array itself
1347     CompositeLocation destLocation =
1348         checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation(),
1349             constraint, true);
1350
1351     CompositeLocation rhsLocation;
1352     CompositeLocation srcLocation;
1353
1354     if (!postinc) {
1355       rhsLocation =
1356           checkLocationFromExpressionNode(md, nametable, an.getSrc(), new CompositeLocation(),
1357               constraint, false);
1358
1359       System.out.println("dstLocation=" + destLocation);
1360       System.out.println("rhsLocation=" + rhsLocation);
1361       System.out.println("constraint=" + constraint);
1362
1363       srcLocation = rhsLocation;
1364
1365       if (!rhsLocation.get(rhsLocation.getSize() - 1).isTop()) {
1366         if (constraint != null) {
1367           inputGLBSet.add(rhsLocation);
1368           inputGLBSet.add(constraint);
1369           srcLocation = CompositeLattice.calculateGLB(inputGLBSet, generateErrorMessage(cd, an));
1370         }
1371       }
1372
1373       if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1374         throw new Error("The value flow from " + srcLocation + " to " + destLocation
1375             + " does not respect location hierarchy on the assignment " + an.printNode(0) + " at "
1376             + cd.getSourceFileName() + "::" + an.getNumLine());
1377       }
1378
1379     } else {
1380       destLocation =
1381           rhsLocation =
1382               checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation(),
1383                   constraint, false);
1384
1385       if (constraint != null) {
1386         inputGLBSet.add(rhsLocation);
1387         inputGLBSet.add(constraint);
1388         srcLocation = CompositeLattice.calculateGLB(inputGLBSet, generateErrorMessage(cd, an));
1389       } else {
1390         srcLocation = rhsLocation;
1391       }
1392
1393       System.out.println("srcLocation=" + srcLocation);
1394       System.out.println("rhsLocation=" + rhsLocation);
1395       System.out.println("constraint=" + constraint);
1396
1397       if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1398
1399         if (srcLocation.equals(destLocation)) {
1400           throw new Error("Location " + srcLocation
1401               + " is not allowed to have the value flow that moves within the same location at '"
1402               + an.printNode(0) + "' of " + cd.getSourceFileName() + "::" + an.getNumLine());
1403         } else {
1404           throw new Error("The value flow from " + srcLocation + " to " + destLocation
1405               + " does not respect location hierarchy on the assignment " + an.printNode(0)
1406               + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1407         }
1408
1409       }
1410
1411     }
1412
1413     return destLocation;
1414   }
1415
1416   private void assignLocationOfVarDescriptor(VarDescriptor vd, MethodDescriptor md,
1417       SymbolTable nametable, TreeNode n) {
1418
1419     ClassDescriptor cd = md.getClassDesc();
1420     Vector<AnnotationDescriptor> annotationVec = vd.getType().getAnnotationMarkers();
1421
1422     // currently enforce every variable to have corresponding location
1423     if (annotationVec.size() == 0) {
1424       throw new Error("Location is not assigned to variable " + vd.getSymbol() + " in the method "
1425           + md.getSymbol() + " of the class " + cd.getSymbol());
1426     }
1427
1428     if (annotationVec.size() > 1) { // variable can have at most one location
1429       throw new Error(vd.getSymbol() + " has more than one location.");
1430     }
1431
1432     AnnotationDescriptor ad = annotationVec.elementAt(0);
1433
1434     if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1435
1436       if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1437         String locDec = ad.getValue(); // check if location is defined
1438
1439         if (locDec.startsWith(SSJavaAnalysis.DELTA)) {
1440           DeltaLocation deltaLoc = parseDeltaDeclaration(md, n, locDec);
1441           d2loc.put(vd, deltaLoc);
1442           addLocationType(vd.getType(), deltaLoc);
1443         } else {
1444           CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1445
1446           Location lastElement = compLoc.get(compLoc.getSize() - 1);
1447           if (ssjava.isSharedLocation(lastElement)) {
1448             ssjava.mapSharedLocation2Descriptor(lastElement, vd);
1449           }
1450
1451           d2loc.put(vd, compLoc);
1452           addLocationType(vd.getType(), compLoc);
1453         }
1454
1455       }
1456     }
1457
1458   }
1459
1460   private DeltaLocation parseDeltaDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1461
1462     int deltaCount = 0;
1463     int dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1464     while (dIdx >= 0) {
1465       deltaCount++;
1466       int beginIdx = dIdx + 6;
1467       locDec = locDec.substring(beginIdx, locDec.length() - 1);
1468       dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1469     }
1470
1471     CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1472     DeltaLocation deltaLoc = new DeltaLocation(compLoc, deltaCount);
1473
1474     return deltaLoc;
1475   }
1476
1477   private Location parseFieldLocDeclaraton(String decl, String msg) throws Exception {
1478
1479     int idx = decl.indexOf(".");
1480
1481     String className = decl.substring(0, idx);
1482     String fieldName = decl.substring(idx + 1);
1483
1484     className.replaceAll(" ", "");
1485     fieldName.replaceAll(" ", "");
1486
1487     Descriptor d = state.getClassSymbolTable().get(className);
1488
1489     if (d == null) {
1490       System.out.println("state.getClassSymbolTable()=" + state.getClassSymbolTable());
1491       throw new Error("The class in the location declaration '" + decl + "' does not exist at "
1492           + msg);
1493     }
1494
1495     assert (d instanceof ClassDescriptor);
1496     SSJavaLattice<String> lattice = ssjava.getClassLattice((ClassDescriptor) d);
1497     if (!lattice.containsKey(fieldName)) {
1498       throw new Error("The location " + fieldName + " is not defined in the field lattice of '"
1499           + className + "' at " + msg);
1500     }
1501
1502     return new Location(d, fieldName);
1503   }
1504
1505   private CompositeLocation parseLocationDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1506
1507     CompositeLocation compLoc = new CompositeLocation();
1508
1509     StringTokenizer tokenizer = new StringTokenizer(locDec, ",");
1510     List<String> locIdList = new ArrayList<String>();
1511     while (tokenizer.hasMoreTokens()) {
1512       String locId = tokenizer.nextToken();
1513       locIdList.add(locId);
1514     }
1515
1516     // at least,one location element needs to be here!
1517     assert (locIdList.size() > 0);
1518
1519     // assume that loc with idx 0 comes from the local lattice
1520     // loc with idx 1 comes from the field lattice
1521
1522     String localLocId = locIdList.get(0);
1523     SSJavaLattice<String> localLattice = CompositeLattice.getLatticeByDescriptor(md);
1524     Location localLoc = new Location(md, localLocId);
1525     if (localLattice == null || (!localLattice.containsKey(localLocId))) {
1526       System.out.println("locDec=" + locDec);
1527       throw new Error("Location " + localLocId
1528           + " is not defined in the local variable lattice at "
1529           + md.getClassDesc().getSourceFileName() + "::" + (n != null ? n.getNumLine() : md) + ".");
1530     }
1531     compLoc.addLocation(localLoc);
1532
1533     for (int i = 1; i < locIdList.size(); i++) {
1534       String locName = locIdList.get(i);
1535       try {
1536         Location fieldLoc =
1537             parseFieldLocDeclaraton(locName, generateErrorMessage(md.getClassDesc(), n));
1538         compLoc.addLocation(fieldLoc);
1539       } catch (Exception e) {
1540         throw new Error("The location declaration '" + locName + "' is wrong  at "
1541             + generateErrorMessage(md.getClassDesc(), n));
1542       }
1543     }
1544
1545     return compLoc;
1546
1547   }
1548
1549   private void checkDeclarationNode(MethodDescriptor md, SymbolTable nametable, DeclarationNode dn) {
1550     VarDescriptor vd = dn.getVarDescriptor();
1551     assignLocationOfVarDescriptor(vd, md, nametable, dn);
1552   }
1553
1554   private void checkDeclarationInClass(ClassDescriptor cd) {
1555     // Check to see that fields are okay
1556     for (Iterator field_it = cd.getFields(); field_it.hasNext();) {
1557       FieldDescriptor fd = (FieldDescriptor) field_it.next();
1558
1559       if (!(fd.isFinal() && fd.isStatic())) {
1560         checkFieldDeclaration(cd, fd);
1561       } else {
1562         // for static final, assign top location by default
1563         Location loc = Location.createTopLocation(cd);
1564         addLocationType(fd.getType(), loc);
1565       }
1566     }
1567   }
1568
1569   private Location checkFieldDeclaration(ClassDescriptor cd, FieldDescriptor fd) {
1570
1571     Vector<AnnotationDescriptor> annotationVec = fd.getType().getAnnotationMarkers();
1572
1573     // currently enforce every field to have corresponding location
1574     if (annotationVec.size() == 0) {
1575       throw new Error("Location is not assigned to the field '" + fd.getSymbol()
1576           + "' of the class " + cd.getSymbol() + " at " + cd.getSourceFileName());
1577     }
1578
1579     if (annotationVec.size() > 1) {
1580       // variable can have at most one location
1581       throw new Error("Field " + fd.getSymbol() + " of class " + cd
1582           + " has more than one location.");
1583     }
1584
1585     AnnotationDescriptor ad = annotationVec.elementAt(0);
1586     Location loc = null;
1587
1588     if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1589       if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1590         String locationID = ad.getValue();
1591         // check if location is defined
1592         SSJavaLattice<String> lattice = ssjava.getClassLattice(cd);
1593         if (lattice == null || (!lattice.containsKey(locationID))) {
1594           throw new Error("Location " + locationID
1595               + " is not defined in the field lattice of class " + cd.getSymbol() + " at"
1596               + cd.getSourceFileName() + ".");
1597         }
1598         loc = new Location(cd, locationID);
1599
1600         if (ssjava.isSharedLocation(loc)) {
1601           ssjava.mapSharedLocation2Descriptor(loc, fd);
1602         }
1603
1604         addLocationType(fd.getType(), loc);
1605
1606       }
1607     }
1608
1609     return loc;
1610   }
1611
1612   private void addLocationType(TypeDescriptor type, CompositeLocation loc) {
1613     if (type != null) {
1614       type.setExtension(loc);
1615     }
1616   }
1617
1618   private void addLocationType(TypeDescriptor type, Location loc) {
1619     if (type != null) {
1620       type.setExtension(loc);
1621     }
1622   }
1623
1624   static class CompositeLattice {
1625
1626     public static boolean isGreaterThan(CompositeLocation loc1, CompositeLocation loc2, String msg) {
1627
1628       System.out.println("\nisGreaterThan=" + loc1 + " " + loc2 + " msg=" + msg);
1629       int baseCompareResult = compareBaseLocationSet(loc1, loc2, true, false, msg);
1630       if (baseCompareResult == ComparisonResult.EQUAL) {
1631         if (compareDelta(loc1, loc2) == ComparisonResult.GREATER) {
1632           return true;
1633         } else {
1634           return false;
1635         }
1636       } else if (baseCompareResult == ComparisonResult.GREATER) {
1637         return true;
1638       } else {
1639         return false;
1640       }
1641
1642     }
1643
1644     public static int compare(CompositeLocation loc1, CompositeLocation loc2, boolean ignore,
1645         String msg) {
1646
1647       System.out.println("compare=" + loc1 + " " + loc2);
1648       int baseCompareResult = compareBaseLocationSet(loc1, loc2, false, ignore, msg);
1649
1650       if (baseCompareResult == ComparisonResult.EQUAL) {
1651         return compareDelta(loc1, loc2);
1652       } else {
1653         return baseCompareResult;
1654       }
1655
1656     }
1657
1658     private static int compareDelta(CompositeLocation dLoc1, CompositeLocation dLoc2) {
1659
1660       int deltaCount1 = 0;
1661       int deltaCount2 = 0;
1662       if (dLoc1 instanceof DeltaLocation) {
1663         deltaCount1 = ((DeltaLocation) dLoc1).getNumDelta();
1664       }
1665
1666       if (dLoc2 instanceof DeltaLocation) {
1667         deltaCount2 = ((DeltaLocation) dLoc2).getNumDelta();
1668       }
1669       if (deltaCount1 < deltaCount2) {
1670         return ComparisonResult.GREATER;
1671       } else if (deltaCount1 == deltaCount2) {
1672         return ComparisonResult.EQUAL;
1673       } else {
1674         return ComparisonResult.LESS;
1675       }
1676
1677     }
1678
1679     private static int compareBaseLocationSet(CompositeLocation compLoc1,
1680         CompositeLocation compLoc2, boolean awareSharedLoc, boolean ignore, String msg) {
1681
1682       // if compLoc1 is greater than compLoc2, return true
1683       // else return false;
1684
1685       // compare one by one in according to the order of the tuple
1686       int numOfTie = 0;
1687       for (int i = 0; i < compLoc1.getSize(); i++) {
1688         Location loc1 = compLoc1.get(i);
1689         if (i >= compLoc2.getSize()) {
1690           if (ignore) {
1691             return ComparisonResult.INCOMPARABLE;
1692           } else {
1693             throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1694                 + " because they are not comparable at " + msg);
1695           }
1696         }
1697         Location loc2 = compLoc2.get(i);
1698
1699         Descriptor descriptor = getCommonParentDescriptor(loc1, loc2, msg);
1700         SSJavaLattice<String> lattice = getLatticeByDescriptor(descriptor);
1701
1702         // check if the shared location is appeared only at the end of the
1703         // composite location
1704         if (lattice.getSharedLocSet().contains(loc1.getLocIdentifier())) {
1705           if (i != (compLoc1.getSize() - 1)) {
1706             throw new Error("The shared location " + loc1.getLocIdentifier()
1707                 + " cannot be appeared in the middle of composite location at" + msg);
1708           }
1709         }
1710
1711         if (lattice.getSharedLocSet().contains(loc2.getLocIdentifier())) {
1712           if (i != (compLoc2.getSize() - 1)) {
1713             throw new Error("The shared location " + loc2.getLocIdentifier()
1714                 + " cannot be appeared in the middle of composite location at " + msg);
1715           }
1716         }
1717
1718         // if (!lattice1.equals(lattice2)) {
1719         // throw new Error("Failed to compare two locations of " + compLoc1 +
1720         // " and " + compLoc2
1721         // + " because they are not comparable at " + msg);
1722         // }
1723
1724         if (loc1.getLocIdentifier().equals(loc2.getLocIdentifier())) {
1725           numOfTie++;
1726           // check if the current location is the spinning location
1727           // note that the spinning location only can be appeared in the last
1728           // part of the composite location
1729           if (awareSharedLoc && numOfTie == compLoc1.getSize()
1730               && lattice.getSharedLocSet().contains(loc1.getLocIdentifier())) {
1731             return ComparisonResult.GREATER;
1732           }
1733           continue;
1734         } else if (lattice.isGreaterThan(loc1.getLocIdentifier(), loc2.getLocIdentifier())) {
1735           return ComparisonResult.GREATER;
1736         } else {
1737           return ComparisonResult.LESS;
1738         }
1739
1740       }
1741
1742       if (numOfTie == compLoc1.getSize()) {
1743
1744         if (numOfTie != compLoc2.getSize()) {
1745
1746           if (ignore) {
1747             return ComparisonResult.INCOMPARABLE;
1748           } else {
1749             throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1750                 + " because they are not comparable at " + msg);
1751           }
1752
1753         }
1754
1755         return ComparisonResult.EQUAL;
1756       }
1757
1758       return ComparisonResult.LESS;
1759
1760     }
1761
1762     public static CompositeLocation calculateGLB(Set<CompositeLocation> inputSet, String errMsg) {
1763
1764       System.out.println("Calculating GLB=" + inputSet);
1765       CompositeLocation glbCompLoc = new CompositeLocation();
1766
1767       // calculate GLB of the first(priority) element
1768       Set<String> priorityLocIdentifierSet = new HashSet<String>();
1769       Descriptor priorityDescriptor = null;
1770
1771       Hashtable<String, Set<CompositeLocation>> locId2CompLocSet =
1772           new Hashtable<String, Set<CompositeLocation>>();
1773       // mapping from the priority loc ID to its full representation by the
1774       // composite location
1775
1776       int maxTupleSize = 0;
1777       CompositeLocation maxCompLoc = null;
1778
1779       Location prevPriorityLoc = null;
1780       for (Iterator iterator = inputSet.iterator(); iterator.hasNext();) {
1781         CompositeLocation compLoc = (CompositeLocation) iterator.next();
1782         if (compLoc.getSize() > maxTupleSize) {
1783           maxTupleSize = compLoc.getSize();
1784           maxCompLoc = compLoc;
1785         }
1786         Location priorityLoc = compLoc.get(0);
1787         String priorityLocId = priorityLoc.getLocIdentifier();
1788         priorityLocIdentifierSet.add(priorityLocId);
1789
1790         if (locId2CompLocSet.containsKey(priorityLocId)) {
1791           locId2CompLocSet.get(priorityLocId).add(compLoc);
1792         } else {
1793           Set<CompositeLocation> newSet = new HashSet<CompositeLocation>();
1794           newSet.add(compLoc);
1795           locId2CompLocSet.put(priorityLocId, newSet);
1796         }
1797
1798         // check if priority location are coming from the same lattice
1799         if (priorityDescriptor == null) {
1800           priorityDescriptor = priorityLoc.getDescriptor();
1801         } else {
1802           priorityDescriptor = getCommonParentDescriptor(priorityLoc, prevPriorityLoc, errMsg);
1803         }
1804         prevPriorityLoc = priorityLoc;
1805         // else if (!priorityDescriptor.equals(priorityLoc.getDescriptor())) {
1806         // throw new Error("Failed to calculate GLB of " + inputSet
1807         // + " because they are from different lattices.");
1808         // }
1809       }
1810
1811       SSJavaLattice<String> locOrder = getLatticeByDescriptor(priorityDescriptor);
1812       String glbOfPriorityLoc = locOrder.getGLB(priorityLocIdentifierSet);
1813
1814       glbCompLoc.addLocation(new Location(priorityDescriptor, glbOfPriorityLoc));
1815       Set<CompositeLocation> compSet = locId2CompLocSet.get(glbOfPriorityLoc);
1816
1817       if (compSet == null) {
1818         // when GLB(x1,x2)!=x1 and !=x2 : GLB case 4
1819         // mean that the result is already lower than <x1,y1> and <x2,y2>
1820         // assign TOP to the rest of the location elements
1821
1822         // in this case, do not take care about delta
1823         // CompositeLocation inputComp = inputSet.iterator().next();
1824         for (int i = 1; i < maxTupleSize; i++) {
1825           glbCompLoc.addLocation(Location.createTopLocation(maxCompLoc.get(i).getDescriptor()));
1826         }
1827       } else {
1828
1829         // here find out composite location that has a maximum length tuple
1830         // if we have three input set: [A], [A,B], [A,B,C]
1831         // maximum length tuple will be [A,B,C]
1832         int max = 0;
1833         CompositeLocation maxFromCompSet = null;
1834         for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1835           CompositeLocation c = (CompositeLocation) iterator.next();
1836           if (c.getSize() > max) {
1837             max = c.getSize();
1838             maxFromCompSet = c;
1839           }
1840         }
1841
1842         if (compSet.size() == 1) {
1843           // if GLB(x1,x2)==x1 or x2 : GLB case 2,3
1844           CompositeLocation comp = compSet.iterator().next();
1845           for (int i = 1; i < comp.getSize(); i++) {
1846             glbCompLoc.addLocation(comp.get(i));
1847           }
1848
1849           // if input location corresponding to glb is a delta, need to apply
1850           // delta to glb result
1851           if (comp instanceof DeltaLocation) {
1852             glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1853           }
1854
1855         } else {
1856           // when GLB(x1,x2)==x1 and x2 : GLB case 1
1857           // if more than one location shares the same priority GLB
1858           // need to calculate the rest of GLB loc
1859
1860           // setup input set starting from the second tuple item
1861           Set<CompositeLocation> innerGLBInput = new HashSet<CompositeLocation>();
1862           for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1863             CompositeLocation compLoc = (CompositeLocation) iterator.next();
1864             CompositeLocation innerCompLoc = new CompositeLocation();
1865             for (int idx = 1; idx < compLoc.getSize(); idx++) {
1866               innerCompLoc.addLocation(compLoc.get(idx));
1867             }
1868             if (innerCompLoc.getSize() > 0) {
1869               innerGLBInput.add(innerCompLoc);
1870             }
1871           }
1872
1873           if (innerGLBInput.size() > 0) {
1874             CompositeLocation innerGLB = CompositeLattice.calculateGLB(innerGLBInput, errMsg);
1875             for (int idx = 0; idx < innerGLB.getSize(); idx++) {
1876               glbCompLoc.addLocation(innerGLB.get(idx));
1877             }
1878           }
1879
1880           // if input location corresponding to glb is a delta, need to apply
1881           // delta to glb result
1882
1883           for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1884             CompositeLocation compLoc = (CompositeLocation) iterator.next();
1885             if (compLoc instanceof DeltaLocation) {
1886               if (glbCompLoc.equals(compLoc)) {
1887                 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1888                 break;
1889               }
1890             }
1891           }
1892
1893         }
1894       }
1895
1896       System.out.println("GLB=" + glbCompLoc);
1897       return glbCompLoc;
1898
1899     }
1900
1901     static SSJavaLattice<String> getLatticeByDescriptor(Descriptor d) {
1902
1903       SSJavaLattice<String> lattice = null;
1904
1905       if (d instanceof ClassDescriptor) {
1906         lattice = ssjava.getCd2lattice().get(d);
1907       } else if (d instanceof MethodDescriptor) {
1908         if (ssjava.getMd2lattice().containsKey(d)) {
1909           lattice = ssjava.getMd2lattice().get(d);
1910         } else {
1911           // use default lattice for the method
1912           lattice = ssjava.getCd2methodDefault().get(((MethodDescriptor) d).getClassDesc());
1913         }
1914       }
1915
1916       return lattice;
1917     }
1918
1919     static Descriptor getCommonParentDescriptor(Location loc1, Location loc2, String msg) {
1920
1921       Descriptor d1 = loc1.getDescriptor();
1922       Descriptor d2 = loc2.getDescriptor();
1923
1924       Descriptor descriptor;
1925
1926       if (d1 instanceof ClassDescriptor && d2 instanceof ClassDescriptor) {
1927
1928         if (d1.equals(d2)) {
1929           descriptor = d1;
1930         } else {
1931           // identifying which one is parent class
1932           Set<Descriptor> d1SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d1);
1933           Set<Descriptor> d2SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d2);
1934
1935           if (d1 == null && d2 == null) {
1936             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1937                 + " because they are not comparable at " + msg);
1938           } else if (d1SubClassesSet != null && d1SubClassesSet.contains(d2)) {
1939             descriptor = d1;
1940           } else if (d2SubClassesSet != null && d2SubClassesSet.contains(d1)) {
1941             descriptor = d2;
1942           } else {
1943             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1944                 + " because they are not comparable at " + msg);
1945           }
1946         }
1947
1948       } else if (d1 instanceof MethodDescriptor && d2 instanceof MethodDescriptor) {
1949
1950         if (d1.equals(d2)) {
1951           descriptor = d1;
1952         } else {
1953
1954           // identifying which one is parent class
1955           MethodDescriptor md1 = (MethodDescriptor) d1;
1956           MethodDescriptor md2 = (MethodDescriptor) d2;
1957
1958           if (!md1.matches(md2)) {
1959             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1960                 + " because they are not comparable at " + msg);
1961           }
1962
1963           Set<Descriptor> d1SubClassesSet =
1964               ssjava.tu.getSubClasses(((MethodDescriptor) d1).getClassDesc());
1965           Set<Descriptor> d2SubClassesSet =
1966               ssjava.tu.getSubClasses(((MethodDescriptor) d2).getClassDesc());
1967
1968           if (d1 == null && d2 == null) {
1969             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1970                 + " because they are not comparable at " + msg);
1971           } else if (d1 != null && d1SubClassesSet.contains(d2)) {
1972             descriptor = d1;
1973           } else if (d2 != null && d2SubClassesSet.contains(d1)) {
1974             descriptor = d2;
1975           } else {
1976             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1977                 + " because they are not comparable at " + msg);
1978           }
1979         }
1980
1981       } else {
1982         throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1983             + " because they are not comparable at " + msg);
1984       }
1985
1986       return descriptor;
1987
1988     }
1989
1990   }
1991
1992   class ComparisonResult {
1993
1994     public static final int GREATER = 0;
1995     public static final int EQUAL = 1;
1996     public static final int LESS = 2;
1997     public static final int INCOMPARABLE = 3;
1998     int result;
1999
2000   }
2001
2002 }
2003
2004 class ReturnLocGenerator {
2005
2006   public static final int PARAMISHIGHER = 0;
2007   public static final int PARAMISSAME = 1;
2008   public static final int IGNORE = 2;
2009
2010   private Hashtable<Integer, Integer> paramIdx2paramType;
2011
2012   private CompositeLocation declaredReturnLoc = null;
2013
2014   public ReturnLocGenerator(CompositeLocation returnLoc, MethodDescriptor md,
2015       List<CompositeLocation> params, String msg) {
2016
2017     CompositeLocation thisLoc = params.get(0);
2018     if (returnLoc.get(0).equals(thisLoc.get(0)) && returnLoc.getSize() > 1) {
2019       // if the declared return location consists of THIS and field location,
2020       // return location for the caller's side has to have same field element
2021       this.declaredReturnLoc = returnLoc;
2022     } else {
2023       // creating mappings
2024       paramIdx2paramType = new Hashtable<Integer, Integer>();
2025       for (int i = 0; i < params.size(); i++) {
2026         CompositeLocation param = params.get(i);
2027         int compareResult = CompositeLattice.compare(param, returnLoc, true, msg);
2028
2029         int type;
2030         if (compareResult == ComparisonResult.GREATER) {
2031           type = 0;
2032         } else if (compareResult == ComparisonResult.EQUAL) {
2033           type = 1;
2034         } else {
2035           type = 2;
2036         }
2037         paramIdx2paramType.put(new Integer(i), new Integer(type));
2038       }
2039     }
2040
2041   }
2042
2043   public CompositeLocation computeReturnLocation(List<CompositeLocation> args) {
2044
2045     if (declaredReturnLoc != null) {
2046       // when developer specify that the return value is [THIS,field]
2047       // needs to translate to the caller's location
2048       CompositeLocation callerLoc = new CompositeLocation();
2049       CompositeLocation callerBaseLocation = args.get(0);
2050
2051       for (int i = 0; i < callerBaseLocation.getSize(); i++) {
2052         callerLoc.addLocation(callerBaseLocation.get(i));
2053       }
2054       for (int i = 1; i < declaredReturnLoc.getSize(); i++) {
2055         callerLoc.addLocation(declaredReturnLoc.get(i));
2056       }
2057       return callerLoc;
2058     } else {
2059       // compute the highest possible location in caller's side
2060       assert paramIdx2paramType.keySet().size() == args.size();
2061
2062       Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
2063       for (int i = 0; i < args.size(); i++) {
2064         int type = (paramIdx2paramType.get(new Integer(i))).intValue();
2065         CompositeLocation argLoc = args.get(i);
2066         if (type == PARAMISHIGHER) {
2067           // return loc is lower than param
2068           DeltaLocation delta = new DeltaLocation(argLoc, 1);
2069           inputGLB.add(delta);
2070         } else if (type == PARAMISSAME) {
2071           // return loc is equal or lower than param
2072           inputGLB.add(argLoc);
2073         }
2074       }
2075
2076       // compute GLB of arguments subset that are same or higher than return
2077       // location
2078       CompositeLocation glb = CompositeLattice.calculateGLB(inputGLB, "");
2079       return glb;
2080     }
2081
2082   }
2083 }