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