adding more annotations for mp3decoder
[IRC.git] / Robust / src / Analysis / SSJava / FlowDownCheck.java
1 package Analysis.SSJava;
2
3 import java.util.ArrayList;
4 import java.util.HashSet;
5 import java.util.Hashtable;
6 import java.util.Iterator;
7 import java.util.List;
8 import java.util.Set;
9 import java.util.StringTokenizer;
10 import java.util.Vector;
11
12 import Analysis.SSJava.FlowDownCheck.ComparisonResult;
13 import Analysis.SSJava.FlowDownCheck.CompositeLattice;
14 import IR.AnnotationDescriptor;
15 import IR.ClassDescriptor;
16 import IR.Descriptor;
17 import IR.FieldDescriptor;
18 import IR.MethodDescriptor;
19 import IR.NameDescriptor;
20 import IR.Operation;
21 import IR.State;
22 import IR.SymbolTable;
23 import IR.TypeDescriptor;
24 import IR.VarDescriptor;
25 import IR.Tree.ArrayAccessNode;
26 import IR.Tree.AssignmentNode;
27 import IR.Tree.BlockExpressionNode;
28 import IR.Tree.BlockNode;
29 import IR.Tree.BlockStatementNode;
30 import IR.Tree.CastNode;
31 import IR.Tree.CreateObjectNode;
32 import IR.Tree.DeclarationNode;
33 import IR.Tree.ExpressionNode;
34 import IR.Tree.FieldAccessNode;
35 import IR.Tree.IfStatementNode;
36 import IR.Tree.Kind;
37 import IR.Tree.LiteralNode;
38 import IR.Tree.LoopNode;
39 import IR.Tree.MethodInvokeNode;
40 import IR.Tree.NameNode;
41 import IR.Tree.OpNode;
42 import IR.Tree.ReturnNode;
43 import IR.Tree.SubBlockNode;
44 import IR.Tree.SwitchBlockNode;
45 import IR.Tree.SwitchStatementNode;
46 import IR.Tree.TertiaryNode;
47 import IR.Tree.TreeNode;
48 import Util.Pair;
49
50 public class FlowDownCheck {
51
52   State state;
53   static SSJavaAnalysis ssjava;
54
55   HashSet toanalyze;
56
57   // mapping from 'descriptor' to 'composite location'
58   Hashtable<Descriptor, CompositeLocation> d2loc;
59
60   Hashtable<MethodDescriptor, CompositeLocation> md2ReturnLoc;
61   Hashtable<MethodDescriptor, ReturnLocGenerator> md2ReturnLocGen;
62
63   // mapping from 'locID' to 'class descriptor'
64   Hashtable<String, ClassDescriptor> fieldLocName2cd;
65
66   public FlowDownCheck(SSJavaAnalysis ssjava, State state) {
67     this.ssjava = ssjava;
68     this.state = state;
69     this.toanalyze = new HashSet();
70     this.d2loc = new Hashtable<Descriptor, CompositeLocation>();
71     this.fieldLocName2cd = new Hashtable<String, ClassDescriptor>();
72     this.md2ReturnLoc = new Hashtable<MethodDescriptor, CompositeLocation>();
73     this.md2ReturnLocGen = new Hashtable<MethodDescriptor, ReturnLocGenerator>();
74   }
75
76   public void init() {
77
78     // construct mapping from the location name to the class descriptor
79     // assume that the location name is unique through the whole program
80
81     Set<ClassDescriptor> cdSet = ssjava.getCd2lattice().keySet();
82     for (Iterator iterator = cdSet.iterator(); iterator.hasNext();) {
83       ClassDescriptor cd = (ClassDescriptor) iterator.next();
84       SSJavaLattice<String> lattice = ssjava.getCd2lattice().get(cd);
85       Set<String> fieldLocNameSet = lattice.getKeySet();
86
87       for (Iterator iterator2 = fieldLocNameSet.iterator(); iterator2.hasNext();) {
88         String fieldLocName = (String) iterator2.next();
89         fieldLocName2cd.put(fieldLocName, cd);
90       }
91
92     }
93
94   }
95
96   public void flowDownCheck() {
97     SymbolTable classtable = state.getClassSymbolTable();
98
99     // phase 1 : checking declaration node and creating mapping of 'type
100     // desciptor' & 'location'
101     toanalyze.addAll(classtable.getValueSet());
102     toanalyze.addAll(state.getTaskSymbolTable().getValueSet());
103     while (!toanalyze.isEmpty()) {
104       Object obj = toanalyze.iterator().next();
105       ClassDescriptor cd = (ClassDescriptor) obj;
106       toanalyze.remove(cd);
107
108       if (ssjava.needToBeAnnoated(cd) && (!cd.isInterface())) {
109
110         ClassDescriptor superDesc = cd.getSuperDesc();
111         if (superDesc != null && (!superDesc.isInterface())
112             && (!superDesc.getSymbol().equals("Object"))) {
113           checkOrderingInheritance(superDesc, cd);
114         }
115
116         checkDeclarationInClass(cd);
117         for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
118           MethodDescriptor md = (MethodDescriptor) method_it.next();
119           if (ssjava.needTobeAnnotated(md)) {
120             checkDeclarationInMethodBody(cd, md);
121           }
122         }
123       }
124
125     }
126
127     // phase2 : checking assignments
128     toanalyze.addAll(classtable.getValueSet());
129     toanalyze.addAll(state.getTaskSymbolTable().getValueSet());
130     while (!toanalyze.isEmpty()) {
131       Object obj = toanalyze.iterator().next();
132       ClassDescriptor cd = (ClassDescriptor) obj;
133       toanalyze.remove(cd);
134
135       checkClass(cd);
136       for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
137         MethodDescriptor md = (MethodDescriptor) method_it.next();
138         if (ssjava.needTobeAnnotated(md)) {
139           checkMethodBody(cd, md);
140         }
141       }
142     }
143
144   }
145
146   private void checkOrderingInheritance(ClassDescriptor superCd, ClassDescriptor cd) {
147     // here, we're going to check that sub class keeps same relative orderings
148     // in respect to super class
149
150     SSJavaLattice<String> superLattice = ssjava.getClassLattice(superCd);
151     SSJavaLattice<String> subLattice = ssjava.getClassLattice(cd);
152
153     if (superLattice != null) {
154
155       if (subLattice == null) {
156         throw new Error("If a parent class '" + superCd
157             + "' has a ordering lattice, its subclass '" + cd + "' should have one.");
158       }
159
160       Set<Pair<String, String>> superPairSet = superLattice.getOrderingPairSet();
161       Set<Pair<String, String>> subPairSet = subLattice.getOrderingPairSet();
162
163       for (Iterator iterator = superPairSet.iterator(); iterator.hasNext();) {
164         Pair<String, String> pair = (Pair<String, String>) iterator.next();
165
166         if (!subPairSet.contains(pair)) {
167           throw new Error("Subclass '" + cd + "' does not have the relative ordering '"
168               + pair.getSecond() + " < " + pair.getFirst()
169               + "' that is defined by its superclass '" + superCd + "'.");
170         }
171       }
172
173     }
174     // if super class doesn't define lattice, then we don't need to check its
175     // subclass
176
177   }
178
179   public Hashtable getMap() {
180     return d2loc;
181   }
182
183   private void checkDeclarationInMethodBody(ClassDescriptor cd, MethodDescriptor md) {
184     BlockNode bn = state.getMethodBody(md);
185
186     // parsing returnloc annotation
187     if (ssjava.needTobeAnnotated(md)) {
188
189       Vector<AnnotationDescriptor> methodAnnotations = md.getModifiers().getAnnotations();
190       if (methodAnnotations != null) {
191         for (int i = 0; i < methodAnnotations.size(); i++) {
192           AnnotationDescriptor an = methodAnnotations.elementAt(i);
193           if (an.getMarker().equals(ssjava.RETURNLOC)) {
194             // developer explicitly defines method lattice
195             String returnLocDeclaration = an.getValue();
196             CompositeLocation returnLocComp =
197                 parseLocationDeclaration(md, null, returnLocDeclaration);
198             md2ReturnLoc.put(md, returnLocComp);
199           }
200         }
201
202         if (!md.getReturnType().isVoid() && !md2ReturnLoc.containsKey(md)) {
203           throw new Error("Return location is not specified for the method " + md + " at "
204               + cd.getSourceFileName());
205         }
206
207       }
208     }
209
210     List<CompositeLocation> paramList = new ArrayList<CompositeLocation>();
211
212     boolean hasReturnValue = (!md.getReturnType().isVoid());
213     if (hasReturnValue) {
214       MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
215       String thisLocId = methodLattice.getThisLoc();
216       if (thisLocId == null) {
217         throw new Error("Method '" + md + "' does not have the definition of 'this' location at "
218             + md.getClassDesc().getSourceFileName());
219       }
220       CompositeLocation thisLoc = new CompositeLocation(new Location(md, thisLocId));
221       paramList.add(thisLoc);
222     }
223
224     for (int i = 0; i < md.numParameters(); i++) {
225       // process annotations on method parameters
226       VarDescriptor vd = (VarDescriptor) md.getParameter(i);
227       assignLocationOfVarDescriptor(vd, md, md.getParameterTable(), bn);
228       if (hasReturnValue) {
229         paramList.add(d2loc.get(vd));
230       }
231     }
232
233     if (hasReturnValue) {
234       md2ReturnLocGen.put(md, new ReturnLocGenerator(md2ReturnLoc.get(md), paramList));
235     }
236
237     checkDeclarationInBlockNode(md, md.getParameterTable(), bn);
238   }
239
240   private void checkDeclarationInBlockNode(MethodDescriptor md, SymbolTable nametable, BlockNode bn) {
241     bn.getVarTable().setParent(nametable);
242     for (int i = 0; i < bn.size(); i++) {
243       BlockStatementNode bsn = bn.get(i);
244       checkDeclarationInBlockStatementNode(md, bn.getVarTable(), bsn);
245     }
246   }
247
248   private void checkDeclarationInBlockStatementNode(MethodDescriptor md, SymbolTable nametable,
249       BlockStatementNode bsn) {
250
251     switch (bsn.kind()) {
252     case Kind.SubBlockNode:
253       checkDeclarationInSubBlockNode(md, nametable, (SubBlockNode) bsn);
254       return;
255
256     case Kind.DeclarationNode:
257       checkDeclarationNode(md, nametable, (DeclarationNode) bsn);
258       break;
259
260     case Kind.LoopNode:
261       checkDeclarationInLoopNode(md, nametable, (LoopNode) bsn);
262       break;
263     }
264   }
265
266   private void checkDeclarationInLoopNode(MethodDescriptor md, SymbolTable nametable, LoopNode ln) {
267
268     if (ln.getType() == LoopNode.FORLOOP) {
269       // check for loop case
270       ClassDescriptor cd = md.getClassDesc();
271       BlockNode bn = ln.getInitializer();
272       for (int i = 0; i < bn.size(); i++) {
273         BlockStatementNode bsn = bn.get(i);
274         checkDeclarationInBlockStatementNode(md, nametable, bsn);
275       }
276     }
277
278     // check loop body
279     checkDeclarationInBlockNode(md, nametable, ln.getBody());
280   }
281
282   private void checkMethodBody(ClassDescriptor cd, MethodDescriptor md) {
283     BlockNode bn = state.getMethodBody(md);
284     checkLocationFromBlockNode(md, md.getParameterTable(), bn);
285   }
286
287   private CompositeLocation checkLocationFromBlockNode(MethodDescriptor md, SymbolTable nametable,
288       BlockNode bn) {
289
290     bn.getVarTable().setParent(nametable);
291     // it will return the lowest location in the block node
292     CompositeLocation lowestLoc = null;
293
294     for (int i = 0; i < bn.size(); i++) {
295       BlockStatementNode bsn = bn.get(i);
296       CompositeLocation bLoc = checkLocationFromBlockStatementNode(md, bn.getVarTable(), bsn);
297       if (!bLoc.isEmpty()) {
298         if (lowestLoc == null) {
299           lowestLoc = bLoc;
300         } else {
301           if (CompositeLattice.isGreaterThan(lowestLoc, bLoc)) {
302             lowestLoc = bLoc;
303           }
304         }
305       }
306
307     }
308
309     if (lowestLoc == null) {
310       lowestLoc = new CompositeLocation(Location.createBottomLocation(md));
311     }
312
313     return lowestLoc;
314   }
315
316   private CompositeLocation checkLocationFromBlockStatementNode(MethodDescriptor md,
317       SymbolTable nametable, BlockStatementNode bsn) {
318
319     CompositeLocation compLoc = null;
320     switch (bsn.kind()) {
321     case Kind.BlockExpressionNode:
322       compLoc = checkLocationFromBlockExpressionNode(md, nametable, (BlockExpressionNode) bsn);
323       break;
324
325     case Kind.DeclarationNode:
326       compLoc = checkLocationFromDeclarationNode(md, nametable, (DeclarationNode) bsn);
327       break;
328
329     case Kind.IfStatementNode:
330       compLoc = checkLocationFromIfStatementNode(md, nametable, (IfStatementNode) bsn);
331       break;
332
333     case Kind.LoopNode:
334       compLoc = checkLocationFromLoopNode(md, nametable, (LoopNode) bsn);
335       break;
336
337     case Kind.ReturnNode:
338       compLoc = checkLocationFromReturnNode(md, nametable, (ReturnNode) bsn);
339       break;
340
341     case Kind.SubBlockNode:
342       compLoc = checkLocationFromSubBlockNode(md, nametable, (SubBlockNode) bsn);
343       break;
344
345     case Kind.ContinueBreakNode:
346       compLoc = new CompositeLocation();
347       break;
348
349     case Kind.SwitchStatementNode:
350       compLoc = checkLocationFromSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn);
351
352     }
353     return compLoc;
354   }
355
356   private CompositeLocation checkLocationFromSwitchStatementNode(MethodDescriptor md,
357       SymbolTable nametable, SwitchStatementNode ssn) {
358
359     ClassDescriptor cd = md.getClassDesc();
360     CompositeLocation condLoc =
361         checkLocationFromExpressionNode(md, nametable, ssn.getCondition(), new CompositeLocation());
362     BlockNode sbn = ssn.getSwitchBody();
363
364     Set<CompositeLocation> blockLocSet = new HashSet<CompositeLocation>();
365     for (int i = 0; i < sbn.size(); i++) {
366       CompositeLocation blockLoc =
367           checkLocationFromSwitchBlockNode(md, nametable, (SwitchBlockNode) sbn.get(i));
368       if (!CompositeLattice.isGreaterThan(condLoc, blockLoc)) {
369         throw new Error(
370             "The location of the switch-condition statement is lower than the conditional body at "
371                 + cd.getSourceFileName() + ":" + ssn.getCondition().getNumLine());
372       }
373
374       blockLocSet.add(blockLoc);
375     }
376     return CompositeLattice.calculateGLB(blockLocSet);
377   }
378
379   private CompositeLocation checkLocationFromSwitchBlockNode(MethodDescriptor md,
380       SymbolTable nametable, SwitchBlockNode sbn) {
381
382     CompositeLocation blockLoc =
383         checkLocationFromBlockNode(md, nametable, sbn.getSwitchBlockStatement());
384
385     return blockLoc;
386
387   }
388
389   private CompositeLocation checkLocationFromReturnNode(MethodDescriptor md, SymbolTable nametable,
390       ReturnNode rn) {
391
392     ExpressionNode returnExp = rn.getReturnExpression();
393
394     CompositeLocation expLoc;
395     if (returnExp != null) {
396       expLoc = checkLocationFromExpressionNode(md, nametable, returnExp, new CompositeLocation());
397       // check if return value is equal or higher than RETRUNLOC of method
398       // declaration annotation
399       CompositeLocation returnLocAt = md2ReturnLoc.get(md);
400
401       if (CompositeLattice.isGreaterThan(returnLocAt, expLoc)) {
402         throw new Error(
403             "Return value location is not equal or higher than the declaraed return location at "
404                 + md.getClassDesc().getSourceFileName() + "::" + rn.getNumLine());
405       }
406     }
407
408     return new CompositeLocation();
409   }
410
411   private boolean hasOnlyLiteralValue(ExpressionNode en) {
412     if (en.kind() == Kind.LiteralNode) {
413       return true;
414     } else {
415       return false;
416     }
417   }
418
419   private CompositeLocation checkLocationFromLoopNode(MethodDescriptor md, SymbolTable nametable,
420       LoopNode ln) {
421
422     ClassDescriptor cd = md.getClassDesc();
423     if (ln.getType() == LoopNode.WHILELOOP || ln.getType() == LoopNode.DOWHILELOOP) {
424
425       CompositeLocation condLoc =
426           checkLocationFromExpressionNode(md, nametable, ln.getCondition(), new CompositeLocation());
427       addLocationType(ln.getCondition().getType(), (condLoc));
428
429       CompositeLocation bodyLoc = checkLocationFromBlockNode(md, nametable, ln.getBody());
430
431       if (!CompositeLattice.isGreaterThan(condLoc, bodyLoc)) {
432         // loop condition should be higher than loop body
433         throw new Error(
434             "The location of the while-condition statement is lower than the loop body at "
435                 + cd.getSourceFileName() + ":" + ln.getCondition().getNumLine());
436       }
437
438       return bodyLoc;
439
440     } else {
441       // check for loop case
442       BlockNode bn = ln.getInitializer();
443       bn.getVarTable().setParent(nametable);
444
445       // calculate glb location of condition and update statements
446       CompositeLocation condLoc =
447           checkLocationFromExpressionNode(md, bn.getVarTable(), ln.getCondition(),
448               new CompositeLocation());
449       addLocationType(ln.getCondition().getType(), condLoc);
450
451       CompositeLocation updateLoc =
452           checkLocationFromBlockNode(md, bn.getVarTable(), ln.getUpdate());
453
454       Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
455       glbInputSet.add(condLoc);
456       // glbInputSet.add(updateLoc);
457
458       CompositeLocation glbLocOfForLoopCond = CompositeLattice.calculateGLB(glbInputSet);
459
460       // check location of 'forloop' body
461       CompositeLocation blockLoc = checkLocationFromBlockNode(md, bn.getVarTable(), ln.getBody());
462
463       // compute glb of body including loop body and update statement
464       glbInputSet.clear();
465
466       if (blockLoc == null) {
467         // when there is no statement in the loop body
468
469         if (updateLoc == null) {
470           // also there is no update statement in the loop body
471           return glbLocOfForLoopCond;
472         }
473         glbInputSet.add(updateLoc);
474
475       } else {
476         glbInputSet.add(blockLoc);
477         glbInputSet.add(updateLoc);
478       }
479
480       CompositeLocation loopBodyLoc = CompositeLattice.calculateGLB(glbInputSet);
481
482       if (!CompositeLattice.isGreaterThan(glbLocOfForLoopCond, loopBodyLoc)) {
483         throw new Error(
484             "The location of the for-condition statement is lower than the for-loop body at "
485                 + cd.getSourceFileName() + ":" + ln.getCondition().getNumLine());
486       }
487       return blockLoc;
488     }
489
490   }
491
492   private CompositeLocation checkLocationFromSubBlockNode(MethodDescriptor md,
493       SymbolTable nametable, SubBlockNode sbn) {
494     CompositeLocation compLoc = checkLocationFromBlockNode(md, nametable, sbn.getBlockNode());
495     return compLoc;
496   }
497
498   private CompositeLocation checkLocationFromIfStatementNode(MethodDescriptor md,
499       SymbolTable nametable, IfStatementNode isn) {
500
501     ClassDescriptor localCD = md.getClassDesc();
502     Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
503
504     CompositeLocation condLoc =
505         checkLocationFromExpressionNode(md, nametable, isn.getCondition(), new CompositeLocation());
506
507     addLocationType(isn.getCondition().getType(), condLoc);
508     glbInputSet.add(condLoc);
509
510     CompositeLocation locTrueBlock = checkLocationFromBlockNode(md, nametable, isn.getTrueBlock());
511     if (locTrueBlock != null) {
512       glbInputSet.add(locTrueBlock);
513       // here, the location of conditional block should be higher than the
514       // location of true/false blocks
515       if (locTrueBlock != null && !CompositeLattice.isGreaterThan(condLoc, locTrueBlock)) {
516         // error
517         throw new Error(
518             "The location of the if-condition statement is lower than the conditional block at "
519                 + localCD.getSourceFileName() + ":" + isn.getCondition().getNumLine());
520       }
521     }
522
523     if (isn.getFalseBlock() != null) {
524       CompositeLocation locFalseBlock =
525           checkLocationFromBlockNode(md, nametable, isn.getFalseBlock());
526
527       if (locFalseBlock != null) {
528         glbInputSet.add(locFalseBlock);
529
530         if (!CompositeLattice.isGreaterThan(condLoc, locFalseBlock)) {
531           // error
532           throw new Error(
533               "The location of the if-condition statement is lower than the conditional block at "
534                   + localCD.getSourceFileName() + ":" + isn.getCondition().getNumLine());
535         }
536       }
537
538     }
539
540     // return GLB location of condition, true, and false block
541     CompositeLocation glbLoc = CompositeLattice.calculateGLB(glbInputSet);
542
543     return glbLoc;
544   }
545
546   private CompositeLocation checkLocationFromDeclarationNode(MethodDescriptor md,
547       SymbolTable nametable, DeclarationNode dn) {
548     VarDescriptor vd = dn.getVarDescriptor();
549
550     CompositeLocation destLoc = d2loc.get(vd);
551
552     if (dn.getExpression() != null) {
553       CompositeLocation expressionLoc =
554           checkLocationFromExpressionNode(md, nametable, dn.getExpression(),
555               new CompositeLocation());
556       // addTypeLocation(dn.getExpression().getType(), expressionLoc);
557
558       if (expressionLoc != null) {
559         // checking location order
560         if (!CompositeLattice.isGreaterThan(expressionLoc, destLoc)) {
561           throw new Error("The value flow from " + expressionLoc + " to " + destLoc
562               + " does not respect location hierarchy on the assignment " + dn.printNode(0)
563               + " at " + md.getClassDesc().getSourceFileName() + "::" + dn.getNumLine());
564         }
565       }
566       return expressionLoc;
567
568     } else {
569
570       return new CompositeLocation();
571
572     }
573
574   }
575
576   private void checkDeclarationInSubBlockNode(MethodDescriptor md, SymbolTable nametable,
577       SubBlockNode sbn) {
578     checkDeclarationInBlockNode(md, nametable.getParent(), sbn.getBlockNode());
579   }
580
581   private CompositeLocation checkLocationFromBlockExpressionNode(MethodDescriptor md,
582       SymbolTable nametable, BlockExpressionNode ben) {
583     CompositeLocation compLoc =
584         checkLocationFromExpressionNode(md, nametable, ben.getExpression(), null);
585     // addTypeLocation(ben.getExpression().getType(), compLoc);
586     return compLoc;
587   }
588
589   private CompositeLocation checkLocationFromExpressionNode(MethodDescriptor md,
590       SymbolTable nametable, ExpressionNode en, CompositeLocation loc) {
591
592     CompositeLocation compLoc = null;
593     switch (en.kind()) {
594
595     case Kind.AssignmentNode:
596       compLoc = checkLocationFromAssignmentNode(md, nametable, (AssignmentNode) en, loc);
597       break;
598
599     case Kind.FieldAccessNode:
600       compLoc = checkLocationFromFieldAccessNode(md, nametable, (FieldAccessNode) en, loc);
601       break;
602
603     case Kind.NameNode:
604       compLoc = checkLocationFromNameNode(md, nametable, (NameNode) en, loc);
605       break;
606
607     case Kind.OpNode:
608       compLoc = checkLocationFromOpNode(md, nametable, (OpNode) en);
609       break;
610
611     case Kind.CreateObjectNode:
612       compLoc = checkLocationFromCreateObjectNode(md, nametable, (CreateObjectNode) en);
613       break;
614
615     case Kind.ArrayAccessNode:
616       compLoc = checkLocationFromArrayAccessNode(md, nametable, (ArrayAccessNode) en);
617       break;
618
619     case Kind.LiteralNode:
620       compLoc = checkLocationFromLiteralNode(md, nametable, (LiteralNode) en, loc);
621       break;
622
623     case Kind.MethodInvokeNode:
624       compLoc = checkLocationFromMethodInvokeNode(md, nametable, (MethodInvokeNode) en, loc);
625       break;
626
627     case Kind.TertiaryNode:
628       compLoc = checkLocationFromTertiaryNode(md, nametable, (TertiaryNode) en);
629       break;
630
631     case Kind.CastNode:
632       compLoc = checkLocationFromCastNode(md, nametable, (CastNode) en);
633       break;
634
635     // case Kind.InstanceOfNode:
636     // checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
637     // return null;
638
639     // case Kind.ArrayInitializerNode:
640     // checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en,
641     // td);
642     // return null;
643
644     // case Kind.ClassTypeNode:
645     // checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
646     // return null;
647
648     // case Kind.OffsetNode:
649     // checkOffsetNode(md, nametable, (OffsetNode)en, td);
650     // return null;
651
652     default:
653       return null;
654
655     }
656     // addTypeLocation(en.getType(), compLoc);
657     return compLoc;
658
659   }
660
661   private CompositeLocation checkLocationFromCastNode(MethodDescriptor md, SymbolTable nametable,
662       CastNode cn) {
663
664     ExpressionNode en = cn.getExpression();
665     return checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation());
666
667   }
668
669   private CompositeLocation checkLocationFromTertiaryNode(MethodDescriptor md,
670       SymbolTable nametable, TertiaryNode tn) {
671     ClassDescriptor cd = md.getClassDesc();
672
673     CompositeLocation condLoc =
674         checkLocationFromExpressionNode(md, nametable, tn.getCond(), new CompositeLocation());
675     addLocationType(tn.getCond().getType(), condLoc);
676     CompositeLocation trueLoc =
677         checkLocationFromExpressionNode(md, nametable, tn.getTrueExpr(), new CompositeLocation());
678     addLocationType(tn.getTrueExpr().getType(), trueLoc);
679     CompositeLocation falseLoc =
680         checkLocationFromExpressionNode(md, nametable, tn.getFalseExpr(), new CompositeLocation());
681     addLocationType(tn.getFalseExpr().getType(), falseLoc);
682
683     // check if condLoc is higher than trueLoc & falseLoc
684     if (!CompositeLattice.isGreaterThan(condLoc, trueLoc)) {
685       throw new Error(
686           "The location of the condition expression is lower than the true expression at "
687               + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
688     }
689
690     if (!CompositeLattice.isGreaterThan(condLoc, falseLoc)) {
691       throw new Error(
692           "The location of the condition expression is lower than the true expression at "
693               + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
694     }
695
696     // then, return glb of trueLoc & falseLoc
697     Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
698     glbInputSet.add(trueLoc);
699     glbInputSet.add(falseLoc);
700
701     return CompositeLattice.calculateGLB(glbInputSet);
702   }
703
704   private CompositeLocation checkLocationFromMethodInvokeNode(MethodDescriptor md,
705       SymbolTable nametable, MethodInvokeNode min, CompositeLocation loc) {
706
707     checkCalleeConstraints(md, nametable, min);
708
709     CompositeLocation baseLocation = null;
710     if (min.getExpression() != null) {
711       baseLocation =
712           checkLocationFromExpressionNode(md, nametable, min.getExpression(),
713               new CompositeLocation());
714     } else {
715       String thisLocId = ssjava.getMethodLattice(md).getThisLoc();
716       baseLocation = new CompositeLocation(new Location(md, thisLocId));
717     }
718
719     if (!min.getMethod().getReturnType().isVoid()) {
720       // If method has a return value, compute the highest possible return
721       // location in the caller's perspective
722       CompositeLocation ceilingLoc =
723           computeCeilingLocationForCaller(md, nametable, min, baseLocation);
724       return ceilingLoc;
725     }
726
727     return new CompositeLocation();
728
729   }
730
731   private CompositeLocation computeCeilingLocationForCaller(MethodDescriptor md,
732       SymbolTable nametable, MethodInvokeNode min, CompositeLocation baseLocation) {
733     List<CompositeLocation> argList = new ArrayList<CompositeLocation>();
734
735     // by default, method has a THIS parameter
736     argList.add(baseLocation);
737
738     for (int i = 0; i < min.numArgs(); i++) {
739       ExpressionNode en = min.getArg(i);
740       CompositeLocation callerArg =
741           checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation());
742       argList.add(callerArg);
743     }
744     return md2ReturnLocGen.get(min.getMethod()).computeReturnLocation(argList);
745
746   }
747
748   private void checkCalleeConstraints(MethodDescriptor md, SymbolTable nametable,
749       MethodInvokeNode min) {
750
751     if (min.numArgs() > 1) {
752       // caller needs to guarantee that it passes arguments in regarding to
753       // callee's hierarchy
754       for (int i = 0; i < min.numArgs(); i++) {
755         ExpressionNode en = min.getArg(i);
756         CompositeLocation callerArg1 =
757             checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation());
758
759         ClassDescriptor calleecd = min.getMethod().getClassDesc();
760         VarDescriptor calleevd = (VarDescriptor) min.getMethod().getParameter(i);
761         CompositeLocation calleeLoc1 = d2loc.get(calleevd);
762
763         if (!callerArg1.get(0).isTop()) {
764           // here, check if ordering relations among caller's args respect
765           // ordering relations in-between callee's args
766           for (int currentIdx = 0; currentIdx < min.numArgs(); currentIdx++) {
767             if (currentIdx != i) { // skip itself
768               ExpressionNode argExp = min.getArg(currentIdx);
769
770               CompositeLocation callerArg2 =
771                   checkLocationFromExpressionNode(md, nametable, argExp, new CompositeLocation());
772
773               VarDescriptor calleevd2 = (VarDescriptor) min.getMethod().getParameter(currentIdx);
774               CompositeLocation calleeLoc2 = d2loc.get(calleevd2);
775
776               int callerResult = CompositeLattice.compare(callerArg1, callerArg2);
777               int calleeResult = CompositeLattice.compare(calleeLoc1, calleeLoc2);
778               if (calleeResult == ComparisonResult.GREATER
779                   && callerResult != ComparisonResult.GREATER) {
780                 // If calleeLoc1 is higher than calleeLoc2
781                 // then, caller should have same ordering relation in-bet
782                 // callerLoc1 & callerLoc2
783
784                 throw new Error("Caller doesn't respect ordering relations among method arguments:"
785                     + md.getClassDesc().getSourceFileName() + ":" + min.getNumLine());
786               }
787
788             }
789           }
790         }
791
792       }
793
794     }
795
796   }
797
798   private CompositeLocation checkLocationFromArrayAccessNode(MethodDescriptor md,
799       SymbolTable nametable, ArrayAccessNode aan) {
800
801     // return glb location of array itself and index
802
803     ClassDescriptor cd = md.getClassDesc();
804
805     Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
806
807     CompositeLocation arrayLoc =
808         checkLocationFromExpressionNode(md, nametable, aan.getExpression(), new CompositeLocation());
809     // addTypeLocation(aan.getExpression().getType(), arrayLoc);
810     glbInputSet.add(arrayLoc);
811     CompositeLocation indexLoc =
812         checkLocationFromExpressionNode(md, nametable, aan.getIndex(), new CompositeLocation());
813     glbInputSet.add(indexLoc);
814     // addTypeLocation(aan.getIndex().getType(), indexLoc);
815
816     CompositeLocation glbLoc = CompositeLattice.calculateGLB(glbInputSet);
817     return glbLoc;
818   }
819
820   private CompositeLocation checkLocationFromCreateObjectNode(MethodDescriptor md,
821       SymbolTable nametable, CreateObjectNode con) {
822
823     ClassDescriptor cd = md.getClassDesc();
824
825     // check arguments
826     Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
827     for (int i = 0; i < con.numArgs(); i++) {
828       ExpressionNode en = con.getArg(i);
829       CompositeLocation argLoc =
830           checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation());
831       glbInputSet.add(argLoc);
832       addLocationType(en.getType(), argLoc);
833     }
834
835     // check array initializers
836     // if ((con.getArrayInitializer() != null)) {
837     // checkLocationFromArrayInitializerNode(md, nametable,
838     // con.getArrayInitializer());
839     // }
840
841     if (glbInputSet.size() > 0) {
842       return CompositeLattice.calculateGLB(glbInputSet);
843     }
844
845     CompositeLocation compLoc = new CompositeLocation();
846     compLoc.addLocation(Location.createTopLocation(md));
847     return compLoc;
848
849   }
850
851   private CompositeLocation checkLocationFromOpNode(MethodDescriptor md, SymbolTable nametable,
852       OpNode on) {
853
854     ClassDescriptor cd = md.getClassDesc();
855     CompositeLocation leftLoc = new CompositeLocation();
856     leftLoc = checkLocationFromExpressionNode(md, nametable, on.getLeft(), leftLoc);
857     // addTypeLocation(on.getLeft().getType(), leftLoc);
858
859     CompositeLocation rightLoc = new CompositeLocation();
860     if (on.getRight() != null) {
861       rightLoc = checkLocationFromExpressionNode(md, nametable, on.getRight(), rightLoc);
862       // addTypeLocation(on.getRight().getType(), rightLoc);
863     }
864
865     // System.out.println("checking op node=" + on.printNode(0));
866     // System.out.println("left loc=" + leftLoc + " from " +
867     // on.getLeft().getClass());
868     // System.out.println("right loc=" + rightLoc + " from " +
869     // on.getRight().getClass());
870
871     Operation op = on.getOp();
872
873     switch (op.getOp()) {
874
875     case Operation.UNARYPLUS:
876     case Operation.UNARYMINUS:
877     case Operation.LOGIC_NOT:
878       // single operand
879       return leftLoc;
880
881     case Operation.LOGIC_OR:
882     case Operation.LOGIC_AND:
883     case Operation.COMP:
884     case Operation.BIT_OR:
885     case Operation.BIT_XOR:
886     case Operation.BIT_AND:
887     case Operation.ISAVAILABLE:
888     case Operation.EQUAL:
889     case Operation.NOTEQUAL:
890     case Operation.LT:
891     case Operation.GT:
892     case Operation.LTE:
893     case Operation.GTE:
894     case Operation.ADD:
895     case Operation.SUB:
896     case Operation.MULT:
897     case Operation.DIV:
898     case Operation.MOD:
899     case Operation.LEFTSHIFT:
900     case Operation.RIGHTSHIFT:
901     case Operation.URIGHTSHIFT:
902
903       Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
904       inputSet.add(leftLoc);
905       inputSet.add(rightLoc);
906       CompositeLocation glbCompLoc = CompositeLattice.calculateGLB(inputSet);
907       return glbCompLoc;
908
909     default:
910       throw new Error(op.toString());
911     }
912
913   }
914
915   private CompositeLocation checkLocationFromLiteralNode(MethodDescriptor md,
916       SymbolTable nametable, LiteralNode en, CompositeLocation loc) {
917
918     // literal value has the top location so that value can be flowed into any
919     // location
920     Location literalLoc = Location.createTopLocation(md);
921     loc.addLocation(literalLoc);
922     return loc;
923
924   }
925
926   private CompositeLocation checkLocationFromNameNode(MethodDescriptor md, SymbolTable nametable,
927       NameNode nn, CompositeLocation loc) {
928
929     NameDescriptor nd = nn.getName();
930     if (nd.getBase() != null) {
931
932       loc = checkLocationFromExpressionNode(md, nametable, nn.getExpression(), loc);
933       // addTypeLocation(nn.getExpression().getType(), loc);
934     } else {
935       String varname = nd.toString();
936
937       if (varname.equals("this")) {
938         // 'this' itself!
939         MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
940         String thisLocId = methodLattice.getThisLoc();
941         if (thisLocId == null) {
942           throw new Error("The location for 'this' is not defined at "
943               + md.getClassDesc().getSourceFileName() + "::" + nn.getNumLine());
944         }
945         Location locElement = new Location(md, thisLocId);
946         loc.addLocation(locElement);
947         return loc;
948       }
949       Descriptor d = (Descriptor) nametable.get(varname);
950
951       // CompositeLocation localLoc = null;
952       if (d instanceof VarDescriptor) {
953         VarDescriptor vd = (VarDescriptor) d;
954         // localLoc = d2loc.get(vd);
955         // the type of var descriptor has a composite location!
956         loc = ((CompositeLocation) vd.getType().getExtension()).clone();
957       } else if (d instanceof FieldDescriptor) {
958         // the type of field descriptor has a location!
959         FieldDescriptor fd = (FieldDescriptor) d;
960
961         if (fd.isStatic()) {
962           if (fd.isFinal()) {
963             // if it is 'static final', the location has TOP since no one can
964             // change its value
965             loc.addLocation(Location.createTopLocation(md));
966           } else {
967             // if 'static', the location has pre-assigned global loc
968             MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
969             String globalLocId = localLattice.getGlobalLoc();
970             if (globalLocId == null) {
971               throw new Error("Global location element is not defined in the method " + md);
972             }
973             Location globalLoc = new Location(md, globalLocId);
974
975             loc.addLocation(globalLoc);
976           }
977         } else {
978           // the location of field access starts from this, followed by field
979           // location
980           MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
981           Location thisLoc = new Location(md, localLattice.getThisLoc());
982           loc.addLocation(thisLoc);
983         }
984
985         Location fieldLoc = (Location) fd.getType().getExtension();
986         loc.addLocation(fieldLoc);
987       }
988     }
989     return loc;
990   }
991
992   private CompositeLocation checkLocationFromFieldAccessNode(MethodDescriptor md,
993       SymbolTable nametable, FieldAccessNode fan, CompositeLocation loc) {
994
995     ExpressionNode left = fan.getExpression();
996     loc = checkLocationFromExpressionNode(md, nametable, left, loc);
997
998     if (!left.getType().isPrimitive()) {
999       FieldDescriptor fd = fan.getField();
1000       Location fieldLoc = (Location) fd.getType().getExtension();
1001       loc.addLocation(fieldLoc);
1002     }
1003
1004     return loc;
1005   }
1006
1007   private CompositeLocation checkLocationFromAssignmentNode(MethodDescriptor md,
1008       SymbolTable nametable, AssignmentNode an, CompositeLocation loc) {
1009
1010     ClassDescriptor cd = md.getClassDesc();
1011
1012     boolean postinc = true;
1013     if (an.getOperation().getBaseOp() == null
1014         || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
1015             .getBaseOp().getOp() != Operation.POSTDEC))
1016       postinc = false;
1017
1018     CompositeLocation destLocation =
1019         checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation());
1020
1021     CompositeLocation srcLocation = new CompositeLocation();
1022
1023     if (!postinc) {
1024       if (hasOnlyLiteralValue(an.getSrc())) {
1025         // if source is literal value, src location is TOP. so do not need to
1026         // compare!
1027         return destLocation;
1028       }
1029       srcLocation = new CompositeLocation();
1030       srcLocation = checkLocationFromExpressionNode(md, nametable, an.getSrc(), srcLocation);
1031       // System.out.println(" an= " + an.printNode(0) + " an.getSrc()=" +
1032       // an.getSrc().getClass()
1033       // + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1034       // System.out.println("srcLocation=" + srcLocation);
1035       // System.out.println("dstLocation=" + destLocation);
1036       if (!CompositeLattice.isGreaterThan(srcLocation, destLocation)) {
1037         throw new Error("The value flow from " + srcLocation + " to " + destLocation
1038             + " does not respect location hierarchy on the assignment " + an.printNode(0) + " at "
1039             + cd.getSourceFileName() + "::" + an.getNumLine());
1040       }
1041     } else {
1042       destLocation =
1043           srcLocation = checkLocationFromExpressionNode(md, nametable, an.getDest(), srcLocation);
1044
1045       if (!CompositeLattice.isGreaterThan(srcLocation, destLocation)) {
1046         throw new Error("Location " + destLocation
1047             + " is not allowed to have the value flow that moves within the same location at "
1048             + cd.getSourceFileName() + "::" + an.getNumLine());
1049       }
1050
1051     }
1052
1053     return destLocation;
1054   }
1055
1056   private void assignLocationOfVarDescriptor(VarDescriptor vd, MethodDescriptor md,
1057       SymbolTable nametable, TreeNode n) {
1058
1059     ClassDescriptor cd = md.getClassDesc();
1060     Vector<AnnotationDescriptor> annotationVec = vd.getType().getAnnotationMarkers();
1061
1062     if (!md.getModifiers().isAbstract()) {
1063       // currently enforce every variable to have corresponding location
1064       if (annotationVec.size() == 0) {
1065         throw new Error("Location is not assigned to variable " + vd.getSymbol()
1066             + " in the method " + md.getSymbol() + " of the class " + cd.getSymbol());
1067       }
1068
1069       if (annotationVec.size() > 1) { // variable can have at most one location
1070         throw new Error(vd.getSymbol() + " has more than one location.");
1071       }
1072
1073       AnnotationDescriptor ad = annotationVec.elementAt(0);
1074
1075       if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1076
1077         if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1078           String locDec = ad.getValue(); // check if location is defined
1079
1080           if (locDec.startsWith(SSJavaAnalysis.DELTA)) {
1081             DeltaLocation deltaLoc = parseDeltaDeclaration(md, n, locDec);
1082             d2loc.put(vd, deltaLoc);
1083             addLocationType(vd.getType(), deltaLoc);
1084           } else {
1085             CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1086
1087             Location lastElement = compLoc.get(compLoc.getSize() - 1);
1088             if (ssjava.isSharedLocation(lastElement)) {
1089               ssjava.mapSharedLocation2Descriptor(lastElement, vd);
1090             }
1091
1092             d2loc.put(vd, compLoc);
1093             addLocationType(vd.getType(), compLoc);
1094           }
1095
1096         }
1097       }
1098     }
1099
1100   }
1101
1102   private DeltaLocation parseDeltaDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1103
1104     int deltaCount = 0;
1105     int dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1106     while (dIdx >= 0) {
1107       deltaCount++;
1108       int beginIdx = dIdx + 6;
1109       locDec = locDec.substring(beginIdx, locDec.length() - 1);
1110       dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1111     }
1112
1113     CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1114     DeltaLocation deltaLoc = new DeltaLocation(compLoc, deltaCount);
1115
1116     return deltaLoc;
1117   }
1118
1119   private Location parseFieldLocDeclaraton(String decl) {
1120
1121     int idx = decl.indexOf(".");
1122     String className = decl.substring(0, idx);
1123     String fieldName = decl.substring(idx + 1);
1124
1125     Descriptor d = state.getClassSymbolTable().get(className);
1126
1127     assert (d instanceof ClassDescriptor);
1128     SSJavaLattice<String> lattice = ssjava.getClassLattice((ClassDescriptor) d);
1129     if (!lattice.containsKey(fieldName)) {
1130       throw new Error("The location " + fieldName + " is not defined in the field lattice of '"
1131           + className + "'.");
1132     }
1133
1134     return new Location(d, fieldName);
1135   }
1136
1137   private CompositeLocation parseLocationDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1138
1139     CompositeLocation compLoc = new CompositeLocation();
1140
1141     StringTokenizer tokenizer = new StringTokenizer(locDec, ",");
1142     List<String> locIdList = new ArrayList<String>();
1143     while (tokenizer.hasMoreTokens()) {
1144       String locId = tokenizer.nextToken();
1145       locIdList.add(locId);
1146     }
1147
1148     // at least,one location element needs to be here!
1149     assert (locIdList.size() > 0);
1150
1151     // assume that loc with idx 0 comes from the local lattice
1152     // loc with idx 1 comes from the field lattice
1153
1154     String localLocId = locIdList.get(0);
1155     SSJavaLattice<String> localLattice = CompositeLattice.getLatticeByDescriptor(md);
1156     Location localLoc = new Location(md, localLocId);
1157     if (localLattice == null || (!localLattice.containsKey(localLocId))) {
1158       throw new Error("Location " + localLocId
1159           + " is not defined in the local variable lattice at "
1160           + md.getClassDesc().getSourceFileName() + "::" + (n != null ? n.getNumLine() : "") + ".");
1161     }
1162     compLoc.addLocation(localLoc);
1163
1164     for (int i = 1; i < locIdList.size(); i++) {
1165       String locName = locIdList.get(i);
1166
1167       Location fieldLoc = parseFieldLocDeclaraton(locName);
1168       // ClassDescriptor cd = fieldLocName2cd.get(locName);
1169       // SSJavaLattice<String> fieldLattice =
1170       // CompositeLattice.getLatticeByDescriptor(cd);
1171       //
1172       // if (fieldLattice == null || (!fieldLattice.containsKey(locName))) {
1173       // throw new Error("Location " + locName +
1174       // " is not defined in the field lattice at "
1175       // + cd.getSourceFileName() + ".");
1176       // }
1177       // Location fieldLoc = new Location(cd, locName);
1178       compLoc.addLocation(fieldLoc);
1179     }
1180
1181     return compLoc;
1182
1183   }
1184
1185   private void checkDeclarationNode(MethodDescriptor md, SymbolTable nametable, DeclarationNode dn) {
1186     VarDescriptor vd = dn.getVarDescriptor();
1187     assignLocationOfVarDescriptor(vd, md, nametable, dn);
1188   }
1189
1190   private void checkClass(ClassDescriptor cd) {
1191     // Check to see that methods respects ss property
1192     for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
1193       MethodDescriptor md = (MethodDescriptor) method_it.next();
1194       checkMethodDeclaration(cd, md);
1195     }
1196   }
1197
1198   private void checkDeclarationInClass(ClassDescriptor cd) {
1199     // Check to see that fields are okay
1200     for (Iterator field_it = cd.getFields(); field_it.hasNext();) {
1201       FieldDescriptor fd = (FieldDescriptor) field_it.next();
1202
1203       if (!(fd.isFinal() && fd.isStatic())) {
1204         checkFieldDeclaration(cd, fd);
1205       }
1206     }
1207   }
1208
1209   private void checkMethodDeclaration(ClassDescriptor cd, MethodDescriptor md) {
1210     // TODO
1211   }
1212
1213   private void checkFieldDeclaration(ClassDescriptor cd, FieldDescriptor fd) {
1214
1215     Vector<AnnotationDescriptor> annotationVec = fd.getType().getAnnotationMarkers();
1216
1217     // currently enforce every field to have corresponding location
1218     if (annotationVec.size() == 0) {
1219       throw new Error("Location is not assigned to the field '" + fd.getSymbol()
1220           + "' of the class " + cd.getSymbol() + " at " + cd.getSourceFileName());
1221     }
1222
1223     if (annotationVec.size() > 1) {
1224       // variable can have at most one location
1225       throw new Error("Field " + fd.getSymbol() + " of class " + cd
1226           + " has more than one location.");
1227     }
1228
1229     AnnotationDescriptor ad = annotationVec.elementAt(0);
1230
1231     if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1232
1233       if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1234         String locationID = ad.getValue();
1235         // check if location is defined
1236         SSJavaLattice<String> lattice = ssjava.getClassLattice(cd);
1237         if (lattice == null || (!lattice.containsKey(locationID))) {
1238           throw new Error("Location " + locationID
1239               + " is not defined in the field lattice of class " + cd.getSymbol() + " at"
1240               + cd.getSourceFileName() + ".");
1241         }
1242         Location loc = new Location(cd, locationID);
1243
1244         if (ssjava.isSharedLocation(loc)) {
1245           ssjava.mapSharedLocation2Descriptor(loc, fd);
1246         }
1247
1248         addLocationType(fd.getType(), loc);
1249
1250       }
1251     }
1252
1253   }
1254
1255   private void addLocationType(TypeDescriptor type, CompositeLocation loc) {
1256     if (type != null) {
1257       type.setExtension(loc);
1258     }
1259   }
1260
1261   private void addLocationType(TypeDescriptor type, Location loc) {
1262     if (type != null) {
1263       type.setExtension(loc);
1264     }
1265   }
1266
1267   static class CompositeLattice {
1268
1269     public static boolean isGreaterThan(CompositeLocation loc1, CompositeLocation loc2) {
1270
1271       int baseCompareResult = compareBaseLocationSet(loc1, loc2, true);
1272       if (baseCompareResult == ComparisonResult.EQUAL) {
1273         if (compareDelta(loc1, loc2) == ComparisonResult.GREATER) {
1274           return true;
1275         } else {
1276           return false;
1277         }
1278       } else if (baseCompareResult == ComparisonResult.GREATER) {
1279         return true;
1280       } else {
1281         return false;
1282       }
1283
1284     }
1285
1286     public static int compare(CompositeLocation loc1, CompositeLocation loc2) {
1287
1288       // System.out.println("compare=" + loc1 + " " + loc2);
1289       int baseCompareResult = compareBaseLocationSet(loc1, loc2, false);
1290
1291       if (baseCompareResult == ComparisonResult.EQUAL) {
1292         return compareDelta(loc1, loc2);
1293       } else {
1294         return baseCompareResult;
1295       }
1296
1297     }
1298
1299     private static int compareDelta(CompositeLocation dLoc1, CompositeLocation dLoc2) {
1300
1301       int deltaCount1 = 0;
1302       int deltaCount2 = 0;
1303       if (dLoc1 instanceof DeltaLocation) {
1304         deltaCount1 = ((DeltaLocation) dLoc1).getNumDelta();
1305       }
1306
1307       if (dLoc2 instanceof DeltaLocation) {
1308         deltaCount2 = ((DeltaLocation) dLoc2).getNumDelta();
1309       }
1310       if (deltaCount1 < deltaCount2) {
1311         return ComparisonResult.GREATER;
1312       } else if (deltaCount1 == deltaCount2) {
1313         return ComparisonResult.EQUAL;
1314       } else {
1315         return ComparisonResult.LESS;
1316       }
1317
1318     }
1319
1320     private static int compareBaseLocationSet(CompositeLocation compLoc1,
1321         CompositeLocation compLoc2, boolean awareSharedLoc) {
1322
1323       // if compLoc1 is greater than compLoc2, return true
1324       // else return false;
1325
1326       // compare one by one in according to the order of the tuple
1327       int numOfTie = 0;
1328       for (int i = 0; i < compLoc1.getSize(); i++) {
1329         Location loc1 = compLoc1.get(i);
1330         if (i >= compLoc2.getSize()) {
1331           throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1332               + " because they are not comparable.");
1333         }
1334         Location loc2 = compLoc2.get(i);
1335
1336         if (!loc1.getDescriptor().equals(loc2.getDescriptor())) {
1337           throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1338               + " because they are not comparable.");
1339         }
1340
1341         Descriptor d1 = loc1.getDescriptor();
1342         Descriptor d2 = loc2.getDescriptor();
1343
1344         SSJavaLattice<String> lattice1 = getLatticeByDescriptor(d1);
1345         SSJavaLattice<String> lattice2 = getLatticeByDescriptor(d2);
1346
1347         // check if the spin location is appeared only at the end of the
1348         // composite location
1349         if (lattice1.getSpinLocSet().contains(loc1.getLocIdentifier())) {
1350           if (i != (compLoc1.getSize() - 1)) {
1351             throw new Error("The spin location " + loc1.getLocIdentifier()
1352                 + " cannot be appeared in the middle of composite location.");
1353           }
1354         }
1355
1356         if (lattice2.getSpinLocSet().contains(loc2.getLocIdentifier())) {
1357           if (i != (compLoc2.getSize() - 1)) {
1358             throw new Error("The spin location " + loc2.getLocIdentifier()
1359                 + " cannot be appeared in the middle of composite location.");
1360           }
1361         }
1362
1363         if (!lattice1.equals(lattice2)) {
1364           throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1365               + " because they are not comparable.");
1366         }
1367
1368         if (loc1.getLocIdentifier().equals(loc2.getLocIdentifier())) {
1369           numOfTie++;
1370           // check if the current location is the spinning location
1371           // note that the spinning location only can be appeared in the last
1372           // part of the composite location
1373           if (awareSharedLoc && numOfTie == compLoc1.getSize()
1374               && lattice1.getSpinLocSet().contains(loc1.getLocIdentifier())) {
1375             return ComparisonResult.GREATER;
1376           }
1377           continue;
1378         } else if (lattice1.isGreaterThan(loc1.getLocIdentifier(), loc2.getLocIdentifier())) {
1379           return ComparisonResult.GREATER;
1380         } else {
1381           return ComparisonResult.LESS;
1382         }
1383
1384       }
1385
1386       if (numOfTie == compLoc1.getSize()) {
1387
1388         if (numOfTie != compLoc2.getSize()) {
1389           throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1390               + " because they are not comparable.");
1391         }
1392
1393         return ComparisonResult.EQUAL;
1394       }
1395
1396       return ComparisonResult.LESS;
1397
1398     }
1399
1400     public static CompositeLocation calculateGLB(Set<CompositeLocation> inputSet) {
1401
1402       // System.out.println("Calculating GLB=" + inputSet);
1403       CompositeLocation glbCompLoc = new CompositeLocation();
1404
1405       // calculate GLB of the first(priority) element
1406       Set<String> priorityLocIdentifierSet = new HashSet<String>();
1407       Descriptor priorityDescriptor = null;
1408
1409       Hashtable<String, Set<CompositeLocation>> locId2CompLocSet =
1410           new Hashtable<String, Set<CompositeLocation>>();
1411       // mapping from the priority loc ID to its full representation by the
1412       // composite location
1413
1414       int maxTupleSize = 0;
1415       CompositeLocation maxCompLoc = null;
1416
1417       for (Iterator iterator = inputSet.iterator(); iterator.hasNext();) {
1418         CompositeLocation compLoc = (CompositeLocation) iterator.next();
1419         if (compLoc.getSize() > maxTupleSize) {
1420           maxTupleSize = compLoc.getSize();
1421           maxCompLoc = compLoc;
1422         }
1423         Location priorityLoc = compLoc.get(0);
1424         String priorityLocId = priorityLoc.getLocIdentifier();
1425         priorityLocIdentifierSet.add(priorityLocId);
1426
1427         if (locId2CompLocSet.containsKey(priorityLocId)) {
1428           locId2CompLocSet.get(priorityLocId).add(compLoc);
1429         } else {
1430           Set<CompositeLocation> newSet = new HashSet<CompositeLocation>();
1431           newSet.add(compLoc);
1432           locId2CompLocSet.put(priorityLocId, newSet);
1433         }
1434
1435         // check if priority location are coming from the same lattice
1436         if (priorityDescriptor == null) {
1437           priorityDescriptor = priorityLoc.getDescriptor();
1438         } else if (!priorityDescriptor.equals(priorityLoc.getDescriptor())) {
1439           throw new Error("Failed to calculate GLB of " + inputSet
1440               + " because they are from different lattices.");
1441         }
1442       }
1443
1444       SSJavaLattice<String> locOrder = getLatticeByDescriptor(priorityDescriptor);
1445       String glbOfPriorityLoc = locOrder.getGLB(priorityLocIdentifierSet);
1446
1447       glbCompLoc.addLocation(new Location(priorityDescriptor, glbOfPriorityLoc));
1448       Set<CompositeLocation> compSet = locId2CompLocSet.get(glbOfPriorityLoc);
1449
1450       // here find out composite location that has a maximum length tuple
1451       // if we have three input set: [A], [A,B], [A,B,C]
1452       // maximum length tuple will be [A,B,C]
1453       int max = 0;
1454       CompositeLocation maxFromCompSet = null;
1455       for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1456         CompositeLocation c = (CompositeLocation) iterator.next();
1457         if (c.getSize() > max) {
1458           max = c.getSize();
1459           maxFromCompSet = c;
1460         }
1461       }
1462
1463       if (compSet == null) {
1464         // when GLB(x1,x2)!=x1 and !=x2 : GLB case 4
1465         // mean that the result is already lower than <x1,y1> and <x2,y2>
1466         // assign TOP to the rest of the location elements
1467
1468         // in this case, do not take care about delta
1469         // CompositeLocation inputComp = inputSet.iterator().next();
1470         CompositeLocation inputComp = maxCompLoc;
1471         for (int i = 1; i < inputComp.getSize(); i++) {
1472           glbCompLoc.addLocation(Location.createTopLocation(inputComp.get(i).getDescriptor()));
1473         }
1474       } else {
1475         if (compSet.size() == 1) {
1476
1477           // if GLB(x1,x2)==x1 or x2 : GLB case 2,3
1478           CompositeLocation comp = compSet.iterator().next();
1479           for (int i = 1; i < comp.getSize(); i++) {
1480             glbCompLoc.addLocation(comp.get(i));
1481           }
1482
1483           // if input location corresponding to glb is a delta, need to apply
1484           // delta to glb result
1485           if (comp instanceof DeltaLocation) {
1486             glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1487           }
1488
1489         } else {
1490           // when GLB(x1,x2)==x1 and x2 : GLB case 1
1491           // if more than one location shares the same priority GLB
1492           // need to calculate the rest of GLB loc
1493
1494           // int compositeLocSize = compSet.iterator().next().getSize();
1495           int compositeLocSize = maxFromCompSet.getSize();
1496
1497           Set<String> glbInputSet = new HashSet<String>();
1498           Descriptor currentD = null;
1499           for (int i = 1; i < compositeLocSize; i++) {
1500             for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1501               CompositeLocation compositeLocation = (CompositeLocation) iterator.next();
1502               if (compositeLocation.getSize() > i) {
1503                 Location currentLoc = compositeLocation.get(i);
1504                 currentD = currentLoc.getDescriptor();
1505                 // making set of the current location sharing the same idx
1506                 glbInputSet.add(currentLoc.getLocIdentifier());
1507               }
1508             }
1509             // calculate glb for the current lattice
1510
1511             SSJavaLattice<String> currentLattice = getLatticeByDescriptor(currentD);
1512             String currentGLBLocId = currentLattice.getGLB(glbInputSet);
1513             glbCompLoc.addLocation(new Location(currentD, currentGLBLocId));
1514           }
1515
1516           // if input location corresponding to glb is a delta, need to apply
1517           // delta to glb result
1518
1519           for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1520             CompositeLocation compLoc = (CompositeLocation) iterator.next();
1521             if (compLoc instanceof DeltaLocation) {
1522               if (glbCompLoc.equals(compLoc)) {
1523                 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1524                 break;
1525               }
1526             }
1527           }
1528
1529         }
1530       }
1531
1532       return glbCompLoc;
1533
1534     }
1535
1536     static SSJavaLattice<String> getLatticeByDescriptor(Descriptor d) {
1537
1538       SSJavaLattice<String> lattice = null;
1539
1540       if (d instanceof ClassDescriptor) {
1541         lattice = ssjava.getCd2lattice().get(d);
1542       } else if (d instanceof MethodDescriptor) {
1543         if (ssjava.getMd2lattice().containsKey(d)) {
1544           lattice = ssjava.getMd2lattice().get(d);
1545         } else {
1546           // use default lattice for the method
1547           lattice = ssjava.getCd2methodDefault().get(((MethodDescriptor) d).getClassDesc());
1548         }
1549       }
1550
1551       return lattice;
1552     }
1553
1554   }
1555
1556   class ComparisonResult {
1557
1558     public static final int GREATER = 0;
1559     public static final int EQUAL = 1;
1560     public static final int LESS = 2;
1561     public static final int INCOMPARABLE = 3;
1562     int result;
1563
1564   }
1565
1566 }
1567
1568 class ReturnLocGenerator {
1569
1570   public static final int PARAMISHIGHER = 0;
1571   public static final int PARAMISSAME = 1;
1572   public static final int IGNORE = 2;
1573
1574   Hashtable<Integer, Integer> paramIdx2paramType;
1575
1576   public ReturnLocGenerator(CompositeLocation returnLoc, List<CompositeLocation> params) {
1577     // creating mappings
1578     paramIdx2paramType = new Hashtable<Integer, Integer>();
1579     for (int i = 0; i < params.size(); i++) {
1580       CompositeLocation param = params.get(i);
1581       int compareResult = CompositeLattice.compare(param, returnLoc);
1582
1583       int type;
1584       if (compareResult == ComparisonResult.GREATER) {
1585         type = 0;
1586       } else if (compareResult == ComparisonResult.EQUAL) {
1587         type = 1;
1588       } else {
1589         type = 2;
1590       }
1591       paramIdx2paramType.put(new Integer(i), new Integer(type));
1592     }
1593
1594   }
1595
1596   public CompositeLocation computeReturnLocation(List<CompositeLocation> args) {
1597
1598     // compute the highest possible location in caller's side
1599     assert paramIdx2paramType.keySet().size() == args.size();
1600
1601     Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
1602     for (int i = 0; i < args.size(); i++) {
1603       int type = (paramIdx2paramType.get(new Integer(i))).intValue();
1604       CompositeLocation argLoc = args.get(i);
1605       if (type == PARAMISHIGHER) {
1606         // return loc is lower than param
1607         DeltaLocation delta = new DeltaLocation(argLoc, 1);
1608         inputGLB.add(delta);
1609       } else if (type == PARAMISSAME) {
1610         // return loc is equal or lower than param
1611         inputGLB.add(argLoc);
1612       }
1613     }
1614
1615     // compute GLB of arguments subset that are same or higher than return
1616     // location
1617     CompositeLocation glb = CompositeLattice.calculateGLB(inputGLB);
1618     return glb;
1619   }
1620 }