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