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