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