bug fix on flow-down rule: check if all of assignments done by invoking method respec...
[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, null);
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       CompositeLocation constraints) {
436     BlockNode bn = state.getMethodBody(md);
437     checkLocationFromBlockNode(md, md.getParameterTable(), bn, constraints);
438   }
439
440   private String generateErrorMessage(ClassDescriptor cd, TreeNode tn) {
441     if (tn != null) {
442       return cd.getSourceFileName() + "::" + tn.getNumLine();
443     } else {
444       return cd.getSourceFileName();
445     }
446
447   }
448
449   private CompositeLocation checkLocationFromBlockNode(MethodDescriptor md, SymbolTable nametable,
450       BlockNode bn, CompositeLocation constraint) {
451
452     bn.getVarTable().setParent(nametable);
453     for (int i = 0; i < bn.size(); i++) {
454       BlockStatementNode bsn = bn.get(i);
455       checkLocationFromBlockStatementNode(md, bn.getVarTable(), bsn, constraint);
456     }
457     return new CompositeLocation();
458
459   }
460
461   private CompositeLocation checkLocationFromBlockStatementNode(MethodDescriptor md,
462       SymbolTable nametable, BlockStatementNode bsn, CompositeLocation constraint) {
463
464     CompositeLocation compLoc = null;
465     switch (bsn.kind()) {
466     case Kind.BlockExpressionNode:
467       compLoc =
468           checkLocationFromBlockExpressionNode(md, nametable, (BlockExpressionNode) bsn, constraint);
469       break;
470
471     case Kind.DeclarationNode:
472       compLoc = checkLocationFromDeclarationNode(md, nametable, (DeclarationNode) bsn, constraint);
473       break;
474
475     case Kind.IfStatementNode:
476       compLoc = checkLocationFromIfStatementNode(md, nametable, (IfStatementNode) bsn, constraint);
477       break;
478
479     case Kind.LoopNode:
480       compLoc = checkLocationFromLoopNode(md, nametable, (LoopNode) bsn, constraint);
481       break;
482
483     case Kind.ReturnNode:
484       compLoc = checkLocationFromReturnNode(md, nametable, (ReturnNode) bsn, constraint);
485       break;
486
487     case Kind.SubBlockNode:
488       compLoc = checkLocationFromSubBlockNode(md, nametable, (SubBlockNode) bsn, constraint);
489       break;
490
491     case Kind.ContinueBreakNode:
492       compLoc = new CompositeLocation();
493       break;
494
495     case Kind.SwitchStatementNode:
496       compLoc =
497           checkLocationFromSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn, constraint);
498
499     }
500     return compLoc;
501   }
502
503   private CompositeLocation checkLocationFromSwitchStatementNode(MethodDescriptor md,
504       SymbolTable nametable, SwitchStatementNode ssn, CompositeLocation constraint) {
505
506     ClassDescriptor cd = md.getClassDesc();
507     CompositeLocation condLoc =
508         checkLocationFromExpressionNode(md, nametable, ssn.getCondition(), new CompositeLocation(),
509             constraint, false);
510     BlockNode sbn = ssn.getSwitchBody();
511
512     constraint = generateNewConstraint(constraint, condLoc);
513
514     for (int i = 0; i < sbn.size(); i++) {
515       checkLocationFromSwitchBlockNode(md, nametable, (SwitchBlockNode) sbn.get(i), constraint);
516     }
517     return new CompositeLocation();
518   }
519
520   private CompositeLocation checkLocationFromSwitchBlockNode(MethodDescriptor md,
521       SymbolTable nametable, SwitchBlockNode sbn, CompositeLocation constraint) {
522
523     CompositeLocation blockLoc =
524         checkLocationFromBlockNode(md, nametable, sbn.getSwitchBlockStatement(), constraint);
525
526     return blockLoc;
527
528   }
529
530   private CompositeLocation checkLocationFromReturnNode(MethodDescriptor md, SymbolTable nametable,
531       ReturnNode rn, CompositeLocation constraint) {
532
533     ExpressionNode returnExp = rn.getReturnExpression();
534
535     CompositeLocation returnValueLoc;
536     if (returnExp != null) {
537       returnValueLoc =
538           checkLocationFromExpressionNode(md, nametable, returnExp, new CompositeLocation(),
539               constraint, false);
540
541       // if this return statement is inside branch, return value has an implicit
542       // flow from conditional location
543       if (constraint != null) {
544         Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
545         inputGLB.add(returnValueLoc);
546         inputGLB.add(constraint);
547         returnValueLoc =
548             CompositeLattice.calculateGLB(inputGLB, generateErrorMessage(md.getClassDesc(), rn));
549       }
550
551       // check if return value is equal or higher than RETRUNLOC of method
552       // declaration annotation
553       CompositeLocation declaredReturnLoc = md2ReturnLoc.get(md);
554
555       int compareResult =
556           CompositeLattice.compare(returnValueLoc, declaredReturnLoc, false,
557               generateErrorMessage(md.getClassDesc(), rn));
558
559       if (compareResult == ComparisonResult.LESS || compareResult == ComparisonResult.INCOMPARABLE) {
560         throw new Error(
561             "Return value location is not equal or higher than the declaraed return location at "
562                 + md.getClassDesc().getSourceFileName() + "::" + rn.getNumLine());
563       }
564     }
565
566     return new CompositeLocation();
567   }
568
569   private boolean hasOnlyLiteralValue(ExpressionNode en) {
570     if (en.kind() == Kind.LiteralNode) {
571       return true;
572     } else {
573       return false;
574     }
575   }
576
577   private CompositeLocation checkLocationFromLoopNode(MethodDescriptor md, SymbolTable nametable,
578       LoopNode ln, CompositeLocation constraint) {
579
580     ClassDescriptor cd = md.getClassDesc();
581     if (ln.getType() == LoopNode.WHILELOOP || ln.getType() == LoopNode.DOWHILELOOP) {
582
583       CompositeLocation condLoc =
584           checkLocationFromExpressionNode(md, nametable, ln.getCondition(),
585               new CompositeLocation(), constraint, false);
586       // addLocationType(ln.getCondition().getType(), (condLoc));
587
588       constraint = generateNewConstraint(constraint, condLoc);
589       checkLocationFromBlockNode(md, nametable, ln.getBody(), constraint);
590
591       return new CompositeLocation();
592
593     } else {
594       // check 'for loop' case
595       BlockNode bn = ln.getInitializer();
596       bn.getVarTable().setParent(nametable);
597
598       // calculate glb location of condition and update statements
599       CompositeLocation condLoc =
600           checkLocationFromExpressionNode(md, bn.getVarTable(), ln.getCondition(),
601               new CompositeLocation(), constraint, false);
602       // addLocationType(ln.getCondition().getType(), condLoc);
603
604       constraint = generateNewConstraint(constraint, condLoc);
605
606       checkLocationFromBlockNode(md, bn.getVarTable(), ln.getUpdate(), constraint);
607       checkLocationFromBlockNode(md, bn.getVarTable(), ln.getBody(), constraint);
608
609       return new CompositeLocation();
610
611     }
612
613   }
614
615   private CompositeLocation checkLocationFromSubBlockNode(MethodDescriptor md,
616       SymbolTable nametable, SubBlockNode sbn, CompositeLocation constraint) {
617     CompositeLocation compLoc =
618         checkLocationFromBlockNode(md, nametable, sbn.getBlockNode(), constraint);
619     return compLoc;
620   }
621
622   private CompositeLocation generateNewConstraint(CompositeLocation currentCon,
623       CompositeLocation newCon) {
624
625     if (currentCon == null) {
626       return newCon;
627     } else {
628       // compute GLB of current constraint and new constraint
629       Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
630       inputSet.add(currentCon);
631       inputSet.add(newCon);
632       return CompositeLattice.calculateGLB(inputSet, "");
633     }
634
635   }
636
637   private CompositeLocation checkLocationFromIfStatementNode(MethodDescriptor md,
638       SymbolTable nametable, IfStatementNode isn, CompositeLocation constraint) {
639
640     CompositeLocation condLoc =
641         checkLocationFromExpressionNode(md, nametable, isn.getCondition(), new CompositeLocation(),
642             constraint, false);
643
644     // addLocationType(isn.getCondition().getType(), condLoc);
645
646     constraint = generateNewConstraint(constraint, condLoc);
647     checkLocationFromBlockNode(md, nametable, isn.getTrueBlock(), constraint);
648
649     if (isn.getFalseBlock() != null) {
650       checkLocationFromBlockNode(md, nametable, isn.getFalseBlock(), constraint);
651     }
652
653     return new CompositeLocation();
654   }
655
656   private CompositeLocation checkLocationFromDeclarationNode(MethodDescriptor md,
657       SymbolTable nametable, DeclarationNode dn, CompositeLocation constraint) {
658
659     VarDescriptor vd = dn.getVarDescriptor();
660
661     CompositeLocation destLoc = d2loc.get(vd);
662
663     if (dn.getExpression() != null) {
664       CompositeLocation expressionLoc =
665           checkLocationFromExpressionNode(md, nametable, dn.getExpression(),
666               new CompositeLocation(), constraint, false);
667       // addTypeLocation(dn.getExpression().getType(), expressionLoc);
668
669       if (expressionLoc != null) {
670         // checking location order
671         if (!CompositeLattice.isGreaterThan(expressionLoc, destLoc,
672             generateErrorMessage(md.getClassDesc(), dn))) {
673           throw new Error("The value flow from " + expressionLoc + " to " + destLoc
674               + " does not respect location hierarchy on the assignment " + dn.printNode(0)
675               + " at " + md.getClassDesc().getSourceFileName() + "::" + dn.getNumLine());
676         }
677       }
678       return expressionLoc;
679
680     } else {
681
682       return new CompositeLocation();
683
684     }
685
686   }
687
688   private void checkDeclarationInSubBlockNode(MethodDescriptor md, SymbolTable nametable,
689       SubBlockNode sbn) {
690     checkDeclarationInBlockNode(md, nametable.getParent(), sbn.getBlockNode());
691   }
692
693   private CompositeLocation checkLocationFromBlockExpressionNode(MethodDescriptor md,
694       SymbolTable nametable, BlockExpressionNode ben, CompositeLocation constraint) {
695     CompositeLocation compLoc =
696         checkLocationFromExpressionNode(md, nametable, ben.getExpression(), null, constraint, false);
697     // addTypeLocation(ben.getExpression().getType(), compLoc);
698     return compLoc;
699   }
700
701   private CompositeLocation checkLocationFromExpressionNode(MethodDescriptor md,
702       SymbolTable nametable, ExpressionNode en, CompositeLocation loc,
703       CompositeLocation constraint, boolean isLHS) {
704
705     CompositeLocation compLoc = null;
706     switch (en.kind()) {
707
708     case Kind.AssignmentNode:
709       compLoc =
710           checkLocationFromAssignmentNode(md, nametable, (AssignmentNode) en, loc, constraint);
711       break;
712
713     case Kind.FieldAccessNode:
714       compLoc =
715           checkLocationFromFieldAccessNode(md, nametable, (FieldAccessNode) en, loc, constraint);
716       break;
717
718     case Kind.NameNode:
719       compLoc = checkLocationFromNameNode(md, nametable, (NameNode) en, loc, constraint);
720       break;
721
722     case Kind.OpNode:
723       compLoc = checkLocationFromOpNode(md, nametable, (OpNode) en, constraint);
724       break;
725
726     case Kind.CreateObjectNode:
727       compLoc = checkLocationFromCreateObjectNode(md, nametable, (CreateObjectNode) en);
728       break;
729
730     case Kind.ArrayAccessNode:
731       compLoc =
732           checkLocationFromArrayAccessNode(md, nametable, (ArrayAccessNode) en, constraint, isLHS);
733       break;
734
735     case Kind.LiteralNode:
736       compLoc = checkLocationFromLiteralNode(md, nametable, (LiteralNode) en, loc);
737       break;
738
739     case Kind.MethodInvokeNode:
740       compLoc =
741           checkLocationFromMethodInvokeNode(md, nametable, (MethodInvokeNode) en, loc, constraint);
742       break;
743
744     case Kind.TertiaryNode:
745       compLoc = checkLocationFromTertiaryNode(md, nametable, (TertiaryNode) en, constraint);
746       break;
747
748     case Kind.CastNode:
749       compLoc = checkLocationFromCastNode(md, nametable, (CastNode) en, constraint);
750       break;
751
752     // case Kind.InstanceOfNode:
753     // checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
754     // return null;
755
756     // case Kind.ArrayInitializerNode:
757     // checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en,
758     // td);
759     // return null;
760
761     // case Kind.ClassTypeNode:
762     // checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
763     // return null;
764
765     // case Kind.OffsetNode:
766     // checkOffsetNode(md, nametable, (OffsetNode)en, td);
767     // return null;
768
769     default:
770       return null;
771
772     }
773     // addTypeLocation(en.getType(), compLoc);
774     return compLoc;
775
776   }
777
778   private CompositeLocation checkLocationFromCastNode(MethodDescriptor md, SymbolTable nametable,
779       CastNode cn, CompositeLocation constraint) {
780
781     ExpressionNode en = cn.getExpression();
782     return checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
783         false);
784
785   }
786
787   private CompositeLocation checkLocationFromTertiaryNode(MethodDescriptor md,
788       SymbolTable nametable, TertiaryNode tn, CompositeLocation constraint) {
789     ClassDescriptor cd = md.getClassDesc();
790
791     CompositeLocation condLoc =
792         checkLocationFromExpressionNode(md, nametable, tn.getCond(), new CompositeLocation(),
793             constraint, false);
794     // addLocationType(tn.getCond().getType(), condLoc);
795     CompositeLocation trueLoc =
796         checkLocationFromExpressionNode(md, nametable, tn.getTrueExpr(), new CompositeLocation(),
797             constraint, false);
798     // addLocationType(tn.getTrueExpr().getType(), trueLoc);
799     CompositeLocation falseLoc =
800         checkLocationFromExpressionNode(md, nametable, tn.getFalseExpr(), new CompositeLocation(),
801             constraint, false);
802     // addLocationType(tn.getFalseExpr().getType(), falseLoc);
803
804     // locations from true/false branches can be TOP when there are only literal
805     // values
806     // in this case, we don't need to check flow down rule!
807
808     // check if condLoc is higher than trueLoc & falseLoc
809     if (!trueLoc.get(0).isTop()
810         && !CompositeLattice.isGreaterThan(condLoc, trueLoc, generateErrorMessage(cd, tn))) {
811       throw new Error(
812           "The location of the condition expression is lower than the true expression at "
813               + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
814     }
815
816     if (!falseLoc.get(0).isTop()
817         && !CompositeLattice.isGreaterThan(condLoc, falseLoc,
818             generateErrorMessage(cd, tn.getCond()))) {
819       throw new Error(
820           "The location of the condition expression is lower than the true expression at "
821               + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
822     }
823
824     // then, return glb of trueLoc & falseLoc
825     Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
826     glbInputSet.add(trueLoc);
827     glbInputSet.add(falseLoc);
828
829     return CompositeLattice.calculateGLB(glbInputSet, generateErrorMessage(cd, tn));
830   }
831
832   private CompositeLocation checkLocationFromMethodInvokeNode(MethodDescriptor md,
833       SymbolTable nametable, MethodInvokeNode min, CompositeLocation loc,
834       CompositeLocation constraint) {
835
836     ClassDescriptor cd = md.getClassDesc();
837     MethodDescriptor calleeMD = min.getMethod();
838
839     if (!ssjava.isTrustMethod(calleeMD)) {
840       CompositeLocation baseLocation = null;
841       if (min.getExpression() != null) {
842         baseLocation =
843             checkLocationFromExpressionNode(md, nametable, min.getExpression(),
844                 new CompositeLocation(), constraint, false);
845       } else {
846
847         if (min.getMethod().isStatic()) {
848           String globalLocId = ssjava.getMethodLattice(md).getGlobalLoc();
849           if (globalLocId == null) {
850             throw new Error("Method lattice does not define global variable location at "
851                 + generateErrorMessage(md.getClassDesc(), min));
852           }
853           baseLocation = new CompositeLocation(new Location(md, globalLocId));
854         } else {
855           String thisLocId = ssjava.getMethodLattice(md).getThisLoc();
856           baseLocation = new CompositeLocation(new Location(md, thisLocId));
857         }
858
859       }
860
861       System.out.println("\n#checkLocationFromMethodInvokeNode=" + min.printNode(0)
862           + " baseLocation=" + baseLocation);
863
864       int compareResult =
865           CompositeLattice.compare(constraint, baseLocation, true, generateErrorMessage(cd, min));
866
867       if (compareResult == ComparisonResult.LESS) {
868         throw new Error("Method invocation does not respect the current branch constraint at "
869             + generateErrorMessage(cd, min));
870       } else if (compareResult != ComparisonResult.GREATER) {
871         // if the current constraint is higher than method's THIS location
872         // no need to check constraints!
873         CompositeLocation calleeConstraint =
874             translateCallerLocToCalleeLoc(calleeMD, baseLocation, constraint);
875         checkMethodBody(calleeMD.getClassDesc(), calleeMD, calleeConstraint);
876       }
877
878       checkCalleeConstraints(md, nametable, min, baseLocation, constraint);
879
880       checkCallerArgumentLocationConstraints(md, nametable, min, baseLocation, constraint);
881
882       if (!min.getMethod().getReturnType().isVoid()) {
883         // If method has a return value, compute the highest possible return
884         // location in the caller's perspective
885         CompositeLocation ceilingLoc =
886             computeCeilingLocationForCaller(md, nametable, min, baseLocation, constraint);
887         return ceilingLoc;
888       }
889     }
890
891     return new CompositeLocation();
892
893   }
894
895   private CompositeLocation translateCallerLocToCalleeLoc(MethodDescriptor calleeMD,
896       CompositeLocation calleeBaseLoc, CompositeLocation constraint) {
897
898     CompositeLocation calleeConstraint = new CompositeLocation();
899
900     // if (constraint.startsWith(calleeBaseLoc)) {
901     // if the first part of constraint loc is matched with callee base loc
902     Location thisLoc = new Location(calleeMD, ssjava.getMethodLattice(calleeMD).getThisLoc());
903     calleeConstraint.addLocation(thisLoc);
904     for (int i = calleeBaseLoc.getSize(); i < constraint.getSize(); i++) {
905       calleeConstraint.addLocation(constraint.get(i));
906     }
907
908     // }
909
910     return calleeConstraint;
911   }
912
913   private void checkCallerArgumentLocationConstraints(MethodDescriptor md, SymbolTable nametable,
914       MethodInvokeNode min, CompositeLocation callerBaseLoc, CompositeLocation constraint) {
915     // if parameter location consists of THIS and FIELD location,
916     // caller should pass an argument that is comparable to the declared
917     // parameter location
918     // and is not lower than the declared parameter location in the field
919     // lattice.
920
921     MethodDescriptor calleemd = min.getMethod();
922
923     List<CompositeLocation> callerArgList = new ArrayList<CompositeLocation>();
924     List<CompositeLocation> calleeParamList = new ArrayList<CompositeLocation>();
925
926     MethodLattice<String> calleeLattice = ssjava.getMethodLattice(calleemd);
927     Location calleeThisLoc = new Location(calleemd, calleeLattice.getThisLoc());
928
929     for (int i = 0; i < min.numArgs(); i++) {
930       ExpressionNode en = min.getArg(i);
931       CompositeLocation callerArgLoc =
932           checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
933               false);
934       callerArgList.add(callerArgLoc);
935     }
936
937     // setup callee params set
938     for (int i = 0; i < calleemd.numParameters(); i++) {
939       VarDescriptor calleevd = (VarDescriptor) calleemd.getParameter(i);
940       CompositeLocation calleeLoc = d2loc.get(calleevd);
941       calleeParamList.add(calleeLoc);
942     }
943
944     String errorMsg = generateErrorMessage(md.getClassDesc(), min);
945
946     System.out.println("checkCallerArgumentLocationConstraints=" + min.printNode(0));
947     System.out.println("base location=" + callerBaseLoc);
948
949     for (int i = 0; i < calleeParamList.size(); i++) {
950       CompositeLocation calleeParamLoc = calleeParamList.get(i);
951       if (calleeParamLoc.get(0).equals(calleeThisLoc) && calleeParamLoc.getSize() > 1) {
952
953         // callee parameter location has field information
954         CompositeLocation callerArgLoc = callerArgList.get(i);
955
956         CompositeLocation paramLocation =
957             translateCalleeParamLocToCaller(md, calleeParamLoc, callerBaseLoc, errorMsg);
958
959         Set<CompositeLocation> inputGLBSet = new HashSet<CompositeLocation>();
960         if (constraint != null) {
961           inputGLBSet.add(callerArgLoc);
962           inputGLBSet.add(constraint);
963           callerArgLoc =
964               CompositeLattice.calculateGLB(inputGLBSet,
965                   generateErrorMessage(md.getClassDesc(), min));
966         }
967
968         if (!CompositeLattice.isGreaterThan(callerArgLoc, paramLocation, errorMsg)) {
969           throw new Error("Caller argument '" + min.getArg(i).printNode(0) + " : " + callerArgLoc
970               + "' should be higher than corresponding callee's parameter : " + paramLocation
971               + " at " + errorMsg);
972         }
973
974       }
975     }
976
977   }
978
979   private CompositeLocation translateCalleeParamLocToCaller(MethodDescriptor md,
980       CompositeLocation calleeParamLoc, CompositeLocation callerBaseLocation, String errorMsg) {
981
982     CompositeLocation translate = new CompositeLocation();
983
984     for (int i = 0; i < callerBaseLocation.getSize(); i++) {
985       translate.addLocation(callerBaseLocation.get(i));
986     }
987
988     for (int i = 1; i < calleeParamLoc.getSize(); i++) {
989       translate.addLocation(calleeParamLoc.get(i));
990     }
991
992     System.out.println("TRANSLATED=" + translate + " from calleeParamLoc=" + calleeParamLoc);
993
994     return translate;
995   }
996
997   private CompositeLocation computeCeilingLocationForCaller(MethodDescriptor md,
998       SymbolTable nametable, MethodInvokeNode min, CompositeLocation baseLocation,
999       CompositeLocation constraint) {
1000     List<CompositeLocation> argList = new ArrayList<CompositeLocation>();
1001
1002     // by default, method has a THIS parameter
1003     argList.add(baseLocation);
1004
1005     for (int i = 0; i < min.numArgs(); i++) {
1006       ExpressionNode en = min.getArg(i);
1007       CompositeLocation callerArg =
1008           checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
1009               false);
1010       argList.add(callerArg);
1011     }
1012
1013     System.out.println("\n## computeReturnLocation=" + min.getMethod() + " argList=" + argList);
1014     CompositeLocation ceilLoc = md2ReturnLocGen.get(min.getMethod()).computeReturnLocation(argList);
1015     System.out.println("## ReturnLocation=" + ceilLoc);
1016
1017     return ceilLoc;
1018
1019   }
1020
1021   private void checkCalleeConstraints(MethodDescriptor md, SymbolTable nametable,
1022       MethodInvokeNode min, CompositeLocation callerBaseLoc, CompositeLocation constraint) {
1023
1024     System.out.println("checkCalleeConstraints=" + min.printNode(0));
1025
1026     MethodDescriptor calleemd = min.getMethod();
1027
1028     MethodLattice<String> calleeLattice = ssjava.getMethodLattice(calleemd);
1029     CompositeLocation calleeThisLoc =
1030         new CompositeLocation(new Location(calleemd, calleeLattice.getThisLoc()));
1031
1032     List<CompositeLocation> callerArgList = new ArrayList<CompositeLocation>();
1033     List<CompositeLocation> calleeParamList = new ArrayList<CompositeLocation>();
1034
1035     if (min.numArgs() > 0) {
1036       // caller needs to guarantee that it passes arguments in regarding to
1037       // callee's hierarchy
1038
1039       // setup caller args set
1040       // first, add caller's base(this) location
1041       callerArgList.add(callerBaseLoc);
1042       // second, add caller's arguments
1043       for (int i = 0; i < min.numArgs(); i++) {
1044         ExpressionNode en = min.getArg(i);
1045         CompositeLocation callerArgLoc =
1046             checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
1047                 false);
1048         callerArgList.add(callerArgLoc);
1049       }
1050
1051       // setup callee params set
1052       // first, add callee's this location
1053       calleeParamList.add(calleeThisLoc);
1054       // second, add callee's parameters
1055       for (int i = 0; i < calleemd.numParameters(); i++) {
1056         VarDescriptor calleevd = (VarDescriptor) calleemd.getParameter(i);
1057         CompositeLocation calleeLoc = d2loc.get(calleevd);
1058         System.out.println("calleevd=" + calleevd + " loc=" + calleeLoc);
1059         calleeParamList.add(calleeLoc);
1060       }
1061
1062       // here, check if ordering relations among caller's args respect
1063       // ordering relations in-between callee's args
1064       CHECK: for (int i = 0; i < calleeParamList.size(); i++) {
1065         CompositeLocation calleeLoc1 = calleeParamList.get(i);
1066         CompositeLocation callerLoc1 = callerArgList.get(i);
1067
1068         for (int j = 0; j < calleeParamList.size(); j++) {
1069           if (i != j) {
1070             CompositeLocation calleeLoc2 = calleeParamList.get(j);
1071             CompositeLocation callerLoc2 = callerArgList.get(j);
1072
1073             if (callerLoc1.get(callerLoc1.getSize() - 1).isTop()
1074                 || callerLoc2.get(callerLoc2.getSize() - 1).isTop()) {
1075               continue CHECK;
1076             }
1077
1078             System.out.println("calleeLoc1=" + calleeLoc1);
1079             System.out.println("calleeLoc2=" + calleeLoc2 + "calleeParamList=" + calleeParamList);
1080
1081             int callerResult =
1082                 CompositeLattice.compare(callerLoc1, callerLoc2, true,
1083                     generateErrorMessage(md.getClassDesc(), min));
1084             int calleeResult =
1085                 CompositeLattice.compare(calleeLoc1, calleeLoc2, true,
1086                     generateErrorMessage(md.getClassDesc(), min));
1087
1088             if (calleeResult == ComparisonResult.GREATER
1089                 && callerResult != ComparisonResult.GREATER) {
1090               // If calleeLoc1 is higher than calleeLoc2
1091               // then, caller should have same ordering relation in-bet
1092               // callerLoc1 & callerLoc2
1093
1094               String paramName1, paramName2;
1095
1096               if (i == 0) {
1097                 paramName1 = "'THIS'";
1098               } else {
1099                 paramName1 = "'parameter " + calleemd.getParamName(i - 1) + "'";
1100               }
1101
1102               if (j == 0) {
1103                 paramName2 = "'THIS'";
1104               } else {
1105                 paramName2 = "'parameter " + calleemd.getParamName(j - 1) + "'";
1106               }
1107
1108               throw new Error(
1109                   "Caller doesn't respect an ordering relation among method arguments: callee expects that "
1110                       + paramName1 + " should be higher than " + paramName2 + " in " + calleemd
1111                       + " at " + md.getClassDesc().getSourceFileName() + ":" + min.getNumLine());
1112             }
1113           }
1114
1115         }
1116       }
1117
1118     }
1119
1120   }
1121
1122   private CompositeLocation checkLocationFromArrayAccessNode(MethodDescriptor md,
1123       SymbolTable nametable, ArrayAccessNode aan, CompositeLocation constraint, boolean isLHS) {
1124
1125     ClassDescriptor cd = md.getClassDesc();
1126
1127     CompositeLocation arrayLoc =
1128         checkLocationFromExpressionNode(md, nametable, aan.getExpression(),
1129             new CompositeLocation(), constraint, isLHS);
1130     // addTypeLocation(aan.getExpression().getType(), arrayLoc);
1131     CompositeLocation indexLoc =
1132         checkLocationFromExpressionNode(md, nametable, aan.getIndex(), new CompositeLocation(),
1133             constraint, isLHS);
1134     // addTypeLocation(aan.getIndex().getType(), indexLoc);
1135
1136     if (isLHS) {
1137       if (!CompositeLattice.isGreaterThan(indexLoc, arrayLoc, generateErrorMessage(cd, aan))) {
1138         throw new Error("Array index value is not higher than array location at "
1139             + generateErrorMessage(cd, aan));
1140       }
1141       return arrayLoc;
1142     } else {
1143       Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
1144       inputGLB.add(arrayLoc);
1145       inputGLB.add(indexLoc);
1146       return CompositeLattice.calculateGLB(inputGLB, generateErrorMessage(cd, aan));
1147     }
1148
1149   }
1150
1151   private CompositeLocation checkLocationFromCreateObjectNode(MethodDescriptor md,
1152       SymbolTable nametable, CreateObjectNode con) {
1153
1154     ClassDescriptor cd = md.getClassDesc();
1155
1156     CompositeLocation compLoc = new CompositeLocation();
1157     compLoc.addLocation(Location.createTopLocation(md));
1158     return compLoc;
1159
1160   }
1161
1162   private CompositeLocation checkLocationFromOpNode(MethodDescriptor md, SymbolTable nametable,
1163       OpNode on, CompositeLocation constraint) {
1164
1165     ClassDescriptor cd = md.getClassDesc();
1166     CompositeLocation leftLoc = new CompositeLocation();
1167     leftLoc =
1168         checkLocationFromExpressionNode(md, nametable, on.getLeft(), leftLoc, constraint, false);
1169     // addTypeLocation(on.getLeft().getType(), leftLoc);
1170
1171     CompositeLocation rightLoc = new CompositeLocation();
1172     if (on.getRight() != null) {
1173       rightLoc =
1174           checkLocationFromExpressionNode(md, nametable, on.getRight(), rightLoc, constraint, false);
1175       // addTypeLocation(on.getRight().getType(), rightLoc);
1176     }
1177
1178     System.out.println("\n# OP NODE=" + on.printNode(0));
1179     System.out.println("# left loc=" + leftLoc + " from " + on.getLeft().getClass());
1180     if (on.getRight() != null) {
1181       System.out.println("# right loc=" + rightLoc + " from " + on.getRight().getClass());
1182     }
1183
1184     Operation op = on.getOp();
1185
1186     switch (op.getOp()) {
1187
1188     case Operation.UNARYPLUS:
1189     case Operation.UNARYMINUS:
1190     case Operation.LOGIC_NOT:
1191       // single operand
1192       return leftLoc;
1193
1194     case Operation.LOGIC_OR:
1195     case Operation.LOGIC_AND:
1196     case Operation.COMP:
1197     case Operation.BIT_OR:
1198     case Operation.BIT_XOR:
1199     case Operation.BIT_AND:
1200     case Operation.ISAVAILABLE:
1201     case Operation.EQUAL:
1202     case Operation.NOTEQUAL:
1203     case Operation.LT:
1204     case Operation.GT:
1205     case Operation.LTE:
1206     case Operation.GTE:
1207     case Operation.ADD:
1208     case Operation.SUB:
1209     case Operation.MULT:
1210     case Operation.DIV:
1211     case Operation.MOD:
1212     case Operation.LEFTSHIFT:
1213     case Operation.RIGHTSHIFT:
1214     case Operation.URIGHTSHIFT:
1215
1216       Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
1217       inputSet.add(leftLoc);
1218       inputSet.add(rightLoc);
1219       CompositeLocation glbCompLoc =
1220           CompositeLattice.calculateGLB(inputSet, generateErrorMessage(cd, on));
1221       System.out.println("# glbCompLoc=" + glbCompLoc);
1222       return glbCompLoc;
1223
1224     default:
1225       throw new Error(op.toString());
1226     }
1227
1228   }
1229
1230   private CompositeLocation checkLocationFromLiteralNode(MethodDescriptor md,
1231       SymbolTable nametable, LiteralNode en, CompositeLocation loc) {
1232
1233     // literal value has the top location so that value can be flowed into any
1234     // location
1235     Location literalLoc = Location.createTopLocation(md);
1236     loc.addLocation(literalLoc);
1237     return loc;
1238
1239   }
1240
1241   private CompositeLocation checkLocationFromNameNode(MethodDescriptor md, SymbolTable nametable,
1242       NameNode nn, CompositeLocation loc, CompositeLocation constraint) {
1243
1244     NameDescriptor nd = nn.getName();
1245     if (nd.getBase() != null) {
1246       loc =
1247           checkLocationFromExpressionNode(md, nametable, nn.getExpression(), loc, constraint, false);
1248     } else {
1249       String varname = nd.toString();
1250       if (varname.equals("this")) {
1251         // 'this' itself!
1252         MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
1253         String thisLocId = methodLattice.getThisLoc();
1254         if (thisLocId == null) {
1255           throw new Error("The location for 'this' is not defined at "
1256               + md.getClassDesc().getSourceFileName() + "::" + nn.getNumLine());
1257         }
1258         Location locElement = new Location(md, thisLocId);
1259         loc.addLocation(locElement);
1260         return loc;
1261
1262       }
1263
1264       Descriptor d = (Descriptor) nametable.get(varname);
1265
1266       // CompositeLocation localLoc = null;
1267       if (d instanceof VarDescriptor) {
1268         VarDescriptor vd = (VarDescriptor) d;
1269         // localLoc = d2loc.get(vd);
1270         // the type of var descriptor has a composite location!
1271         loc = ((CompositeLocation) vd.getType().getExtension()).clone();
1272       } else if (d instanceof FieldDescriptor) {
1273         // the type of field descriptor has a location!
1274         FieldDescriptor fd = (FieldDescriptor) d;
1275         if (fd.isStatic()) {
1276           if (fd.isFinal()) {
1277             // if it is 'static final', the location has TOP since no one can
1278             // change its value
1279             loc.addLocation(Location.createTopLocation(md));
1280             return loc;
1281           } else {
1282             // if 'static', the location has pre-assigned global loc
1283             MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1284             String globalLocId = localLattice.getGlobalLoc();
1285             if (globalLocId == null) {
1286               throw new Error("Global location element is not defined in the method " + md);
1287             }
1288             Location globalLoc = new Location(md, globalLocId);
1289
1290             loc.addLocation(globalLoc);
1291           }
1292         } else {
1293           // the location of field access starts from this, followed by field
1294           // location
1295           MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1296           Location thisLoc = new Location(md, localLattice.getThisLoc());
1297           loc.addLocation(thisLoc);
1298         }
1299
1300         Location fieldLoc = (Location) fd.getType().getExtension();
1301         loc.addLocation(fieldLoc);
1302       } else if (d == null) {
1303         // access static field
1304         ClassDescriptor cd = nn.getClassDesc();
1305
1306         MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1307         String globalLocId = localLattice.getGlobalLoc();
1308         if (globalLocId == null) {
1309           throw new Error("Method lattice does not define global variable location at "
1310               + generateErrorMessage(md.getClassDesc(), nn));
1311         }
1312         loc.addLocation(new Location(md, globalLocId));
1313         return loc;
1314
1315       }
1316     }
1317     return loc;
1318   }
1319
1320   private CompositeLocation checkLocationFromFieldAccessNode(MethodDescriptor md,
1321       SymbolTable nametable, FieldAccessNode fan, CompositeLocation loc,
1322       CompositeLocation constraint) {
1323
1324     ExpressionNode left = fan.getExpression();
1325     TypeDescriptor ltd = left.getType();
1326
1327     FieldDescriptor fd = fan.getField();
1328
1329     String varName = null;
1330     if (left.kind() == Kind.NameNode) {
1331       NameDescriptor nd = ((NameNode) left).getName();
1332       varName = nd.toString();
1333     }
1334
1335     if (ltd.isClassNameRef() || (varName != null && varName.equals("this"))) {
1336       // using a class name directly or access using this
1337       if (fd.isStatic() && fd.isFinal()) {
1338         loc.addLocation(Location.createTopLocation(md));
1339         return loc;
1340       }
1341     }
1342
1343     loc = checkLocationFromExpressionNode(md, nametable, left, loc, constraint, false);
1344     System.out.println("### checkLocationFromFieldAccessNode=" + fan.printNode(0));
1345     System.out.println("### left=" + left.printNode(0));
1346     if (!left.getType().isPrimitive()) {
1347       Location fieldLoc = getFieldLocation(fd);
1348       loc.addLocation(fieldLoc);
1349     }
1350
1351     return loc;
1352   }
1353
1354   private Location getFieldLocation(FieldDescriptor fd) {
1355
1356     System.out.println("### getFieldLocation=" + fd);
1357     System.out.println("### fd.getType().getExtension()=" + fd.getType().getExtension());
1358
1359     Location fieldLoc = (Location) fd.getType().getExtension();
1360
1361     // handle the case that method annotation checking skips checking field
1362     // declaration
1363     if (fieldLoc == null) {
1364       fieldLoc = checkFieldDeclaration(fd.getClassDescriptor(), fd);
1365     }
1366
1367     return fieldLoc;
1368
1369   }
1370
1371   private CompositeLocation checkLocationFromAssignmentNode(MethodDescriptor md,
1372       SymbolTable nametable, AssignmentNode an, CompositeLocation loc, CompositeLocation constraint) {
1373
1374     System.out.println("\n# ASSIGNMENTNODE=" + an.printNode(0));
1375
1376     ClassDescriptor cd = md.getClassDesc();
1377
1378     Set<CompositeLocation> inputGLBSet = new HashSet<CompositeLocation>();
1379
1380     boolean postinc = true;
1381     if (an.getOperation().getBaseOp() == null
1382         || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
1383             .getBaseOp().getOp() != Operation.POSTDEC))
1384       postinc = false;
1385
1386     // if LHS is array access node, need to check if array index is higher
1387     // than array itself
1388     CompositeLocation destLocation =
1389         checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation(),
1390             constraint, true);
1391
1392     CompositeLocation rhsLocation;
1393     CompositeLocation srcLocation;
1394
1395     if (!postinc) {
1396       rhsLocation =
1397           checkLocationFromExpressionNode(md, nametable, an.getSrc(), new CompositeLocation(),
1398               constraint, false);
1399
1400       srcLocation = rhsLocation;
1401
1402       // if (!rhsLocation.get(rhsLocation.getSize() - 1).isTop()) {
1403       if (constraint != null) {
1404         inputGLBSet.add(rhsLocation);
1405         inputGLBSet.add(constraint);
1406         srcLocation = CompositeLattice.calculateGLB(inputGLBSet, generateErrorMessage(cd, an));
1407       }
1408       // }
1409
1410       System.out.println("dstLocation=" + destLocation);
1411       System.out.println("rhsLocation=" + rhsLocation);
1412       System.out.println("srcLocation=" + srcLocation);
1413       System.out.println("constraint=" + constraint);
1414
1415       if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1416
1417         String context = "";
1418         if (constraint != null) {
1419           context = " and the current context constraint is " + constraint;
1420         }
1421
1422         throw new Error("The value flow from " + srcLocation + " to " + destLocation
1423             + " does not respect location hierarchy on the assignment " + an.printNode(0) + context
1424             + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1425       }
1426
1427     } else {
1428       destLocation =
1429           rhsLocation =
1430               checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation(),
1431                   constraint, false);
1432
1433       if (constraint != null) {
1434         inputGLBSet.add(rhsLocation);
1435         inputGLBSet.add(constraint);
1436         srcLocation = CompositeLattice.calculateGLB(inputGLBSet, generateErrorMessage(cd, an));
1437       } else {
1438         srcLocation = rhsLocation;
1439       }
1440
1441       System.out.println("srcLocation=" + srcLocation);
1442       System.out.println("rhsLocation=" + rhsLocation);
1443       System.out.println("constraint=" + constraint);
1444
1445       if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1446
1447         if (srcLocation.equals(destLocation)) {
1448           throw new Error("Location " + srcLocation
1449               + " is not allowed to have the value flow that moves within the same location at '"
1450               + an.printNode(0) + "' of " + cd.getSourceFileName() + "::" + an.getNumLine());
1451         } else {
1452           throw new Error("The value flow from " + srcLocation + " to " + destLocation
1453               + " does not respect location hierarchy on the assignment " + an.printNode(0)
1454               + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1455         }
1456
1457       }
1458
1459     }
1460
1461     return destLocation;
1462   }
1463
1464   private void assignLocationOfVarDescriptor(VarDescriptor vd, MethodDescriptor md,
1465       SymbolTable nametable, TreeNode n) {
1466
1467     ClassDescriptor cd = md.getClassDesc();
1468     Vector<AnnotationDescriptor> annotationVec = vd.getType().getAnnotationMarkers();
1469
1470     // currently enforce every variable to have corresponding location
1471     if (annotationVec.size() == 0) {
1472       throw new Error("Location is not assigned to variable " + vd.getSymbol() + " in the method "
1473           + md.getSymbol() + " of the class " + cd.getSymbol());
1474     }
1475
1476     if (annotationVec.size() > 1) { // variable can have at most one location
1477       throw new Error(vd.getSymbol() + " has more than one location.");
1478     }
1479
1480     AnnotationDescriptor ad = annotationVec.elementAt(0);
1481
1482     if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1483
1484       if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1485         String locDec = ad.getValue(); // check if location is defined
1486
1487         if (locDec.startsWith(SSJavaAnalysis.DELTA)) {
1488           DeltaLocation deltaLoc = parseDeltaDeclaration(md, n, locDec);
1489           d2loc.put(vd, deltaLoc);
1490           addLocationType(vd.getType(), deltaLoc);
1491         } else {
1492           CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1493
1494           Location lastElement = compLoc.get(compLoc.getSize() - 1);
1495           if (ssjava.isSharedLocation(lastElement)) {
1496             ssjava.mapSharedLocation2Descriptor(lastElement, vd);
1497           }
1498
1499           d2loc.put(vd, compLoc);
1500           addLocationType(vd.getType(), compLoc);
1501         }
1502
1503       }
1504     }
1505
1506   }
1507
1508   private DeltaLocation parseDeltaDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1509
1510     int deltaCount = 0;
1511     int dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1512     while (dIdx >= 0) {
1513       deltaCount++;
1514       int beginIdx = dIdx + 6;
1515       locDec = locDec.substring(beginIdx, locDec.length() - 1);
1516       dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1517     }
1518
1519     CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1520     DeltaLocation deltaLoc = new DeltaLocation(compLoc, deltaCount);
1521
1522     return deltaLoc;
1523   }
1524
1525   private Location parseFieldLocDeclaraton(String decl, String msg) throws Exception {
1526
1527     int idx = decl.indexOf(".");
1528
1529     String className = decl.substring(0, idx);
1530     String fieldName = decl.substring(idx + 1);
1531
1532     className.replaceAll(" ", "");
1533     fieldName.replaceAll(" ", "");
1534
1535     Descriptor d = state.getClassSymbolTable().get(className);
1536
1537     if (d == null) {
1538       System.out.println("state.getClassSymbolTable()=" + state.getClassSymbolTable());
1539       throw new Error("The class in the location declaration '" + decl + "' does not exist at "
1540           + msg);
1541     }
1542
1543     assert (d instanceof ClassDescriptor);
1544     SSJavaLattice<String> lattice = ssjava.getClassLattice((ClassDescriptor) d);
1545     if (!lattice.containsKey(fieldName)) {
1546       throw new Error("The location " + fieldName + " is not defined in the field lattice of '"
1547           + className + "' at " + msg);
1548     }
1549
1550     return new Location(d, fieldName);
1551   }
1552
1553   private CompositeLocation parseLocationDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1554
1555     CompositeLocation compLoc = new CompositeLocation();
1556
1557     StringTokenizer tokenizer = new StringTokenizer(locDec, ",");
1558     List<String> locIdList = new ArrayList<String>();
1559     while (tokenizer.hasMoreTokens()) {
1560       String locId = tokenizer.nextToken();
1561       locIdList.add(locId);
1562     }
1563
1564     // at least,one location element needs to be here!
1565     assert (locIdList.size() > 0);
1566
1567     // assume that loc with idx 0 comes from the local lattice
1568     // loc with idx 1 comes from the field lattice
1569
1570     String localLocId = locIdList.get(0);
1571     SSJavaLattice<String> localLattice = CompositeLattice.getLatticeByDescriptor(md);
1572     Location localLoc = new Location(md, localLocId);
1573     if (localLattice == null || (!localLattice.containsKey(localLocId))) {
1574       System.out.println("locDec=" + locDec);
1575       throw new Error("Location " + localLocId
1576           + " is not defined in the local variable lattice at "
1577           + md.getClassDesc().getSourceFileName() + "::" + (n != null ? n.getNumLine() : md) + ".");
1578     }
1579     compLoc.addLocation(localLoc);
1580
1581     for (int i = 1; i < locIdList.size(); i++) {
1582       String locName = locIdList.get(i);
1583       try {
1584         Location fieldLoc =
1585             parseFieldLocDeclaraton(locName, generateErrorMessage(md.getClassDesc(), n));
1586         compLoc.addLocation(fieldLoc);
1587       } catch (Exception e) {
1588         throw new Error("The location declaration '" + locName + "' is wrong  at "
1589             + generateErrorMessage(md.getClassDesc(), n));
1590       }
1591     }
1592
1593     return compLoc;
1594
1595   }
1596
1597   private void checkDeclarationNode(MethodDescriptor md, SymbolTable nametable, DeclarationNode dn) {
1598     VarDescriptor vd = dn.getVarDescriptor();
1599     assignLocationOfVarDescriptor(vd, md, nametable, dn);
1600   }
1601
1602   private void checkDeclarationInClass(ClassDescriptor cd) {
1603     // Check to see that fields are okay
1604     for (Iterator field_it = cd.getFields(); field_it.hasNext();) {
1605       FieldDescriptor fd = (FieldDescriptor) field_it.next();
1606
1607       if (!(fd.isFinal() && fd.isStatic())) {
1608         checkFieldDeclaration(cd, fd);
1609       } else {
1610         // for static final, assign top location by default
1611         Location loc = Location.createTopLocation(cd);
1612         addLocationType(fd.getType(), loc);
1613       }
1614     }
1615   }
1616
1617   private Location checkFieldDeclaration(ClassDescriptor cd, FieldDescriptor fd) {
1618
1619     Vector<AnnotationDescriptor> annotationVec = fd.getType().getAnnotationMarkers();
1620
1621     // currently enforce every field to have corresponding location
1622     if (annotationVec.size() == 0) {
1623       throw new Error("Location is not assigned to the field '" + fd.getSymbol()
1624           + "' of the class " + cd.getSymbol() + " at " + cd.getSourceFileName());
1625     }
1626
1627     if (annotationVec.size() > 1) {
1628       // variable can have at most one location
1629       throw new Error("Field " + fd.getSymbol() + " of class " + cd
1630           + " has more than one location.");
1631     }
1632
1633     AnnotationDescriptor ad = annotationVec.elementAt(0);
1634     Location loc = null;
1635
1636     if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1637       if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1638         String locationID = ad.getValue();
1639         // check if location is defined
1640         SSJavaLattice<String> lattice = ssjava.getClassLattice(cd);
1641         if (lattice == null || (!lattice.containsKey(locationID))) {
1642           throw new Error("Location " + locationID
1643               + " is not defined in the field lattice of class " + cd.getSymbol() + " at"
1644               + cd.getSourceFileName() + ".");
1645         }
1646         loc = new Location(cd, locationID);
1647
1648         if (ssjava.isSharedLocation(loc)) {
1649           ssjava.mapSharedLocation2Descriptor(loc, fd);
1650         }
1651
1652         addLocationType(fd.getType(), loc);
1653
1654       }
1655     }
1656
1657     return loc;
1658   }
1659
1660   private void addLocationType(TypeDescriptor type, CompositeLocation loc) {
1661     if (type != null) {
1662       type.setExtension(loc);
1663     }
1664   }
1665
1666   private void addLocationType(TypeDescriptor type, Location loc) {
1667     if (type != null) {
1668       type.setExtension(loc);
1669     }
1670   }
1671
1672   static class CompositeLattice {
1673
1674     public static boolean isGreaterThan(CompositeLocation loc1, CompositeLocation loc2, String msg) {
1675
1676       System.out.println("\nisGreaterThan=" + loc1 + " " + loc2 + " msg=" + msg);
1677       int baseCompareResult = compareBaseLocationSet(loc1, loc2, true, false, msg);
1678       if (baseCompareResult == ComparisonResult.EQUAL) {
1679         if (compareDelta(loc1, loc2) == ComparisonResult.GREATER) {
1680           return true;
1681         } else {
1682           return false;
1683         }
1684       } else if (baseCompareResult == ComparisonResult.GREATER) {
1685         return true;
1686       } else {
1687         return false;
1688       }
1689
1690     }
1691
1692     public static int compare(CompositeLocation loc1, CompositeLocation loc2, boolean ignore,
1693         String msg) {
1694
1695       System.out.println("compare=" + loc1 + " " + loc2);
1696       int baseCompareResult = compareBaseLocationSet(loc1, loc2, false, ignore, msg);
1697
1698       if (baseCompareResult == ComparisonResult.EQUAL) {
1699         return compareDelta(loc1, loc2);
1700       } else {
1701         return baseCompareResult;
1702       }
1703
1704     }
1705
1706     private static int compareDelta(CompositeLocation dLoc1, CompositeLocation dLoc2) {
1707
1708       int deltaCount1 = 0;
1709       int deltaCount2 = 0;
1710       if (dLoc1 instanceof DeltaLocation) {
1711         deltaCount1 = ((DeltaLocation) dLoc1).getNumDelta();
1712       }
1713
1714       if (dLoc2 instanceof DeltaLocation) {
1715         deltaCount2 = ((DeltaLocation) dLoc2).getNumDelta();
1716       }
1717       if (deltaCount1 < deltaCount2) {
1718         return ComparisonResult.GREATER;
1719       } else if (deltaCount1 == deltaCount2) {
1720         return ComparisonResult.EQUAL;
1721       } else {
1722         return ComparisonResult.LESS;
1723       }
1724
1725     }
1726
1727     private static int compareBaseLocationSet(CompositeLocation compLoc1,
1728         CompositeLocation compLoc2, boolean awareSharedLoc, boolean ignore, String msg) {
1729
1730       // if compLoc1 is greater than compLoc2, return true
1731       // else return false;
1732
1733       // compare one by one in according to the order of the tuple
1734       int numOfTie = 0;
1735       for (int i = 0; i < compLoc1.getSize(); i++) {
1736         Location loc1 = compLoc1.get(i);
1737         if (i >= compLoc2.getSize()) {
1738           if (ignore) {
1739             return ComparisonResult.INCOMPARABLE;
1740           } else {
1741             throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1742                 + " because they are not comparable at " + msg);
1743           }
1744         }
1745         Location loc2 = compLoc2.get(i);
1746
1747         Descriptor descriptor = getCommonParentDescriptor(loc1, loc2, msg);
1748         SSJavaLattice<String> lattice = getLatticeByDescriptor(descriptor);
1749
1750         // check if the shared location is appeared only at the end of the
1751         // composite location
1752         if (lattice.getSharedLocSet().contains(loc1.getLocIdentifier())) {
1753           if (i != (compLoc1.getSize() - 1)) {
1754             throw new Error("The shared location " + loc1.getLocIdentifier()
1755                 + " cannot be appeared in the middle of composite location at" + msg);
1756           }
1757         }
1758
1759         if (lattice.getSharedLocSet().contains(loc2.getLocIdentifier())) {
1760           if (i != (compLoc2.getSize() - 1)) {
1761             throw new Error("The shared location " + loc2.getLocIdentifier()
1762                 + " cannot be appeared in the middle of composite location at " + msg);
1763           }
1764         }
1765
1766         // if (!lattice1.equals(lattice2)) {
1767         // throw new Error("Failed to compare two locations of " + compLoc1 +
1768         // " and " + compLoc2
1769         // + " because they are not comparable at " + msg);
1770         // }
1771
1772         if (loc1.getLocIdentifier().equals(loc2.getLocIdentifier())) {
1773           numOfTie++;
1774           // check if the current location is the spinning location
1775           // note that the spinning location only can be appeared in the last
1776           // part of the composite location
1777           if (awareSharedLoc && numOfTie == compLoc1.getSize()
1778               && lattice.getSharedLocSet().contains(loc1.getLocIdentifier())) {
1779             return ComparisonResult.GREATER;
1780           }
1781           continue;
1782         } else if (lattice.isGreaterThan(loc1.getLocIdentifier(), loc2.getLocIdentifier())) {
1783           return ComparisonResult.GREATER;
1784         } else {
1785           return ComparisonResult.LESS;
1786         }
1787
1788       }
1789
1790       if (numOfTie == compLoc1.getSize()) {
1791
1792         if (numOfTie != compLoc2.getSize()) {
1793
1794           if (ignore) {
1795             return ComparisonResult.INCOMPARABLE;
1796           } else {
1797             throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1798                 + " because they are not comparable at " + msg);
1799           }
1800
1801         }
1802
1803         return ComparisonResult.EQUAL;
1804       }
1805
1806       return ComparisonResult.LESS;
1807
1808     }
1809
1810     public static CompositeLocation calculateGLB(Set<CompositeLocation> inputSet, String errMsg) {
1811
1812       System.out.println("Calculating GLB=" + inputSet);
1813       CompositeLocation glbCompLoc = new CompositeLocation();
1814
1815       // calculate GLB of the first(priority) element
1816       Set<String> priorityLocIdentifierSet = new HashSet<String>();
1817       Descriptor priorityDescriptor = null;
1818
1819       Hashtable<String, Set<CompositeLocation>> locId2CompLocSet =
1820           new Hashtable<String, Set<CompositeLocation>>();
1821       // mapping from the priority loc ID to its full representation by the
1822       // composite location
1823
1824       int maxTupleSize = 0;
1825       CompositeLocation maxCompLoc = null;
1826
1827       Location prevPriorityLoc = null;
1828       for (Iterator iterator = inputSet.iterator(); iterator.hasNext();) {
1829         CompositeLocation compLoc = (CompositeLocation) iterator.next();
1830         if (compLoc.getSize() > maxTupleSize) {
1831           maxTupleSize = compLoc.getSize();
1832           maxCompLoc = compLoc;
1833         }
1834         Location priorityLoc = compLoc.get(0);
1835         String priorityLocId = priorityLoc.getLocIdentifier();
1836         priorityLocIdentifierSet.add(priorityLocId);
1837
1838         if (locId2CompLocSet.containsKey(priorityLocId)) {
1839           locId2CompLocSet.get(priorityLocId).add(compLoc);
1840         } else {
1841           Set<CompositeLocation> newSet = new HashSet<CompositeLocation>();
1842           newSet.add(compLoc);
1843           locId2CompLocSet.put(priorityLocId, newSet);
1844         }
1845
1846         // check if priority location are coming from the same lattice
1847         if (priorityDescriptor == null) {
1848           priorityDescriptor = priorityLoc.getDescriptor();
1849         } else {
1850           priorityDescriptor = getCommonParentDescriptor(priorityLoc, prevPriorityLoc, errMsg);
1851         }
1852         prevPriorityLoc = priorityLoc;
1853         // else if (!priorityDescriptor.equals(priorityLoc.getDescriptor())) {
1854         // throw new Error("Failed to calculate GLB of " + inputSet
1855         // + " because they are from different lattices.");
1856         // }
1857       }
1858
1859       SSJavaLattice<String> locOrder = getLatticeByDescriptor(priorityDescriptor);
1860       String glbOfPriorityLoc = locOrder.getGLB(priorityLocIdentifierSet);
1861
1862       glbCompLoc.addLocation(new Location(priorityDescriptor, glbOfPriorityLoc));
1863       Set<CompositeLocation> compSet = locId2CompLocSet.get(glbOfPriorityLoc);
1864
1865       if (compSet == null) {
1866         // when GLB(x1,x2)!=x1 and !=x2 : GLB case 4
1867         // mean that the result is already lower than <x1,y1> and <x2,y2>
1868         // assign TOP to the rest of the location elements
1869
1870         // in this case, do not take care about delta
1871         // CompositeLocation inputComp = inputSet.iterator().next();
1872         for (int i = 1; i < maxTupleSize; i++) {
1873           glbCompLoc.addLocation(Location.createTopLocation(maxCompLoc.get(i).getDescriptor()));
1874         }
1875       } else {
1876
1877         // here find out composite location that has a maximum length tuple
1878         // if we have three input set: [A], [A,B], [A,B,C]
1879         // maximum length tuple will be [A,B,C]
1880         int max = 0;
1881         CompositeLocation maxFromCompSet = null;
1882         for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1883           CompositeLocation c = (CompositeLocation) iterator.next();
1884           if (c.getSize() > max) {
1885             max = c.getSize();
1886             maxFromCompSet = c;
1887           }
1888         }
1889
1890         if (compSet.size() == 1) {
1891           // if GLB(x1,x2)==x1 or x2 : GLB case 2,3
1892           CompositeLocation comp = compSet.iterator().next();
1893           for (int i = 1; i < comp.getSize(); i++) {
1894             glbCompLoc.addLocation(comp.get(i));
1895           }
1896
1897           // if input location corresponding to glb is a delta, need to apply
1898           // delta to glb result
1899           if (comp instanceof DeltaLocation) {
1900             glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1901           }
1902
1903         } else {
1904           // when GLB(x1,x2)==x1 and x2 : GLB case 1
1905           // if more than one location shares the same priority GLB
1906           // need to calculate the rest of GLB loc
1907
1908           // setup input set starting from the second tuple item
1909           Set<CompositeLocation> innerGLBInput = new HashSet<CompositeLocation>();
1910           for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1911             CompositeLocation compLoc = (CompositeLocation) iterator.next();
1912             CompositeLocation innerCompLoc = new CompositeLocation();
1913             for (int idx = 1; idx < compLoc.getSize(); idx++) {
1914               innerCompLoc.addLocation(compLoc.get(idx));
1915             }
1916             if (innerCompLoc.getSize() > 0) {
1917               innerGLBInput.add(innerCompLoc);
1918             }
1919           }
1920
1921           if (innerGLBInput.size() > 0) {
1922             CompositeLocation innerGLB = CompositeLattice.calculateGLB(innerGLBInput, errMsg);
1923             for (int idx = 0; idx < innerGLB.getSize(); idx++) {
1924               glbCompLoc.addLocation(innerGLB.get(idx));
1925             }
1926           }
1927
1928           // if input location corresponding to glb is a delta, need to apply
1929           // delta to glb result
1930
1931           for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1932             CompositeLocation compLoc = (CompositeLocation) iterator.next();
1933             if (compLoc instanceof DeltaLocation) {
1934               if (glbCompLoc.equals(compLoc)) {
1935                 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1936                 break;
1937               }
1938             }
1939           }
1940
1941         }
1942       }
1943
1944       System.out.println("GLB=" + glbCompLoc);
1945       return glbCompLoc;
1946
1947     }
1948
1949     static SSJavaLattice<String> getLatticeByDescriptor(Descriptor d) {
1950
1951       SSJavaLattice<String> lattice = null;
1952
1953       if (d instanceof ClassDescriptor) {
1954         lattice = ssjava.getCd2lattice().get(d);
1955       } else if (d instanceof MethodDescriptor) {
1956         if (ssjava.getMd2lattice().containsKey(d)) {
1957           lattice = ssjava.getMd2lattice().get(d);
1958         } else {
1959           // use default lattice for the method
1960           lattice = ssjava.getCd2methodDefault().get(((MethodDescriptor) d).getClassDesc());
1961         }
1962       }
1963
1964       return lattice;
1965     }
1966
1967     static Descriptor getCommonParentDescriptor(Location loc1, Location loc2, String msg) {
1968
1969       Descriptor d1 = loc1.getDescriptor();
1970       Descriptor d2 = loc2.getDescriptor();
1971
1972       Descriptor descriptor;
1973
1974       if (d1 instanceof ClassDescriptor && d2 instanceof ClassDescriptor) {
1975
1976         if (d1.equals(d2)) {
1977           descriptor = d1;
1978         } else {
1979           // identifying which one is parent class
1980           Set<Descriptor> d1SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d1);
1981           Set<Descriptor> d2SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d2);
1982
1983           if (d1 == null && d2 == null) {
1984             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1985                 + " because they are not comparable at " + msg);
1986           } else if (d1SubClassesSet != null && d1SubClassesSet.contains(d2)) {
1987             descriptor = d1;
1988           } else if (d2SubClassesSet != null && d2SubClassesSet.contains(d1)) {
1989             descriptor = d2;
1990           } else {
1991             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1992                 + " because they are not comparable at " + msg);
1993           }
1994         }
1995
1996       } else if (d1 instanceof MethodDescriptor && d2 instanceof MethodDescriptor) {
1997
1998         if (d1.equals(d2)) {
1999           descriptor = d1;
2000         } else {
2001
2002           // identifying which one is parent class
2003           MethodDescriptor md1 = (MethodDescriptor) d1;
2004           MethodDescriptor md2 = (MethodDescriptor) d2;
2005
2006           if (!md1.matches(md2)) {
2007             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2008                 + " because they are not comparable at " + msg);
2009           }
2010
2011           Set<Descriptor> d1SubClassesSet =
2012               ssjava.tu.getSubClasses(((MethodDescriptor) d1).getClassDesc());
2013           Set<Descriptor> d2SubClassesSet =
2014               ssjava.tu.getSubClasses(((MethodDescriptor) d2).getClassDesc());
2015
2016           if (d1 == null && d2 == null) {
2017             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2018                 + " because they are not comparable at " + msg);
2019           } else if (d1 != null && d1SubClassesSet.contains(d2)) {
2020             descriptor = d1;
2021           } else if (d2 != null && d2SubClassesSet.contains(d1)) {
2022             descriptor = d2;
2023           } else {
2024             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2025                 + " because they are not comparable at " + msg);
2026           }
2027         }
2028
2029       } else {
2030         throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2031             + " because they are not comparable at " + msg);
2032       }
2033
2034       return descriptor;
2035
2036     }
2037
2038   }
2039
2040   class ComparisonResult {
2041
2042     public static final int GREATER = 0;
2043     public static final int EQUAL = 1;
2044     public static final int LESS = 2;
2045     public static final int INCOMPARABLE = 3;
2046     int result;
2047
2048   }
2049
2050 }
2051
2052 class ReturnLocGenerator {
2053
2054   public static final int PARAMISHIGHER = 0;
2055   public static final int PARAMISSAME = 1;
2056   public static final int IGNORE = 2;
2057
2058   private Hashtable<Integer, Integer> paramIdx2paramType;
2059
2060   private CompositeLocation declaredReturnLoc = null;
2061
2062   public ReturnLocGenerator(CompositeLocation returnLoc, MethodDescriptor md,
2063       List<CompositeLocation> params, String msg) {
2064
2065     CompositeLocation thisLoc = params.get(0);
2066     if (returnLoc.get(0).equals(thisLoc.get(0)) && returnLoc.getSize() > 1) {
2067       // if the declared return location consists of THIS and field location,
2068       // return location for the caller's side has to have same field element
2069       this.declaredReturnLoc = returnLoc;
2070     } else {
2071       // creating mappings
2072       paramIdx2paramType = new Hashtable<Integer, Integer>();
2073       for (int i = 0; i < params.size(); i++) {
2074         CompositeLocation param = params.get(i);
2075         int compareResult = CompositeLattice.compare(param, returnLoc, true, msg);
2076
2077         int type;
2078         if (compareResult == ComparisonResult.GREATER) {
2079           type = 0;
2080         } else if (compareResult == ComparisonResult.EQUAL) {
2081           type = 1;
2082         } else {
2083           type = 2;
2084         }
2085         paramIdx2paramType.put(new Integer(i), new Integer(type));
2086       }
2087     }
2088
2089   }
2090
2091   public CompositeLocation computeReturnLocation(List<CompositeLocation> args) {
2092
2093     if (declaredReturnLoc != null) {
2094       // when developer specify that the return value is [THIS,field]
2095       // needs to translate to the caller's location
2096       CompositeLocation callerLoc = new CompositeLocation();
2097       CompositeLocation callerBaseLocation = args.get(0);
2098
2099       for (int i = 0; i < callerBaseLocation.getSize(); i++) {
2100         callerLoc.addLocation(callerBaseLocation.get(i));
2101       }
2102       for (int i = 1; i < declaredReturnLoc.getSize(); i++) {
2103         callerLoc.addLocation(declaredReturnLoc.get(i));
2104       }
2105       return callerLoc;
2106     } else {
2107       // compute the highest possible location in caller's side
2108       assert paramIdx2paramType.keySet().size() == args.size();
2109
2110       Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
2111       for (int i = 0; i < args.size(); i++) {
2112         int type = (paramIdx2paramType.get(new Integer(i))).intValue();
2113         CompositeLocation argLoc = args.get(i);
2114         if (type == PARAMISHIGHER || type == PARAMISSAME) {
2115           // return loc is equal to or lower than param
2116           inputGLB.add(argLoc);
2117         }
2118       }
2119
2120       // compute GLB of arguments subset that are same or higher than return
2121       // location
2122       CompositeLocation glb = CompositeLattice.calculateGLB(inputGLB, "");
2123       return glb;
2124     }
2125
2126   }
2127 }