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