63514e3037ff54d2c41af1647e1764a6c579d31a
[IRC.git] / Robust / src / Analysis / SSJava / LocationInference.java
1 package Analysis.SSJava;
2
3 import java.io.BufferedReader;
4 import java.io.BufferedWriter;
5 import java.io.FileReader;
6 import java.io.FileWriter;
7 import java.io.IOException;
8 import java.util.ArrayList;
9 import java.util.Collections;
10 import java.util.Comparator;
11 import java.util.HashMap;
12 import java.util.HashSet;
13 import java.util.Iterator;
14 import java.util.LinkedList;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.Set;
18 import java.util.Stack;
19 import java.util.Vector;
20
21 import IR.ClassDescriptor;
22 import IR.Descriptor;
23 import IR.FieldDescriptor;
24 import IR.MethodDescriptor;
25 import IR.NameDescriptor;
26 import IR.Operation;
27 import IR.State;
28 import IR.SymbolTable;
29 import IR.TypeDescriptor;
30 import IR.TypeUtil;
31 import IR.VarDescriptor;
32 import IR.Tree.ArrayAccessNode;
33 import IR.Tree.AssignmentNode;
34 import IR.Tree.BlockExpressionNode;
35 import IR.Tree.BlockNode;
36 import IR.Tree.BlockStatementNode;
37 import IR.Tree.CastNode;
38 import IR.Tree.CreateObjectNode;
39 import IR.Tree.DeclarationNode;
40 import IR.Tree.ExpressionNode;
41 import IR.Tree.FieldAccessNode;
42 import IR.Tree.IfStatementNode;
43 import IR.Tree.Kind;
44 import IR.Tree.LiteralNode;
45 import IR.Tree.LoopNode;
46 import IR.Tree.MethodInvokeNode;
47 import IR.Tree.NameNode;
48 import IR.Tree.OpNode;
49 import IR.Tree.ReturnNode;
50 import IR.Tree.SubBlockNode;
51 import IR.Tree.SwitchBlockNode;
52 import IR.Tree.SwitchStatementNode;
53 import IR.Tree.TertiaryNode;
54 import IR.Tree.TreeNode;
55 import Util.Pair;
56
57 public class LocationInference {
58
59   static int COUNT = 0;
60
61   State state;
62   SSJavaAnalysis ssjava;
63   TypeUtil tu;
64
65   List<ClassDescriptor> temp_toanalyzeList;
66   List<MethodDescriptor> temp_toanalyzeMethodList;
67   Map<MethodDescriptor, FlowGraph> mapMethodDescriptorToFlowGraph;
68
69   LinkedList<MethodDescriptor> toanalyze_methodDescList;
70   Set<ClassDescriptor> toanalyze_classDescSet;
71
72   // InheritanceTree<ClassDescriptor> inheritanceTree;
73
74   // map a method descriptor to its set of parameter descriptors
75   Map<MethodDescriptor, Set<Descriptor>> mapMethodDescriptorToParamDescSet;
76
77   // keep current descriptors to visit in fixed-point interprocedural analysis,
78   private Stack<MethodDescriptor> methodDescriptorsToVisitStack;
79
80   // map a class descriptor to a field lattice
81   private Map<ClassDescriptor, SSJavaLattice<String>> cd2lattice;
82
83   // map a method descriptor to a method lattice
84   private Map<MethodDescriptor, SSJavaLattice<String>> md2lattice;
85
86   // map a method/class descriptor to a hierarchy graph
87   private Map<Descriptor, HierarchyGraph> mapDescriptorToHierarchyGraph;
88
89   // map a method/class descriptor to a skeleton hierarchy graph
90   private Map<Descriptor, HierarchyGraph> mapDescriptorToSkeletonHierarchyGraph;
91
92   private Map<Descriptor, HierarchyGraph> mapDescriptorToSimpleHierarchyGraph;
93
94   // map a method/class descriptor to a skeleton hierarchy graph with combination nodes
95   private Map<Descriptor, HierarchyGraph> mapDescriptorToCombineSkeletonHierarchyGraph;
96
97   // map a descriptor to a simple lattice
98   private Map<Descriptor, SSJavaLattice<String>> mapDescriptorToSimpleLattice;
99
100   // map a method descriptor to the set of method invocation nodes which are
101   // invoked by the method descriptor
102   private Map<MethodDescriptor, Set<MethodInvokeNode>> mapMethodDescriptorToMethodInvokeNodeSet;
103
104   private Map<MethodInvokeNode, Map<Integer, NTuple<Descriptor>>> mapMethodInvokeNodeToArgIdxMap;
105
106   private Map<MethodInvokeNode, NTuple<Descriptor>> mapMethodInvokeNodeToBaseTuple;
107
108   private Map<MethodInvokeNode, Set<NTuple<Location>>> mapMethodInvokeNodeToPCLocTupleSet;
109
110   private Map<MethodDescriptor, MethodLocationInfo> mapMethodDescToMethodLocationInfo;
111
112   private Map<ClassDescriptor, LocationInfo> mapClassToLocationInfo;
113
114   private Map<MethodDescriptor, Set<MethodDescriptor>> mapMethodToCalleeSet;
115
116   private Map<MethodDescriptor, Set<FlowNode>> mapMethodDescToParamNodeFlowsToReturnValue;
117
118   private Map<String, Vector<String>> mapFileNameToLineVector;
119
120   private Map<Descriptor, Integer> mapDescToDefinitionLine;
121
122   private Map<Descriptor, LocationSummary> mapDescToLocationSummary;
123
124   private Map<MethodDescriptor, Set<MethodInvokeNode>> mapMethodDescToMethodInvokeNodeSet;
125
126   // maps a method descriptor to a sub global flow graph that captures all value flows caused by the
127   // set of callees reachable from the method
128   private Map<MethodDescriptor, GlobalFlowGraph> mapMethodDescriptorToSubGlobalFlowGraph;
129
130   private Map<MethodInvokeNode, Map<NTuple<Descriptor>, NTuple<Descriptor>>> mapMethodInvokeNodeToMapCallerArgToCalleeArg;
131
132   private Map<MethodDescriptor, Boolean> mapMethodDescriptorToCompositeReturnCase;
133
134   private Map<MethodDescriptor, MethodDescriptor> mapMethodDescToHighestOverriddenMethodDesc;
135
136   private Map<MethodDescriptor, Set<MethodDescriptor>> mapHighestOverriddenMethodDescToMethodDescSet;
137
138   private Map<MethodDescriptor, NTuple<Descriptor>> mapHighestOverriddenMethodDescToReturnLocTuple;
139
140   private Map<MethodDescriptor, NTuple<Descriptor>> mapHighestOverriddenMethodDescToPCLocTuple;
141
142   private Map<MethodDescriptor, Set<NTuple<Descriptor>>> mapHighestOverriddenMethodDescToSetLowerThanPCLoc;
143
144   private Map<MethodDescriptor, Set<NTuple<Descriptor>>> mapHighestOverriddenMethodDescToSetHigherThanRETURNLoc;
145
146   public static final String GLOBALLOC = "GLOBALLOC";
147
148   public static final String INTERLOC = "INTERLOC";
149
150   public static final String PCLOC = "_PCLOC_";
151
152   public static final String RLOC = "_RLOC_";
153
154   public static final Descriptor GLOBALDESC = new NameDescriptor(GLOBALLOC);
155
156   public static final Descriptor TOPDESC = new NameDescriptor(SSJavaAnalysis.TOP);
157
158   public static final Descriptor BOTTOMDESC = new NameDescriptor(SSJavaAnalysis.BOTTOM);
159
160   public static final Descriptor RETURNLOC = new NameDescriptor(RLOC);
161
162   public static final Descriptor LITERALDESC = new NameDescriptor("LITERAL");
163
164   public static final HNode TOPHNODE = new HNode(TOPDESC);
165
166   public static final HNode BOTTOMHNODE = new HNode(BOTTOMDESC);
167
168   public static String newline = System.getProperty("line.separator");
169
170   LocationInfo curMethodInfo;
171
172   private boolean hasChanges = false;
173
174   boolean debug = true;
175
176   public static int locSeed = 0;
177
178   private Stack<String> arrayAccessNodeStack;
179
180   private ClassDescriptor rootClassDescriptor;
181
182   private BuildLattice buildLattice;
183
184   public static int numLocationsSInfer = 0;
185   public static int numLocationsNaive = 0;
186
187   public LocationInference(SSJavaAnalysis ssjava, State state, TypeUtil tu) {
188     this.ssjava = ssjava;
189     this.state = state;
190     this.tu = tu;
191     this.toanalyze_classDescSet = new HashSet<ClassDescriptor>();
192     this.temp_toanalyzeList = new ArrayList<ClassDescriptor>();
193     this.temp_toanalyzeMethodList = new ArrayList<MethodDescriptor>();
194     this.mapMethodDescriptorToFlowGraph = new HashMap<MethodDescriptor, FlowGraph>();
195     this.cd2lattice = new HashMap<ClassDescriptor, SSJavaLattice<String>>();
196     this.md2lattice = new HashMap<MethodDescriptor, SSJavaLattice<String>>();
197     this.methodDescriptorsToVisitStack = new Stack<MethodDescriptor>();
198     this.mapMethodDescriptorToMethodInvokeNodeSet =
199         new HashMap<MethodDescriptor, Set<MethodInvokeNode>>();
200     this.mapMethodInvokeNodeToArgIdxMap =
201         new HashMap<MethodInvokeNode, Map<Integer, NTuple<Descriptor>>>();
202     this.mapMethodDescToMethodLocationInfo = new HashMap<MethodDescriptor, MethodLocationInfo>();
203     this.mapMethodToCalleeSet = new HashMap<MethodDescriptor, Set<MethodDescriptor>>();
204     this.mapClassToLocationInfo = new HashMap<ClassDescriptor, LocationInfo>();
205
206     this.mapFileNameToLineVector = new HashMap<String, Vector<String>>();
207     this.mapDescToDefinitionLine = new HashMap<Descriptor, Integer>();
208     this.mapMethodDescToParamNodeFlowsToReturnValue =
209         new HashMap<MethodDescriptor, Set<FlowNode>>();
210
211     this.mapDescriptorToHierarchyGraph = new HashMap<Descriptor, HierarchyGraph>();
212     this.mapMethodInvokeNodeToBaseTuple = new HashMap<MethodInvokeNode, NTuple<Descriptor>>();
213
214     this.mapDescriptorToSkeletonHierarchyGraph = new HashMap<Descriptor, HierarchyGraph>();
215     this.mapDescriptorToCombineSkeletonHierarchyGraph = new HashMap<Descriptor, HierarchyGraph>();
216     this.mapDescriptorToSimpleHierarchyGraph = new HashMap<Descriptor, HierarchyGraph>();
217
218     this.mapDescriptorToSimpleLattice = new HashMap<Descriptor, SSJavaLattice<String>>();
219
220     this.mapDescToLocationSummary = new HashMap<Descriptor, LocationSummary>();
221
222     this.mapMethodDescriptorToSubGlobalFlowGraph = new HashMap<MethodDescriptor, GlobalFlowGraph>();
223
224     this.mapMethodInvokeNodeToMapCallerArgToCalleeArg =
225         new HashMap<MethodInvokeNode, Map<NTuple<Descriptor>, NTuple<Descriptor>>>();
226
227     this.mapMethodInvokeNodeToPCLocTupleSet =
228         new HashMap<MethodInvokeNode, Set<NTuple<Location>>>();
229
230     this.arrayAccessNodeStack = new Stack<String>();
231
232     this.mapMethodDescToMethodInvokeNodeSet =
233         new HashMap<MethodDescriptor, Set<MethodInvokeNode>>();
234
235     this.mapMethodDescriptorToCompositeReturnCase = new HashMap<MethodDescriptor, Boolean>();
236
237     mapMethodDescToHighestOverriddenMethodDesc = new HashMap<MethodDescriptor, MethodDescriptor>();
238
239     mapHighestOverriddenMethodDescToSetLowerThanPCLoc =
240         new HashMap<MethodDescriptor, Set<NTuple<Descriptor>>>();
241
242     mapHighestOverriddenMethodDescToMethodDescSet =
243         new HashMap<MethodDescriptor, Set<MethodDescriptor>>();
244
245     mapHighestOverriddenMethodDescToReturnLocTuple =
246         new HashMap<MethodDescriptor, NTuple<Descriptor>>();
247
248     mapHighestOverriddenMethodDescToPCLocTuple =
249         new HashMap<MethodDescriptor, NTuple<Descriptor>>();
250
251     mapHighestOverriddenMethodDescToSetHigherThanRETURNLoc =
252         new HashMap<MethodDescriptor, Set<NTuple<Descriptor>>>();
253
254     this.buildLattice = new BuildLattice(this);
255
256   }
257
258   public void setupToAnalyze() {
259     SymbolTable classtable = state.getClassSymbolTable();
260     temp_toanalyzeList.clear();
261     temp_toanalyzeList.addAll(classtable.getValueSet());
262     // Collections.sort(toanalyzeList, new Comparator<ClassDescriptor>() {
263     // public int compare(ClassDescriptor o1, ClassDescriptor o2) {
264     // return o1.getClassName().compareToIgnoreCase(o2.getClassName());
265     // }
266     // });
267   }
268
269   public void setupToAnalazeMethod(ClassDescriptor cd) {
270
271     SymbolTable methodtable = cd.getMethodTable();
272     temp_toanalyzeMethodList.clear();
273     temp_toanalyzeMethodList.addAll(methodtable.getValueSet());
274     Collections.sort(temp_toanalyzeMethodList, new Comparator<MethodDescriptor>() {
275       public int compare(MethodDescriptor o1, MethodDescriptor o2) {
276         return o1.getSymbol().compareToIgnoreCase(o2.getSymbol());
277       }
278     });
279   }
280
281   public boolean toAnalyzeMethodIsEmpty() {
282     return temp_toanalyzeMethodList.isEmpty();
283   }
284
285   public boolean toAnalyzeIsEmpty() {
286     return temp_toanalyzeList.isEmpty();
287   }
288
289   public ClassDescriptor toAnalyzeNext() {
290     return temp_toanalyzeList.remove(0);
291   }
292
293   public MethodDescriptor toAnalyzeMethodNext() {
294     return temp_toanalyzeMethodList.remove(0);
295   }
296
297   public void inference() {
298
299     ssjava.init();
300
301     // construct value flow graph
302     constructFlowGraph();
303
304     constructGlobalFlowGraph();
305
306     checkReturnNodes();
307
308     assignCompositeLocation();
309     updateFlowGraph();
310     calculateExtraLocations();
311     addAdditionalOrderingConstraints();
312
313     _debug_writeFlowGraph();
314
315     buildInheritanceTree();
316     calculateReturnPCLocInheritance();
317
318     constructHierarchyGraph();
319
320     addInheritanceConstraintsToHierarchyGraph();
321
322     debug_writeHierarchyDotFiles();
323
324     simplifyHierarchyGraph();
325
326     debug_writeSimpleHierarchyDotFiles();
327
328     constructSkeletonHierarchyGraph();
329
330     debug_writeSkeletonHierarchyDotFiles();
331
332     insertCombinationNodes();
333
334     debug_writeSkeletonCombinationHierarchyDotFiles();
335
336     buildLatticeInheritanceTree();
337     // buildLattice();
338
339     debug_writeLattices();
340
341     updateCompositeLocationAssignments();
342
343     generateMethodSummary();
344
345     generateAnnoatedCode();
346
347     for (Iterator iterator = cd2lattice.keySet().iterator(); iterator.hasNext();) {
348       ClassDescriptor cd = (ClassDescriptor) iterator.next();
349       SSJavaLattice<String> lattice = getLattice(cd);
350       HierarchyGraph hg = mapDescriptorToHierarchyGraph.get(cd);
351       // System.out.println("~~~\t" + cd + "\t" + lattice.getKeySet().size() + "\t"
352       // + hg.getNodeSet().size());
353     }
354
355     for (Iterator iterator = md2lattice.keySet().iterator(); iterator.hasNext();) {
356       MethodDescriptor md = (MethodDescriptor) iterator.next();
357       SSJavaLattice<String> locOrder = getLattice(md);
358       // writeLatticeDotFile(md.getClassDesc(), md, getMethodLattice(md));
359       HierarchyGraph hg = mapDescriptorToHierarchyGraph.get(md);
360       // System.out.println("~~~\t" + md.getClassDesc() + "_" + md + "\t"
361       // + locOrder.getKeySet().size() + "\t" + hg.getNodeSet().size());
362     }
363
364     System.out.println("The number of elements: Naive=" + numLocationsNaive + " SInfer="
365         + numLocationsSInfer);
366
367     System.exit(0);
368
369   }
370
371   private void calculateReturnPCLocInheritance() {
372     calculateHighestPCLocInheritance();
373     calculateLowestReturnLocInheritance();
374     updateFlowGraphPCReturnLocInheritance();
375   }
376
377   private void updateFlowGraphPCReturnLocInheritance() {
378
379     Set<MethodDescriptor> keySet = mapHighestOverriddenMethodDescToMethodDescSet.keySet();
380     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
381       MethodDescriptor highestMethodDesc = (MethodDescriptor) iterator.next();
382
383       if (mapHighestOverriddenMethodDescToMethodDescSet.get(highestMethodDesc).size() == 1) {
384         continue;
385       }
386
387       Set<MethodDescriptor> methodDescSet =
388           mapHighestOverriddenMethodDescToMethodDescSet.get(highestMethodDesc);
389
390       NTuple<Descriptor> highestPCLocDescTuple =
391           mapHighestOverriddenMethodDescToPCLocTuple.get(highestMethodDesc);
392
393       NTuple<Descriptor> highestRETURNLocDescTuple =
394           mapHighestOverriddenMethodDescToReturnLocTuple.get(highestMethodDesc);
395
396       // System.out.println("\n$$$$$$$$$$$$$$$$updateFlowGraphPCReturnLocInheritance="
397       // + highestMethodDesc);
398       // System.out.println("-----highestPCLoc=" + highestPCLocDescTuple);
399       // System.out.println("-----highestRETURNLoc=" + highestRETURNLocDescTuple);
400
401       for (Iterator iterator2 = methodDescSet.iterator(); iterator2.hasNext();) {
402         MethodDescriptor md = (MethodDescriptor) iterator2.next();
403         // System.out.println("\n --------MD=" + md);
404         FlowGraph flowGraph = getFlowGraph(md);
405
406         MethodSummary summary = getMethodSummary(md);
407         CompositeLocation curPCLoc = summary.getPCLoc();
408         NTuple<Descriptor> curPCDescTuple = translateToDescTuple(curPCLoc.getTuple());
409         // System.out.println("md=" + md + "  curPCLoc=" + curPCLoc);
410         // System.out.println("highestPCLoc=" + highestPCLocDescTuple);
411
412         if (highestPCLocDescTuple == null) {
413           // this case: PCLOC is top
414           // System.out.println("###SET PCLOC AS TOP");
415           if (curPCDescTuple != null && !curPCLoc.get(0).isTop()) {
416             FlowNode pcFlowNode = flowGraph.getFlowNode(curPCDescTuple);
417             flowGraph.removeNode(pcFlowNode);
418           }
419           summary.setPCLoc(new CompositeLocation(new Location(md, Location.TOP)));
420         } else {
421           NTuple<Descriptor> newPCDescTuple = new NTuple<Descriptor>();
422           if (highestPCLocDescTuple.size() == 1) {
423             newPCDescTuple.add(highestPCLocDescTuple.get(0));
424           } else {
425             newPCDescTuple.add(md.getThis());
426             newPCDescTuple.add(highestPCLocDescTuple.get(1));
427           }
428           if (!curPCDescTuple.equals(newPCDescTuple)) {
429             FlowNode pcFlowNode = flowGraph.getFlowNode(curPCDescTuple);
430             flowGraph.updateTuple(pcFlowNode, newPCDescTuple);
431             // flowGraph.removeNode(pcFlowNode);
432             Set<NTuple<Descriptor>> descSetLowerThanPCLoc =
433                 mapHighestOverriddenMethodDescToSetLowerThanPCLoc.get(highestMethodDesc);
434             for (Iterator iterator3 = descSetLowerThanPCLoc.iterator(); iterator3.hasNext();) {
435               NTuple<Descriptor> lowerNTuple = (NTuple<Descriptor>) iterator3.next();
436               flowGraph.addValueFlowEdge(newPCDescTuple, lowerNTuple);
437             }
438             CompositeLocation newPCCompLoc =
439                 new CompositeLocation(translateToLocTuple(md, newPCDescTuple));
440             summary.setPCLoc(newPCCompLoc);
441           }
442
443         }
444
445         // update return loc
446         if (highestRETURNLocDescTuple != null) {
447           CompositeLocation curRETURNLoc = summary.getRETURNLoc();
448           NTuple<Descriptor> curReturnDescTuple = translateToDescTuple(curRETURNLoc.getTuple());
449
450           if (!curReturnDescTuple.equals(highestRETURNLocDescTuple)) {
451             // handle the case that RETURNLOC is started with 'this'...
452             NTuple<Descriptor> newRETURNLocDescTuple = new NTuple<Descriptor>();
453             if (highestRETURNLocDescTuple.size() == 1) {
454               newRETURNLocDescTuple.add(highestRETURNLocDescTuple.get(0));
455             } else {
456               newRETURNLocDescTuple.add(md.getThis());
457               newRETURNLocDescTuple.add(highestRETURNLocDescTuple.get(1));
458             }
459
460             FlowNode returnFlowNode = flowGraph.getFlowNode(curReturnDescTuple);
461             flowGraph.updateTuple(returnFlowNode, newRETURNLocDescTuple);
462
463             Set<NTuple<Descriptor>> descSetHigherThanRETURNLoc =
464                 mapHighestOverriddenMethodDescToSetHigherThanRETURNLoc.get(highestMethodDesc);
465             for (Iterator iterator3 = descSetHigherThanRETURNLoc.iterator(); iterator3.hasNext();) {
466               NTuple<Descriptor> higherNTuple = (NTuple<Descriptor>) iterator3.next();
467               flowGraph.addValueFlowEdge(higherNTuple, newRETURNLocDescTuple);
468             }
469
470             CompositeLocation newRETURNLocCompLoc =
471                 new CompositeLocation(translateToLocTuple(md, newRETURNLocDescTuple));
472             summary.setRETURNLoc(newRETURNLocCompLoc);
473           }
474         }
475       }
476     }
477   }
478
479   private void calculateHighestPCLocInheritance() {
480
481     Set<MethodDescriptor> keySet = mapHighestOverriddenMethodDescToMethodDescSet.keySet();
482
483     Map<MethodDescriptor, Integer> mapMethodDescToParamCount =
484         new HashMap<MethodDescriptor, Integer>();
485
486     next: for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
487       MethodDescriptor highestMethodDesc = (MethodDescriptor) iterator.next();
488
489       NTuple<Descriptor> tempTuple = null;
490
491       if (getMethodSummary(highestMethodDesc).getPCLoc() != null) {
492
493         Set<MethodDescriptor> methodDescSet =
494             mapHighestOverriddenMethodDescToMethodDescSet.get(highestMethodDesc);
495
496         if (methodDescSet.size() > 1) {
497           // System.out.println("---method desc set=" + methodDescSet + "  from=" +
498           // highestMethodDesc);
499         } else {
500           continue next;
501         }
502
503         for (Iterator iterator2 = methodDescSet.iterator(); iterator2.hasNext();) {
504           MethodDescriptor md = (MethodDescriptor) iterator2.next();
505
506           FlowGraph flowGraph = getFlowGraph(md);
507           if (flowGraph == null) {
508             continue;
509           }
510           Set<FlowNode> paramNodeSet = flowGraph.getParamFlowNodeSet();
511           // System.out.println("###md=" + md + "   paramNodeSet=" + paramNodeSet);
512
513           CompositeLocation pcLOC = getMethodSummary(md).getPCLoc();
514           // System.out.println("---pcLOC=" + pcLOC);
515
516           if (md.equals(highestMethodDesc)) {
517             mapHighestOverriddenMethodDescToPCLocTuple.put(highestMethodDesc,
518                 translateToDescTuple(pcLOC.getTuple()));
519           }
520
521           if (!pcLOC.get(0).isTop()) {
522
523             FlowNode pcFlowNode = flowGraph.getFlowNode(translateToDescTuple(pcLOC.getTuple()));
524
525             int count = 0;
526             for (Iterator iterator3 = paramNodeSet.iterator(); iterator3.hasNext();) {
527               FlowNode paramNode = (FlowNode) iterator3.next();
528               if (flowGraph.getReachableSetFrom(pcFlowNode.getCurrentDescTuple().subList(0, 1))
529                   .contains(paramNode)) {
530                 count++;
531               }
532             }
533             mapMethodDescToParamCount.put(md, count);
534
535           } else {
536
537             // the PC location is top
538             // if one of pcloc among the method inheritance chain has the TOP,
539             // all methods in the same chain should have the TOP.
540             mapHighestOverriddenMethodDescToPCLocTuple.remove(highestMethodDesc);
541             // System.out.println("highest=" + highestMethodDesc + "  HIGHEST PCLOC="
542             // + mapHighestOverriddenMethodDescToPCLocTuple.get(highestMethodDesc));
543
544             Set<NTuple<Descriptor>> descTupleSetLowerThanPC = new HashSet<NTuple<Descriptor>>();
545             for (Iterator iterator3 = paramNodeSet.iterator(); iterator3.hasNext();) {
546               FlowNode flowNode = (FlowNode) iterator3.next();
547               descTupleSetLowerThanPC.add(flowNode.getCurrentDescTuple());
548             }
549             mapHighestOverriddenMethodDescToSetLowerThanPCLoc.put(highestMethodDesc,
550                 descTupleSetLowerThanPC);
551
552             continue next;
553           }
554         }
555
556         // identify which method in the inheritance chain has the highest PCLOC
557         // basically, finds a method that has the highest count or TOP location
558         int highestCount = -1;
559         MethodDescriptor methodDescHighestCount = null;
560         for (Iterator iterator2 = methodDescSet.iterator(); iterator2.hasNext();) {
561           MethodDescriptor methodDesc = (MethodDescriptor) iterator2.next();
562           if (mapMethodDescToParamCount.containsKey(methodDesc)) {
563             int curCount = mapMethodDescToParamCount.get(methodDesc).intValue();
564             if (highestCount < curCount) {
565               highestCount = curCount;
566               methodDescHighestCount = methodDesc;
567             }
568           }
569         }
570
571         if (methodDescHighestCount != null) {
572           FlowGraph flowGraph = getFlowGraph(methodDescHighestCount);
573           CompositeLocation pcLOC = getMethodSummary(methodDescHighestCount).getPCLoc();
574           FlowNode pcFlowNode = flowGraph.getFlowNode(translateToDescTuple(pcLOC.getTuple()));
575           Set<FlowNode> reachableSet =
576               flowGraph.getReachableSetFrom(pcFlowNode.getCurrentDescTuple().subList(0, 1));
577
578           Set<FlowNode> reachableParamNodeSet = new HashSet<FlowNode>();
579           for (Iterator iterator3 = reachableSet.iterator(); iterator3.hasNext();) {
580             FlowNode flowNode = (FlowNode) iterator3.next();
581             if (flowGraph.isParameter(flowNode.getCurrentDescTuple())) {
582               reachableParamNodeSet.add(flowNode);
583             }
584
585           }
586
587           Set<NTuple<Descriptor>> descTupleSetLowerThanPC = new HashSet<NTuple<Descriptor>>();
588           for (Iterator iterator2 = reachableParamNodeSet.iterator(); iterator2.hasNext();) {
589             FlowNode flowNode = (FlowNode) iterator2.next();
590             descTupleSetLowerThanPC.add(flowNode.getCurrentDescTuple());
591           }
592
593           // mapHighestOverriddenMethodDescToPCLocTuple.remove(highestMethodDesc);
594           mapHighestOverriddenMethodDescToSetLowerThanPCLoc.put(highestMethodDesc,
595               descTupleSetLowerThanPC);
596         }
597
598       }
599
600       // System.out.println("####################################");
601       // System.out.println("  highest=" + highestMethodDesc + "  HIGHEST PCLOC="
602       // + mapHighestOverriddenMethodDescToPCLocTuple.get(highestMethodDesc));
603       // System.out.println("  setLowerThanPCLoc="
604       // + mapHighestOverriddenMethodDescToSetLowerThanPCLoc.get(highestMethodDesc));
605     }
606
607   }
608
609   private void calculateLowestReturnLocInheritance() {
610
611     Set<MethodDescriptor> keySet = mapHighestOverriddenMethodDescToMethodDescSet.keySet();
612
613     Map<MethodDescriptor, Integer> mapMethodDescToParamCount =
614         new HashMap<MethodDescriptor, Integer>();
615
616     next: for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
617       MethodDescriptor highestMethodDesc = (MethodDescriptor) iterator.next();
618
619       Set<MethodDescriptor> methodDescSet =
620           mapHighestOverriddenMethodDescToMethodDescSet.get(highestMethodDesc);
621
622       if (methodDescSet.size() > 1 && getMethodSummary(highestMethodDesc).getRETURNLoc() != null) {
623       } else {
624         continue next;
625       }
626
627       for (Iterator iterator2 = methodDescSet.iterator(); iterator2.hasNext();) {
628         MethodDescriptor md = (MethodDescriptor) iterator2.next();
629
630         FlowGraph flowGraph = getFlowGraph(md);
631         Set<FlowNode> paramNodeSet = flowGraph.getParamFlowNodeSet();
632
633         CompositeLocation returnLoc = getMethodSummary(md).getRETURNLoc();
634
635         FlowNode returnFlowNode = flowGraph.getFlowNode(translateToDescTuple(returnLoc.getTuple()));
636
637         int count = 0;
638         for (Iterator iterator3 = paramNodeSet.iterator(); iterator3.hasNext();) {
639           FlowNode paramNode = (FlowNode) iterator3.next();
640           if (flowGraph.getReachableSetFrom(paramNode.getCurrentDescTuple().subList(0, 1))
641               .contains(returnFlowNode)) {
642             count++;
643           }
644         }
645         mapMethodDescToParamCount.put(md, count);
646         // System.out.println("###returnLoc=" + returnLoc + "    count higher=" + count);
647       }
648
649       // identify which method in the inheritance chain has the highest PCLOC
650       // basically, finds a method that has the highest count or TOP location
651       int highestCount = -1;
652       MethodDescriptor methodDescHighestCount = null;
653       for (Iterator iterator2 = methodDescSet.iterator(); iterator2.hasNext();) {
654         MethodDescriptor methodDesc = (MethodDescriptor) iterator2.next();
655         int curCount = mapMethodDescToParamCount.get(methodDesc).intValue();
656         if (highestCount < curCount) {
657           highestCount = curCount;
658           methodDescHighestCount = methodDesc;
659         }
660       }
661
662       if (methodDescHighestCount != null) {
663         FlowGraph flowGraph = getFlowGraph(methodDescHighestCount);
664         CompositeLocation returnLOC = getMethodSummary(methodDescHighestCount).getRETURNLoc();
665         NTuple<Descriptor> returnLocTuple = translateToDescTuple(returnLOC.getTuple());
666         FlowNode returnFlowNode = flowGraph.getFlowNode(returnLocTuple);
667
668         Set<FlowNode> curMethodParamNodeSet = flowGraph.getParamFlowNodeSet();
669         Set<NTuple<Descriptor>> descTupleSetHigherThanPC = new HashSet<NTuple<Descriptor>>();
670         for (Iterator iterator3 = curMethodParamNodeSet.iterator(); iterator3.hasNext();) {
671           FlowNode paramNode = (FlowNode) iterator3.next();
672           if (flowGraph.getReachableSetFrom(paramNode.getCurrentDescTuple().subList(0, 1))
673               .contains(returnFlowNode)) {
674             descTupleSetHigherThanPC.add(paramNode.getCurrentDescTuple());
675           }
676         }
677
678         mapHighestOverriddenMethodDescToReturnLocTuple.put(highestMethodDesc, returnLocTuple);
679         mapHighestOverriddenMethodDescToSetHigherThanRETURNLoc.put(highestMethodDesc,
680             descTupleSetHigherThanPC);
681
682       }
683
684       // System.out.println("####################################");
685       // System.out.println("  highest=" + highestMethodDesc + "  LOWEST RETURNLOC="
686       // + mapHighestOverriddenMethodDescToReturnLocTuple.get(highestMethodDesc));
687       // System.out.println("  setHigherThanReturnLoc="
688       // + mapHighestOverriddenMethodDescToSetHigherThanRETURNLoc.get(highestMethodDesc));
689
690     }
691
692   }
693
694   private void addMapHighestMethodDescToMethodDesc(MethodDescriptor highest, MethodDescriptor md) {
695     if (!mapHighestOverriddenMethodDescToMethodDescSet.containsKey(highest)) {
696       mapHighestOverriddenMethodDescToMethodDescSet.put(highest, new HashSet<MethodDescriptor>());
697     }
698     mapHighestOverriddenMethodDescToMethodDescSet.get(highest).add(md);
699   }
700
701   private void DFSInheritanceTreeCalculatingHighestOverriddenMethod(ClassDescriptor cd) {
702
703     // ClassDescriptor cd = node.getData();
704
705     for (Iterator iterator = cd.getMethods(); iterator.hasNext();) {
706       MethodDescriptor md = (MethodDescriptor) iterator.next();
707       MethodDescriptor highestMethodDesc = getHighestOverriddenMethod(md.getClassDesc(), md);
708       mapMethodDescToHighestOverriddenMethodDesc.put(md, highestMethodDesc);
709       addMapHighestMethodDescToMethodDesc(highestMethodDesc, md);
710
711     }
712
713     // traverse children
714     Set<ClassDescriptor> children = getDirectSubClasses(cd);
715     for (Iterator iterator = children.iterator(); iterator.hasNext();) {
716       ClassDescriptor child = (ClassDescriptor) iterator.next();
717       DFSInheritanceTreeCalculatingHighestOverriddenMethod(child);
718     }
719
720   }
721
722   private MethodDescriptor getHighestOverriddenMethod(ClassDescriptor curClassDesc,
723       MethodDescriptor curMethodDesc) {
724
725     // Node<ClassDescriptor> curNode = inheritanceTree.getTreeNode(curClassDesc);
726     // Node<ClassDescriptor> parentNode = curNode.getParent();
727     ClassDescriptor parentClassDesc = curClassDesc.getSuperDesc();
728
729     if (parentClassDesc != null) {
730       if (parentClassDesc.getMethodTable().contains(curMethodDesc.getSymbol())) {
731         Set<MethodDescriptor> methodDescSet =
732             parentClassDesc.getMethodTable().getSet(curMethodDesc.getSymbol());
733         for (Iterator iterator = methodDescSet.iterator(); iterator.hasNext();) {
734           MethodDescriptor md = (MethodDescriptor) iterator.next();
735           if (md.matches(curMethodDesc)) {
736             return getHighestOverriddenMethod(parentClassDesc, md);
737           }
738         }
739       }
740       // traverse to the parent!
741       return getHighestOverriddenMethod(parentClassDesc, curMethodDesc);
742     }
743     return curMethodDesc;
744   }
745
746   private void buildInheritanceTree() {
747
748     DFSInheritanceTreeCalculatingHighestOverriddenMethod(rootClassDescriptor);
749
750   }
751
752   private void addInheritanceConstraintsToHierarchyGraph() {
753
754     // DFS the inheritance tree and propagates nodes/edges of parent to child
755
756     // Node<ClassDescriptor> rootNode = inheritanceTree.getRootNode();
757     DFSInheritanceTree(rootClassDescriptor);
758
759   }
760
761   private void DFSInheritanceTree(ClassDescriptor parentClassDescriptor) {
762
763     // ClassDescriptor parentClassDescriptor = parentNode.getData();
764
765     Set<ClassDescriptor> children = getDirectSubClasses(parentClassDescriptor);
766     for (Iterator iterator = children.iterator(); iterator.hasNext();) {
767       ClassDescriptor childClassDescriptor = (ClassDescriptor) iterator.next();
768
769       HierarchyGraph parentGraph = getHierarchyGraph(parentClassDescriptor);
770       HierarchyGraph childGraph = getHierarchyGraph(childClassDescriptor);
771
772       Set<HNode> parentNodeSet = parentGraph.getNodeSet();
773       for (Iterator iterator2 = parentNodeSet.iterator(); iterator2.hasNext();) {
774         HNode hNode = (HNode) iterator2.next();
775         childGraph.addNode(hNode);
776       }
777
778       // copies extra information from the parent hierarchy graph
779       Map<HNode, Set<HNode>> parentMergeNodeMap = parentGraph.getMapHNodetoMergeSet();
780       Map<HNode, Set<HNode>> childMergeNodeMap = childGraph.getMapHNodetoMergeSet();
781
782       Set<HNode> keySet = parentMergeNodeMap.keySet();
783       for (Iterator iterator2 = keySet.iterator(); iterator2.hasNext();) {
784         HNode parentKey = (HNode) iterator2.next();
785         if (!childMergeNodeMap.containsKey(parentKey)) {
786           childMergeNodeMap.put(parentKey, new HashSet<HNode>());
787         }
788         childMergeNodeMap.get(parentKey).addAll(parentMergeNodeMap.get(parentKey));
789       }
790
791       // copies nodes/edges from the parent class...
792       for (Iterator iterator2 = parentNodeSet.iterator(); iterator2.hasNext();) {
793         HNode parentHNode = (HNode) iterator2.next();
794
795         Set<HNode> parentIncomingHNode = parentGraph.getIncomingNodeSet(parentHNode);
796         Set<HNode> parentOutgoingHNode = parentGraph.getOutgoingNodeSet(parentHNode);
797
798         for (Iterator iterator3 = parentIncomingHNode.iterator(); iterator3.hasNext();) {
799           HNode inHNode = (HNode) iterator3.next();
800           childGraph.addEdge(inHNode.getDescriptor(), parentHNode.getDescriptor());
801         }
802
803         for (Iterator iterator3 = parentOutgoingHNode.iterator(); iterator3.hasNext();) {
804           HNode outHNode = (HNode) iterator3.next();
805           childGraph.addEdge(parentHNode.getDescriptor(), outHNode.getDescriptor());
806         }
807
808       }
809
810       // copies nodes/edges from parent methods to overridden methods
811
812       for (Iterator iterator3 = childClassDescriptor.getMethods(); iterator3.hasNext();) {
813         MethodDescriptor childMethodDescriptor = (MethodDescriptor) iterator3.next();
814
815         MethodDescriptor parentMethodDesc =
816             getParentMethodDesc(childMethodDescriptor.getClassDesc(), childMethodDescriptor);
817
818         if (parentMethodDesc != null) {
819
820           HierarchyGraph parentMethodGraph = getHierarchyGraph(parentMethodDesc);
821           HierarchyGraph childMethodGraph = getHierarchyGraph(childMethodDescriptor);
822
823           Set<HNode> parentMethodNodeSet = parentMethodGraph.getNodeSet();
824           for (Iterator iterator2 = parentMethodNodeSet.iterator(); iterator2.hasNext();) {
825             HNode hNode = (HNode) iterator2.next();
826             childMethodGraph.addNode(hNode);
827           }
828
829           // copies extra information from the parent hierarchy graph
830           Map<HNode, Set<HNode>> parentMethodMergeNodeMap =
831               parentMethodGraph.getMapHNodetoMergeSet();
832           Map<HNode, Set<HNode>> childMethodMergeNodeMap = childMethodGraph.getMapHNodetoMergeSet();
833
834           Set<HNode> methodKeySet = parentMethodMergeNodeMap.keySet();
835           for (Iterator iterator2 = methodKeySet.iterator(); iterator2.hasNext();) {
836             HNode parentKey = (HNode) iterator2.next();
837             if (!childMethodMergeNodeMap.containsKey(parentKey)) {
838               childMethodMergeNodeMap.put(parentKey, new HashSet<HNode>());
839             }
840             childMethodMergeNodeMap.get(parentKey).addAll(parentMethodMergeNodeMap.get(parentKey));
841           }
842
843           // copies nodes/edges from the parent method...
844           for (Iterator iterator2 = parentMethodGraph.getNodeSet().iterator(); iterator2.hasNext();) {
845             HNode parentHNode = (HNode) iterator2.next();
846
847             Set<HNode> parentIncomingHNode = parentMethodGraph.getIncomingNodeSet(parentHNode);
848             Set<HNode> parentOutgoingHNode = parentMethodGraph.getOutgoingNodeSet(parentHNode);
849
850             for (Iterator iterator4 = parentIncomingHNode.iterator(); iterator4.hasNext();) {
851               HNode inHNode = (HNode) iterator4.next();
852               childMethodGraph.addEdge(inHNode, parentHNode);
853             }
854
855             for (Iterator iterator4 = parentOutgoingHNode.iterator(); iterator4.hasNext();) {
856               HNode outHNode = (HNode) iterator4.next();
857               childMethodGraph.addEdge(parentHNode, outHNode);
858             }
859
860           }
861
862         }
863
864       }
865
866       DFSInheritanceTree(childClassDescriptor);
867     }
868
869   }
870
871   public MethodDescriptor getParentMethodDesc(ClassDescriptor classDesc, MethodDescriptor methodDesc) {
872
873     // Node<ClassDescriptor> childNode = inheritanceTree.getTreeNode(classDesc);
874     ClassDescriptor parentClassDesc = classDesc.getSuperDesc();
875     // Node<ClassDescriptor> parentNode = childNode.getParent();
876
877     if (parentClassDesc != null) {
878       // ClassDescriptor parentClassDesc = parentNode.getData();
879       if (parentClassDesc.getMethodTable().contains(methodDesc.getSymbol())) {
880         Set<MethodDescriptor> methodDescSet =
881             parentClassDesc.getMethodTable().getSet(methodDesc.getSymbol());
882         for (Iterator iterator = methodDescSet.iterator(); iterator.hasNext();) {
883           MethodDescriptor md = (MethodDescriptor) iterator.next();
884           if (md.matches(methodDesc)) {
885             return md;
886           }
887         }
888       }
889
890       // traverse to the parent!
891       getParentMethodDesc(parentClassDesc, methodDesc);
892
893     }
894
895     return null;
896   }
897
898   private void checkReturnNodes() {
899     LinkedList<MethodDescriptor> methodDescList =
900         (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
901
902     while (!methodDescList.isEmpty()) {
903       MethodDescriptor md = methodDescList.removeLast();
904
905       if (md.getReturnType() != null && !md.getReturnType().isVoid()) {
906         checkFlowNodeReturnThisField(md);
907       }
908       // // in this case, this method will return the composite location that starts with 'this'
909       // FlowGraph flowGraph = getFlowGraph(md);
910       // Set<FlowNode> returnNodeSet = flowGraph.getReturnNodeSet();
911       // }
912
913     }
914
915   }
916
917   private void addSuperClasses(ClassDescriptor cd) {
918     ClassDescriptor parentClassDesc = cd.getSuperDesc();
919     if (parentClassDesc != null) {
920       toanalyze_classDescSet.add(parentClassDesc);
921       addSuperClasses(parentClassDesc);
922     }
923   }
924
925   private void updateFlowGraph() {
926
927     LinkedList<MethodDescriptor> methodDescList =
928         (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
929
930     while (!methodDescList.isEmpty()) {
931       MethodDescriptor md = methodDescList.removeLast();
932       if (state.SSJAVADEBUG) {
933         System.out.println();
934         System.out.println("SSJAVA: Updating a flow graph: " + md);
935         propagateFlowsFromCalleesWithNoCompositeLocation(md);
936       }
937
938       Set<FlowNode> nodeSet = getFlowGraph(md).getNodeSet();
939       for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
940         FlowNode flowNode = (FlowNode) iterator.next();
941         NTuple<Descriptor> descTuple = flowNode.getCurrentDescTuple();
942         NTuple<Location> locTuple = translateToLocTuple(md, descTuple);
943         for (int i = 0; i < locTuple.size(); i++) {
944           Location loc = locTuple.get(i);
945           if (loc.getDescriptor() instanceof ClassDescriptor) {
946             ClassDescriptor classDesc = (ClassDescriptor) loc.getDescriptor();
947             toanalyze_classDescSet.add(classDesc);
948             addSuperClasses(classDesc);
949           } else if (loc.getDescriptor() instanceof MethodDescriptor) {
950             toanalyze_classDescSet.add(((MethodDescriptor) loc.getDescriptor()).getClassDesc());
951           }
952         }
953
954       }
955
956     }
957   }
958
959   public Map<NTuple<Descriptor>, NTuple<Descriptor>> getMapCallerArgToCalleeParam(
960       MethodInvokeNode min) {
961
962     if (!mapMethodInvokeNodeToMapCallerArgToCalleeArg.containsKey(min)) {
963       mapMethodInvokeNodeToMapCallerArgToCalleeArg.put(min,
964           new HashMap<NTuple<Descriptor>, NTuple<Descriptor>>());
965     }
966
967     return mapMethodInvokeNodeToMapCallerArgToCalleeArg.get(min);
968   }
969
970   public void addMapCallerArgToCalleeParam(MethodInvokeNode min, NTuple<Descriptor> callerArg,
971       NTuple<Descriptor> calleeParam) {
972     getMapCallerArgToCalleeParam(min).put(callerArg, calleeParam);
973   }
974
975   private void assignCompositeLocation() {
976     calculateGlobalValueFlowCompositeLocation();
977     translateCompositeLocationAssignmentToFlowGraph();
978   }
979
980   private void translateCompositeLocationAssignmentToFlowGraph() {
981     System.out.println("\nSSJAVA: Translate composite location assignments to flow graphs:");
982     MethodDescriptor methodEventLoopDesc = ssjava.getMethodContainingSSJavaLoop();
983     translateCompositeLocationAssignmentToFlowGraph(methodEventLoopDesc);
984   }
985
986   private void translateCompositeLocationAssignmentToFlowGraph2() {
987     System.out.println("\nSSJAVA: Translate composite location assignments to flow graphs:");
988     MethodDescriptor methodEventLoopDesc = ssjava.getMethodContainingSSJavaLoop();
989     translateCompositeLocationAssignmentToFlowGraph(methodEventLoopDesc);
990   }
991
992   private void addAdditionalOrderingConstraints() {
993     System.out.println("\nSSJAVA: Add addtional ordering constriants:");
994     MethodDescriptor methodEventLoopDesc = ssjava.getMethodContainingSSJavaLoop();
995     addAddtionalOrderingConstraints(methodEventLoopDesc);
996     // calculateReturnHolderLocation();
997   }
998
999   private void calculateReturnHolderLocation() {
1000     LinkedList<MethodDescriptor> methodDescList =
1001         (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
1002
1003     while (!methodDescList.isEmpty()) {
1004       MethodDescriptor md = methodDescList.removeLast();
1005
1006       FlowGraph fg = getFlowGraph(md);
1007       Set<FlowNode> nodeSet = fg.getNodeSet();
1008       for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
1009         FlowNode flowNode = (FlowNode) iterator.next();
1010         if (flowNode.isFromHolder()) {
1011           calculateCompositeLocationFromFlowGraph(md, flowNode);
1012         }
1013       }
1014
1015     }
1016   }
1017
1018   private void updateCompositeLocationAssignments() {
1019
1020     LinkedList<MethodDescriptor> methodDescList =
1021         (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
1022
1023     while (!methodDescList.isEmpty()) {
1024       MethodDescriptor md = methodDescList.removeLast();
1025
1026       // System.out.println("\n#updateCompositeLocationAssignments=" + md);
1027
1028       FlowGraph flowGraph = getFlowGraph(md);
1029
1030       MethodSummary methodSummary = getMethodSummary(md);
1031
1032       Set<FlowNode> nodeSet = flowGraph.getNodeSet();
1033       for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
1034         FlowNode node = (FlowNode) iterator.next();
1035         // System.out.println("-node=" + node + "   node.getDescTuple=" + node.getDescTuple());
1036         if (node.getCompositeLocation() != null) {
1037           CompositeLocation compLoc = node.getCompositeLocation();
1038           CompositeLocation updatedCompLoc = updateCompositeLocation(compLoc);
1039           node.setCompositeLocation(updatedCompLoc);
1040           // System.out.println("---updatedCompLoc1=" + updatedCompLoc);
1041         } else {
1042           NTuple<Descriptor> descTuple = node.getDescTuple();
1043           // System.out.println("update desc=" + descTuple);
1044           CompositeLocation compLoc = convertToCompositeLocation(md, descTuple);
1045           compLoc = updateCompositeLocation(compLoc);
1046           node.setCompositeLocation(compLoc);
1047           // System.out.println("---updatedCompLoc2=" + compLoc);
1048         }
1049
1050         if (node.isDeclaratonNode()) {
1051           Descriptor localVarDesc = node.getDescTuple().get(0);
1052           CompositeLocation compLoc = updateCompositeLocation(node.getCompositeLocation());
1053           methodSummary.addMapVarNameToInferCompLoc(localVarDesc, compLoc);
1054         }
1055       }
1056
1057       // update PCLOC and RETURNLOC if they have a composite location assignment
1058       if (methodSummary.getRETURNLoc() != null) {
1059         methodSummary.setRETURNLoc(updateCompositeLocation(methodSummary.getRETURNLoc()));
1060       }
1061       if (methodSummary.getPCLoc() != null) {
1062         methodSummary.setPCLoc(updateCompositeLocation(methodSummary.getPCLoc()));
1063       }
1064
1065     }
1066
1067   }
1068
1069   private CompositeLocation updateCompositeLocation(CompositeLocation compLoc) {
1070     CompositeLocation updatedCompLoc = new CompositeLocation();
1071     for (int i = 0; i < compLoc.getSize(); i++) {
1072       Location loc = compLoc.get(i);
1073       String nodeIdentifier = loc.getLocIdentifier();
1074       Descriptor enclosingDesc = loc.getDescriptor();
1075       String locName;
1076       if (!enclosingDesc.equals(GLOBALDESC)) {
1077         LocationSummary locSummary = getLocationSummary(enclosingDesc);
1078         // HierarchyGraph scGraph = getSkeletonCombinationHierarchyGraph(enclosingDesc);
1079         HierarchyGraph scGraph = getSimpleHierarchyGraph(enclosingDesc);
1080         if (scGraph != null) {
1081           HNode curNode = scGraph.getCurrentHNode(nodeIdentifier);
1082           // System.out.println("nodeID=" + nodeIdentifier + " curNode=" + curNode
1083           // + "  enclosingDesc=" + enclosingDesc);
1084           if (curNode != null) {
1085             nodeIdentifier = curNode.getName();
1086           }
1087         }
1088         locName = locSummary.getLocationName(nodeIdentifier);
1089       } else {
1090         locName = nodeIdentifier;
1091       }
1092       Location updatedLoc = new Location(enclosingDesc, locName);
1093       updatedCompLoc.addLocation(updatedLoc);
1094     }
1095
1096     return updatedCompLoc;
1097   }
1098
1099   private void translateCompositeLocationAssignmentToFlowGraph(MethodDescriptor mdCaller) {
1100
1101     // System.out.println("\n\n###translateCompositeLocationAssignmentToFlowGraph mdCaller="
1102     // + mdCaller);
1103
1104     // First, assign a composite location to a node in the flow graph
1105     GlobalFlowGraph callerGlobalFlowGraph = getSubGlobalFlowGraph(mdCaller);
1106
1107     FlowGraph callerFlowGraph = getFlowGraph(mdCaller);
1108     Map<Location, CompositeLocation> callerMapLocToCompLoc =
1109         callerGlobalFlowGraph.getMapLocationToInferCompositeLocation();
1110
1111     Set<Location> methodLocSet = callerMapLocToCompLoc.keySet();
1112     for (Iterator iterator = methodLocSet.iterator(); iterator.hasNext();) {
1113       Location methodLoc = (Location) iterator.next();
1114       if (methodLoc.getDescriptor().equals(mdCaller)) {
1115         CompositeLocation inferCompLoc = callerMapLocToCompLoc.get(methodLoc);
1116         assignCompositeLocationToFlowGraph(callerFlowGraph, methodLoc, inferCompLoc);
1117       }
1118     }
1119
1120     Set<MethodInvokeNode> minSet = mapMethodDescriptorToMethodInvokeNodeSet.get(mdCaller);
1121
1122     Set<MethodDescriptor> calleeSet = new HashSet<MethodDescriptor>();
1123     for (Iterator iterator = minSet.iterator(); iterator.hasNext();) {
1124       MethodInvokeNode min = (MethodInvokeNode) iterator.next();
1125       // need to translate a composite location that is started with the base
1126       // tuple of 'min'.
1127       translateMapLocationToInferCompositeLocationToCalleeGraph(callerGlobalFlowGraph, min);
1128       MethodDescriptor mdCallee = min.getMethod();
1129       calleeSet.add(mdCallee);
1130
1131     }
1132
1133     for (Iterator iterator = calleeSet.iterator(); iterator.hasNext();) {
1134       MethodDescriptor callee = (MethodDescriptor) iterator.next();
1135       translateCompositeLocationAssignmentToFlowGraph(callee);
1136     }
1137
1138   }
1139
1140   private void addAddtionalOrderingConstraints(MethodDescriptor mdCaller) {
1141
1142     // First, assign a composite location to a node in the flow graph
1143     GlobalFlowGraph callerGlobalFlowGraph = getSubGlobalFlowGraph(mdCaller);
1144
1145     FlowGraph callerFlowGraph = getFlowGraph(mdCaller);
1146     Map<Location, CompositeLocation> callerMapLocToCompLoc =
1147         callerGlobalFlowGraph.getMapLocationToInferCompositeLocation();
1148     Set<Location> methodLocSet = callerMapLocToCompLoc.keySet();
1149
1150     Set<MethodInvokeNode> minSet = mapMethodDescriptorToMethodInvokeNodeSet.get(mdCaller);
1151
1152     Set<MethodDescriptor> calleeSet = new HashSet<MethodDescriptor>();
1153     for (Iterator iterator = minSet.iterator(); iterator.hasNext();) {
1154       MethodInvokeNode min = (MethodInvokeNode) iterator.next();
1155       MethodDescriptor mdCallee = min.getMethod();
1156       calleeSet.add(mdCallee);
1157
1158       //
1159       // add an additional ordering constraint
1160       // if the first element of a parameter composite location matches 'this' reference,
1161       // the corresponding argument in the caller is required to be higher than the translated
1162       // parameter location in the caller lattice
1163       // TODO
1164       // addOrderingConstraintFromCompLocParamToArg(mdCaller, min);
1165
1166       //
1167       // update return flow nodes in the caller
1168       CompositeLocation returnLoc = getMethodSummary(mdCallee).getRETURNLoc();
1169       // System.out.println("### min=" + min.printNode(0) + "  returnLoc=" + returnLoc);
1170       if (returnLoc != null && returnLoc.get(0).getLocDescriptor().equals(mdCallee.getThis())
1171           && returnLoc.getSize() > 1) {
1172         // System.out.println("###RETURN COMP LOC=" + returnLoc);
1173         NTuple<Location> returnLocTuple = returnLoc.getTuple();
1174         NTuple<Descriptor> baseTuple = mapMethodInvokeNodeToBaseTuple.get(min);
1175         // System.out.println("###basetuple=" + baseTuple);
1176         NTuple<Descriptor> newReturnTuple = baseTuple.clone();
1177         for (int i = 1; i < returnLocTuple.size(); i++) {
1178           newReturnTuple.add(returnLocTuple.get(i).getLocDescriptor());
1179         }
1180         // System.out.println("###NEW RETURN TUPLE FOR CALLER=" + newReturnTuple);
1181
1182         FlowReturnNode holderNode = callerFlowGraph.getFlowReturnNode(min);
1183         NodeTupleSet holderTupleSet =
1184             getNodeTupleSetFromReturnNode(getFlowGraph(mdCaller), holderNode);
1185
1186         callerFlowGraph.getFlowReturnNode(min).setNewTuple(newReturnTuple);
1187
1188         // then need to remove old constraints
1189         // TODO SAT
1190         // System.out.println("###REMOVE OLD CONSTRAINTS=" + holderNode);
1191         for (Iterator<NTuple<Descriptor>> iter = holderTupleSet.iterator(); iter.hasNext();) {
1192           NTuple<Descriptor> tupleFromHolder = iter.next();
1193           Set<FlowEdge> holderOutEdge = callerFlowGraph.getOutEdgeSet(holderNode);
1194           for (Iterator iterator2 = holderOutEdge.iterator(); iterator2.hasNext();) {
1195             FlowEdge outEdge = (FlowEdge) iterator2.next();
1196             NTuple<Descriptor> toberemovedTuple = outEdge.getEndTuple();
1197             // System.out.println("---remove " + tupleFromHolder + " -> " + toberemovedTuple);
1198             callerFlowGraph.removeEdge(tupleFromHolder, toberemovedTuple);
1199           }
1200         }
1201
1202       } else {
1203         // if the return loc set was empty and later pcloc was connected to the return loc
1204         // need to make sure that return loc reflects to this changes.
1205         FlowReturnNode flowReturnNode = callerFlowGraph.getFlowReturnNode(min);
1206         if (flowReturnNode != null && flowReturnNode.getReturnTupleSet().isEmpty()) {
1207
1208           if (needToUpdateReturnLocHolder(min.getMethod(), flowReturnNode)) {
1209             NTuple<Descriptor> baseTuple = mapMethodInvokeNodeToBaseTuple.get(min);
1210             NTuple<Descriptor> newReturnTuple = baseTuple.clone();
1211             flowReturnNode.addTuple(newReturnTuple);
1212           }
1213
1214         }
1215
1216       }
1217
1218     }
1219
1220     for (Iterator iterator = calleeSet.iterator(); iterator.hasNext();) {
1221       MethodDescriptor callee = (MethodDescriptor) iterator.next();
1222       addAddtionalOrderingConstraints(callee);
1223     }
1224
1225   }
1226
1227   private boolean needToUpdateReturnLocHolder(MethodDescriptor mdCallee,
1228       FlowReturnNode flowReturnNode) {
1229     FlowGraph fg = getFlowGraph(mdCallee);
1230     MethodSummary summary = getMethodSummary(mdCallee);
1231     CompositeLocation returnCompLoc = summary.getRETURNLoc();
1232     NTuple<Descriptor> returnDescTuple = translateToDescTuple(returnCompLoc.getTuple());
1233     Set<FlowNode> incomingNodeToReturnNode =
1234         fg.getIncomingFlowNodeSet(fg.getFlowNode(returnDescTuple));
1235     for (Iterator iterator = incomingNodeToReturnNode.iterator(); iterator.hasNext();) {
1236       FlowNode inNode = (FlowNode) iterator.next();
1237       if (inNode.getDescTuple().get(0).equals(mdCallee.getThis())) {
1238         return true;
1239       }
1240     }
1241     return false;
1242   }
1243
1244   private void addMapMethodDescToMethodInvokeNodeSet(MethodInvokeNode min) {
1245     MethodDescriptor md = min.getMethod();
1246     if (!mapMethodDescToMethodInvokeNodeSet.containsKey(md)) {
1247       mapMethodDescToMethodInvokeNodeSet.put(md, new HashSet<MethodInvokeNode>());
1248     }
1249     mapMethodDescToMethodInvokeNodeSet.get(md).add(min);
1250   }
1251
1252   private Set<MethodInvokeNode> getMethodInvokeNodeSetByMethodDesc(MethodDescriptor md) {
1253     if (!mapMethodDescToMethodInvokeNodeSet.containsKey(md)) {
1254       mapMethodDescToMethodInvokeNodeSet.put(md, new HashSet<MethodInvokeNode>());
1255     }
1256     return mapMethodDescToMethodInvokeNodeSet.get(md);
1257   }
1258
1259   public void assignCompositeLocationToFlowGraph(FlowGraph flowGraph, Location loc,
1260       CompositeLocation inferCompLoc) {
1261     Descriptor localDesc = loc.getLocDescriptor();
1262
1263     Set<FlowNode> nodeSet = flowGraph.getNodeSet();
1264     for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
1265       FlowNode node = (FlowNode) iterator.next();
1266       if (node.getDescTuple().startsWith(localDesc)
1267           && !node.getDescTuple().get(0).equals(LITERALDESC)) {
1268         // need to assign the inferred composite location to this node
1269         CompositeLocation newCompLoc = generateCompositeLocation(node.getDescTuple(), inferCompLoc);
1270         node.setCompositeLocation(newCompLoc);
1271         // System.out.println("SET Node=" + node + "  inferCompLoc=" + newCompLoc);
1272       }
1273     }
1274   }
1275
1276   private CompositeLocation generateCompositeLocation(NTuple<Descriptor> nodeDescTuple,
1277       CompositeLocation inferCompLoc) {
1278
1279     // System.out.println("generateCompositeLocation=" + nodeDescTuple + " with inferCompLoc="
1280     // + inferCompLoc);
1281
1282     MethodDescriptor md = (MethodDescriptor) inferCompLoc.get(0).getDescriptor();
1283
1284     CompositeLocation newCompLoc = new CompositeLocation();
1285     for (int i = 0; i < inferCompLoc.getSize(); i++) {
1286       newCompLoc.addLocation(inferCompLoc.get(i));
1287     }
1288
1289     Descriptor lastDescOfPrefix = nodeDescTuple.get(0);
1290     Descriptor enclosingDescriptor;
1291     if (lastDescOfPrefix instanceof InterDescriptor) {
1292       enclosingDescriptor = getFlowGraph(md).getEnclosingDescriptor(lastDescOfPrefix);
1293     } else {
1294       enclosingDescriptor = ((VarDescriptor) lastDescOfPrefix).getType().getClassDesc();
1295     }
1296
1297     for (int i = 1; i < nodeDescTuple.size(); i++) {
1298       Descriptor desc = nodeDescTuple.get(i);
1299       Location locElement = new Location(enclosingDescriptor, desc);
1300       newCompLoc.addLocation(locElement);
1301
1302       enclosingDescriptor = ((FieldDescriptor) desc).getClassDescriptor();
1303     }
1304
1305     return newCompLoc;
1306   }
1307
1308   private void translateMapLocationToInferCompositeLocationToCalleeGraph(
1309       GlobalFlowGraph callerGraph, MethodInvokeNode min) {
1310
1311     MethodDescriptor mdCallee = min.getMethod();
1312     MethodDescriptor mdCaller = callerGraph.getMethodDescriptor();
1313     Map<Location, CompositeLocation> callerMapLocToCompLoc =
1314         callerGraph.getMapLocationToInferCompositeLocation();
1315
1316     Map<Integer, NTuple<Descriptor>> mapIdxToArgTuple = mapMethodInvokeNodeToArgIdxMap.get(min);
1317
1318     FlowGraph calleeFlowGraph = getFlowGraph(mdCallee);
1319     GlobalFlowGraph calleeGlobalGraph = getSubGlobalFlowGraph(mdCallee);
1320
1321     NTuple<Location> baseLocTuple = null;
1322     if (mapMethodInvokeNodeToBaseTuple.containsKey(min)) {
1323       baseLocTuple = translateToLocTuple(mdCaller, mapMethodInvokeNodeToBaseTuple.get(min));
1324     }
1325
1326     // System.out.println("\n-#translate caller=" + mdCaller + " infer composite loc to callee="
1327     // + mdCallee + " baseLocTuple=" + baseLocTuple);
1328
1329     Set<Location> keySet = callerMapLocToCompLoc.keySet();
1330     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1331       Location key = (Location) iterator.next();
1332       CompositeLocation callerCompLoc = callerMapLocToCompLoc.get(key);
1333
1334       if (!key.getDescriptor().equals(mdCaller)) {
1335
1336         CompositeLocation newCalleeCompLoc;
1337         if (baseLocTuple != null && callerCompLoc.getTuple().startsWith(baseLocTuple)) {
1338           // System.out.println("-----need to translate callerCompLoc=" + callerCompLoc
1339           // + " with baseTuple=" + baseLocTuple);
1340           newCalleeCompLoc =
1341               translateCompositeLocationToCallee(callerCompLoc, baseLocTuple, mdCallee);
1342
1343           calleeGlobalGraph.addMapLocationToInferCompositeLocation(key, newCalleeCompLoc);
1344           // System.out.println("1---key=" + key + "  callerCompLoc=" + callerCompLoc
1345           // + "  newCalleeCompLoc=" + newCalleeCompLoc);
1346           // System.out.println("-----caller=" + mdCaller + "    callee=" + mdCallee);
1347           if (!newCalleeCompLoc.get(0).getDescriptor().equals(mdCallee)) {
1348             System.exit(0);
1349           }
1350
1351           // System.out.println("-----baseLoctuple=" + baseLocTuple);
1352         } else {
1353           // check if it is the global access
1354           Location compLocFirstElement = callerCompLoc.getTuple().get(0);
1355           if (compLocFirstElement.getDescriptor().equals(mdCallee)
1356               && compLocFirstElement.getLocDescriptor().equals(GLOBALDESC)) {
1357
1358             newCalleeCompLoc = new CompositeLocation();
1359             Location newMethodLoc = new Location(mdCallee, GLOBALDESC);
1360
1361             newCalleeCompLoc.addLocation(newMethodLoc);
1362             for (int i = 1; i < callerCompLoc.getSize(); i++) {
1363               newCalleeCompLoc.addLocation(callerCompLoc.get(i));
1364             }
1365             calleeGlobalGraph.addMapLocationToInferCompositeLocation(key, newCalleeCompLoc);
1366             // System.out.println("2---key=" + key + "  callerCompLoc=" + callerCompLoc
1367             // + "  newCalleeCompLoc=" + newCalleeCompLoc);
1368             // System.out.println("-----caller=" + mdCaller + "    callee=" + mdCallee);
1369
1370           } else {
1371             int paramIdx = getParamIdx(callerCompLoc, mapIdxToArgTuple);
1372             if (paramIdx == -1) {
1373               // here, the first element of the current composite location comes from the current
1374               // callee
1375               // so transfer the same composite location to the callee
1376               if (!calleeGlobalGraph.contrainsInferCompositeLocationMapKey(key)) {
1377                 if (callerCompLoc.get(0).getDescriptor().equals(mdCallee)) {
1378                   // System.out.println("3---key=" + key + "  callerCompLoc=" + callerCompLoc
1379                   // + "  newCalleeCompLoc=" + callerCompLoc);
1380                   // System.out.println("-----caller=" + mdCaller + "    callee=" + mdCallee);
1381                   calleeGlobalGraph.addMapLocationToInferCompositeLocation(key, callerCompLoc);
1382                 } else {
1383                   // System.out.println("3---SKIP key=" + key + " callerCompLoc=" + callerCompLoc);
1384                 }
1385               }
1386               continue;
1387             }
1388
1389             // It is the case where two parameters have relative orderings between them by having
1390             // composite locations
1391             // if we found the param idx, it means that the first part of the caller composite
1392             // location corresponds to the one of arguments.
1393             // for example, if the caller argument is <<caller.this>,<Decoder.br>>
1394             // and the current caller composite location mapping
1395             // <<caller.this>,<Decoder.br>,<Br.value>>
1396             // and the parameter which matches with the caller argument is 'Br brParam'
1397             // then, the translated callee composite location will be <<callee.brParam>,<Br.value>>
1398             NTuple<Descriptor> argTuple = mapIdxToArgTuple.get(paramIdx);
1399
1400             FlowNode paramFlowNode = calleeFlowGraph.getParamFlowNode(paramIdx);
1401             NTuple<Location> paramLocTuple =
1402                 translateToLocTuple(mdCallee, paramFlowNode.getDescTuple());
1403             newCalleeCompLoc = new CompositeLocation();
1404             for (int i = 0; i < paramLocTuple.size(); i++) {
1405               newCalleeCompLoc.addLocation(paramLocTuple.get(i));
1406             }
1407             for (int i = argTuple.size(); i < callerCompLoc.getSize(); i++) {
1408               newCalleeCompLoc.addLocation(callerCompLoc.get(i));
1409             }
1410             calleeGlobalGraph.addMapLocationToInferCompositeLocation(key, newCalleeCompLoc);
1411             // System.out.println("4---key=" + key + "  callerCompLoc=" + callerCompLoc
1412             // + "  newCalleeCompLoc=" + newCalleeCompLoc);
1413             // System.out.println("-----caller=" + mdCaller + "    callee=" + mdCallee);
1414
1415           }
1416
1417         }
1418
1419       }
1420     }
1421
1422     // System.out.println("#ASSIGN COMP LOC TO CALLEE PARAMS: callee=" + mdCallee + "  caller="
1423     // + mdCaller);
1424     // If the location of an argument has a composite location
1425     // need to assign a proper composite location to the corresponding callee parameter
1426     Set<Integer> idxSet = mapIdxToArgTuple.keySet();
1427     for (Iterator iterator = idxSet.iterator(); iterator.hasNext();) {
1428       Integer idx = (Integer) iterator.next();
1429
1430       if (idx == 0 && !min.getMethod().isStatic()) {
1431         continue;
1432       }
1433
1434       NTuple<Descriptor> argTuple = mapIdxToArgTuple.get(idx);
1435       // System.out.println("-argTuple=" + argTuple + "   idx=" + idx);
1436       if (argTuple.size() > 0) {
1437         // check if an arg tuple has been already assigned to a composite location
1438         NTuple<Location> argLocTuple = translateToLocTuple(mdCaller, argTuple);
1439         Location argLocalLoc = argLocTuple.get(0);
1440
1441         // if (!isPrimitiveType(argTuple)) {
1442         if (callerMapLocToCompLoc.containsKey(argLocalLoc)) {
1443
1444           CompositeLocation callerCompLoc = callerMapLocToCompLoc.get(argLocalLoc);
1445           for (int i = 1; i < argLocTuple.size(); i++) {
1446             callerCompLoc.addLocation(argLocTuple.get(i));
1447           }
1448
1449           // System.out.println("---callerCompLoc=" + callerCompLoc);
1450
1451           // if (baseLocTuple != null && callerCompLoc.getTuple().startsWith(baseLocTuple)) {
1452
1453           FlowNode calleeParamFlowNode = calleeFlowGraph.getParamFlowNode(idx);
1454
1455           NTuple<Descriptor> calleeParamDescTuple = calleeParamFlowNode.getDescTuple();
1456           NTuple<Location> calleeParamLocTuple =
1457               translateToLocTuple(mdCallee, calleeParamDescTuple);
1458
1459           int refParamIdx = getParamIdx(callerCompLoc, mapIdxToArgTuple);
1460           // System.out.println("-----paramIdx=" + refParamIdx);
1461           if (refParamIdx == 0 && !mdCallee.isStatic()) {
1462
1463             // System.out.println("-------need to translate callerCompLoc=" + callerCompLoc
1464             // + " with baseTuple=" + baseLocTuple + "   calleeParamLocTuple="
1465             // + calleeParamLocTuple);
1466
1467             CompositeLocation newCalleeCompLoc =
1468                 translateCompositeLocationToCallee(callerCompLoc, baseLocTuple, mdCallee);
1469
1470             calleeGlobalGraph.addMapLocationToInferCompositeLocation(calleeParamLocTuple.get(0),
1471                 newCalleeCompLoc);
1472
1473             // System.out.println("---------key=" + calleeParamLocTuple.get(0) + "  callerCompLoc="
1474             // + callerCompLoc + "  newCalleeCompLoc=" + newCalleeCompLoc);
1475
1476           } else if (refParamIdx != -1) {
1477             // the first element of an argument composite location matches with one of paramtere
1478             // composite locations
1479
1480             // System.out.println("-------param match case=");
1481
1482             NTuple<Descriptor> argTupleRef = mapIdxToArgTuple.get(refParamIdx);
1483             FlowNode refParamFlowNode = calleeFlowGraph.getParamFlowNode(refParamIdx);
1484             NTuple<Location> refParamLocTuple =
1485                 translateToLocTuple(mdCallee, refParamFlowNode.getDescTuple());
1486
1487             // System.out.println("---------refParamLocTuple=" + refParamLocTuple
1488             // + "  from argTupleRef=" + argTupleRef);
1489
1490             CompositeLocation newCalleeCompLoc = new CompositeLocation();
1491             for (int i = 0; i < refParamLocTuple.size(); i++) {
1492               newCalleeCompLoc.addLocation(refParamLocTuple.get(i));
1493             }
1494             for (int i = argTupleRef.size(); i < callerCompLoc.getSize(); i++) {
1495               newCalleeCompLoc.addLocation(callerCompLoc.get(i));
1496             }
1497
1498             calleeGlobalGraph.addMapLocationToInferCompositeLocation(calleeParamLocTuple.get(0),
1499                 newCalleeCompLoc);
1500
1501             calleeParamFlowNode.setCompositeLocation(newCalleeCompLoc);
1502             // System.out.println("-----------key=" + calleeParamLocTuple.get(0) +
1503             // "  callerCompLoc="
1504             // + callerCompLoc + "  newCalleeCompLoc=" + newCalleeCompLoc);
1505
1506           } else {
1507             CompositeLocation newCalleeCompLoc =
1508                 calculateCompositeLocationFromSubGlobalGraph(mdCallee, calleeParamFlowNode);
1509             if (newCalleeCompLoc != null) {
1510               calleeGlobalGraph.addMapLocationToInferCompositeLocation(calleeParamLocTuple.get(0),
1511                   newCalleeCompLoc);
1512               calleeParamFlowNode.setCompositeLocation(newCalleeCompLoc);
1513             }
1514           }
1515
1516           // System.out.println("-----------------calleeParamFlowNode="
1517           // + calleeParamFlowNode.getCompositeLocation());
1518
1519           // }
1520
1521         }
1522       }
1523
1524     }
1525
1526   }
1527
1528   private CompositeLocation calculateCompositeLocationFromSubGlobalGraph(MethodDescriptor md,
1529       FlowNode paramNode) {
1530
1531     // System.out.println("#############################################################");
1532     // System.out.println("calculateCompositeLocationFromSubGlobalGraph=" + paramNode);
1533
1534     GlobalFlowGraph subGlobalFlowGraph = getSubGlobalFlowGraph(md);
1535     NTuple<Location> paramLocTuple = translateToLocTuple(md, paramNode.getDescTuple());
1536     GlobalFlowNode paramGlobalNode = subGlobalFlowGraph.getFlowNode(paramLocTuple);
1537
1538     List<NTuple<Location>> prefixList = calculatePrefixList(subGlobalFlowGraph, paramGlobalNode);
1539
1540     Location prefixLoc = paramLocTuple.get(0);
1541
1542     Set<GlobalFlowNode> reachableNodeSet =
1543         subGlobalFlowGraph.getReachableNodeSetByPrefix(paramGlobalNode.getLocTuple().get(0));
1544     // Set<GlobalFlowNode> reachNodeSet = globalFlowGraph.getReachableNodeSetFrom(node);
1545
1546     // System.out.println("node=" + node + "    prefixList=" + prefixList);
1547
1548     for (int i = 0; i < prefixList.size(); i++) {
1549       NTuple<Location> curPrefix = prefixList.get(i);
1550       Set<NTuple<Location>> reachableCommonPrefixSet = new HashSet<NTuple<Location>>();
1551
1552       for (Iterator iterator2 = reachableNodeSet.iterator(); iterator2.hasNext();) {
1553         GlobalFlowNode reachNode = (GlobalFlowNode) iterator2.next();
1554         if (reachNode.getLocTuple().startsWith(curPrefix)) {
1555           reachableCommonPrefixSet.add(reachNode.getLocTuple());
1556         }
1557       }
1558       // System.out.println("reachableCommonPrefixSet=" + reachableCommonPrefixSet);
1559
1560       if (!reachableCommonPrefixSet.isEmpty()) {
1561
1562         MethodDescriptor curPrefixFirstElementMethodDesc =
1563             (MethodDescriptor) curPrefix.get(0).getDescriptor();
1564
1565         MethodDescriptor nodePrefixLocFirstElementMethodDesc =
1566             (MethodDescriptor) prefixLoc.getDescriptor();
1567
1568         // System.out.println("curPrefixFirstElementMethodDesc=" +
1569         // curPrefixFirstElementMethodDesc);
1570         // System.out.println("nodePrefixLocFirstElementMethodDesc="
1571         // + nodePrefixLocFirstElementMethodDesc);
1572
1573         if (curPrefixFirstElementMethodDesc.equals(nodePrefixLocFirstElementMethodDesc)
1574             || isTransitivelyCalledFrom(nodePrefixLocFirstElementMethodDesc,
1575                 curPrefixFirstElementMethodDesc)) {
1576
1577           // TODO
1578           // if (!node.getLocTuple().startsWith(curPrefix.get(0))) {
1579
1580           Location curPrefixLocalLoc = curPrefix.get(0);
1581           if (subGlobalFlowGraph.mapLocationToInferCompositeLocation.containsKey(curPrefixLocalLoc)) {
1582             // in this case, the local variable of the current prefix has already got a composite
1583             // location
1584             // so we just ignore the current composite location.
1585
1586             // System.out.println("HERE WE DO NOT ASSIGN A COMPOSITE LOCATION TO =" + node
1587             // + " DUE TO " + curPrefix);
1588             return null;
1589           }
1590
1591           if (!needToGenerateCompositeLocation(paramGlobalNode, curPrefix)) {
1592             // System.out.println("NO NEED TO GENERATE COMP LOC to " + paramGlobalNode
1593             // + " with prefix=" + curPrefix);
1594             return null;
1595           }
1596
1597           Location targetLocalLoc = paramGlobalNode.getLocTuple().get(0);
1598           CompositeLocation newCompLoc = generateCompositeLocation(curPrefix);
1599           // System.out.println("NEED TO ASSIGN COMP LOC TO " + paramGlobalNode + " with prefix="
1600           // + curPrefix);
1601           // System.out.println("-targetLocalLoc=" + targetLocalLoc + "   - newCompLoc=" +
1602           // newCompLoc);
1603
1604           // makes sure that a newly generated location appears in the hierarchy graph
1605           for (int compIdx = 0; compIdx < newCompLoc.getSize(); compIdx++) {
1606             Location curLoc = newCompLoc.get(compIdx);
1607             getHierarchyGraph(curLoc.getDescriptor()).getHNode(curLoc.getLocDescriptor());
1608           }
1609
1610           subGlobalFlowGraph.addMapLocationToInferCompositeLocation(targetLocalLoc, newCompLoc);
1611
1612           return newCompLoc;
1613
1614         }
1615
1616       }
1617
1618     }
1619     return null;
1620   }
1621
1622   private int getParamIdx(CompositeLocation compLoc,
1623       Map<Integer, NTuple<Descriptor>> mapIdxToArgTuple) {
1624
1625     // if the composite location is started with the argument descriptor
1626     // return the argument's index. o.t. return -1
1627
1628     Set<Integer> keySet = mapIdxToArgTuple.keySet();
1629     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1630       Integer key = (Integer) iterator.next();
1631       NTuple<Descriptor> argTuple = mapIdxToArgTuple.get(key);
1632       if (argTuple.size() > 0 && translateToDescTuple(compLoc.getTuple()).startsWith(argTuple)) {
1633         // System.out.println("compLoc.getTuple=" + compLoc + " is started with " + argTuple);
1634         return key.intValue();
1635       }
1636     }
1637
1638     return -1;
1639   }
1640
1641   private boolean isPrimitiveType(NTuple<Descriptor> argTuple) {
1642
1643     Descriptor lastDesc = argTuple.get(argTuple.size() - 1);
1644
1645     if (lastDesc instanceof FieldDescriptor) {
1646       return ((FieldDescriptor) lastDesc).getType().isPrimitive();
1647     } else if (lastDesc instanceof VarDescriptor) {
1648       return ((VarDescriptor) lastDesc).getType().isPrimitive();
1649     } else if (lastDesc instanceof InterDescriptor) {
1650       return true;
1651     }
1652
1653     return false;
1654   }
1655
1656   private CompositeLocation translateCompositeLocationToCallee(CompositeLocation callerCompLoc,
1657       NTuple<Location> baseLocTuple, MethodDescriptor mdCallee) {
1658
1659     CompositeLocation newCalleeCompLoc = new CompositeLocation();
1660
1661     Location calleeThisLoc = new Location(mdCallee, mdCallee.getThis());
1662     newCalleeCompLoc.addLocation(calleeThisLoc);
1663
1664     // remove the base tuple from the caller
1665     // ex; In the method invoation foo.bar.methodA(), the callee will have the composite location
1666     // ,which is relative to the 'this' variable, <THIS,...>
1667     for (int i = baseLocTuple.size(); i < callerCompLoc.getSize(); i++) {
1668       newCalleeCompLoc.addLocation(callerCompLoc.get(i));
1669     }
1670
1671     return newCalleeCompLoc;
1672
1673   }
1674
1675   private void calculateGlobalValueFlowCompositeLocation() {
1676
1677     System.out.println("SSJAVA: Calculate composite locations in the global value flow graph");
1678     MethodDescriptor methodDescEventLoop = ssjava.getMethodContainingSSJavaLoop();
1679     GlobalFlowGraph globalFlowGraph = getSubGlobalFlowGraph(methodDescEventLoop);
1680
1681     Set<Location> calculatedPrefixSet = new HashSet<Location>();
1682
1683     Set<GlobalFlowNode> nodeSet = globalFlowGraph.getNodeSet();
1684
1685     next: for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
1686       GlobalFlowNode node = (GlobalFlowNode) iterator.next();
1687
1688       Location prefixLoc = node.getLocTuple().get(0);
1689
1690       if (calculatedPrefixSet.contains(prefixLoc)) {
1691         // the prefix loc has been already assigned to a composite location
1692         continue;
1693       }
1694
1695       calculatedPrefixSet.add(prefixLoc);
1696
1697       // Set<GlobalFlowNode> incomingNodeSet = globalFlowGraph.getIncomingNodeSet(node);
1698       List<NTuple<Location>> prefixList = calculatePrefixList(globalFlowGraph, node);
1699
1700       Set<GlobalFlowNode> reachableNodeSet =
1701           globalFlowGraph.getReachableNodeSetByPrefix(node.getLocTuple().get(0));
1702       // Set<GlobalFlowNode> reachNodeSet = globalFlowGraph.getReachableNodeSetFrom(node);
1703
1704       // System.out.println("node=" + node + "    prefixList=" + prefixList);
1705       // System.out.println("---prefixList=" + prefixList);
1706
1707       nextprefix: for (int i = 0; i < prefixList.size(); i++) {
1708         NTuple<Location> curPrefix = prefixList.get(i);
1709         // System.out.println("---curPrefix=" + curPrefix);
1710         Set<NTuple<Location>> reachableCommonPrefixSet = new HashSet<NTuple<Location>>();
1711
1712         for (Iterator iterator2 = reachableNodeSet.iterator(); iterator2.hasNext();) {
1713           GlobalFlowNode reachNode = (GlobalFlowNode) iterator2.next();
1714           if (reachNode.getLocTuple().startsWith(curPrefix)) {
1715             reachableCommonPrefixSet.add(reachNode.getLocTuple());
1716           }
1717         }
1718         // System.out.println("reachableCommonPrefixSet=" + reachableCommonPrefixSet);
1719
1720         if (!reachableCommonPrefixSet.isEmpty()) {
1721
1722           MethodDescriptor curPrefixFirstElementMethodDesc =
1723               (MethodDescriptor) curPrefix.get(0).getDescriptor();
1724
1725           MethodDescriptor nodePrefixLocFirstElementMethodDesc =
1726               (MethodDescriptor) prefixLoc.getDescriptor();
1727
1728           // System.out.println("curPrefixFirstElementMethodDesc=" +
1729           // curPrefixFirstElementMethodDesc);
1730           // System.out.println("nodePrefixLocFirstElementMethodDesc="
1731           // + nodePrefixLocFirstElementMethodDesc);
1732
1733           if (curPrefixFirstElementMethodDesc.equals(nodePrefixLocFirstElementMethodDesc)
1734               || isTransitivelyCalledFrom(nodePrefixLocFirstElementMethodDesc,
1735                   curPrefixFirstElementMethodDesc)) {
1736
1737             // TODO
1738             // if (!node.getLocTuple().startsWith(curPrefix.get(0))) {
1739
1740             Location curPrefixLocalLoc = curPrefix.get(0);
1741             if (globalFlowGraph.mapLocationToInferCompositeLocation.containsKey(curPrefixLocalLoc)) {
1742               // in this case, the local variable of the current prefix has already got a composite
1743               // location
1744               // so we just ignore the current composite location.
1745
1746               // System.out.println("HERE WE DO NOT ASSIGN A COMPOSITE LOCATION TO =" + node
1747               // + " DUE TO " + curPrefix);
1748
1749               continue next;
1750             }
1751
1752             if (!needToGenerateCompositeLocation(node, curPrefix)) {
1753               // System.out.println("NO NEED TO GENERATE COMP LOC to " + node + " with prefix="
1754               // + curPrefix);
1755               // System.out.println("prefixList=" + prefixList);
1756               // System.out.println("reachableNodeSet=" + reachableNodeSet);
1757               continue nextprefix;
1758             }
1759
1760             Location targetLocalLoc = node.getLocTuple().get(0);
1761             CompositeLocation newCompLoc = generateCompositeLocation(curPrefix);
1762             // System.out.println("NEED TO ASSIGN COMP LOC TO " + node + " with prefix=" +
1763             // curPrefix);
1764             // System.out.println("-targetLocalLoc=" + targetLocalLoc + "   - newCompLoc="
1765             // + newCompLoc);
1766             globalFlowGraph.addMapLocationToInferCompositeLocation(targetLocalLoc, newCompLoc);
1767             // }
1768
1769             continue next;
1770             // }
1771
1772           }
1773
1774         }
1775
1776       }
1777
1778     }
1779   }
1780
1781   private boolean checkFlowNodeReturnThisField(MethodDescriptor md) {
1782
1783     MethodDescriptor methodDescEventLoop = ssjava.getMethodContainingSSJavaLoop();
1784     GlobalFlowGraph globalFlowGraph = getSubGlobalFlowGraph(methodDescEventLoop);
1785
1786     FlowGraph flowGraph = getFlowGraph(md);
1787
1788     ClassDescriptor enclosingDesc = getClassTypeDescriptor(md.getThis());
1789     if (enclosingDesc == null) {
1790       return false;
1791     }
1792
1793     int count = 0;
1794     Set<FlowNode> returnNodeSet = flowGraph.getReturnNodeSet();
1795     Set<GlobalFlowNode> globalReturnNodeSet = new HashSet<GlobalFlowNode>();
1796     for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
1797       FlowNode flowNode = (FlowNode) iterator.next();
1798       NTuple<Location> locTuple = translateToLocTuple(md, flowNode.getDescTuple());
1799       GlobalFlowNode globalReturnNode = globalFlowGraph.getFlowNode(locTuple);
1800       globalReturnNodeSet.add(globalReturnNode);
1801
1802       List<NTuple<Location>> prefixList = calculatePrefixList(globalFlowGraph, globalReturnNode);
1803       for (int i = 0; i < prefixList.size(); i++) {
1804         NTuple<Location> curPrefix = prefixList.get(i);
1805         ClassDescriptor cd =
1806             getClassTypeDescriptor(curPrefix.get(curPrefix.size() - 1).getLocDescriptor());
1807         if (cd != null && cd.equals(enclosingDesc)) {
1808           count++;
1809           break;
1810         }
1811       }
1812
1813     }
1814
1815     if (count == returnNodeSet.size()) {
1816       // in this case, all return nodes in the method returns values coming from a location that
1817       // starts with "this"
1818
1819       // System.out.println("$$$SET RETURN LOC TRUE=" + md);
1820       mapMethodDescriptorToCompositeReturnCase.put(md, Boolean.TRUE);
1821
1822       // NameDescriptor returnLocDesc = new NameDescriptor("RLOC" + (locSeed++));
1823       // NTuple<Descriptor> rDescTuple = new NTuple<Descriptor>();
1824       // rDescTuple.add(md.getThis());
1825       // rDescTuple.add(returnLocDesc);
1826       //
1827       // for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
1828       // FlowNode rnode = (FlowNode) iterator.next();
1829       // flowGraph.addValueFlowEdge(rnode.getDescTuple(), rDescTuple);
1830       // }
1831       //
1832       // getMethodSummary(md).setRETURNLoc(new CompositeLocation(translateToLocTuple(md,
1833       // rDescTuple)));
1834
1835     } else {
1836       mapMethodDescriptorToCompositeReturnCase.put(md, Boolean.FALSE);
1837     }
1838
1839     return mapMethodDescriptorToCompositeReturnCase.get(md).booleanValue();
1840
1841   }
1842
1843   private boolean needToGenerateCompositeLocation(GlobalFlowNode node, NTuple<Location> curPrefix) {
1844     // return true if there is a path between a node to which we want to give a composite location
1845     // and nodes which start with curPrefix
1846
1847     // System.out.println("---needToGenerateCompositeLocation curPrefix=" + curPrefix);
1848
1849     Location targetLocalLoc = node.getLocTuple().get(0);
1850
1851     MethodDescriptor md = (MethodDescriptor) targetLocalLoc.getDescriptor();
1852     FlowGraph flowGraph = getFlowGraph(md);
1853
1854     FlowNode flowNode = flowGraph.getFlowNode(node.getDescTuple());
1855     Set<FlowNode> reachableSet = flowGraph.getReachFlowNodeSetFrom(flowNode);
1856
1857     Set<FlowNode> paramNodeSet = flowGraph.getParamFlowNodeSet();
1858     for (Iterator iterator = paramNodeSet.iterator(); iterator.hasNext();) {
1859       FlowNode paramFlowNode = (FlowNode) iterator.next();
1860       if (curPrefix.startsWith(translateToLocTuple(md, paramFlowNode.getDescTuple()))) {
1861         return true;
1862       }
1863     }
1864
1865     if (targetLocalLoc.getLocDescriptor() instanceof InterDescriptor) {
1866       Pair<MethodInvokeNode, Integer> pair =
1867           ((InterDescriptor) targetLocalLoc.getLocDescriptor()).getMethodArgIdxPair();
1868
1869       if (pair != null) {
1870         // System.out.println("$$$TARGETLOCALLOC HOLDER=" + targetLocalLoc);
1871
1872         MethodInvokeNode min = pair.getFirst();
1873         Integer paramIdx = pair.getSecond();
1874         MethodDescriptor mdCallee = min.getMethod();
1875
1876         FlowNode paramNode = getFlowGraph(mdCallee).getParamFlowNode(paramIdx);
1877         if (checkNodeReachToReturnNode(mdCallee, paramNode)) {
1878           return true;
1879         }
1880
1881       }
1882
1883     }
1884
1885     GlobalFlowGraph subGlobalFlowGraph = getSubGlobalFlowGraph(md);
1886     Set<GlobalFlowNode> subGlobalReachableSet = subGlobalFlowGraph.getReachableNodeSetFrom(node);
1887
1888     if (!md.isStatic()) {
1889       ClassDescriptor currentMethodThisType = getClassTypeDescriptor(md.getThis());
1890       for (int i = 0; i < curPrefix.size(); i++) {
1891         ClassDescriptor prefixType = getClassTypeDescriptor(curPrefix.get(i).getLocDescriptor());
1892         if (prefixType != null && prefixType.equals(currentMethodThisType)) {
1893           // System.out.println("PREFIX TYPE MATCHES WITH=" + currentMethodThisType);
1894
1895           if (mapMethodDescriptorToCompositeReturnCase.containsKey(md)) {
1896             boolean hasCompReturnLocWithThis =
1897                 mapMethodDescriptorToCompositeReturnCase.get(md).booleanValue();
1898             if (hasCompReturnLocWithThis) {
1899               if (checkNodeReachToReturnNode(md, flowNode)) {
1900                 return true;
1901               }
1902             }
1903           }
1904
1905           for (Iterator iterator3 = subGlobalReachableSet.iterator(); iterator3.hasNext();) {
1906             GlobalFlowNode subGlobalReachalbeNode = (GlobalFlowNode) iterator3.next();
1907             if (subGlobalReachalbeNode.getLocTuple().get(0).getLocDescriptor().equals(md.getThis())) {
1908               // System.out.println("PREFIX FOUND=" + subGlobalReachalbeNode);
1909               return true;
1910             }
1911           }
1912         }
1913       }
1914     }
1915
1916     Location lastLocationOfPrefix = curPrefix.get(curPrefix.size() - 1);
1917     // check whether prefix appears in the list of parameters
1918     Set<MethodInvokeNode> minSet = mapMethodDescToMethodInvokeNodeSet.get(md);
1919     // System.out.println("$$$md=" + md + "   minSet=" + minSet);
1920     if (minSet == null) {
1921       return false;
1922     }
1923     found: for (Iterator iterator = minSet.iterator(); iterator.hasNext();) {
1924       MethodInvokeNode min = (MethodInvokeNode) iterator.next();
1925       Map<Integer, NTuple<Descriptor>> map = mapMethodInvokeNodeToArgIdxMap.get(min);
1926       Set<Integer> keySet = map.keySet();
1927       // System.out.println("min=" + min.printNode(0));
1928
1929       for (Iterator iterator2 = keySet.iterator(); iterator2.hasNext();) {
1930         Integer argIdx = (Integer) iterator2.next();
1931         NTuple<Descriptor> argTuple = map.get(argIdx);
1932
1933         if (!(!md.isStatic() && argIdx == 0)) {
1934           // if the argTuple is empty, we don't need to do with anything(LITERAL CASE).
1935           if (argTuple.size() > 0
1936               && argTuple.get(argTuple.size() - 1).equals(lastLocationOfPrefix.getLocDescriptor())) {
1937             NTuple<Location> locTuple =
1938                 translateToLocTuple(md, flowGraph.getParamFlowNode(argIdx).getDescTuple());
1939             lastLocationOfPrefix = locTuple.get(0);
1940             // System.out.println("ARG CASE=" + locTuple);
1941             for (Iterator iterator3 = subGlobalReachableSet.iterator(); iterator3.hasNext();) {
1942               GlobalFlowNode subGlobalReachalbeNode = (GlobalFlowNode) iterator3.next();
1943               // NTuple<Location> locTuple = translateToLocTuple(md, reachalbeNode.getDescTuple());
1944               NTuple<Location> globalReachlocTuple = subGlobalReachalbeNode.getLocTuple();
1945               for (int i = 0; i < globalReachlocTuple.size(); i++) {
1946                 if (globalReachlocTuple.get(i).equals(lastLocationOfPrefix)) {
1947                   // System.out.println("ARG  " + argTuple + "  IS MATCHED WITH="
1948                   // + lastLocationOfPrefix);
1949                   return true;
1950                 }
1951               }
1952             }
1953           }
1954         }
1955       }
1956     }
1957
1958     return false;
1959   }
1960
1961   private boolean checkNodeReachToReturnNode(MethodDescriptor md, FlowNode node) {
1962
1963     FlowGraph flowGraph = getFlowGraph(md);
1964     Set<FlowNode> reachableSet = flowGraph.getReachFlowNodeSetFrom(node);
1965     if (mapMethodDescriptorToCompositeReturnCase.containsKey(md)) {
1966       boolean hasCompReturnLocWithThis =
1967           mapMethodDescriptorToCompositeReturnCase.get(md).booleanValue();
1968
1969       if (hasCompReturnLocWithThis) {
1970         for (Iterator iterator = flowGraph.getReturnNodeSet().iterator(); iterator.hasNext();) {
1971           FlowNode returnFlowNode = (FlowNode) iterator.next();
1972           if (reachableSet.contains(returnFlowNode)) {
1973             return true;
1974           }
1975         }
1976       }
1977     }
1978     return false;
1979   }
1980
1981   private void assignCompositeLocation(CompositeLocation compLocPrefix, GlobalFlowNode node) {
1982     CompositeLocation newCompLoc = compLocPrefix.clone();
1983     NTuple<Location> locTuple = node.getLocTuple();
1984     for (int i = 1; i < locTuple.size(); i++) {
1985       newCompLoc.addLocation(locTuple.get(i));
1986     }
1987     node.setInferCompositeLocation(newCompLoc);
1988   }
1989
1990   private List<NTuple<Location>> calculatePrefixList(GlobalFlowGraph graph, GlobalFlowNode node) {
1991
1992     // System.out.println("\n##### calculatePrefixList node=" + node);
1993
1994     Set<GlobalFlowNode> incomingNodeSetPrefix =
1995         graph.getIncomingNodeSetByPrefix(node.getLocTuple().get(0));
1996     // System.out.println("---incomingNodeSetPrefix=" + incomingNodeSetPrefix);
1997
1998     Set<GlobalFlowNode> reachableNodeSetPrefix =
1999         graph.getReachableNodeSetByPrefix(node.getLocTuple().get(0));
2000     // System.out.println("---reachableNodeSetPrefix=" + reachableNodeSetPrefix);
2001
2002     List<NTuple<Location>> prefixList = new ArrayList<NTuple<Location>>();
2003
2004     for (Iterator iterator = incomingNodeSetPrefix.iterator(); iterator.hasNext();) {
2005       GlobalFlowNode inNode = (GlobalFlowNode) iterator.next();
2006       NTuple<Location> inNodeTuple = inNode.getLocTuple();
2007
2008       if (inNodeTuple.get(0).getLocDescriptor() instanceof InterDescriptor
2009           || inNodeTuple.get(0).getLocDescriptor().equals(GLOBALDESC)) {
2010         continue;
2011       }
2012
2013       for (int i = 1; i < inNodeTuple.size(); i++) {
2014         NTuple<Location> prefix = inNodeTuple.subList(0, i);
2015         if (!prefixList.contains(prefix)) {
2016           prefixList.add(prefix);
2017         }
2018       }
2019     }
2020
2021     Collections.sort(prefixList, new Comparator<NTuple<Location>>() {
2022       public int compare(NTuple<Location> arg0, NTuple<Location> arg1) {
2023         int s0 = arg0.size();
2024         int s1 = arg1.size();
2025         if (s0 > s1) {
2026           return -1;
2027         } else if (s0 == s1) {
2028           return 0;
2029         } else {
2030           return 1;
2031         }
2032       }
2033     });
2034
2035     return prefixList;
2036
2037   }
2038
2039   private CompositeLocation calculateCompositeLocationFromFlowGraph(MethodDescriptor md,
2040       FlowNode node) {
2041
2042     // System.out.println("#############################################################");
2043     // System.out.println("calculateCompositeLocationFromFlowGraph=" + node);
2044
2045     FlowGraph flowGraph = getFlowGraph(md);
2046     // NTuple<Location> paramLocTuple = translateToLocTuple(md, paramNode.getDescTuple());
2047     // GlobalFlowNode paramGlobalNode = subGlobalFlowGraph.getFlowNode(paramLocTuple);
2048
2049     List<NTuple<Location>> prefixList = calculatePrefixListFlowGraph(flowGraph, node);
2050
2051     // Set<GlobalFlowNode> reachableNodeSet =
2052     // subGlobalFlowGraph.getReachableNodeSetByPrefix(paramGlobalNode.getLocTuple().get(0));
2053     //
2054     Set<FlowNode> reachableNodeSet =
2055         flowGraph.getReachableSetFrom(node.getDescTuple().subList(0, 1));
2056
2057     // Set<GlobalFlowNode> reachNodeSet = globalFlowGraph.getReachableNodeSetFrom(node);
2058
2059     // System.out.println("node=" + node + "    prefixList=" + prefixList);
2060
2061     for (int i = 0; i < prefixList.size(); i++) {
2062       NTuple<Location> curPrefix = prefixList.get(i);
2063       Set<NTuple<Location>> reachableCommonPrefixSet = new HashSet<NTuple<Location>>();
2064
2065       for (Iterator iterator2 = reachableNodeSet.iterator(); iterator2.hasNext();) {
2066         FlowNode reachNode = (FlowNode) iterator2.next();
2067         NTuple<Location> reachLocTuple = translateToLocTuple(md, reachNode.getCurrentDescTuple());
2068         if (reachLocTuple.startsWith(curPrefix)) {
2069           reachableCommonPrefixSet.add(reachLocTuple);
2070         }
2071       }
2072       // System.out.println("reachableCommonPrefixSet=" + reachableCommonPrefixSet);
2073
2074       if (!reachableCommonPrefixSet.isEmpty()) {
2075
2076         MethodDescriptor curPrefixFirstElementMethodDesc =
2077             (MethodDescriptor) curPrefix.get(0).getDescriptor();
2078
2079         Location curPrefixLocalLoc = curPrefix.get(0);
2080
2081         Location targetLocalLoc = new Location(md, node.getDescTuple().get(0));
2082         // Location targetLocalLoc = paramGlobalNode.getLocTuple().get(0);
2083
2084         CompositeLocation newCompLoc = generateCompositeLocation(curPrefix);
2085         // System.out.println("NEED2ASSIGN COMP LOC TO " + node + " with prefix=" + curPrefix);
2086         // System.out.println("-targetLocalLoc=" + targetLocalLoc + "   - newCompLoc=" +
2087         // newCompLoc);
2088
2089         node.setCompositeLocation(newCompLoc);
2090
2091         return newCompLoc;
2092
2093       }
2094
2095     }
2096     return null;
2097   }
2098
2099   private List<NTuple<Location>> calculatePrefixListFlowGraph(FlowGraph graph, FlowNode node) {
2100
2101     // System.out.println("\n##### calculatePrefixList node=" + node);
2102
2103     MethodDescriptor md = graph.getMethodDescriptor();
2104     Set<FlowNode> incomingNodeSetPrefix =
2105         graph.getIncomingNodeSetByPrefix(node.getDescTuple().get(0));
2106     // System.out.println("---incomingNodeSetPrefix=" + incomingNodeSetPrefix);
2107
2108     Set<FlowNode> reachableNodeSetPrefix =
2109         graph.getReachableSetFrom(node.getDescTuple().subList(0, 1));
2110     // System.out.println("---reachableNodeSetPrefix=" + reachableNodeSetPrefix);
2111
2112     List<NTuple<Location>> prefixList = new ArrayList<NTuple<Location>>();
2113
2114     for (Iterator iterator = incomingNodeSetPrefix.iterator(); iterator.hasNext();) {
2115       FlowNode inNode = (FlowNode) iterator.next();
2116       NTuple<Location> inNodeTuple = translateToLocTuple(md, inNode.getCurrentDescTuple());
2117
2118       // if (inNodeTuple.get(0).getLocDescriptor() instanceof InterDescriptor
2119       // || inNodeTuple.get(0).getLocDescriptor().equals(GLOBALDESC)) {
2120       // continue;
2121       // }
2122
2123       for (int i = 1; i < inNodeTuple.size(); i++) {
2124         NTuple<Location> prefix = inNodeTuple.subList(0, i);
2125         if (!prefixList.contains(prefix)) {
2126           prefixList.add(prefix);
2127         }
2128       }
2129     }
2130
2131     Collections.sort(prefixList, new Comparator<NTuple<Location>>() {
2132       public int compare(NTuple<Location> arg0, NTuple<Location> arg1) {
2133         int s0 = arg0.size();
2134         int s1 = arg1.size();
2135         if (s0 > s1) {
2136           return -1;
2137         } else if (s0 == s1) {
2138           return 0;
2139         } else {
2140           return 1;
2141         }
2142       }
2143     });
2144
2145     return prefixList;
2146
2147   }
2148
2149   private GlobalFlowGraph constructSubGlobalFlowGraph(FlowGraph flowGraph) {
2150
2151     MethodDescriptor md = flowGraph.getMethodDescriptor();
2152
2153     GlobalFlowGraph globalGraph = getSubGlobalFlowGraph(md);
2154
2155     // Set<FlowNode> nodeSet = flowGraph.getNodeSet();
2156     Set<FlowEdge> edgeSet = flowGraph.getEdgeSet();
2157
2158     for (Iterator iterator = edgeSet.iterator(); iterator.hasNext();) {
2159
2160       FlowEdge edge = (FlowEdge) iterator.next();
2161       NTuple<Descriptor> srcDescTuple = edge.getInitTuple();
2162       NTuple<Descriptor> dstDescTuple = edge.getEndTuple();
2163
2164       if (flowGraph.getFlowNode(srcDescTuple) instanceof FlowReturnNode
2165           || flowGraph.getFlowNode(dstDescTuple) instanceof FlowReturnNode) {
2166         continue;
2167       }
2168
2169       // here only keep the first element(method location) of the descriptor
2170       // tuple
2171       NTuple<Location> srcLocTuple = translateToLocTuple(md, srcDescTuple);
2172       NTuple<Location> dstLocTuple = translateToLocTuple(md, dstDescTuple);
2173
2174       globalGraph.addValueFlowEdge(srcLocTuple, dstLocTuple);
2175
2176     }
2177
2178     return globalGraph;
2179   }
2180
2181   private NTuple<Location> translateToLocTuple(MethodDescriptor md, NTuple<Descriptor> descTuple) {
2182
2183     NTuple<Location> locTuple = new NTuple<Location>();
2184
2185     Descriptor enclosingDesc = md;
2186     for (int i = 0; i < descTuple.size(); i++) {
2187       Descriptor desc = descTuple.get(i);
2188
2189       Location loc = new Location(enclosingDesc, desc);
2190       locTuple.add(loc);
2191
2192       if (desc instanceof VarDescriptor) {
2193         enclosingDesc = ((VarDescriptor) desc).getType().getClassDesc();
2194       } else if (desc instanceof FieldDescriptor) {
2195         enclosingDesc = ((FieldDescriptor) desc).getType().getClassDesc();
2196       } else {
2197         enclosingDesc = desc;
2198       }
2199
2200     }
2201
2202     return locTuple;
2203
2204   }
2205
2206   private void addValueFlowsFromCalleeSubGlobalFlowGraph(MethodDescriptor mdCaller) {
2207
2208     // the transformation for a call site propagates flows through parameters
2209     // if the method is virtual, it also grab all relations from any possible
2210     // callees
2211
2212     Set<MethodInvokeNode> setMethodInvokeNode = getMethodInvokeNodeSet(mdCaller);
2213
2214     for (Iterator iterator = setMethodInvokeNode.iterator(); iterator.hasNext();) {
2215       MethodInvokeNode min = (MethodInvokeNode) iterator.next();
2216       MethodDescriptor mdCallee = min.getMethod();
2217       Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
2218       if (mdCallee.isStatic()) {
2219         setPossibleCallees.add(mdCallee);
2220       } else {
2221         Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getMethods(mdCallee);
2222         // removes method descriptors that are not invoked by the caller
2223         calleeSet.retainAll(mapMethodToCalleeSet.get(mdCaller));
2224         setPossibleCallees.addAll(calleeSet);
2225       }
2226
2227       for (Iterator iterator2 = setPossibleCallees.iterator(); iterator2.hasNext();) {
2228         MethodDescriptor possibleMdCallee = (MethodDescriptor) iterator2.next();
2229         propagateValueFlowsToCallerFromSubGlobalFlowGraph(min, mdCaller, possibleMdCallee);
2230       }
2231
2232     }
2233
2234   }
2235
2236   private void propagateValueFlowsToCallerFromSubGlobalFlowGraph(MethodInvokeNode min,
2237       MethodDescriptor mdCaller, MethodDescriptor possibleMdCallee) {
2238
2239     // System.out.println("---propagate from " + min.printNode(0) + " to caller=" + mdCaller);
2240     FlowGraph calleeFlowGraph = getFlowGraph(possibleMdCallee);
2241     Map<Integer, NTuple<Descriptor>> mapIdxToArg = mapMethodInvokeNodeToArgIdxMap.get(min);
2242
2243     // System.out.println("-----mapMethodInvokeNodeToArgIdxMap.get(min)="
2244     // + mapMethodInvokeNodeToArgIdxMap.get(min));
2245
2246     Set<Integer> keySet = mapIdxToArg.keySet();
2247     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
2248       Integer idx = (Integer) iterator.next();
2249       NTuple<Descriptor> argDescTuple = mapIdxToArg.get(idx);
2250       if (argDescTuple.size() > 0) {
2251         NTuple<Location> argLocTuple = translateToLocTuple(mdCaller, argDescTuple);
2252         NTuple<Descriptor> paramDescTuple = calleeFlowGraph.getParamFlowNode(idx).getDescTuple();
2253         NTuple<Location> paramLocTuple = translateToLocTuple(possibleMdCallee, paramDescTuple);
2254         // System.out.println("-------paramDescTuple=" + paramDescTuple + "->argDescTuple="
2255         // + argDescTuple);
2256         addMapCallerArgToCalleeParam(min, argDescTuple, paramDescTuple);
2257       }
2258     }
2259
2260     // addValueFlowBetweenParametersToCaller(min, mdCaller, possibleMdCallee);
2261
2262     NTuple<Descriptor> baseTuple = mapMethodInvokeNodeToBaseTuple.get(min);
2263     GlobalFlowGraph calleeSubGlobalGraph = getSubGlobalFlowGraph(possibleMdCallee);
2264     Set<GlobalFlowNode> calleeNodeSet = calleeSubGlobalGraph.getNodeSet();
2265     for (Iterator iterator = calleeNodeSet.iterator(); iterator.hasNext();) {
2266       GlobalFlowNode calleeNode = (GlobalFlowNode) iterator.next();
2267       addValueFlowFromCalleeNode(min, mdCaller, possibleMdCallee, calleeNode);
2268     }
2269
2270     // System.out.println("$$$GLOBAL PC LOC ADD=" + mdCaller);
2271     Set<NTuple<Location>> pcLocTupleSet = mapMethodInvokeNodeToPCLocTupleSet.get(min);
2272     // System.out.println("---pcLocTupleSet=" + pcLocTupleSet);
2273     GlobalFlowGraph callerSubGlobalGraph = getSubGlobalFlowGraph(mdCaller);
2274     for (Iterator iterator = calleeNodeSet.iterator(); iterator.hasNext();) {
2275       GlobalFlowNode calleeNode = (GlobalFlowNode) iterator.next();
2276       if (calleeNode.isParamNodeWithIncomingFlows()) {
2277         // System.out.println("calleeNode.getLocTuple()" + calleeNode.getLocTuple());
2278         NTuple<Location> callerSrcNodeLocTuple =
2279             translateToCallerLocTuple(min, possibleMdCallee, mdCaller, calleeNode.getLocTuple());
2280         // System.out.println("---callerSrcNodeLocTuple=" + callerSrcNodeLocTuple);
2281         if (callerSrcNodeLocTuple != null && callerSrcNodeLocTuple.size() > 0) {
2282           for (Iterator iterator2 = pcLocTupleSet.iterator(); iterator2.hasNext();) {
2283             NTuple<Location> pcLocTuple = (NTuple<Location>) iterator2.next();
2284
2285             callerSubGlobalGraph.addValueFlowEdge(pcLocTuple, callerSrcNodeLocTuple);
2286           }
2287         }
2288       }
2289
2290     }
2291
2292   }
2293
2294   private void addValueFlowFromCalleeNode(MethodInvokeNode min, MethodDescriptor mdCaller,
2295       MethodDescriptor mdCallee, GlobalFlowNode calleeSrcNode) {
2296
2297     GlobalFlowGraph calleeSubGlobalGraph = getSubGlobalFlowGraph(mdCallee);
2298     GlobalFlowGraph callerSubGlobalGraph = getSubGlobalFlowGraph(mdCaller);
2299
2300     // System.out.println("$addValueFlowFromCalleeNode calleeSrcNode=" + calleeSrcNode);
2301
2302     NTuple<Location> callerSrcNodeLocTuple =
2303         translateToCallerLocTuple(min, mdCallee, mdCaller, calleeSrcNode.getLocTuple());
2304     // System.out.println("---callerSrcNodeLocTuple=" + callerSrcNodeLocTuple);
2305
2306     if (callerSrcNodeLocTuple != null && callerSrcNodeLocTuple.size() > 0) {
2307
2308       Set<GlobalFlowNode> outNodeSet = calleeSubGlobalGraph.getOutNodeSet(calleeSrcNode);
2309
2310       for (Iterator iterator = outNodeSet.iterator(); iterator.hasNext();) {
2311         GlobalFlowNode outNode = (GlobalFlowNode) iterator.next();
2312         NTuple<Location> callerDstNodeLocTuple =
2313             translateToCallerLocTuple(min, mdCallee, mdCaller, outNode.getLocTuple());
2314         // System.out.println("outNode=" + outNode + "   callerDstNodeLocTuple="
2315         // + callerDstNodeLocTuple);
2316         if (callerSrcNodeLocTuple != null && callerDstNodeLocTuple != null
2317             && callerSrcNodeLocTuple.size() > 0 && callerDstNodeLocTuple.size() > 0) {
2318           callerSubGlobalGraph.addValueFlowEdge(callerSrcNodeLocTuple, callerDstNodeLocTuple);
2319         }
2320       }
2321     }
2322
2323   }
2324
2325   private NTuple<Location> translateToCallerLocTuple(MethodInvokeNode min,
2326       MethodDescriptor mdCallee, MethodDescriptor mdCaller, NTuple<Location> nodeLocTuple) {
2327     // this method will return the same nodeLocTuple if the corresponding argument is literal
2328     // value.
2329
2330     // System.out.println("translateToCallerLocTuple=" + nodeLocTuple);
2331
2332     FlowGraph calleeFlowGraph = getFlowGraph(mdCallee);
2333     NTuple<Descriptor> nodeDescTuple = translateToDescTuple(nodeLocTuple);
2334     if (calleeFlowGraph.isParameter(nodeDescTuple)) {
2335       int paramIdx = calleeFlowGraph.getParamIdx(nodeDescTuple);
2336       NTuple<Descriptor> argDescTuple = mapMethodInvokeNodeToArgIdxMap.get(min).get(paramIdx);
2337
2338       // if (isPrimitive(nodeLocTuple.get(0).getLocDescriptor())) {
2339       // // the type of argument is primitive.
2340       // return nodeLocTuple.clone();
2341       // }
2342       // System.out.println("paramIdx=" + paramIdx + "  argDescTuple=" + argDescTuple + " from min="
2343       // + min.printNode(0));
2344       NTuple<Location> argLocTuple = translateToLocTuple(mdCaller, argDescTuple);
2345
2346       NTuple<Location> callerLocTuple = new NTuple<Location>();
2347
2348       callerLocTuple.addAll(argLocTuple);
2349       for (int i = 1; i < nodeLocTuple.size(); i++) {
2350         callerLocTuple.add(nodeLocTuple.get(i));
2351       }
2352       return callerLocTuple;
2353     } else {
2354       return nodeLocTuple.clone();
2355     }
2356
2357   }
2358
2359   public static boolean isPrimitive(Descriptor desc) {
2360
2361     if (desc instanceof FieldDescriptor) {
2362       return ((FieldDescriptor) desc).getType().isPrimitive();
2363     } else if (desc instanceof VarDescriptor) {
2364       return ((VarDescriptor) desc).getType().isPrimitive();
2365     } else if (desc instanceof InterDescriptor) {
2366       return true;
2367     }
2368
2369     return false;
2370   }
2371
2372   public static boolean isReference(Descriptor desc) {
2373
2374     if (desc instanceof FieldDescriptor) {
2375
2376       TypeDescriptor type = ((FieldDescriptor) desc).getType();
2377       if (type.isArray()) {
2378         return !type.isPrimitive();
2379       } else {
2380         return type.isPtr();
2381       }
2382
2383     } else if (desc instanceof VarDescriptor) {
2384       TypeDescriptor type = ((VarDescriptor) desc).getType();
2385       if (type.isArray()) {
2386         return !type.isPrimitive();
2387       } else {
2388         return type.isPtr();
2389       }
2390     }
2391
2392     return false;
2393   }
2394
2395   private NTuple<Descriptor> translateToDescTuple(NTuple<Location> locTuple) {
2396
2397     NTuple<Descriptor> descTuple = new NTuple<Descriptor>();
2398     for (int i = 0; i < locTuple.size(); i++) {
2399       descTuple.add(locTuple.get(i).getLocDescriptor());
2400     }
2401     return descTuple;
2402
2403   }
2404
2405   public LocationSummary getLocationSummary(Descriptor d) {
2406     if (!mapDescToLocationSummary.containsKey(d)) {
2407       if (d instanceof MethodDescriptor) {
2408         mapDescToLocationSummary.put(d, new MethodSummary((MethodDescriptor) d));
2409       } else if (d instanceof ClassDescriptor) {
2410         mapDescToLocationSummary.put(d, new FieldSummary());
2411       }
2412     }
2413     return mapDescToLocationSummary.get(d);
2414   }
2415
2416   private void generateMethodSummary() {
2417
2418     Set<MethodDescriptor> keySet = md2lattice.keySet();
2419     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
2420       MethodDescriptor md = (MethodDescriptor) iterator.next();
2421
2422       System.out.println("\nSSJAVA: generate method summary: " + md);
2423
2424       FlowGraph flowGraph = getFlowGraph(md);
2425       if (flowGraph == null) {
2426         continue;
2427       }
2428       MethodSummary methodSummary = getMethodSummary(md);
2429
2430       HierarchyGraph scGraph = getSkeletonCombinationHierarchyGraph(md);
2431
2432       // set the 'this' reference location
2433       if (!md.isStatic()) {
2434         // System.out.println("setThisLocName=" + scGraph.getHNode(md.getThis()).getName());
2435         methodSummary.setThisLocName(scGraph.getHNode(md.getThis()).getName());
2436       }
2437
2438       // set the 'global' reference location if needed
2439       if (methodSummary.hasGlobalAccess()) {
2440         methodSummary.setGlobalLocName(scGraph.getHNode(GLOBALDESC).getName());
2441       }
2442
2443       // construct a parameter mapping that maps a parameter descriptor to an
2444       // inferred composite location
2445       for (int paramIdx = 0; paramIdx < flowGraph.getNumParameters(); paramIdx++) {
2446         FlowNode flowNode = flowGraph.getParamFlowNode(paramIdx);
2447         CompositeLocation inferredCompLoc =
2448             updateCompositeLocation(flowNode.getCompositeLocation());
2449         // System.out.println("-paramIdx=" + paramIdx + "   infer=" + inferredCompLoc + " original="
2450         // + flowNode.getCompositeLocation());
2451
2452         Descriptor localVarDesc = flowNode.getDescTuple().get(0);
2453         methodSummary.addMapVarNameToInferCompLoc(localVarDesc, inferredCompLoc);
2454         methodSummary.addMapParamIdxToInferLoc(paramIdx, inferredCompLoc);
2455       }
2456
2457     }
2458
2459   }
2460
2461   private boolean hasOrderingRelation(NTuple<Location> locTuple1, NTuple<Location> locTuple2) {
2462
2463     int size = locTuple1.size() >= locTuple2.size() ? locTuple2.size() : locTuple1.size();
2464
2465     for (int idx = 0; idx < size; idx++) {
2466       Location loc1 = locTuple1.get(idx);
2467       Location loc2 = locTuple2.get(idx);
2468
2469       Descriptor desc1 = loc1.getDescriptor();
2470       Descriptor desc2 = loc2.getDescriptor();
2471
2472       if (!desc1.equals(desc2)) {
2473         throw new Error("Fail to compare " + locTuple1 + " and " + locTuple2);
2474       }
2475
2476       Descriptor locDesc1 = loc1.getLocDescriptor();
2477       Descriptor locDesc2 = loc2.getLocDescriptor();
2478
2479       HierarchyGraph hierarchyGraph = getHierarchyGraph(desc1);
2480
2481       HNode node1 = hierarchyGraph.getHNode(locDesc1);
2482       HNode node2 = hierarchyGraph.getHNode(locDesc2);
2483
2484       // System.out.println("---node1=" + node1 + "  node2=" + node2);
2485       // System.out.println("---hierarchyGraph.getIncomingNodeSet(node2)="
2486       // + hierarchyGraph.getIncomingNodeSet(node2));
2487
2488       if (locDesc1.equals(locDesc2)) {
2489         continue;
2490       } else if (!hierarchyGraph.getIncomingNodeSet(node2).contains(node1)
2491           && !hierarchyGraph.getIncomingNodeSet(node1).contains(node2)) {
2492         return false;
2493       } else {
2494         return true;
2495       }
2496
2497     }
2498
2499     return false;
2500
2501   }
2502
2503   private boolean isHigherThan(NTuple<Location> locTuple1, NTuple<Location> locTuple2) {
2504
2505     int size = locTuple1.size() >= locTuple2.size() ? locTuple2.size() : locTuple1.size();
2506
2507     for (int idx = 0; idx < size; idx++) {
2508       Location loc1 = locTuple1.get(idx);
2509       Location loc2 = locTuple2.get(idx);
2510
2511       Descriptor desc1 = loc1.getDescriptor();
2512       Descriptor desc2 = loc2.getDescriptor();
2513
2514       if (!desc1.equals(desc2)) {
2515         throw new Error("Fail to compare " + locTuple1 + " and " + locTuple2);
2516       }
2517
2518       Descriptor locDesc1 = loc1.getLocDescriptor();
2519       Descriptor locDesc2 = loc2.getLocDescriptor();
2520
2521       HierarchyGraph hierarchyGraph = getHierarchyGraph(desc1);
2522
2523       HNode node1 = hierarchyGraph.getHNode(locDesc1);
2524       HNode node2 = hierarchyGraph.getHNode(locDesc2);
2525
2526       // System.out.println("---node1=" + node1 + "  node2=" + node2);
2527       // System.out.println("---hierarchyGraph.getIncomingNodeSet(node2)="
2528       // + hierarchyGraph.getIncomingNodeSet(node2));
2529
2530       if (locDesc1.equals(locDesc2)) {
2531         continue;
2532       } else if (hierarchyGraph.getIncomingNodeSet(node2).contains(node1)) {
2533         return true;
2534       } else {
2535         return false;
2536       }
2537
2538     }
2539
2540     return false;
2541   }
2542
2543   private void debug_writeLattices() {
2544
2545     Set<Descriptor> keySet = mapDescriptorToSimpleLattice.keySet();
2546     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
2547       Descriptor key = (Descriptor) iterator.next();
2548       SSJavaLattice<String> simpleLattice = mapDescriptorToSimpleLattice.get(key);
2549       // HierarchyGraph simpleHierarchyGraph = getSimpleHierarchyGraph(key);
2550       HierarchyGraph scHierarchyGraph = getSkeletonCombinationHierarchyGraph(key);
2551       if (key instanceof ClassDescriptor) {
2552         // writeInferredLatticeDotFile((ClassDescriptor) key, scHierarchyGraph, simpleLattice,
2553         // "_SIMPLE");
2554       } else if (key instanceof MethodDescriptor) {
2555         MethodDescriptor md = (MethodDescriptor) key;
2556         // writeInferredLatticeDotFile(md.getClassDesc(), md, scHierarchyGraph, simpleLattice,
2557         // "_SIMPLE");
2558       }
2559
2560       LocationSummary ls = getLocationSummary(key);
2561       // System.out.println("####LOC SUMMARY=" + key + "\n" + ls.getMapHNodeNameToLocationName());
2562     }
2563
2564     Set<ClassDescriptor> cdKeySet = cd2lattice.keySet();
2565     for (Iterator iterator = cdKeySet.iterator(); iterator.hasNext();) {
2566       ClassDescriptor cd = (ClassDescriptor) iterator.next();
2567       // System.out.println("########cd=" + cd);
2568       writeInferredLatticeDotFile((ClassDescriptor) cd, getSkeletonCombinationHierarchyGraph(cd),
2569           cd2lattice.get(cd), "");
2570       COUNT += cd2lattice.get(cd).getKeySet().size();
2571     }
2572
2573     Set<MethodDescriptor> mdKeySet = md2lattice.keySet();
2574     for (Iterator iterator = mdKeySet.iterator(); iterator.hasNext();) {
2575       MethodDescriptor md = (MethodDescriptor) iterator.next();
2576       writeInferredLatticeDotFile(md.getClassDesc(), md, getSkeletonCombinationHierarchyGraph(md),
2577           md2lattice.get(md), "");
2578       COUNT += md2lattice.get(md).getKeySet().size();
2579     }
2580     System.out.println("###COUNT=" + COUNT);
2581   }
2582
2583   private void buildLattice(Descriptor desc) {
2584     // System.out.println("buildLattice=" + desc);
2585     SSJavaLattice<String> simpleLattice = buildLattice.buildLattice(desc);
2586
2587     addMapDescToSimpleLattice(desc, simpleLattice);
2588
2589     HierarchyGraph simpleHierarchyGraph = getSimpleHierarchyGraph(desc);
2590     // System.out.println("\n## insertIntermediateNodesToStraightLine:"
2591     // + simpleHierarchyGraph.getName());
2592     SSJavaLattice<String> lattice =
2593         buildLattice.insertIntermediateNodesToStraightLine(desc, simpleLattice);
2594     lattice.removeRedundantEdges();
2595
2596     if (desc instanceof ClassDescriptor) {
2597       // field lattice
2598       cd2lattice.put((ClassDescriptor) desc, lattice);
2599       // ssjava.writeLatticeDotFile((ClassDescriptor) desc, null, lattice);
2600     } else if (desc instanceof MethodDescriptor) {
2601       // method lattice
2602       md2lattice.put((MethodDescriptor) desc, lattice);
2603       MethodDescriptor md = (MethodDescriptor) desc;
2604       ClassDescriptor cd = md.getClassDesc();
2605       // ssjava.writeLatticeDotFile(cd, md, lattice);
2606     }
2607
2608   }
2609
2610   private void buildLattice() {
2611
2612     Set<Descriptor> keySet = mapDescriptorToCombineSkeletonHierarchyGraph.keySet();
2613     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
2614       Descriptor desc = (Descriptor) iterator.next();
2615
2616       SSJavaLattice<String> simpleLattice = buildLattice.buildLattice(desc);
2617
2618       addMapDescToSimpleLattice(desc, simpleLattice);
2619
2620       HierarchyGraph simpleHierarchyGraph = getSimpleHierarchyGraph(desc);
2621       System.out.println("\n## insertIntermediateNodesToStraightLine:"
2622           + simpleHierarchyGraph.getName());
2623       SSJavaLattice<String> lattice =
2624           buildLattice.insertIntermediateNodesToStraightLine(desc, simpleLattice);
2625       lattice.removeRedundantEdges();
2626
2627       LocationInference.numLocationsSInfer += lattice.getKeySet().size();
2628
2629       if (desc instanceof ClassDescriptor) {
2630         // field lattice
2631         cd2lattice.put((ClassDescriptor) desc, lattice);
2632         // ssjava.writeLatticeDotFile((ClassDescriptor) desc, null, lattice);
2633       } else if (desc instanceof MethodDescriptor) {
2634         // method lattice
2635         md2lattice.put((MethodDescriptor) desc, lattice);
2636         MethodDescriptor md = (MethodDescriptor) desc;
2637         ClassDescriptor cd = md.getClassDesc();
2638         // ssjava.writeLatticeDotFile(cd, md, lattice);
2639       }
2640
2641     }
2642
2643   }
2644
2645   private void buildLatticeInheritanceTree() {
2646     // DFS the inheritance tree and propagates lattice nodes/edges from the parent to children
2647     // Node<ClassDescriptor> rootNode = inheritanceTree.getRootNode();
2648     DFSBuildLatticeInheritanceTree(rootClassDescriptor);
2649   }
2650
2651   public Set<ClassDescriptor> getDirectSubClasses(ClassDescriptor parent) {
2652
2653     Set<ClassDescriptor> result = new HashSet<ClassDescriptor>();
2654
2655     Set<ClassDescriptor> children = tu.getDirectSubClasses(parent);
2656     if (children == null) {
2657       children = new HashSet<ClassDescriptor>();
2658     }
2659
2660     for (Iterator iterator = children.iterator(); iterator.hasNext();) {
2661       ClassDescriptor child = (ClassDescriptor) iterator.next();
2662       if (toanalyze_classDescSet.contains(child)) {
2663         result.add(child);
2664       }
2665     }
2666
2667     return result;
2668   }
2669
2670   private void DFSBuildLatticeInheritanceTree(ClassDescriptor cd) {
2671     // ClassDescriptor cd = node.getData();
2672
2673     ClassDescriptor parentClassDesc = cd.getSuperDesc();
2674     if (parentClassDesc != null) {
2675       Map<TripleItem, String> parentMap = buildLattice.getIntermediateLocMap(parentClassDesc);
2676       buildLattice.setIntermediateLocMap(cd, parentMap);
2677     }
2678
2679     buildLattice(cd);
2680
2681     for (Iterator iterator = cd.getMethods(); iterator.hasNext();) {
2682       MethodDescriptor md = (MethodDescriptor) iterator.next();
2683       if (toanalyze_methodDescList.contains(md)) {
2684         MethodDescriptor parentMethodDesc = getParentMethodDesc(md.getClassDesc(), md);
2685         if (parentMethodDesc != null) {
2686           Map<TripleItem, String> parentMap = buildLattice.getIntermediateLocMap(parentMethodDesc);
2687           Map<TripleItem, String> childMap = new HashMap<TripleItem, String>();
2688           Set<TripleItem> keySet = parentMap.keySet();
2689           for (Iterator iterator2 = keySet.iterator(); iterator2.hasNext();) {
2690             TripleItem key = (TripleItem) iterator2.next();
2691             childMap.put(key, parentMap.get(key));
2692           }
2693           buildLattice.setIntermediateLocMap(md, childMap);
2694         }
2695         buildLattice(md);
2696       }
2697     }
2698
2699     // traverse children
2700     Set<ClassDescriptor> children = tu.getDirectSubClasses(cd);
2701     if (children != null) {
2702       for (Iterator iterator = children.iterator(); iterator.hasNext();) {
2703         ClassDescriptor classDescriptor = (ClassDescriptor) iterator.next();
2704         if (toanalyze_classDescSet.contains(classDescriptor)) {
2705           DFSBuildLatticeInheritanceTree(classDescriptor);
2706         } else {
2707           if (classDescriptor.isAbstract()) {
2708             DFSBuildLatticeInheritanceTree(classDescriptor);
2709           }
2710         }
2711       }
2712     }
2713
2714   }
2715
2716   public void addMapDescToSimpleLattice(Descriptor desc, SSJavaLattice<String> lattice) {
2717     mapDescriptorToSimpleLattice.put(desc, lattice);
2718   }
2719
2720   public SSJavaLattice<String> getSimpleLattice(Descriptor desc) {
2721     return mapDescriptorToSimpleLattice.get(desc);
2722   }
2723
2724   private void simplifyHierarchyGraph() {
2725     Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
2726     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
2727       Descriptor desc = (Descriptor) iterator.next();
2728       // System.out.println("SSJAVA: remove redundant edges: " + desc);
2729       HierarchyGraph simpleHierarchyGraph = getHierarchyGraph(desc).clone();
2730       simpleHierarchyGraph.setName(desc + "_SIMPLE");
2731       simpleHierarchyGraph.removeRedundantEdges();
2732       mapDescriptorToSimpleHierarchyGraph.put(desc, simpleHierarchyGraph);
2733     }
2734   }
2735
2736   private void insertCombinationNodes() {
2737     Set<Descriptor> keySet = mapDescriptorToSkeletonHierarchyGraph.keySet();
2738     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
2739       Descriptor desc = (Descriptor) iterator.next();
2740       System.out.println("\nSSJAVA: Inserting Combination Nodes:" + desc);
2741       HierarchyGraph skeletonGraph = getSkeletonHierarchyGraph(desc);
2742       HierarchyGraph skeletonGraphWithCombinationNode = skeletonGraph.clone();
2743       skeletonGraphWithCombinationNode.setName(desc + "_SC");
2744
2745       HierarchyGraph simpleHierarchyGraph = getSimpleHierarchyGraph(desc);
2746       skeletonGraphWithCombinationNode.insertCombinationNodesToGraph(simpleHierarchyGraph);
2747       // skeletonGraphWithCombinationNode.insertCombinationNodesToGraph(simpleHierarchyGraph,
2748       // skeletonGraph);
2749       // skeletonGraphWithCombinationNode.simplifySkeletonCombinationHierarchyGraph();
2750       skeletonGraphWithCombinationNode.removeRedundantEdges();
2751       mapDescriptorToCombineSkeletonHierarchyGraph.put(desc, skeletonGraphWithCombinationNode);
2752     }
2753   }
2754
2755   private void constructSkeletonHierarchyGraph() {
2756     Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
2757     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
2758       Descriptor desc = (Descriptor) iterator.next();
2759       System.out.println("SSJAVA: Constructing Skeleton Hierarchy Graph: " + desc);
2760       HierarchyGraph simpleGraph = getSimpleHierarchyGraph(desc);
2761       HierarchyGraph skeletonGraph = simpleGraph.generateSkeletonGraph();
2762       skeletonGraph.setMapDescToHNode(simpleGraph.getMapDescToHNode());
2763       skeletonGraph.setMapHNodeToDescSet(simpleGraph.getMapHNodeToDescSet());
2764       skeletonGraph.simplifyHierarchyGraph(this);
2765       mapDescriptorToSkeletonHierarchyGraph.put(desc, skeletonGraph);
2766     }
2767   }
2768
2769   private void recurUpAccumulateInheritanceDesc(Descriptor curDesc, Set<Descriptor> set) {
2770
2771     if (curDesc instanceof ClassDescriptor) {
2772       ClassDescriptor cd = (ClassDescriptor) curDesc;
2773       ClassDescriptor parentClassDesc = cd.getSuperDesc();
2774       if (parentClassDesc != null && !parentClassDesc.equals(rootClassDescriptor)) {
2775         set.add(parentClassDesc);
2776         recurUpAccumulateInheritanceDesc(parentClassDesc, set);
2777       }
2778     } else {
2779       MethodDescriptor md = (MethodDescriptor) curDesc;
2780       ClassDescriptor cd = md.getClassDesc();
2781
2782       // traverse up
2783       ClassDescriptor parentClassDesc = cd.getSuperDesc();
2784       if (parentClassDesc != null && !parentClassDesc.equals(rootClassDescriptor)) {
2785
2786         Set<MethodDescriptor> methodDescSet =
2787             parentClassDesc.getMethodTable().getSet(md.getSymbol());
2788         for (Iterator iterator = methodDescSet.iterator(); iterator.hasNext();) {
2789           MethodDescriptor parentMethodDesc = (MethodDescriptor) iterator.next();
2790           if (parentMethodDesc.matches(md)) {
2791             set.add(parentMethodDesc);
2792             recurUpAccumulateInheritanceDesc(parentMethodDesc, set);
2793           }
2794         }
2795       }
2796
2797     }
2798
2799   }
2800
2801   private void recurDownAccumulateInheritanceDesc(Descriptor curDesc, Set<Descriptor> set) {
2802
2803     if (curDesc instanceof ClassDescriptor) {
2804       ClassDescriptor cd = (ClassDescriptor) curDesc;
2805       ClassDescriptor parentClassDesc = cd.getSuperDesc();
2806       Set<ClassDescriptor> directSubClasses = tu.getDirectSubClasses(cd);
2807       for (Iterator iterator = directSubClasses.iterator(); iterator.hasNext();) {
2808         ClassDescriptor child = (ClassDescriptor) iterator.next();
2809         recurDownAccumulateInheritanceDesc(child, set);
2810       }
2811     } else {
2812       MethodDescriptor md = (MethodDescriptor) curDesc;
2813       ClassDescriptor cd = md.getClassDesc();
2814
2815       // traverse down
2816       Set<ClassDescriptor> directSubClasses = tu.getDirectSubClasses(cd);
2817       for (Iterator iterator = directSubClasses.iterator(); iterator.hasNext();) {
2818         ClassDescriptor child = (ClassDescriptor) iterator.next();
2819
2820         Set<MethodDescriptor> methodDescSet = child.getMethodTable().getSet(md.getSymbol());
2821         for (Iterator iterator2 = methodDescSet.iterator(); iterator2.hasNext();) {
2822           MethodDescriptor childMethodDesc = (MethodDescriptor) iterator2.next();
2823           if (childMethodDesc.matches(md)) {
2824             set.add(childMethodDesc);
2825             recurDownAccumulateInheritanceDesc(childMethodDesc, set);
2826           }
2827         }
2828       }
2829
2830     }
2831
2832   }
2833
2834   private void accumulateInheritanceDesc(Descriptor curDesc, Set<Descriptor> set) {
2835
2836     recurUpAccumulateInheritanceDesc(curDesc, set);
2837     recurDownAccumulateInheritanceDesc(curDesc, set);
2838
2839   }
2840
2841   public boolean isValidMergeInheritanceCheck(Descriptor desc, Set<HNode> mergeSet) {
2842
2843     // set up inheritance chain set...
2844     Set<Descriptor> inheritanceDescSet = new HashSet<Descriptor>();
2845     recurUpAccumulateInheritanceDesc(desc, inheritanceDescSet);
2846
2847     nextgraph: for (Iterator iterator = inheritanceDescSet.iterator(); iterator.hasNext();) {
2848       Descriptor inheritDesc = (Descriptor) iterator.next();
2849
2850       if (!desc.equals(inheritDesc)) {
2851         HierarchyGraph graph = getSkeletonCombinationHierarchyGraph(inheritDesc);
2852
2853         // first check whether this graph includes all elements of the merge set
2854         for (Iterator iterator2 = mergeSet.iterator(); iterator2.hasNext();) {
2855           HNode node = (HNode) iterator2.next();
2856           if (!graph.contains(node)) {
2857             continue nextgraph;
2858           }
2859         }
2860
2861         HNode firstNode = mergeSet.iterator().next();
2862
2863         Set<HNode> incomingNode = graph.getIncomingNodeSet(firstNode);
2864         Set<HNode> outgoingNode = graph.getOutgoingNodeSet(firstNode);
2865
2866         for (Iterator iterator2 = mergeSet.iterator(); iterator2.hasNext();) {
2867           HNode node = (HNode) iterator2.next();
2868
2869           if (!graph.getIncomingNodeSet(node).equals(incomingNode)
2870               || !graph.getOutgoingNodeSet(node).equals(outgoingNode)) {
2871             return false;
2872           }
2873
2874         }
2875       }
2876
2877     }
2878
2879     return true;
2880   }
2881
2882   private void debug_writeHierarchyDotFiles() {
2883
2884     Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
2885     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
2886       Descriptor desc = (Descriptor) iterator.next();
2887       getHierarchyGraph(desc).writeGraph();
2888     }
2889
2890   }
2891
2892   private void debug_writeSimpleHierarchyDotFiles() {
2893
2894     Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
2895     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
2896       Descriptor desc = (Descriptor) iterator.next();
2897       getHierarchyGraph(desc).writeGraph();
2898       getSimpleHierarchyGraph(desc).writeGraph();
2899       getSimpleHierarchyGraph(desc).writeGraph(true);
2900     }
2901
2902   }
2903
2904   private void debug_writeSkeletonHierarchyDotFiles() {
2905
2906     Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
2907     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
2908       Descriptor desc = (Descriptor) iterator.next();
2909       getSkeletonHierarchyGraph(desc).writeGraph();
2910     }
2911
2912   }
2913
2914   private void debug_writeSkeletonCombinationHierarchyDotFiles() {
2915
2916     Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
2917     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
2918       Descriptor desc = (Descriptor) iterator.next();
2919       getSkeletonCombinationHierarchyGraph(desc).writeGraph();
2920     }
2921
2922   }
2923
2924   public HierarchyGraph getSimpleHierarchyGraph(Descriptor d) {
2925     return mapDescriptorToSimpleHierarchyGraph.get(d);
2926   }
2927
2928   private HierarchyGraph getSkeletonHierarchyGraph(Descriptor d) {
2929     if (!mapDescriptorToSkeletonHierarchyGraph.containsKey(d)) {
2930       mapDescriptorToSkeletonHierarchyGraph.put(d, new HierarchyGraph(d));
2931     }
2932     return mapDescriptorToSkeletonHierarchyGraph.get(d);
2933   }
2934
2935   public HierarchyGraph getSkeletonCombinationHierarchyGraph(Descriptor d) {
2936     if (!mapDescriptorToCombineSkeletonHierarchyGraph.containsKey(d)) {
2937       mapDescriptorToCombineSkeletonHierarchyGraph.put(d, new HierarchyGraph(d));
2938     }
2939     return mapDescriptorToCombineSkeletonHierarchyGraph.get(d);
2940   }
2941
2942   private void constructHierarchyGraph() {
2943
2944     LinkedList<MethodDescriptor> methodDescList =
2945         (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
2946
2947     while (!methodDescList.isEmpty()) {
2948       MethodDescriptor md = methodDescList.removeLast();
2949       if (state.SSJAVADEBUG) {
2950         HierarchyGraph hierarchyGraph = new HierarchyGraph(md);
2951         System.out.println();
2952         System.out.println("SSJAVA: Construcing the hierarchy graph from " + md);
2953         constructHierarchyGraph(md, hierarchyGraph);
2954         mapDescriptorToHierarchyGraph.put(md, hierarchyGraph);
2955
2956       }
2957     }
2958
2959     setupToAnalyze();
2960     while (!toAnalyzeIsEmpty()) {
2961       ClassDescriptor cd = toAnalyzeNext();
2962       HierarchyGraph graph = getHierarchyGraph(cd);
2963       for (Iterator iter = cd.getFields(); iter.hasNext();) {
2964         FieldDescriptor fieldDesc = (FieldDescriptor) iter.next();
2965         if (!(fieldDesc.isStatic() && fieldDesc.isFinal())) {
2966           graph.getHNode(fieldDesc);
2967         }
2968       }
2969     }
2970
2971     Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
2972     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
2973       Descriptor key = (Descriptor) iterator.next();
2974       HierarchyGraph graph = getHierarchyGraph(key);
2975
2976       Set<HNode> nodeToBeConnected = new HashSet<HNode>();
2977       for (Iterator iterator2 = graph.getNodeSet().iterator(); iterator2.hasNext();) {
2978         HNode node = (HNode) iterator2.next();
2979         if (!node.isSkeleton() && !node.isCombinationNode()) {
2980           if (graph.getIncomingNodeSet(node).size() == 0) {
2981             nodeToBeConnected.add(node);
2982           }
2983         }
2984       }
2985
2986       for (Iterator iterator2 = nodeToBeConnected.iterator(); iterator2.hasNext();) {
2987         HNode node = (HNode) iterator2.next();
2988         // System.out.println("NEED TO BE CONNECTED TO TOP=" + node);
2989         graph.addEdge(graph.getHNode(TOPDESC), node);
2990       }
2991
2992     }
2993
2994   }
2995
2996   private void constructHierarchyGraph2() {
2997
2998     // do fixed-point analysis
2999
3000     LinkedList<MethodDescriptor> descriptorListToAnalyze = ssjava.getSortedDescriptors();
3001
3002     // Collections.sort(descriptorListToAnalyze, new
3003     // Comparator<MethodDescriptor>() {
3004     // public int compare(MethodDescriptor o1, MethodDescriptor o2) {
3005     // return o1.getSymbol().compareToIgnoreCase(o2.getSymbol());
3006     // }
3007     // });
3008
3009     // current descriptors to visit in fixed-point interprocedural analysis,
3010     // prioritized by dependency in the call graph
3011     methodDescriptorsToVisitStack.clear();
3012
3013     Set<MethodDescriptor> methodDescriptorToVistSet = new HashSet<MethodDescriptor>();
3014     methodDescriptorToVistSet.addAll(descriptorListToAnalyze);
3015
3016     while (!descriptorListToAnalyze.isEmpty()) {
3017       MethodDescriptor md = descriptorListToAnalyze.removeFirst();
3018       methodDescriptorsToVisitStack.add(md);
3019     }
3020
3021     // analyze scheduled methods until there are no more to visit
3022     while (!methodDescriptorsToVisitStack.isEmpty()) {
3023       // start to analyze leaf node
3024       MethodDescriptor md = methodDescriptorsToVisitStack.pop();
3025
3026       HierarchyGraph hierarchyGraph = new HierarchyGraph(md);
3027       // MethodSummary methodSummary = new MethodSummary(md);
3028
3029       // MethodLocationInfo methodInfo = new MethodLocationInfo(md);
3030       // curMethodInfo = methodInfo;
3031
3032       System.out.println();
3033       System.out.println("SSJAVA: Construcing the hierarchy graph from " + md);
3034
3035       constructHierarchyGraph(md, hierarchyGraph);
3036
3037       HierarchyGraph prevHierarchyGraph = getHierarchyGraph(md);
3038       // MethodSummary prevMethodSummary = getMethodSummary(md);
3039
3040       if (!hierarchyGraph.equals(prevHierarchyGraph)) {
3041
3042         mapDescriptorToHierarchyGraph.put(md, hierarchyGraph);
3043         // mapDescToLocationSummary.put(md, methodSummary);
3044
3045         // results for callee changed, so enqueue dependents caller for
3046         // further analysis
3047         Iterator<MethodDescriptor> depsItr = ssjava.getDependents(md).iterator();
3048         while (depsItr.hasNext()) {
3049           MethodDescriptor methodNext = depsItr.next();
3050           if (!methodDescriptorsToVisitStack.contains(methodNext)
3051               && methodDescriptorToVistSet.contains(methodNext)) {
3052             methodDescriptorsToVisitStack.add(methodNext);
3053           }
3054         }
3055
3056       }
3057
3058     }
3059
3060     setupToAnalyze();
3061     while (!toAnalyzeIsEmpty()) {
3062       ClassDescriptor cd = toAnalyzeNext();
3063       HierarchyGraph graph = getHierarchyGraph(cd);
3064       for (Iterator iter = cd.getFields(); iter.hasNext();) {
3065         FieldDescriptor fieldDesc = (FieldDescriptor) iter.next();
3066         if (!(fieldDesc.isStatic() && fieldDesc.isFinal())) {
3067           graph.getHNode(fieldDesc);
3068         }
3069       }
3070     }
3071
3072     Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
3073     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
3074       Descriptor key = (Descriptor) iterator.next();
3075       HierarchyGraph graph = getHierarchyGraph(key);
3076
3077       Set<HNode> nodeToBeConnected = new HashSet<HNode>();
3078       for (Iterator iterator2 = graph.getNodeSet().iterator(); iterator2.hasNext();) {
3079         HNode node = (HNode) iterator2.next();
3080         if (!node.isSkeleton() && !node.isCombinationNode()) {
3081           if (graph.getIncomingNodeSet(node).size() == 0) {
3082             nodeToBeConnected.add(node);
3083           }
3084         }
3085       }
3086
3087       for (Iterator iterator2 = nodeToBeConnected.iterator(); iterator2.hasNext();) {
3088         HNode node = (HNode) iterator2.next();
3089         // System.out.println("NEED TO BE CONNECTED TO TOP=" + node);
3090         graph.addEdge(graph.getHNode(TOPDESC), node);
3091       }
3092
3093     }
3094
3095   }
3096
3097   private HierarchyGraph getHierarchyGraph(Descriptor d) {
3098     if (!mapDescriptorToHierarchyGraph.containsKey(d)) {
3099       mapDescriptorToHierarchyGraph.put(d, new HierarchyGraph(d));
3100     }
3101     return mapDescriptorToHierarchyGraph.get(d);
3102   }
3103
3104   private void constructHierarchyGraph(MethodDescriptor md, HierarchyGraph methodGraph) {
3105
3106     // visit each node of method flow graph
3107     FlowGraph fg = getFlowGraph(md);
3108     // Set<FlowNode> nodeSet = fg.getNodeSet();
3109
3110     Set<FlowEdge> edgeSet = fg.getEdgeSet();
3111
3112     Set<Descriptor> paramDescSet = fg.getMapParamDescToIdx().keySet();
3113     for (Iterator iterator = paramDescSet.iterator(); iterator.hasNext();) {
3114       Descriptor desc = (Descriptor) iterator.next();
3115       methodGraph.getHNode(desc).setSkeleton(true);
3116     }
3117
3118     // for the method lattice, we need to look at the first element of
3119     // NTuple<Descriptor>
3120     boolean hasGlobalAccess = false;
3121     // for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
3122     // FlowNode originalSrcNode = (FlowNode) iterator.next();
3123     for (Iterator iterator = edgeSet.iterator(); iterator.hasNext();) {
3124       FlowEdge edge = (FlowEdge) iterator.next();
3125
3126       FlowNode originalSrcNode = fg.getFlowNode(edge.getInitTuple());
3127       Set<FlowNode> sourceNodeSet = new HashSet<FlowNode>();
3128       if (originalSrcNode instanceof FlowReturnNode) {
3129         FlowReturnNode rnode = (FlowReturnNode) originalSrcNode;
3130         // System.out.println("rnode=" + rnode);
3131         Set<NTuple<Descriptor>> tupleSet = rnode.getReturnTupleSet();
3132         for (Iterator iterator2 = tupleSet.iterator(); iterator2.hasNext();) {
3133           NTuple<Descriptor> nTuple = (NTuple<Descriptor>) iterator2.next();
3134           sourceNodeSet.add(fg.getFlowNode(nTuple));
3135           // System.out.println("&&&SOURCE fg.getFlowNode(nTuple)=" + fg.getFlowNode(nTuple));
3136         }
3137       } else {
3138         sourceNodeSet.add(originalSrcNode);
3139       }
3140
3141       // System.out.println("---sourceNodeSet=" + sourceNodeSet + "  from originalSrcNode="
3142       // + originalSrcNode);
3143
3144       for (Iterator iterator3 = sourceNodeSet.iterator(); iterator3.hasNext();) {
3145         FlowNode srcNode = (FlowNode) iterator3.next();
3146
3147         NTuple<Descriptor> srcNodeTuple = srcNode.getDescTuple();
3148         Descriptor srcLocalDesc = srcNodeTuple.get(0);
3149
3150         if (srcLocalDesc instanceof InterDescriptor
3151             && ((InterDescriptor) srcLocalDesc).getMethodArgIdxPair() != null) {
3152
3153           if (srcNode.getCompositeLocation() == null) {
3154             continue;
3155           }
3156         }
3157
3158         // if the srcNode is started with the global descriptor
3159         // need to set as a skeleton node
3160         if (!hasGlobalAccess && srcNode.getDescTuple().startsWith(GLOBALDESC)) {
3161           hasGlobalAccess = true;
3162         }
3163
3164         // Set<FlowEdge> outEdgeSet = fg.getOutEdgeSet(originalSrcNode);
3165         // for (Iterator iterator2 = outEdgeSet.iterator(); iterator2.hasNext();) {
3166         // FlowEdge outEdge = (FlowEdge) iterator2.next();
3167         // FlowNode originalDstNode = outEdge.getDst();
3168         FlowNode originalDstNode = fg.getFlowNode(edge.getEndTuple());
3169
3170         Set<FlowNode> dstNodeSet = new HashSet<FlowNode>();
3171         if (originalDstNode instanceof FlowReturnNode) {
3172           FlowReturnNode rnode = (FlowReturnNode) originalDstNode;
3173           // System.out.println("\n-returnNode=" + rnode);
3174           Set<NTuple<Descriptor>> tupleSet = rnode.getReturnTupleSet();
3175           for (Iterator iterator4 = tupleSet.iterator(); iterator4.hasNext();) {
3176             NTuple<Descriptor> nTuple = (NTuple<Descriptor>) iterator4.next();
3177             dstNodeSet.add(fg.getFlowNode(nTuple));
3178             // System.out.println("&&&DST fg.getFlowNode(nTuple)=" + fg.getFlowNode(nTuple));
3179           }
3180         } else {
3181           dstNodeSet.add(originalDstNode);
3182         }
3183         // System.out.println("---dstNodeSet=" + dstNodeSet);
3184         for (Iterator iterator4 = dstNodeSet.iterator(); iterator4.hasNext();) {
3185           FlowNode dstNode = (FlowNode) iterator4.next();
3186
3187           NTuple<Descriptor> dstNodeTuple = dstNode.getDescTuple();
3188           Descriptor dstLocalDesc = dstNodeTuple.get(0);
3189
3190           if (dstLocalDesc instanceof InterDescriptor
3191               && ((InterDescriptor) dstLocalDesc).getMethodArgIdxPair() != null) {
3192             if (dstNode.getCompositeLocation() == null) {
3193               // System.out.println("%%%%%%%%%%%%%SKIP=" + dstNode);
3194               continue;
3195             }
3196           }
3197
3198           // if (outEdge.getInitTuple().equals(srcNodeTuple)
3199           // && outEdge.getEndTuple().equals(dstNodeTuple)) {
3200
3201           NTuple<Descriptor> srcCurTuple = srcNode.getCurrentDescTuple();
3202           NTuple<Descriptor> dstCurTuple = dstNode.getCurrentDescTuple();
3203
3204           // //////////////////////////
3205           // inheritance check
3206           if (mapMethodDescToHighestOverriddenMethodDesc.containsKey(md)) {
3207
3208             MethodDescriptor highestOverriddenMethodDesc =
3209                 mapMethodDescToHighestOverriddenMethodDesc.get(md);
3210
3211             if (srcCurTuple.get(srcCurTuple.size() - 1).getSymbol().startsWith(PCLOC)) {
3212             }
3213
3214           }
3215           // //////////////////////////
3216
3217           // System.out.println("-srcCurTuple=" + srcCurTuple + "  dstCurTuple=" + dstCurTuple
3218           // + "  srcNode=" + srcNode + "   dstNode=" + dstNode);
3219
3220           // srcCurTuple = translateBaseTuple(srcNode, srcCurTuple);
3221           // dstCurTuple = translateBaseTuple(dstNode, dstCurTuple);
3222
3223           if ((srcCurTuple.size() > 1 && dstCurTuple.size() > 1)
3224               && srcCurTuple.get(0).equals(dstCurTuple.get(0))) {
3225
3226             // value flows between fields
3227             Descriptor desc = srcCurTuple.get(0);
3228             ClassDescriptor classDesc;
3229
3230             if (desc.equals(GLOBALDESC)) {
3231               classDesc = md.getClassDesc();
3232             } else {
3233               VarDescriptor varDesc = (VarDescriptor) srcCurTuple.get(0);
3234               classDesc = varDesc.getType().getClassDesc();
3235             }
3236             extractFlowsBetweenFields(classDesc, srcNode, dstNode, 1);
3237
3238           } else if ((srcCurTuple.size() == 1 && dstCurTuple.size() == 1)
3239               || ((srcCurTuple.size() > 1 || dstCurTuple.size() > 1) && !srcCurTuple.get(0).equals(
3240                   dstCurTuple.get(0)))) {
3241
3242             // value flow between a primitive local var - a primitive local var or local var -
3243             // field
3244
3245             Descriptor srcDesc = srcCurTuple.get(0);
3246             Descriptor dstDesc = dstCurTuple.get(0);
3247
3248             methodGraph.addEdge(srcDesc, dstDesc);
3249
3250             if (fg.isParamDesc(srcDesc)) {
3251               methodGraph.setParamHNode(srcDesc);
3252             }
3253             if (fg.isParamDesc(dstDesc)) {
3254               methodGraph.setParamHNode(dstDesc);
3255             }
3256
3257           }
3258
3259           // }
3260           // }
3261
3262         }
3263
3264       }
3265
3266     }
3267
3268     // If the method accesses static fields
3269     // set hasGloabalAccess true in the method summary.
3270     if (hasGlobalAccess) {
3271       getMethodSummary(md).setHasGlobalAccess();
3272     }
3273     methodGraph.getHNode(GLOBALDESC).setSkeleton(true);
3274
3275     if (ssjava.getMethodContainingSSJavaLoop().equals(md)) {
3276       // if the current method contains the event loop
3277       // we need to set all nodes of the hierarchy graph as a skeleton node
3278       Set<HNode> hnodeSet = methodGraph.getNodeSet();
3279       for (Iterator iterator = hnodeSet.iterator(); iterator.hasNext();) {
3280         HNode hnode = (HNode) iterator.next();
3281         hnode.setSkeleton(true);
3282       }
3283     }
3284
3285   }
3286
3287   private NTuple<Descriptor> translateBaseTuple(FlowNode flowNode, NTuple<Descriptor> inTuple) {
3288
3289     if (flowNode.getBaseTuple() != null) {
3290
3291       NTuple<Descriptor> translatedTuple = new NTuple<Descriptor>();
3292
3293       NTuple<Descriptor> baseTuple = flowNode.getBaseTuple();
3294
3295       for (int i = 0; i < baseTuple.size(); i++) {
3296         translatedTuple.add(baseTuple.get(i));
3297       }
3298
3299       for (int i = 1; i < inTuple.size(); i++) {
3300         translatedTuple.add(inTuple.get(i));
3301       }
3302
3303       // System.out.println("------TRANSLATED " + inTuple + " -> " + translatedTuple);
3304       return translatedTuple;
3305
3306     } else {
3307       return inTuple;
3308     }
3309
3310   }
3311
3312   private MethodSummary getMethodSummary(MethodDescriptor md) {
3313     if (!mapDescToLocationSummary.containsKey(md)) {
3314       mapDescToLocationSummary.put(md, new MethodSummary(md));
3315     }
3316     return (MethodSummary) mapDescToLocationSummary.get(md);
3317   }
3318
3319   private void addMapClassDefinitionToLineNum(ClassDescriptor cd, String strLine, int lineNum) {
3320
3321     String classSymbol = cd.getSymbol();
3322     int idx = classSymbol.lastIndexOf("$");
3323     if (idx != -1) {
3324       classSymbol = classSymbol.substring(idx + 1);
3325     }
3326
3327     String pattern = "class " + classSymbol + " ";
3328     if (strLine.indexOf(pattern) != -1) {
3329       mapDescToDefinitionLine.put(cd, lineNum);
3330     }
3331   }
3332
3333   private void addMapMethodDefinitionToLineNum(Set<MethodDescriptor> methodSet, String strLine,
3334       int lineNum) {
3335     for (Iterator iterator = methodSet.iterator(); iterator.hasNext();) {
3336       MethodDescriptor md = (MethodDescriptor) iterator.next();
3337       String pattern = md.getMethodDeclaration();
3338       if (strLine.indexOf(pattern) != -1) {
3339         mapDescToDefinitionLine.put(md, lineNum);
3340         methodSet.remove(md);
3341         return;
3342       }
3343     }
3344
3345   }
3346
3347   private void readOriginalSourceFiles() {
3348
3349     SymbolTable classtable = state.getClassSymbolTable();
3350
3351     Set<ClassDescriptor> classDescSet = new HashSet<ClassDescriptor>();
3352     classDescSet.addAll(classtable.getValueSet());
3353
3354     try {
3355       // inefficient implement. it may re-visit the same file if the file
3356       // contains more than one class definitions.
3357       for (Iterator iterator = classDescSet.iterator(); iterator.hasNext();) {
3358         ClassDescriptor cd = (ClassDescriptor) iterator.next();
3359
3360         Set<MethodDescriptor> methodSet = new HashSet<MethodDescriptor>();
3361         methodSet.addAll(cd.getMethodTable().getValueSet());
3362
3363         String sourceFileName = cd.getSourceFileName();
3364         Vector<String> lineVec = new Vector<String>();
3365
3366         mapFileNameToLineVector.put(sourceFileName, lineVec);
3367
3368         BufferedReader in = new BufferedReader(new FileReader(sourceFileName));
3369         String strLine;
3370         int lineNum = 1;
3371         lineVec.add(""); // the index is started from 1.
3372         while ((strLine = in.readLine()) != null) {
3373           lineVec.add(lineNum, strLine);
3374           addMapClassDefinitionToLineNum(cd, strLine, lineNum);
3375           addMapMethodDefinitionToLineNum(methodSet, strLine, lineNum);
3376           lineNum++;
3377         }
3378
3379       }
3380
3381     } catch (IOException e) {
3382       e.printStackTrace();
3383     }
3384
3385   }
3386
3387   private String generateLatticeDefinition(Descriptor desc) {
3388
3389     Set<String> sharedLocSet = new HashSet<String>();
3390
3391     SSJavaLattice<String> lattice = getLattice(desc);
3392     String rtr = "@LATTICE(\"";
3393
3394     Map<String, Set<String>> map = lattice.getTable();
3395     Set<String> keySet = map.keySet();
3396
3397     // System.out.println("@generateLatticeDefinition=" + desc + "      map=" + map);
3398
3399     boolean first = true;
3400     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
3401       String key = (String) iterator.next();
3402       if (!key.equals(lattice.getTopItem())) {
3403         Set<String> connectedSet = map.get(key);
3404
3405         if (connectedSet.size() == 1) {
3406           if (connectedSet.iterator().next().equals(lattice.getBottomItem())) {
3407             if (!first) {
3408               rtr += ",";
3409             } else {
3410               rtr += "LOC,";
3411               first = false;
3412             }
3413             rtr += key;
3414             if (lattice.isSharedLoc(key)) {
3415               rtr += "," + key + "*";
3416             }
3417           }
3418         }
3419
3420         for (Iterator iterator2 = connectedSet.iterator(); iterator2.hasNext();) {
3421           String loc = (String) iterator2.next();
3422           if (!loc.equals(lattice.getBottomItem())) {
3423             if (!first) {
3424               rtr += ",";
3425             } else {
3426               rtr += "LOC,";
3427               first = false;
3428             }
3429             rtr += loc + "<" + key;
3430             if (lattice.isSharedLoc(key) && (!sharedLocSet.contains(key))) {
3431               rtr += "," + key + "*";
3432               sharedLocSet.add(key);
3433             }
3434             if (lattice.isSharedLoc(loc) && (!sharedLocSet.contains(loc))) {
3435               rtr += "," + loc + "*";
3436               sharedLocSet.add(loc);
3437             }
3438
3439           }
3440         }
3441       }
3442     }
3443
3444     if (desc instanceof MethodDescriptor) {
3445       // System.out.println("#EXTRA LOC DECLARATION GEN=" + desc);
3446
3447       MethodDescriptor md = (MethodDescriptor) desc;
3448       MethodSummary methodSummary = getMethodSummary(md);
3449
3450       TypeDescriptor returnType = ((MethodDescriptor) desc).getReturnType();
3451       if (!ssjava.getMethodContainingSSJavaLoop().equals(desc) && returnType != null
3452           && (!returnType.isVoid())) {
3453         CompositeLocation returnLoc = methodSummary.getRETURNLoc();
3454         if (returnLoc.getSize() == 1) {
3455           String returnLocStr = generateLocationAnnoatation(methodSummary.getRETURNLoc());
3456           if (rtr.indexOf(returnLocStr) == -1) {
3457             rtr += "," + returnLocStr;
3458           }
3459         }
3460       }
3461       rtr += "\")";
3462
3463       if (!ssjava.getMethodContainingSSJavaLoop().equals(desc)) {
3464         if (returnType != null && (!returnType.isVoid())) {
3465           rtr +=
3466               "\n@RETURNLOC(\"" + generateLocationAnnoatation(methodSummary.getRETURNLoc()) + "\")";
3467         }
3468
3469         CompositeLocation pcLoc = methodSummary.getPCLoc();
3470         if ((pcLoc != null) && (!pcLoc.get(0).isTop())) {
3471           rtr += "\n@PCLOC(\"" + generateLocationAnnoatation(pcLoc) + "\")";
3472         }
3473       }
3474
3475       if (!md.isStatic()) {
3476         rtr += "\n@THISLOC(\"" + methodSummary.getThisLocName() + "\")";
3477       }
3478       rtr += "\n@GLOBALLOC(\"" + methodSummary.getGlobalLocName() + "\")";
3479
3480     } else {
3481       rtr += "\")";
3482     }
3483
3484     return rtr;
3485   }
3486
3487   private void generateAnnoatedCode() {
3488
3489     readOriginalSourceFiles();
3490
3491     setupToAnalyze();
3492     while (!toAnalyzeIsEmpty()) {
3493       ClassDescriptor cd = toAnalyzeNext();
3494
3495       setupToAnalazeMethod(cd);
3496
3497       String sourceFileName = cd.getSourceFileName();
3498
3499       if (cd.isInterface()) {
3500         continue;
3501       }
3502
3503       int classDefLine = mapDescToDefinitionLine.get(cd);
3504       Vector<String> sourceVec = mapFileNameToLineVector.get(sourceFileName);
3505
3506       LocationSummary fieldLocSummary = getLocationSummary(cd);
3507
3508       String fieldLatticeDefStr = generateLatticeDefinition(cd);
3509       String annoatedSrc = fieldLatticeDefStr + newline + sourceVec.get(classDefLine);
3510       sourceVec.set(classDefLine, annoatedSrc);
3511
3512       // generate annotations for field declarations
3513       // Map<Descriptor, CompositeLocation> inferLocMap = fieldLocInfo.getMapDescToInferLocation();
3514       Map<String, String> mapFieldNameToLocName = fieldLocSummary.getMapHNodeNameToLocationName();
3515
3516       for (Iterator iter = cd.getFields(); iter.hasNext();) {
3517         FieldDescriptor fd = (FieldDescriptor) iter.next();
3518
3519         String locAnnotationStr;
3520         // CompositeLocation inferLoc = inferLocMap.get(fd);
3521         String locName = mapFieldNameToLocName.get(fd.getSymbol());
3522
3523         if (locName != null) {
3524           // infer loc is null if the corresponding field is static and final
3525           // locAnnotationStr = "@LOC(\"" + generateLocationAnnoatation(inferLoc) + "\")";
3526           locAnnotationStr = "@LOC(\"" + locName + "\")";
3527           int fdLineNum = fd.getLineNum();
3528           String orgFieldDeclarationStr = sourceVec.get(fdLineNum);
3529           String fieldDeclaration = fd.toString();
3530           fieldDeclaration = fieldDeclaration.substring(0, fieldDeclaration.length() - 1);
3531           String annoatedStr = locAnnotationStr + " " + orgFieldDeclarationStr;
3532           sourceVec.set(fdLineNum, annoatedStr);
3533         }
3534
3535       }
3536
3537       while (!toAnalyzeMethodIsEmpty()) {
3538         MethodDescriptor md = toAnalyzeMethodNext();
3539
3540         if (!ssjava.needTobeAnnotated(md)) {
3541           continue;
3542         }
3543
3544         SSJavaLattice<String> methodLattice = md2lattice.get(md);
3545         // System.out.println("md=" + md + " methodLattice=" + methodLattice);
3546         if (methodLattice != null) {
3547
3548           int methodDefLine = md.getLineNum();
3549
3550           // MethodLocationInfo methodLocInfo = getMethodLocationInfo(md);
3551           // Map<Descriptor, CompositeLocation> methodInferLocMap =
3552           // methodLocInfo.getMapDescToInferLocation();
3553
3554           MethodSummary methodSummary = getMethodSummary(md);
3555
3556           Map<Descriptor, CompositeLocation> mapVarDescToInferLoc =
3557               methodSummary.getMapVarDescToInferCompositeLocation();
3558           // System.out.println("-----md=" + md + " methodDefLine=" + methodDefLine);
3559           // System.out.println("-----mapVarDescToInferLoc=" + mapVarDescToInferLoc);
3560
3561           Set<Descriptor> localVarDescSet = mapVarDescToInferLoc.keySet();
3562
3563           Set<String> localLocElementSet = methodLattice.getElementSet();
3564
3565           for (Iterator iterator = localVarDescSet.iterator(); iterator.hasNext();) {
3566             Descriptor localVarDesc = (Descriptor) iterator.next();
3567             // System.out.println("-------localVarDesc=" + localVarDesc);
3568             CompositeLocation inferLoc = mapVarDescToInferLoc.get(localVarDesc);
3569
3570             String localLocIdentifier = inferLoc.get(0).getLocIdentifier();
3571             if (!localLocElementSet.contains(localLocIdentifier)) {
3572               methodLattice.put(localLocIdentifier);
3573             }
3574
3575             String locAnnotationStr = "@LOC(\"" + generateLocationAnnoatation(inferLoc) + "\")";
3576
3577             if (!isParameter(md, localVarDesc)) {
3578               if (mapDescToDefinitionLine.containsKey(localVarDesc)) {
3579                 int varLineNum = mapDescToDefinitionLine.get(localVarDesc);
3580                 String orgSourceLine = sourceVec.get(varLineNum);
3581                 // System.out.println("varLineNum=" + varLineNum + "  org src=" + orgSourceLine);
3582                 int idx =
3583                     orgSourceLine.indexOf(generateVarDeclaration((VarDescriptor) localVarDesc));
3584                 // System.out.println("idx=" + idx
3585                 // + "  generateVarDeclaration((VarDescriptor) localVarDesc)="
3586                 // + generateVarDeclaration((VarDescriptor) localVarDesc));
3587                 assert (idx != -1);
3588                 String annoatedStr =
3589                     orgSourceLine.substring(0, idx) + locAnnotationStr + " "
3590                         + orgSourceLine.substring(idx);
3591                 sourceVec.set(varLineNum, annoatedStr);
3592               }
3593             } else {
3594               String methodDefStr = sourceVec.get(methodDefLine);
3595
3596               int idx =
3597                   getParamLocation(methodDefStr,
3598                       generateVarDeclaration((VarDescriptor) localVarDesc));
3599               // System.out.println("methodDefStr=" + methodDefStr + " localVarDesc=" + localVarDesc
3600               // + " idx=" + idx);
3601               assert (idx != -1);
3602
3603               String annoatedStr =
3604                   methodDefStr.substring(0, idx) + locAnnotationStr + " "
3605                       + methodDefStr.substring(idx);
3606               sourceVec.set(methodDefLine, annoatedStr);
3607             }
3608
3609           }
3610
3611           // check if the lattice has to have the location type for the this
3612           // reference...
3613
3614           // boolean needToAddthisRef = hasThisReference(md);
3615           // if (localLocElementSet.contains("this")) {
3616           // methodLattice.put("this");
3617           // }
3618
3619           String methodLatticeDefStr = generateLatticeDefinition(md);
3620           String annoatedStr = methodLatticeDefStr + newline + sourceVec.get(methodDefLine);
3621           sourceVec.set(methodDefLine, annoatedStr);
3622
3623         }
3624       }
3625
3626     }
3627
3628     codeGen();
3629   }
3630
3631   private boolean hasThisReference(MethodDescriptor md) {
3632
3633     FlowGraph fg = getFlowGraph(md);
3634     Set<FlowNode> nodeSet = fg.getNodeSet();
3635     for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
3636       FlowNode flowNode = (FlowNode) iterator.next();
3637       if (flowNode.getDescTuple().get(0).equals(md.getThis())) {
3638         return true;
3639       }
3640     }
3641
3642     return false;
3643   }
3644
3645   private int getParamLocation(String methodStr, String paramStr) {
3646
3647     String pattern = paramStr + ",";
3648
3649     int idx = methodStr.indexOf(pattern);
3650     if (idx != -1) {
3651       return idx;
3652     } else {
3653       pattern = paramStr + ")";
3654       return methodStr.indexOf(pattern);
3655     }
3656
3657   }
3658
3659   private String generateVarDeclaration(VarDescriptor varDesc) {
3660
3661     TypeDescriptor td = varDesc.getType();
3662     String rtr = td.toString();
3663     if (td.isArray()) {
3664       for (int i = 0; i < td.getArrayCount(); i++) {
3665         rtr += "[]";
3666       }
3667     }
3668     rtr += " " + varDesc.getName();
3669     return rtr;
3670
3671   }
3672
3673   private String generateLocationAnnoatation(CompositeLocation loc) {
3674     String rtr = "";
3675     // method location
3676     Location methodLoc = loc.get(0);
3677     rtr += methodLoc.getLocIdentifier();
3678
3679     for (int i = 1; i < loc.getSize(); i++) {
3680       Location element = loc.get(i);
3681       rtr += "," + element.getDescriptor().getSymbol() + "." + element.getLocIdentifier();
3682     }
3683
3684     return rtr;
3685   }
3686
3687   private boolean isParameter(MethodDescriptor md, Descriptor localVarDesc) {
3688     return getFlowGraph(md).isParamDesc(localVarDesc);
3689   }
3690
3691   private String extractFileName(String fileName) {
3692     int idx = fileName.lastIndexOf("/");
3693     if (idx == -1) {
3694       return fileName;
3695     } else {
3696       return fileName.substring(idx + 1);
3697     }
3698
3699   }
3700
3701   private void codeGen() {
3702
3703     Set<String> originalFileNameSet = mapFileNameToLineVector.keySet();
3704     for (Iterator iterator = originalFileNameSet.iterator(); iterator.hasNext();) {
3705       String orgFileName = (String) iterator.next();
3706       String outputFileName = extractFileName(orgFileName);
3707
3708       Vector<String> sourceVec = mapFileNameToLineVector.get(orgFileName);
3709
3710       try {
3711
3712         FileWriter fileWriter = new FileWriter("./infer/" + outputFileName);
3713         BufferedWriter out = new BufferedWriter(fileWriter);
3714
3715         for (int i = 0; i < sourceVec.size(); i++) {
3716           out.write(sourceVec.get(i));
3717           out.newLine();
3718         }
3719         out.close();
3720       } catch (IOException e) {
3721         e.printStackTrace();
3722       }
3723
3724     }
3725
3726   }
3727
3728   private void checkLattices() {
3729
3730     LinkedList<MethodDescriptor> descriptorListToAnalyze = ssjava.getSortedDescriptors();
3731
3732     // current descriptors to visit in fixed-point interprocedural analysis,
3733     // prioritized by
3734     // dependency in the call graph
3735     methodDescriptorsToVisitStack.clear();
3736
3737     // descriptorListToAnalyze.removeFirst();
3738
3739     Set<MethodDescriptor> methodDescriptorToVistSet = new HashSet<MethodDescriptor>();
3740     methodDescriptorToVistSet.addAll(descriptorListToAnalyze);
3741
3742     while (!descriptorListToAnalyze.isEmpty()) {
3743       MethodDescriptor md = descriptorListToAnalyze.removeFirst();
3744       checkLatticesOfVirtualMethods(md);
3745     }
3746
3747   }
3748
3749   private void debug_writeLatticeDotFile() {
3750     // generate lattice dot file
3751
3752     setupToAnalyze();
3753
3754     while (!toAnalyzeIsEmpty()) {
3755       ClassDescriptor cd = toAnalyzeNext();
3756
3757       setupToAnalazeMethod(cd);
3758
3759       SSJavaLattice<String> classLattice = cd2lattice.get(cd);
3760       if (classLattice != null) {
3761         ssjava.writeLatticeDotFile(cd, null, classLattice);
3762         // debug_printDescriptorToLocNameMapping(cd);
3763       }
3764
3765       while (!toAnalyzeMethodIsEmpty()) {
3766         MethodDescriptor md = toAnalyzeMethodNext();
3767         SSJavaLattice<String> methodLattice = md2lattice.get(md);
3768         if (methodLattice != null) {
3769           ssjava.writeLatticeDotFile(cd, md, methodLattice);
3770           // debug_printDescriptorToLocNameMapping(md);
3771         }
3772       }
3773     }
3774
3775   }
3776
3777   private void debug_printDescriptorToLocNameMapping(Descriptor desc) {
3778
3779     LocationInfo info = getLocationInfo(desc);
3780     System.out.println("## " + desc + " ##");
3781     System.out.println(info.getMapDescToInferLocation());
3782     LocationInfo locInfo = getLocationInfo(desc);
3783     System.out.println("mapping=" + locInfo.getMapLocSymbolToDescSet());
3784     System.out.println("###################");
3785
3786   }
3787
3788   private void calculateExtraLocations() {
3789
3790     // LinkedList<MethodDescriptor> methodDescList = ssjava.getSortedDescriptors();
3791     LinkedList<MethodDescriptor> methodDescList =
3792         (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
3793     for (Iterator iterator = methodDescList.iterator(); iterator.hasNext();) {
3794       MethodDescriptor md = (MethodDescriptor) iterator.next();
3795       if (!ssjava.getMethodContainingSSJavaLoop().equals(md)) {
3796         calculateExtraLocations(md);
3797       }
3798     }
3799
3800   }
3801
3802   private void checkLatticesOfVirtualMethods(MethodDescriptor md) {
3803
3804     if (!md.isStatic()) {
3805       Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
3806       setPossibleCallees.addAll(ssjava.getCallGraph().getMethods(md));
3807
3808       for (Iterator iterator = setPossibleCallees.iterator(); iterator.hasNext();) {
3809         MethodDescriptor mdCallee = (MethodDescriptor) iterator.next();
3810         if (!md.equals(mdCallee)) {
3811           checkConsistency(md, mdCallee);
3812         }
3813       }
3814
3815     }
3816
3817   }
3818
3819   private void checkConsistency(MethodDescriptor md1, MethodDescriptor md2) {
3820
3821     // check that two lattice have the same relations between parameters(+PC
3822     // LOC, GLOBAL_LOC RETURN LOC)
3823
3824     List<CompositeLocation> list1 = new ArrayList<CompositeLocation>();
3825     List<CompositeLocation> list2 = new ArrayList<CompositeLocation>();
3826
3827     MethodLocationInfo locInfo1 = getMethodLocationInfo(md1);
3828     MethodLocationInfo locInfo2 = getMethodLocationInfo(md2);
3829
3830     Map<Integer, CompositeLocation> paramMap1 = locInfo1.getMapParamIdxToInferLoc();
3831     Map<Integer, CompositeLocation> paramMap2 = locInfo2.getMapParamIdxToInferLoc();
3832
3833     int numParam = locInfo1.getMapParamIdxToInferLoc().keySet().size();
3834
3835     // add location types of paramters
3836     for (int idx = 0; idx < numParam; idx++) {
3837       list1.add(paramMap1.get(Integer.valueOf(idx)));
3838       list2.add(paramMap2.get(Integer.valueOf(idx)));
3839     }
3840
3841     // add program counter location
3842     list1.add(locInfo1.getPCLoc());
3843     list2.add(locInfo2.getPCLoc());
3844
3845     if (!md1.getReturnType().isVoid()) {
3846       // add return value location
3847       CompositeLocation rtrLoc1 = getMethodLocationInfo(md1).getReturnLoc();
3848       CompositeLocation rtrLoc2 = getMethodLocationInfo(md2).getReturnLoc();
3849       list1.add(rtrLoc1);
3850       list2.add(rtrLoc2);
3851     }
3852
3853     // add global location type
3854     if (md1.isStatic()) {
3855       CompositeLocation globalLoc1 =
3856           new CompositeLocation(new Location(md1, locInfo1.getGlobalLocName()));
3857       CompositeLocation globalLoc2 =
3858           new CompositeLocation(new Location(md2, locInfo2.getGlobalLocName()));
3859       list1.add(globalLoc1);
3860       list2.add(globalLoc2);
3861     }
3862
3863     for (int i = 0; i < list1.size(); i++) {
3864       CompositeLocation locA1 = list1.get(i);
3865       CompositeLocation locA2 = list2.get(i);
3866       for (int k = 0; k < list1.size(); k++) {
3867         if (i != k) {
3868           CompositeLocation locB1 = list1.get(k);
3869           CompositeLocation locB2 = list2.get(k);
3870           boolean r1 = isGreaterThan(getLattice(md1), locA1, locB1);
3871
3872           boolean r2 = isGreaterThan(getLattice(md1), locA2, locB2);
3873
3874           if (r1 != r2) {
3875             throw new Error("The method " + md1 + " is not consistent with the method " + md2
3876                 + ".:: They have a different ordering relation between locations (" + locA1 + ","
3877                 + locB1 + ") and (" + locA2 + "," + locB2 + ").");
3878           }
3879         }
3880       }
3881     }
3882
3883   }
3884
3885   private String getSymbol(int idx, FlowNode node) {
3886     Descriptor desc = node.getDescTuple().get(idx);
3887     return desc.getSymbol();
3888   }
3889
3890   private Descriptor getDescriptor(int idx, FlowNode node) {
3891     Descriptor desc = node.getDescTuple().get(idx);
3892     return desc;
3893   }
3894
3895   private void calculatePCLOC(MethodDescriptor md) {
3896
3897     // System.out.println("#CalculatePCLOC");
3898     MethodSummary methodSummary = getMethodSummary(md);
3899     FlowGraph fg = getFlowGraph(md);
3900     Map<Integer, CompositeLocation> mapParamToLoc = methodSummary.getMapParamIdxToInferLoc();
3901
3902     // calculate the initial program counter location
3903     // PC location is higher than location types of parameters which has incoming flows.
3904
3905     Set<NTuple<Location>> paramLocTupleHavingInFlowSet = new HashSet<NTuple<Location>>();
3906     Set<Descriptor> paramDescNOTHavingInFlowSet = new HashSet<Descriptor>();
3907     // Set<FlowNode> paramNodeNOThavingInFlowSet = new HashSet<FlowNode>();
3908
3909     int numParams = fg.getNumParameters();
3910     for (int i = 0; i < numParams; i++) {
3911       FlowNode paramFlowNode = fg.getParamFlowNode(i);
3912       Descriptor prefix = paramFlowNode.getDescTuple().get(0);
3913       NTuple<Descriptor> paramDescTuple = paramFlowNode.getCurrentDescTuple();
3914       NTuple<Location> paramLocTuple = translateToLocTuple(md, paramDescTuple);
3915
3916       Set<FlowNode> inNodeToParamSet = fg.getIncomingNodeSetByPrefix(prefix);
3917       if (inNodeToParamSet.size() > 0) {
3918         // parameter has in-value flows
3919
3920         for (Iterator iterator = inNodeToParamSet.iterator(); iterator.hasNext();) {
3921           FlowNode inNode = (FlowNode) iterator.next();
3922           Set<FlowEdge> outEdgeSet = fg.getOutEdgeSet(inNode);
3923           for (Iterator iterator2 = outEdgeSet.iterator(); iterator2.hasNext();) {
3924             FlowEdge flowEdge = (FlowEdge) iterator2.next();
3925             if (flowEdge.getEndTuple().startsWith(prefix)) {
3926               NTuple<Location> paramLocTupleWithIncomingFlow =
3927                   translateToLocTuple(md, flowEdge.getEndTuple());
3928               paramLocTupleHavingInFlowSet.add(paramLocTupleWithIncomingFlow);
3929             }
3930           }
3931         }
3932
3933         // paramLocTupleHavingInFlowSet.add(paramLocTuple);
3934       } else {
3935         // paramNodeNOThavingInFlowSet.add(fg.getFlowNode(paramDescTuple));
3936         paramDescNOTHavingInFlowSet.add(prefix);
3937       }
3938     }
3939
3940     // System.out.println("paramLocTupleHavingInFlowSet=" + paramLocTupleHavingInFlowSet);
3941
3942     if (paramLocTupleHavingInFlowSet.size() > 0
3943         && !coversAllParamters(md, fg, paramLocTupleHavingInFlowSet)) {
3944
3945       // Here, generates a location in the method lattice that is higher than the
3946       // paramLocTupleHavingInFlowSet
3947       NTuple<Location> pcLocTuple =
3948           generateLocTupleRelativeTo(md, paramLocTupleHavingInFlowSet, PCLOC);
3949
3950       NTuple<Descriptor> pcDescTuple = translateToDescTuple(pcLocTuple);
3951
3952       // System.out.println("pcLoc=" + pcLocTuple);
3953
3954       CompositeLocation curPCLoc = methodSummary.getPCLoc();
3955       if (curPCLoc.get(0).isTop() || pcLocTuple.size() > curPCLoc.getSize()) {
3956         methodSummary.setPCLoc(new CompositeLocation(pcLocTuple));
3957
3958         Set<FlowNode> flowNodeLowerthanPCLocSet = new HashSet<FlowNode>();
3959         GlobalFlowGraph subGlobalFlowGraph = getSubGlobalFlowGraph(md);
3960         // add ordering relations s.t. PCLOC is higher than all flow nodes except the set of
3961         // parameters that do not have incoming flows
3962         for (Iterator iterator = fg.getNodeSet().iterator(); iterator.hasNext();) {
3963           FlowNode node = (FlowNode) iterator.next();
3964
3965           if (!(node instanceof FlowReturnNode)) {
3966             if (!paramDescNOTHavingInFlowSet.contains(node.getCurrentDescTuple().get(0))) {
3967               flowNodeLowerthanPCLocSet.add(node);
3968               fg.addValueFlowEdge(pcDescTuple, node.getDescTuple());
3969
3970               subGlobalFlowGraph.addValueFlowEdge(pcLocTuple,
3971                   translateToLocTuple(md, node.getDescTuple()));
3972             }
3973           } else {
3974             // System.out.println("***SKIP PCLOC -> RETURNLOC=" + node);
3975           }
3976
3977         }
3978         fg.getFlowNode(translateToDescTuple(pcLocTuple)).setSkeleton(true);
3979
3980         if (pcLocTuple.get(0).getLocDescriptor().equals(md.getThis())) {
3981           for (Iterator iterator = flowNodeLowerthanPCLocSet.iterator(); iterator.hasNext();) {
3982             FlowNode lowerNode = (FlowNode) iterator.next();
3983             if (lowerNode.getDescTuple().size() == 1 && lowerNode.getCompositeLocation() == null) {
3984               NTuple<Location> lowerLocTuple = translateToLocTuple(md, lowerNode.getDescTuple());
3985               CompositeLocation newComp =
3986                   calculateCompositeLocationFromSubGlobalGraph(md, lowerNode);
3987               if (newComp != null) {
3988                 subGlobalFlowGraph.addMapLocationToInferCompositeLocation(lowerLocTuple.get(0),
3989                     newComp);
3990                 lowerNode.setCompositeLocation(newComp);
3991                 // System.out.println("NEW COMP LOC=" + newComp + "    to lowerNode=" + lowerNode);
3992               }
3993
3994             }
3995
3996           }
3997         }
3998
3999       }
4000
4001     }
4002   }
4003
4004   private int countFirstDescriptorSetSize(Set<NTuple<Location>> set) {
4005
4006     Set<Descriptor> descSet = new HashSet<Descriptor>();
4007
4008     for (Iterator iterator = set.iterator(); iterator.hasNext();) {
4009       NTuple<Location> locTuple = (NTuple<Location>) iterator.next();
4010       descSet.add(locTuple.get(0).getLocDescriptor());
4011     }
4012
4013     return descSet.size();
4014   }
4015
4016   private boolean coversAllParamters(MethodDescriptor md, FlowGraph fg,
4017       Set<NTuple<Location>> paramLocTupleHavingInFlowSet) {
4018
4019     int numParam = fg.getNumParameters();
4020     // int size = paramLocTupleHavingInFlowSet.size();
4021     int size = countFirstDescriptorSetSize(paramLocTupleHavingInFlowSet);
4022
4023     // System.out.println("numParam=" + numParam + "     size=" + size);
4024
4025     // if (!md.isStatic()) {
4026     //
4027     // // if the method is not static && there is a parameter composite location &&
4028     // // it is started with 'this',
4029     // // paramLocTupleHavingInFlowSet need to have 'this' parameter.
4030     //
4031     // FlowNode thisParamNode = fg.getParamFlowNode(0);
4032     // NTuple<Location> thisParamLocTuple =
4033     // translateToLocTuple(md, thisParamNode.getCurrentDescTuple());
4034     //
4035     // if (!paramLocTupleHavingInFlowSet.contains(thisParamLocTuple)) {
4036     //
4037     // for (Iterator iterator = paramLocTupleHavingInFlowSet.iterator(); iterator.hasNext();) {
4038     // NTuple<Location> paramTuple = (NTuple<Location>) iterator.next();
4039     // if (paramTuple.size() > 1 && paramTuple.get(0).getLocDescriptor().equals(md.getThis())) {
4040     // // paramLocTupleHavingInFlowSet.add(thisParamLocTuple);
4041     // // break;
4042     // size++;
4043     // }
4044     // }
4045     //
4046     // }
4047     // }
4048
4049     if (size == numParam) {
4050       return true;
4051     } else {
4052       return false;
4053     }
4054
4055   }
4056
4057   private void calculateRETURNLOC(MethodDescriptor md) {
4058
4059     // System.out.println("#calculateRETURNLOC= " + md);
4060
4061     // calculate a return location:
4062     // the return location type is lower than all parameters and the location of return values
4063     MethodSummary methodSummary = getMethodSummary(md);
4064     // if (methodSummary.getRETURNLoc() != null) {
4065     // System.out.println("$HERE?");
4066     // return;
4067     // }
4068
4069     FlowGraph fg = getFlowGraph(md);
4070     Map<Integer, CompositeLocation> mapParamToLoc = methodSummary.getMapParamIdxToInferLoc();
4071     Set<Integer> paramIdxSet = mapParamToLoc.keySet();
4072
4073     if (md.getReturnType() != null && !md.getReturnType().isVoid()) {
4074       // first, generate the set of return value location types that starts
4075       // with 'this' reference
4076
4077       Set<FlowNode> paramFlowNodeFlowingToReturnValueSet = getParamNodeFlowingToReturnValue(md);
4078       // System.out.println("paramFlowNodeFlowingToReturnValueSet="
4079       // + paramFlowNodeFlowingToReturnValueSet);
4080
4081       Set<NTuple<Location>> tupleToBeHigherThanReturnLocSet = new HashSet<NTuple<Location>>();
4082       for (Iterator iterator = paramFlowNodeFlowingToReturnValueSet.iterator(); iterator.hasNext();) {
4083         FlowNode fn = (FlowNode) iterator.next();
4084         NTuple<Descriptor> paramDescTuple = fn.getCurrentDescTuple();
4085         tupleToBeHigherThanReturnLocSet.add(translateToLocTuple(md, paramDescTuple));
4086       }
4087
4088       Set<FlowNode> returnNodeSet = fg.getReturnNodeSet();
4089       for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
4090         FlowNode returnNode = (FlowNode) iterator.next();
4091         NTuple<Descriptor> returnDescTuple = returnNode.getCurrentDescTuple();
4092         tupleToBeHigherThanReturnLocSet.add(translateToLocTuple(md, returnDescTuple));
4093       }
4094       // System.out.println("-flow graph's returnNodeSet=" + returnNodeSet);
4095       // System.out.println("tupleSetToBeHigherThanReturnLoc=" + tupleToBeHigherThanReturnLocSet);
4096
4097       // Here, generates a return location in the method lattice that is lower than the
4098       // locFlowingToReturnValueSet
4099       NTuple<Location> returnLocTuple =
4100           generateLocTupleRelativeTo(md, tupleToBeHigherThanReturnLocSet, RLOC);
4101
4102       // System.out.println("returnLocTuple=" + returnLocTuple);
4103       NTuple<Descriptor> returnDescTuple = translateToDescTuple(returnLocTuple);
4104       CompositeLocation curReturnLoc = methodSummary.getRETURNLoc();
4105       if (curReturnLoc == null || returnDescTuple.size() > curReturnLoc.getSize()) {
4106         methodSummary.setRETURNLoc(new CompositeLocation(returnLocTuple));
4107
4108         for (Iterator iterator = tupleToBeHigherThanReturnLocSet.iterator(); iterator.hasNext();) {
4109           NTuple<Location> higherTuple = (NTuple<Location>) iterator.next();
4110           fg.addValueFlowEdge(translateToDescTuple(higherTuple), returnDescTuple);
4111         }
4112         fg.getFlowNode(returnDescTuple).setSkeleton(true);
4113
4114       }
4115
4116       // makes sure that PCLOC is higher than RETURNLOC
4117       CompositeLocation pcLoc = methodSummary.getPCLoc();
4118       if (!pcLoc.get(0).isTop()) {
4119         NTuple<Descriptor> pcLocDescTuple = translateToDescTuple(pcLoc.getTuple());
4120         fg.addValueFlowEdge(pcLocDescTuple, returnDescTuple);
4121       }
4122
4123     }
4124
4125   }
4126
4127   private void calculateExtraLocations(MethodDescriptor md) {
4128     // calcualte pcloc, returnloc,...
4129
4130     System.out.println("\nSSJAVA:Calculate PCLOC/RETURNLOC locations: " + md);
4131
4132     calculatePCLOC(md);
4133     calculateRETURNLOC(md);
4134
4135   }
4136
4137   private NTuple<Location> generateLocTupleRelativeTo(MethodDescriptor md,
4138       Set<NTuple<Location>> paramLocTupleHavingInFlowSet, String locNamePrefix) {
4139
4140     // System.out.println("-generateLocTupleRelativeTo=" + paramLocTupleHavingInFlowSet);
4141
4142     NTuple<Location> higherLocTuple = new NTuple<Location>();
4143
4144     VarDescriptor thisVarDesc = md.getThis();
4145     // check if all paramter loc tuple is started with 'this' reference
4146     boolean hasParamNotStartedWithThisRef = false;
4147
4148     int minSize = 0;
4149
4150     Set<NTuple<Location>> paramLocTupleStartedWithThis = new HashSet<NTuple<Location>>();
4151
4152     next: for (Iterator iterator = paramLocTupleHavingInFlowSet.iterator(); iterator.hasNext();) {
4153       NTuple<Location> paramLocTuple = (NTuple<Location>) iterator.next();
4154       Descriptor paramLocalDesc = paramLocTuple.get(0).getLocDescriptor();
4155       if (!paramLocalDesc.equals(thisVarDesc)) {
4156
4157         Set<FlowNode> inNodeSet = getFlowGraph(md).getIncomingNodeSetByPrefix(paramLocalDesc);
4158         for (Iterator iterator2 = inNodeSet.iterator(); iterator2.hasNext();) {
4159           FlowNode flowNode = (FlowNode) iterator2.next();
4160           if (flowNode.getDescTuple().startsWith(thisVarDesc)) {
4161             // System.out.println("paramLocTuple=" + paramLocTuple + " is lower than THIS");
4162             continue next;
4163           }
4164         }
4165         hasParamNotStartedWithThisRef = true;
4166
4167       } else if (paramLocTuple.size() > 1) {
4168         paramLocTupleStartedWithThis.add(paramLocTuple);
4169         if (minSize == 0 || minSize > paramLocTuple.size()) {
4170           minSize = paramLocTuple.size();
4171         }
4172       }
4173     }
4174
4175     // System.out.println("---paramLocTupleStartedWithThis=" + paramLocTupleStartedWithThis);
4176     Descriptor enclosingDesc = md;
4177     if (hasParamNotStartedWithThisRef) {
4178       // in this case, PCLOC will be the local location
4179     } else {
4180       // all parameter is started with 'this', so PCLOC will be set relative to the composite
4181       // location started with 'this'.
4182       // for (int idx = 0; idx < minSize - 1; idx++) {
4183       for (int idx = 0; idx < 1; idx++) {
4184         Set<Descriptor> locDescSet = new HashSet<Descriptor>();
4185         Location curLoc = null;
4186         NTuple<Location> paramLocTuple = null;
4187         for (Iterator iterator = paramLocTupleStartedWithThis.iterator(); iterator.hasNext();) {
4188           paramLocTuple = (NTuple<Location>) iterator.next();
4189           // System.out.println("-----paramLocTuple=" + paramLocTuple + "  idx=" + idx);
4190           curLoc = paramLocTuple.get(idx);
4191           Descriptor locDesc = curLoc.getLocDescriptor();
4192           locDescSet.add(locDesc);
4193         }
4194         // System.out.println("-----locDescSet=" + locDescSet + " idx=" + idx);
4195         if (locDescSet.size() != 1) {
4196           break;
4197         }
4198         Location newLocElement = new Location(curLoc.getDescriptor(), curLoc.getLocDescriptor());
4199         // System.out.println("newLocElement" + newLocElement);
4200         higherLocTuple.add(newLocElement);
4201         enclosingDesc = getClassTypeDescriptor(curLoc.getLocDescriptor());
4202       }
4203
4204     }
4205
4206     String locIdentifier = locNamePrefix + (locSeed++);
4207     NameDescriptor locDesc = new NameDescriptor(locIdentifier);
4208     Location newLoc = new Location(enclosingDesc, locDesc);
4209     higherLocTuple.add(newLoc);
4210     // System.out.println("---new loc tuple=" + higherLocTuple);
4211
4212     return higherLocTuple;
4213
4214   }
4215
4216   public ClassDescriptor getClassTypeDescriptor(Descriptor in) {
4217
4218     if (in instanceof VarDescriptor) {
4219       return ((VarDescriptor) in).getType().getClassDesc();
4220     } else if (in instanceof FieldDescriptor) {
4221       return ((FieldDescriptor) in).getType().getClassDesc();
4222     }
4223     // else if (in instanceof LocationDescriptor) {
4224     // // here is the case that the descriptor 'in' is the last element of the assigned composite
4225     // // location
4226     // return ((VarDescriptor) locTuple.get(0).getLocDescriptor()).getType().getClassDesc();
4227     // }
4228     else {
4229       return null;
4230     }
4231
4232   }
4233
4234   private Set<NTuple<Location>> calculateHighestLocTupleSet(
4235       Set<NTuple<Location>> paramLocTupleHavingInFlowSet) {
4236
4237     Set<NTuple<Location>> highestSet = new HashSet<NTuple<Location>>();
4238
4239     Iterator<NTuple<Location>> iterator = paramLocTupleHavingInFlowSet.iterator();
4240     NTuple<Location> highest = iterator.next();
4241
4242     for (; iterator.hasNext();) {
4243       NTuple<Location> curLocTuple = (NTuple<Location>) iterator.next();
4244       if (isHigherThan(curLocTuple, highest)) {
4245         // System.out.println(curLocTuple + " is greater than " + highest);
4246         highest = curLocTuple;
4247       }
4248     }
4249
4250     highestSet.add(highest);
4251
4252     MethodDescriptor md = (MethodDescriptor) highest.get(0).getDescriptor();
4253     VarDescriptor thisVarDesc = md.getThis();
4254
4255     // System.out.println("highest=" + highest);
4256
4257     for (Iterator<NTuple<Location>> iter = paramLocTupleHavingInFlowSet.iterator(); iter.hasNext();) {
4258       NTuple<Location> curLocTuple = iter.next();
4259
4260       if (!curLocTuple.equals(highest) && !hasOrderingRelation(highest, curLocTuple)) {
4261
4262         // System.out.println("add it to the highest set=" + curLocTuple);
4263         highestSet.add(curLocTuple);
4264
4265       }
4266     }
4267
4268     return highestSet;
4269
4270   }
4271
4272   private Set<String> getHigherLocSymbolThan(SSJavaLattice<String> lattice, String loc) {
4273     Set<String> higherLocSet = new HashSet<String>();
4274
4275     Set<String> locSet = lattice.getTable().keySet();
4276     for (Iterator iterator = locSet.iterator(); iterator.hasNext();) {
4277       String element = (String) iterator.next();
4278       if (lattice.isGreaterThan(element, loc) && (!element.equals(lattice.getTopItem()))) {
4279         higherLocSet.add(element);
4280       }
4281     }
4282     return higherLocSet;
4283   }
4284
4285   private CompositeLocation getLowest(SSJavaLattice<String> methodLattice,
4286       Set<CompositeLocation> set) {
4287
4288     CompositeLocation lowest = set.iterator().next();
4289
4290     if (set.size() == 1) {
4291       return lowest;
4292     }
4293
4294     for (Iterator iterator = set.iterator(); iterator.hasNext();) {
4295       CompositeLocation loc = (CompositeLocation) iterator.next();
4296
4297       if ((!loc.equals(lowest)) && (!isComparable(methodLattice, lowest, loc))) {
4298         // if there is a case where composite locations are incomparable, just
4299         // return null
4300         return null;
4301       }
4302
4303       if ((!loc.equals(lowest)) && isGreaterThan(methodLattice, lowest, loc)) {
4304         lowest = loc;
4305       }
4306     }
4307     return lowest;
4308   }
4309
4310   private boolean isComparable(SSJavaLattice<String> methodLattice, CompositeLocation comp1,
4311       CompositeLocation comp2) {
4312
4313     int size = comp1.getSize() >= comp2.getSize() ? comp2.getSize() : comp1.getSize();
4314
4315     for (int idx = 0; idx < size; idx++) {
4316       Location loc1 = comp1.get(idx);
4317       Location loc2 = comp2.get(idx);
4318
4319       Descriptor desc1 = loc1.getDescriptor();
4320       Descriptor desc2 = loc2.getDescriptor();
4321
4322       if (!desc1.equals(desc2)) {
4323         throw new Error("Fail to compare " + comp1 + " and " + comp2);
4324       }
4325
4326       String symbol1 = loc1.getLocIdentifier();
4327       String symbol2 = loc2.getLocIdentifier();
4328
4329       SSJavaLattice<String> lattice;
4330       if (idx == 0) {
4331         lattice = methodLattice;
4332       } else {
4333         lattice = getLattice(desc1);
4334       }
4335
4336       if (symbol1.equals(symbol2)) {
4337         continue;
4338       } else if (!lattice.isComparable(symbol1, symbol2)) {
4339         return false;
4340       }
4341
4342     }
4343
4344     return true;
4345   }
4346
4347   private boolean isGreaterThan(SSJavaLattice<String> methodLattice, CompositeLocation comp1,
4348       CompositeLocation comp2) {
4349
4350     int size = comp1.getSize() >= comp2.getSize() ? comp2.getSize() : comp1.getSize();
4351
4352     for (int idx = 0; idx < size; idx++) {
4353       Location loc1 = comp1.get(idx);
4354       Location loc2 = comp2.get(idx);
4355
4356       Descriptor desc1 = loc1.getDescriptor();
4357       Descriptor desc2 = loc2.getDescriptor();
4358
4359       if (!desc1.equals(desc2)) {
4360         throw new Error("Fail to compare " + comp1 + " and " + comp2);
4361       }
4362
4363       String symbol1 = loc1.getLocIdentifier();
4364       String symbol2 = loc2.getLocIdentifier();
4365
4366       SSJavaLattice<String> lattice;
4367       if (idx == 0) {
4368         lattice = methodLattice;
4369       } else {
4370         lattice = getLattice(desc1);
4371       }
4372
4373       if (symbol1.equals(symbol2)) {
4374         continue;
4375       } else if (lattice.isGreaterThan(symbol1, symbol2)) {
4376         return true;
4377       } else {
4378         return false;
4379       }
4380
4381     }
4382
4383     return false;
4384   }
4385
4386   private GlobalFlowGraph getSubGlobalFlowGraph(MethodDescriptor md) {
4387
4388     if (!mapMethodDescriptorToSubGlobalFlowGraph.containsKey(md)) {
4389       mapMethodDescriptorToSubGlobalFlowGraph.put(md, new GlobalFlowGraph(md));
4390     }
4391     return mapMethodDescriptorToSubGlobalFlowGraph.get(md);
4392   }
4393
4394   private void propagateFlowsToCallerWithNoCompositeLocation(MethodInvokeNode min,
4395       MethodDescriptor mdCaller, MethodDescriptor mdCallee) {
4396
4397     // System.out.println("-propagateFlowsToCallerWithNoCompositeLocation=" + min.printNode(0));
4398     // if the parameter A reaches to the parameter B
4399     // then, add an edge the argument A -> the argument B to the caller's flow
4400     // graph
4401
4402     FlowGraph calleeFlowGraph = getFlowGraph(mdCallee);
4403     FlowGraph callerFlowGraph = getFlowGraph(mdCaller);
4404     int numParam = calleeFlowGraph.getNumParameters();
4405
4406     for (int i = 0; i < numParam; i++) {
4407       for (int k = 0; k < numParam; k++) {
4408
4409         if (i != k) {
4410
4411           FlowNode paramNode1 = calleeFlowGraph.getParamFlowNode(i);
4412           FlowNode paramNode2 = calleeFlowGraph.getParamFlowNode(k);
4413
4414           NTuple<Descriptor> arg1Tuple = getNodeTupleByArgIdx(min, i);
4415           NTuple<Descriptor> arg2Tuple = getNodeTupleByArgIdx(min, k);
4416
4417           // check if the callee propagates an ordering constraints through
4418           // parameters
4419
4420           // Set<FlowNode> localReachSet = calleeFlowGraph.getLocalReachFlowNodeSetFrom(paramNode1);
4421           Set<FlowNode> localReachSet =
4422               calleeFlowGraph.getReachableSetFrom(paramNode1.getDescTuple());
4423
4424           NTuple<Descriptor> paramDescTuple1 = paramNode1.getCurrentDescTuple();
4425           NTuple<Descriptor> paramDescTuple2 = paramNode2.getCurrentDescTuple();
4426
4427           // System.out.println("-param1CurTuple=" + paramDescTuple1 + " param2CurTuple="
4428           // + paramDescTuple2);
4429           // System.out.println("-- localReachSet from param1=" + localReachSet);
4430
4431           if (paramDescTuple1.get(0).equals(paramDescTuple2.get(0))) {
4432             // if two parameters share the same prefix
4433             // it already has been assigned to a composite location
4434             // so we don't need to add an additional ordering relation caused by these two
4435             // paramters.
4436             continue;
4437           }
4438
4439           if (arg1Tuple.size() > 0 && arg2Tuple.size() > 0
4440               && containsPrefix(paramNode2.getDescTuple().get(0), localReachSet)) {
4441             // need to propagate an ordering relation s.t. arg1 is higher
4442             // than arg2
4443             // System.out.println("-param1=" + paramNode1 + " is higher than param2=" + paramNode2);
4444
4445             // add a new flow between the corresponding arguments.
4446             callerFlowGraph.addValueFlowEdge(arg1Tuple, arg2Tuple);
4447             // System.out.println("arg1=" + arg1Tuple + "   arg2=" + arg2Tuple);
4448
4449             // System.out
4450             // .println("-arg1Tuple=" + arg1Tuple + " is higher than arg2Tuple=" + arg2Tuple);
4451
4452           }
4453
4454           // System.out.println();
4455         }
4456       }
4457     }
4458
4459     // if a parameter has a composite location and the first element of the parameter location
4460     // matches the callee's 'this'
4461     // we have a more specific constraint: the caller's corresponding argument is higher than the
4462     // parameter location which is translated into the caller
4463
4464     for (int idx = 0; idx < numParam; idx++) {
4465       FlowNode paramNode = calleeFlowGraph.getParamFlowNode(idx);
4466       CompositeLocation compLoc = paramNode.getCompositeLocation();
4467       // System.out.println("paramNode=" + paramNode + "   compLoc=" + compLoc);
4468       if (compLoc != null && compLoc.get(0).getLocDescriptor().equals(min.getMethod().getThis())) {
4469         // System.out.println("$$$COMPLOC CASE=" + compLoc + "  idx=" + idx);
4470
4471         NTuple<Descriptor> argTuple = getNodeTupleByArgIdx(min, idx);
4472         // System.out.println("--- argTuple=" + argTuple + " current compLoc="
4473         // + callerFlowGraph.getFlowNode(argTuple).getCompositeLocation());
4474
4475         NTuple<Descriptor> translatedParamTuple =
4476             translateCompositeLocationToCaller(idx, min, compLoc);
4477         // System.out.println("add a flow edge= " + argTuple + "->" + translatedParamTuple);
4478         callerFlowGraph.addValueFlowEdge(argTuple, translatedParamTuple);
4479
4480         Set<NTuple<Location>> pcLocTupleSet = getPCLocTupleSet(min);
4481         for (Iterator iterator = pcLocTupleSet.iterator(); iterator.hasNext();) {
4482           NTuple<Location> pcLocTuple = (NTuple<Location>) iterator.next();
4483           callerFlowGraph.addValueFlowEdge(translateToDescTuple(pcLocTuple), translatedParamTuple);
4484         }
4485
4486       }
4487     }
4488
4489   }
4490
4491   private boolean containsPrefix(Descriptor prefixDesc, Set<FlowNode> set) {
4492
4493     for (Iterator iterator = set.iterator(); iterator.hasNext();) {
4494       FlowNode flowNode = (FlowNode) iterator.next();
4495       if (flowNode.getDescTuple().startsWith(prefixDesc)) {
4496         // System.out.println("FOUND=" + flowNode);
4497         return true;
4498       }
4499     }
4500     return false;
4501   }
4502
4503   private NTuple<Descriptor> translateCompositeLocationToCaller(int idx, MethodInvokeNode min,
4504       CompositeLocation compLocForParam1) {
4505
4506     NTuple<Descriptor> baseTuple = mapMethodInvokeNodeToBaseTuple.get(min);
4507
4508     NTuple<Descriptor> tuple = new NTuple<Descriptor>();
4509     for (int i = 0; i < baseTuple.size(); i++) {
4510       tuple.add(baseTuple.get(i));
4511     }
4512
4513     for (int i = 1; i < compLocForParam1.getSize(); i++) {
4514       Location loc = compLocForParam1.get(i);
4515       tuple.add(loc.getLocDescriptor());
4516     }
4517
4518     return tuple;
4519   }
4520
4521   private CompositeLocation generateCompositeLocation(NTuple<Location> prefixLocTuple) {
4522
4523     // System.out.println("generateCompositeLocation=" + prefixLocTuple);
4524
4525     CompositeLocation newCompLoc = new CompositeLocation();
4526     for (int i = 0; i < prefixLocTuple.size(); i++) {
4527       newCompLoc.addLocation(prefixLocTuple.get(i));
4528     }
4529
4530     Descriptor lastDescOfPrefix = prefixLocTuple.get(prefixLocTuple.size() - 1).getLocDescriptor();
4531
4532     ClassDescriptor enclosingDescriptor;
4533     if (lastDescOfPrefix instanceof FieldDescriptor) {
4534       enclosingDescriptor = ((FieldDescriptor) lastDescOfPrefix).getType().getClassDesc();
4535       // System.out.println("enclosingDescriptor0=" + enclosingDescriptor);
4536     } else if (lastDescOfPrefix.equals(GLOBALDESC)) {
4537       MethodDescriptor currentMethodDesc = (MethodDescriptor) prefixLocTuple.get(0).getDescriptor();
4538       enclosingDescriptor = currentMethodDesc.getClassDesc();
4539     } else {
4540       // var descriptor case
4541       enclosingDescriptor = ((VarDescriptor) lastDescOfPrefix).getType().getClassDesc();
4542     }
4543     // System.out.println("enclosingDescriptor=" + enclosingDescriptor);
4544
4545     LocationDescriptor newLocDescriptor = generateNewLocationDescriptor();
4546     newLocDescriptor.setEnclosingClassDesc(enclosingDescriptor);
4547
4548     Location newLoc = new Location(enclosingDescriptor, newLocDescriptor.getSymbol());
4549     newLoc.setLocDescriptor(newLocDescriptor);
4550     newCompLoc.addLocation(newLoc);
4551
4552     // System.out.println("--newCompLoc=" + newCompLoc);
4553     return newCompLoc;
4554   }
4555
4556   private CompositeLocation generateCompositeLocation(MethodDescriptor md,
4557       NTuple<Descriptor> paramPrefix) {
4558
4559     // System.out.println("generateCompositeLocation=" + paramPrefix);
4560
4561     CompositeLocation newCompLoc = convertToCompositeLocation(md, paramPrefix);
4562
4563     Descriptor lastDescOfPrefix = paramPrefix.get(paramPrefix.size() - 1);
4564     // System.out.println("lastDescOfPrefix=" + lastDescOfPrefix + "  kind="
4565     // + lastDescOfPrefix.getClass());
4566     ClassDescriptor enclosingDescriptor;
4567     if (lastDescOfPrefix instanceof FieldDescriptor) {
4568       enclosingDescriptor = ((FieldDescriptor) lastDescOfPrefix).getType().getClassDesc();
4569       // System.out.println("enclosingDescriptor0=" + enclosingDescriptor);
4570     } else {
4571       // var descriptor case
4572       enclosingDescriptor = ((VarDescriptor) lastDescOfPrefix).getType().getClassDesc();
4573     }
4574     // System.out.println("enclosingDescriptor=" + enclosingDescriptor);
4575
4576     LocationDescriptor newLocDescriptor = generateNewLocationDescriptor();
4577     newLocDescriptor.setEnclosingClassDesc(enclosingDescriptor);
4578
4579     Location newLoc = new Location(enclosingDescriptor, newLocDescriptor.getSymbol());
4580     newLoc.setLocDescriptor(newLocDescriptor);
4581     newCompLoc.addLocation(newLoc);
4582
4583     // System.out.println("--newCompLoc=" + newCompLoc);
4584     return newCompLoc;
4585   }
4586
4587   private List<NTuple<Descriptor>> translatePrefixListToCallee(Descriptor baseRef,
4588       MethodDescriptor mdCallee, List<NTuple<Descriptor>> callerPrefixList) {
4589
4590     List<NTuple<Descriptor>> calleePrefixList = new ArrayList<NTuple<Descriptor>>();
4591
4592     for (int i = 0; i < callerPrefixList.size(); i++) {
4593       NTuple<Descriptor> prefix = callerPrefixList.get(i);
4594       if (prefix.startsWith(baseRef)) {
4595         NTuple<Descriptor> calleePrefix = new NTuple<Descriptor>();
4596         calleePrefix.add(mdCallee.getThis());
4597         for (int k = 1; k < prefix.size(); k++) {
4598           calleePrefix.add(prefix.get(k));
4599         }
4600         calleePrefixList.add(calleePrefix);
4601       }
4602     }
4603
4604     return calleePrefixList;
4605
4606   }
4607
4608   public CompositeLocation convertToCompositeLocation(MethodDescriptor md, NTuple<Descriptor> tuple) {
4609
4610     CompositeLocation compLoc = new CompositeLocation();
4611
4612     Descriptor enclosingDescriptor = md;
4613
4614     for (int i = 0; i < tuple.size(); i++) {
4615       Descriptor curDescriptor = tuple.get(i);
4616       Location locElement = new Location(enclosingDescriptor, curDescriptor.getSymbol());
4617       locElement.setLocDescriptor(curDescriptor);
4618       compLoc.addLocation(locElement);
4619
4620       if (curDescriptor instanceof VarDescriptor) {
4621         enclosingDescriptor = md.getClassDesc();
4622       } else if (curDescriptor instanceof FieldDescriptor) {
4623         enclosingDescriptor = ((FieldDescriptor) curDescriptor).getClassDescriptor();
4624       } else if (curDescriptor instanceof NameDescriptor) {
4625         // it is "GLOBAL LOC" case!
4626         enclosingDescriptor = GLOBALDESC;
4627       } else if (curDescriptor instanceof InterDescriptor) {
4628         enclosingDescriptor = getFlowGraph(md).getEnclosingDescriptor(curDescriptor);
4629       } else {
4630         enclosingDescriptor = null;
4631       }
4632
4633     }
4634
4635     return compLoc;
4636   }
4637
4638   private LocationDescriptor generateNewLocationDescriptor() {
4639     return new LocationDescriptor("Loc" + (locSeed++));
4640   }
4641
4642   private int getPrefixIndex(NTuple<Descriptor> tuple1, NTuple<Descriptor> tuple2) {
4643
4644     // return the index where the prefix shared by tuple1 and tuple2 is ended
4645     // if there is no prefix shared by both of them, return -1
4646
4647     int minSize = tuple1.size();
4648     if (minSize > tuple2.size()) {
4649       minSize = tuple2.size();
4650     }
4651
4652     int idx = -1;
4653     for (int i = 0; i < minSize; i++) {
4654       if (!tuple1.get(i).equals(tuple2.get(i))) {
4655         break;
4656       } else {
4657         idx++;
4658       }
4659     }
4660
4661     return idx;
4662   }
4663
4664   private CompositeLocation generateInferredCompositeLocation(MethodLocationInfo methodInfo,
4665       NTuple<Location> tuple) {
4666
4667     // first, retrieve inferred location by the local var descriptor
4668     CompositeLocation inferLoc = new CompositeLocation();
4669
4670     CompositeLocation localVarInferLoc =
4671         methodInfo.getInferLocation(tuple.get(0).getLocDescriptor());
4672
4673     localVarInferLoc.get(0).setLocDescriptor(tuple.get(0).getLocDescriptor());
4674
4675     for (int i = 0; i < localVarInferLoc.getSize(); i++) {
4676       inferLoc.addLocation(localVarInferLoc.get(i));
4677     }
4678
4679     for (int i = 1; i < tuple.size(); i++) {
4680       Location cur = tuple.get(i);
4681       Descriptor enclosingDesc = cur.getDescriptor();
4682       Descriptor curDesc = cur.getLocDescriptor();
4683
4684       Location inferLocElement;
4685       if (curDesc == null) {
4686         // in this case, we have a newly generated location.
4687         inferLocElement = new Location(enclosingDesc, cur.getLocIdentifier());
4688       } else {
4689         String fieldLocSymbol =
4690             getLocationInfo(enclosingDesc).getInferLocation(curDesc).get(0).getLocIdentifier();
4691         inferLocElement = new Location(enclosingDesc, fieldLocSymbol);
4692         inferLocElement.setLocDescriptor(curDesc);
4693       }
4694
4695       inferLoc.addLocation(inferLocElement);
4696
4697     }
4698
4699     assert (inferLoc.get(0).getLocDescriptor().getSymbol() == inferLoc.get(0).getLocIdentifier());
4700     return inferLoc;
4701   }
4702
4703   public LocationInfo getLocationInfo(Descriptor d) {
4704     if (d instanceof MethodDescriptor) {
4705       return getMethodLocationInfo((MethodDescriptor) d);
4706     } else {
4707       return getFieldLocationInfo((ClassDescriptor) d);
4708     }
4709   }
4710
4711   private MethodLocationInfo getMethodLocationInfo(MethodDescriptor md) {
4712
4713     if (!mapMethodDescToMethodLocationInfo.containsKey(md)) {
4714       mapMethodDescToMethodLocationInfo.put(md, new MethodLocationInfo(md));
4715     }
4716
4717     return mapMethodDescToMethodLocationInfo.get(md);
4718
4719   }
4720
4721   private LocationInfo getFieldLocationInfo(ClassDescriptor cd) {
4722
4723     if (!mapClassToLocationInfo.containsKey(cd)) {
4724       mapClassToLocationInfo.put(cd, new LocationInfo(cd));
4725     }
4726
4727     return mapClassToLocationInfo.get(cd);
4728
4729   }
4730
4731   private void addPrefixMapping(Map<NTuple<Location>, Set<NTuple<Location>>> map,
4732       NTuple<Location> prefix, NTuple<Location> element) {
4733
4734     if (!map.containsKey(prefix)) {
4735       map.put(prefix, new HashSet<NTuple<Location>>());
4736     }
4737     map.get(prefix).add(element);
4738   }
4739
4740   private boolean containsNonPrimitiveElement(Set<Descriptor> descSet) {
4741     for (Iterator iterator = descSet.iterator(); iterator.hasNext();) {
4742       Descriptor desc = (Descriptor) iterator.next();
4743
4744       if (desc.equals(LocationInference.GLOBALDESC)) {
4745         return true;
4746       } else if (desc instanceof VarDescriptor) {
4747         if (!((VarDescriptor) desc).getType().isPrimitive()) {
4748           return true;
4749         }
4750       } else if (desc instanceof FieldDescriptor) {
4751         if (!((FieldDescriptor) desc).getType().isPrimitive()) {
4752           return true;
4753         }
4754       }
4755
4756     }
4757     return false;
4758   }
4759
4760   public SSJavaLattice<String> getLattice(Descriptor d) {
4761     if (d instanceof MethodDescriptor) {
4762       return getMethodLattice((MethodDescriptor) d);
4763     } else {
4764       return getFieldLattice((ClassDescriptor) d);
4765     }
4766   }
4767
4768   private SSJavaLattice<String> getMethodLattice(MethodDescriptor md) {
4769     if (!md2lattice.containsKey(md)) {
4770       md2lattice.put(md, new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM));
4771     }
4772     return md2lattice.get(md);
4773   }
4774
4775   private void setMethodLattice(MethodDescriptor md, SSJavaLattice<String> lattice) {
4776     md2lattice.put(md, lattice);
4777   }
4778
4779   private void extractFlowsBetweenFields(ClassDescriptor cd, FlowNode srcNode, FlowNode dstNode,
4780       int idx) {
4781
4782     NTuple<Descriptor> srcCurTuple = srcNode.getCurrentDescTuple();
4783     NTuple<Descriptor> dstCurTuple = dstNode.getCurrentDescTuple();
4784
4785     if (srcCurTuple.get(idx).equals(dstCurTuple.get(idx)) && srcCurTuple.size() > (idx + 1)
4786         && dstCurTuple.size() > (idx + 1)) {
4787       // value flow between fields: we don't need to add a binary relation
4788       // for this case
4789
4790       Descriptor desc = srcCurTuple.get(idx);
4791       ClassDescriptor classDesc;
4792
4793       if (idx == 0) {
4794         classDesc = ((VarDescriptor) desc).getType().getClassDesc();
4795       } else {
4796         if (desc instanceof FieldDescriptor) {
4797           classDesc = ((FieldDescriptor) desc).getType().getClassDesc();
4798         } else {
4799           // this case is that the local variable has a composite location assignment
4800           // the following element after the composite location to the local variable
4801           // has the enclosing descriptor of the local variable
4802           Descriptor localDesc = srcNode.getDescTuple().get(0);
4803           classDesc = ((VarDescriptor) localDesc).getType().getClassDesc();
4804         }
4805       }
4806       extractFlowsBetweenFields(classDesc, srcNode, dstNode, idx + 1);
4807
4808     } else {
4809
4810       Descriptor srcFieldDesc = srcCurTuple.get(idx);
4811       Descriptor dstFieldDesc = dstCurTuple.get(idx);
4812
4813       // System.out.println("srcFieldDesc=" + srcFieldDesc + "  dstFieldDesc=" + dstFieldDesc
4814       // + "   idx=" + idx);
4815       if (!srcFieldDesc.equals(dstFieldDesc)) {
4816         // add a new edge
4817         // System.out.println("-ADD EDGE");
4818         getHierarchyGraph(cd).addEdge(srcFieldDesc, dstFieldDesc);
4819       } else if (!isReference(srcFieldDesc) && !isReference(dstFieldDesc)) {
4820         // System.out.println("-ADD EDGE");
4821         getHierarchyGraph(cd).addEdge(srcFieldDesc, dstFieldDesc);
4822       }
4823
4824     }
4825
4826   }
4827
4828   public SSJavaLattice<String> getFieldLattice(ClassDescriptor cd) {
4829     if (!cd2lattice.containsKey(cd)) {
4830       cd2lattice.put(cd, new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM));
4831     }
4832     return cd2lattice.get(cd);
4833   }
4834
4835   public LinkedList<MethodDescriptor> computeMethodList() {
4836
4837     Set<MethodDescriptor> toSort = new HashSet<MethodDescriptor>();
4838
4839     setupToAnalyze();
4840
4841     Set<MethodDescriptor> visited = new HashSet<MethodDescriptor>();
4842     Set<MethodDescriptor> reachableCallee = new HashSet<MethodDescriptor>();
4843
4844     while (!toAnalyzeIsEmpty()) {
4845       ClassDescriptor cd = toAnalyzeNext();
4846
4847       if (cd.getClassName().equals("Object")) {
4848         rootClassDescriptor = cd;
4849         // inheritanceTree = new InheritanceTree<ClassDescriptor>(cd);
4850       }
4851
4852       setupToAnalazeMethod(cd);
4853       temp_toanalyzeMethodList.removeAll(visited);
4854
4855       while (!toAnalyzeMethodIsEmpty()) {
4856         MethodDescriptor md = toAnalyzeMethodNext();
4857         if ((!visited.contains(md))
4858             && (ssjava.needTobeAnnotated(md) || reachableCallee.contains(md))) {
4859
4860           // creates a mapping from a method descriptor to virtual methods
4861           Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
4862           if (md.isStatic()) {
4863             setPossibleCallees.add(md);
4864           } else {
4865             setPossibleCallees.addAll(ssjava.getCallGraph().getMethods(md));
4866           }
4867
4868           Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getCalleeSet(md);
4869           Set<MethodDescriptor> needToAnalyzeCalleeSet = new HashSet<MethodDescriptor>();
4870
4871           for (Iterator iterator = calleeSet.iterator(); iterator.hasNext();) {
4872             MethodDescriptor calleemd = (MethodDescriptor) iterator.next();
4873             if ((!ssjava.isTrustMethod(calleemd))
4874                 && (!ssjava.isSSJavaUtil(calleemd.getClassDesc()))
4875                 && (!calleemd.getModifiers().isNative())) {
4876               if (!visited.contains(calleemd)) {
4877                 temp_toanalyzeMethodList.add(calleemd);
4878               }
4879               reachableCallee.add(calleemd);
4880               needToAnalyzeCalleeSet.add(calleemd);
4881             }
4882           }
4883
4884           mapMethodToCalleeSet.put(md, needToAnalyzeCalleeSet);
4885
4886           visited.add(md);
4887
4888           toSort.add(md);
4889         }
4890       }
4891     }
4892
4893     return ssjava.topologicalSort(toSort);
4894
4895   }
4896
4897   public boolean isTransitivelyCalledFrom(MethodDescriptor callee, MethodDescriptor caller) {
4898     // if the callee is transitively invoked from the caller
4899     // return true;
4900
4901     int callerIdx = toanalyze_methodDescList.indexOf(caller);
4902     int calleeIdx = toanalyze_methodDescList.indexOf(callee);
4903
4904     if (callerIdx < calleeIdx) {
4905       return true;
4906     }
4907
4908     return false;
4909
4910   }
4911
4912   public void constructFlowGraph() {
4913
4914     System.out.println("");
4915     toanalyze_methodDescList = computeMethodList();
4916
4917     // hack... it seems that there is a problem with topological sorting.
4918     // so String.toString(Object o) is appeared too higher in the call chain.
4919     MethodDescriptor mdToString1 = null;
4920     MethodDescriptor mdToString2 = null;
4921     for (Iterator iterator = toanalyze_methodDescList.iterator(); iterator.hasNext();) {
4922       MethodDescriptor md = (MethodDescriptor) iterator.next();
4923       if (md.toString().equals("public static String String.valueOf(Object o)")) {
4924         mdToString1 = md;
4925       }
4926       if (md.toString().equals("public String Object.toString()")) {
4927         mdToString2 = md;
4928       }
4929     }
4930
4931     if (mdToString1 != null) {
4932       toanalyze_methodDescList.remove(mdToString1);
4933       toanalyze_methodDescList.addLast(mdToString1);
4934     }
4935     if (mdToString2 != null) {
4936       toanalyze_methodDescList.remove(mdToString2);
4937       toanalyze_methodDescList.addLast(mdToString2);
4938     }
4939
4940     LinkedList<MethodDescriptor> methodDescList =
4941         (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
4942
4943     // System.out.println("@@@methodDescList=" + methodDescList);
4944     // System.exit(0);
4945
4946     while (!methodDescList.isEmpty()) {
4947       MethodDescriptor md = methodDescList.removeLast();
4948       if (state.SSJAVADEBUG) {
4949         System.out.println();
4950         System.out.println("SSJAVA: Constructing a flow graph: " + md);
4951
4952         // creates a mapping from a parameter descriptor to its index
4953         Map<Descriptor, Integer> mapParamDescToIdx = new HashMap<Descriptor, Integer>();
4954         int offset = 0;
4955         if (!md.isStatic()) {
4956           offset = 1;
4957           mapParamDescToIdx.put(md.getThis(), 0);
4958         }
4959
4960         for (int i = 0; i < md.numParameters(); i++) {
4961           Descriptor paramDesc = (Descriptor) md.getParameter(i);
4962           mapParamDescToIdx.put(paramDesc, new Integer(i + offset));
4963         }
4964
4965         FlowGraph fg = new FlowGraph(md, mapParamDescToIdx);
4966         mapMethodDescriptorToFlowGraph.put(md, fg);
4967
4968         analyzeMethodBody(md.getClassDesc(), md);
4969
4970         // System.out.println("##constructSubGlobalFlowGraph");
4971         // GlobalFlowGraph subGlobalFlowGraph = constructSubGlobalFlowGraph(fg);
4972         // mapMethodDescriptorToSubGlobalFlowGraph.put(md, subGlobalFlowGraph);
4973         //
4974         // // TODO
4975         // System.out.println("##addValueFlowsFromCalleeSubGlobalFlowGraph");
4976         // addValueFlowsFromCalleeSubGlobalFlowGraph(md, subGlobalFlowGraph);
4977         // subGlobalFlowGraph.writeGraph("_SUBGLOBAL");
4978         //
4979         // propagateFlowsFromCalleesWithNoCompositeLocation(md);
4980       }
4981     }
4982     // _debug_printGraph();
4983
4984   }
4985
4986   private void constructGlobalFlowGraph() {
4987     LinkedList<MethodDescriptor> methodDescList =
4988         (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
4989
4990     while (!methodDescList.isEmpty()) {
4991       MethodDescriptor md = methodDescList.removeLast();
4992       if (state.SSJAVADEBUG) {
4993         System.out.println();
4994         System.out.println("SSJAVA: Constructing a sub global flow graph: " + md);
4995
4996         constructSubGlobalFlowGraph(getFlowGraph(md));
4997
4998         // TODO
4999         // System.out.println("-add Value Flows From CalleeSubGlobalFlowGraph");
5000         addValueFlowsFromCalleeSubGlobalFlowGraph(md);
5001         // subGlobalFlowGraph.writeGraph("_SUBGLOBAL");
5002
5003         // System.out.println("-propagate Flows From Callees With No CompositeLocation");
5004         // propagateFlowsFromCalleesWithNoCompositeLocation(md);
5005
5006         // mark if a parameter has incoming flows
5007         checkParamNodesInSubGlobalFlowGraph(md);
5008
5009       }
5010     }
5011   }
5012
5013   private void checkParamNodesInSubGlobalFlowGraph(MethodDescriptor md) {
5014     GlobalFlowGraph globalFlowGraph = getSubGlobalFlowGraph(md);
5015     FlowGraph flowGraph = getFlowGraph(md);
5016
5017     Set<FlowNode> paramFlowNodeSet = flowGraph.getParamFlowNodeSet();
5018     for (Iterator iterator = paramFlowNodeSet.iterator(); iterator.hasNext();) {
5019       FlowNode paramFlowNode = (FlowNode) iterator.next();
5020       // System.out.println("paramFlowNode=" + paramFlowNode);
5021       NTuple<Descriptor> paramDescTuple = paramFlowNode.getDescTuple();
5022       NTuple<Location> paramLocTuple = translateToLocTuple(md, paramDescTuple);
5023       GlobalFlowNode paramGlobalNode = globalFlowGraph.getFlowNode(paramLocTuple);
5024
5025       Set<GlobalFlowNode> incomingNodeSet =
5026           globalFlowGraph.getIncomingNodeSetByPrefix(paramLocTuple.get(0));
5027
5028       if (incomingNodeSet.size() > 0) {
5029         paramGlobalNode.setParamNodeWithIncomingFlows(true);
5030       }
5031
5032     }
5033   }
5034
5035   private Set<MethodInvokeNode> getMethodInvokeNodeSet(MethodDescriptor md) {
5036     if (!mapMethodDescriptorToMethodInvokeNodeSet.containsKey(md)) {
5037       mapMethodDescriptorToMethodInvokeNodeSet.put(md, new HashSet<MethodInvokeNode>());
5038     }
5039     return mapMethodDescriptorToMethodInvokeNodeSet.get(md);
5040   }
5041
5042   private void propagateFlowsFromCalleesWithNoCompositeLocation(MethodDescriptor mdCaller) {
5043
5044     // the transformation for a call site propagates flows through parameters
5045     // if the method is virtual, it also grab all relations from any possible
5046     // callees
5047
5048     Set<MethodInvokeNode> setMethodInvokeNode =
5049         mapMethodDescriptorToMethodInvokeNodeSet.get(mdCaller);
5050
5051     if (setMethodInvokeNode != null) {
5052
5053       for (Iterator iterator = setMethodInvokeNode.iterator(); iterator.hasNext();) {
5054         MethodInvokeNode min = (MethodInvokeNode) iterator.next();
5055         MethodDescriptor mdCallee = min.getMethod();
5056         Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
5057         if (mdCallee.isStatic()) {
5058           setPossibleCallees.add(mdCallee);
5059         } else {
5060           Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getMethods(mdCallee);
5061           // removes method descriptors that are not invoked by the caller
5062           calleeSet.retainAll(mapMethodToCalleeSet.get(mdCaller));
5063           setPossibleCallees.addAll(calleeSet);
5064         }
5065
5066         for (Iterator iterator2 = setPossibleCallees.iterator(); iterator2.hasNext();) {
5067           MethodDescriptor possibleMdCallee = (MethodDescriptor) iterator2.next();
5068           propagateFlowsToCallerWithNoCompositeLocation(min, mdCaller, possibleMdCallee);
5069         }
5070
5071       }
5072     }
5073
5074   }
5075
5076   private void analyzeMethodBody(ClassDescriptor cd, MethodDescriptor md) {
5077     BlockNode bn = state.getMethodBody(md);
5078     NodeTupleSet implicitFlowTupleSet = new NodeTupleSet();
5079     analyzeFlowBlockNode(md, md.getParameterTable(), bn, implicitFlowTupleSet);
5080   }
5081
5082   private void analyzeFlowBlockNode(MethodDescriptor md, SymbolTable nametable, BlockNode bn,
5083       NodeTupleSet implicitFlowTupleSet) {
5084
5085     bn.getVarTable().setParent(nametable);
5086     for (int i = 0; i < bn.size(); i++) {
5087       BlockStatementNode bsn = bn.get(i);
5088       analyzeBlockStatementNode(md, bn.getVarTable(), bsn, implicitFlowTupleSet);
5089     }
5090
5091   }
5092
5093   private void analyzeBlockStatementNode(MethodDescriptor md, SymbolTable nametable,
5094       BlockStatementNode bsn, NodeTupleSet implicitFlowTupleSet) {
5095
5096     switch (bsn.kind()) {
5097     case Kind.BlockExpressionNode:
5098       analyzeBlockExpressionNode(md, nametable, (BlockExpressionNode) bsn, implicitFlowTupleSet);
5099       break;
5100
5101     case Kind.DeclarationNode:
5102       analyzeFlowDeclarationNode(md, nametable, (DeclarationNode) bsn, implicitFlowTupleSet);
5103       break;
5104
5105     case Kind.IfStatementNode:
5106       analyzeFlowIfStatementNode(md, nametable, (IfStatementNode) bsn, implicitFlowTupleSet);
5107       break;
5108
5109     case Kind.LoopNode:
5110       analyzeFlowLoopNode(md, nametable, (LoopNode) bsn, implicitFlowTupleSet);
5111       break;
5112
5113     case Kind.ReturnNode:
5114       analyzeFlowReturnNode(md, nametable, (ReturnNode) bsn, implicitFlowTupleSet);
5115       break;
5116
5117     case Kind.SubBlockNode:
5118       analyzeFlowSubBlockNode(md, nametable, (SubBlockNode) bsn, implicitFlowTupleSet);
5119       break;
5120
5121     case Kind.ContinueBreakNode:
5122       break;
5123
5124     case Kind.SwitchStatementNode:
5125       analyzeSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn, implicitFlowTupleSet);
5126       break;
5127
5128     }
5129
5130   }
5131
5132   private void analyzeSwitchBlockNode(MethodDescriptor md, SymbolTable nametable,
5133       SwitchBlockNode sbn, NodeTupleSet implicitFlowTupleSet) {
5134
5135     analyzeFlowBlockNode(md, nametable, sbn.getSwitchBlockStatement(), implicitFlowTupleSet);
5136
5137   }
5138
5139   private void analyzeSwitchStatementNode(MethodDescriptor md, SymbolTable nametable,
5140       SwitchStatementNode ssn, NodeTupleSet implicitFlowTupleSet) {
5141
5142     NodeTupleSet condTupleNode = new NodeTupleSet();
5143     analyzeFlowExpressionNode(md, nametable, ssn.getCondition(), condTupleNode, null,
5144         implicitFlowTupleSet, false);
5145
5146     NodeTupleSet newImplicitTupleSet = new NodeTupleSet();
5147
5148     newImplicitTupleSet.addTupleSet(implicitFlowTupleSet);
5149     newImplicitTupleSet.addTupleSet(condTupleNode);
5150
5151     if (needToGenerateInterLoc(newImplicitTupleSet)) {
5152       // need to create an intermediate node for the GLB of conditional
5153       // locations & implicit flows
5154
5155       NTuple<Descriptor> interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
5156       for (Iterator<NTuple<Descriptor>> idxIter = newImplicitTupleSet.iterator(); idxIter.hasNext();) {
5157         NTuple<Descriptor> tuple = idxIter.next();
5158         addFlowGraphEdge(md, tuple, interTuple);
5159       }
5160       newImplicitTupleSet.clear();
5161       newImplicitTupleSet.addTuple(interTuple);
5162     }
5163
5164     BlockNode sbn = ssn.getSwitchBody();
5165     for (int i = 0; i < sbn.size(); i++) {
5166       analyzeSwitchBlockNode(md, nametable, (SwitchBlockNode) sbn.get(i), newImplicitTupleSet);
5167     }
5168
5169   }
5170
5171   private void analyzeFlowSubBlockNode(MethodDescriptor md, SymbolTable nametable,
5172       SubBlockNode sbn, NodeTupleSet implicitFlowTupleSet) {
5173     analyzeFlowBlockNode(md, nametable, sbn.getBlockNode(), implicitFlowTupleSet);
5174   }
5175
5176   private void analyzeFlowReturnNode(MethodDescriptor md, SymbolTable nametable, ReturnNode rn,
5177       NodeTupleSet implicitFlowTupleSet) {
5178
5179     // System.out.println("-analyzeFlowReturnNode=" + rn.printNode(0));
5180     ExpressionNode returnExp = rn.getReturnExpression();
5181
5182     if (returnExp != null) {
5183       NodeTupleSet nodeSet = new NodeTupleSet();
5184       // if a return expression returns a literal value, nodeSet is empty
5185       analyzeFlowExpressionNode(md, nametable, returnExp, nodeSet, false);
5186       FlowGraph fg = getFlowGraph(md);
5187
5188       // if (implicitFlowTupleSet.size() == 1
5189       // &&
5190       // fg.getFlowNode(implicitFlowTupleSet.iterator().next()).isIntermediate())
5191       // {
5192       //
5193       // // since there is already an intermediate node for the GLB of implicit
5194       // flows
5195       // // we don't need to create another intermediate node.
5196       // // just re-use the intermediate node for implicit flows.
5197       //
5198       // FlowNode meetNode =
5199       // fg.getFlowNode(implicitFlowTupleSet.iterator().next());
5200       //
5201       // for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
5202       // NTuple<Descriptor> returnNodeTuple = (NTuple<Descriptor>)
5203       // iterator.next();
5204       // fg.addValueFlowEdge(returnNodeTuple, meetNode.getDescTuple());
5205       // }
5206       //
5207       // }
5208
5209       NodeTupleSet currentFlowTupleSet = new NodeTupleSet();
5210
5211       // add tuples from return node
5212       currentFlowTupleSet.addTupleSet(nodeSet);
5213
5214       // add tuples corresponding to the current implicit flows
5215       currentFlowTupleSet.addTupleSet(implicitFlowTupleSet);
5216
5217       // System.out.println("---currentFlowTupleSet=" + currentFlowTupleSet);
5218
5219       if (needToGenerateInterLoc(currentFlowTupleSet)) {
5220
5221         FlowNode meetNode = fg.createIntermediateNode();
5222         for (Iterator iterator = currentFlowTupleSet.iterator(); iterator.hasNext();) {
5223           NTuple<Descriptor> currentFlowTuple = (NTuple<Descriptor>) iterator.next();
5224           fg.addValueFlowEdge(currentFlowTuple, meetNode.getDescTuple());
5225         }
5226         fg.addReturnFlowNode(meetNode.getDescTuple());
5227       } else {
5228         // currentFlowTupleSet = removeLiteralTuple(currentFlowTupleSet);
5229         for (Iterator iterator = currentFlowTupleSet.iterator(); iterator.hasNext();) {
5230           NTuple<Descriptor> currentFlowTuple = (NTuple<Descriptor>) iterator.next();
5231           fg.addReturnFlowNode(currentFlowTuple);
5232         }
5233       }
5234
5235     }
5236
5237   }
5238
5239   private NodeTupleSet removeLiteralTuple(NodeTupleSet inSet) {
5240     NodeTupleSet tupleSet = new NodeTupleSet();
5241     for (Iterator<NTuple<Descriptor>> iter = inSet.iterator(); iter.hasNext();) {
5242       NTuple<Descriptor> tuple = iter.next();
5243       if (!tuple.get(0).equals(LITERALDESC)) {
5244         tupleSet.addTuple(tuple);
5245       }
5246     }
5247     return tupleSet;
5248   }
5249
5250   private boolean needToGenerateInterLoc(NodeTupleSet tupleSet) {
5251     int size = 0;
5252     for (Iterator<NTuple<Descriptor>> iter = tupleSet.iterator(); iter.hasNext();) {
5253       NTuple<Descriptor> descTuple = iter.next();
5254       if (!descTuple.get(0).equals(LITERALDESC)) {
5255         size++;
5256       }
5257     }
5258     if (size > 1) {
5259       // System.out.println("needToGenerateInterLoc=" + tupleSet + "  size=" + size);
5260       return true;
5261     } else {
5262       return false;
5263     }
5264   }
5265
5266   private void analyzeFlowLoopNode(MethodDescriptor md, SymbolTable nametable, LoopNode ln,
5267       NodeTupleSet implicitFlowTupleSet) {
5268
5269     if (ln.getType() == LoopNode.WHILELOOP || ln.getType() == LoopNode.DOWHILELOOP) {
5270
5271       NodeTupleSet condTupleNode = new NodeTupleSet();
5272       analyzeFlowExpressionNode(md, nametable, ln.getCondition(), condTupleNode, null,
5273           implicitFlowTupleSet, false);
5274
5275       NodeTupleSet newImplicitTupleSet = new NodeTupleSet();
5276
5277       newImplicitTupleSet.addTupleSet(implicitFlowTupleSet);
5278       newImplicitTupleSet.addTupleSet(condTupleNode);
5279
5280       newImplicitTupleSet.addGlobalFlowTupleSet(implicitFlowTupleSet.getGlobalLocTupleSet());
5281       newImplicitTupleSet.addGlobalFlowTupleSet(condTupleNode.getGlobalLocTupleSet());
5282
5283       if (needToGenerateInterLoc(newImplicitTupleSet)) {
5284         // need to create an intermediate node for the GLB of conditional
5285         // locations & implicit flows
5286
5287         NTuple<Descriptor> interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
5288         for (Iterator<NTuple<Descriptor>> idxIter = newImplicitTupleSet.iterator(); idxIter
5289             .hasNext();) {
5290           NTuple<Descriptor> tuple = idxIter.next();
5291           addFlowGraphEdge(md, tuple, interTuple);
5292         }
5293         newImplicitTupleSet.clear();
5294         newImplicitTupleSet.addTuple(interTuple);
5295
5296       }
5297
5298       // ///////////
5299       // System.out.println("condTupleNode="+condTupleNode);
5300       // NTuple<Descriptor> interTuple =
5301       // getFlowGraph(md).createIntermediateNode().getDescTuple();
5302       //
5303       // for (Iterator<NTuple<Descriptor>> idxIter = condTupleNode.iterator();
5304       // idxIter.hasNext();) {
5305       // NTuple<Descriptor> tuple = idxIter.next();
5306       // addFlowGraphEdge(md, tuple, interTuple);
5307       // }
5308
5309       // for (Iterator<NTuple<Descriptor>> idxIter =
5310       // implicitFlowTupleSet.iterator(); idxIter
5311       // .hasNext();) {
5312       // NTuple<Descriptor> tuple = idxIter.next();
5313       // addFlowGraphEdge(md, tuple, interTuple);
5314       // }
5315
5316       // NodeTupleSet newImplicitSet = new NodeTupleSet();
5317       // newImplicitSet.addTuple(interTuple);
5318       analyzeFlowBlockNode(md, nametable, ln.getBody(), newImplicitTupleSet);
5319       // ///////////
5320
5321       // condTupleNode.addTupleSet(implicitFlowTupleSet);
5322
5323       // add edges from condNodeTupleSet to all nodes of conditional nodes
5324       // analyzeFlowBlockNode(md, nametable, ln.getBody(), condTupleNode);
5325
5326     } else {
5327       // check 'for loop' case
5328       BlockNode bn = ln.getInitializer();
5329       bn.getVarTable().setParent(nametable);
5330       for (int i = 0; i < bn.size(); i++) {
5331         BlockStatementNode bsn = bn.get(i);
5332         analyzeBlockStatementNode(md, bn.getVarTable(), bsn, implicitFlowTupleSet);
5333       }
5334
5335       NodeTupleSet condTupleNode = new NodeTupleSet();
5336       analyzeFlowExpressionNode(md, bn.getVarTable(), ln.getCondition(), condTupleNode, null,
5337           implicitFlowTupleSet, false);
5338
5339       NodeTupleSet newImplicitTupleSet = new NodeTupleSet();
5340       newImplicitTupleSet.addTupleSet(implicitFlowTupleSet);
5341       newImplicitTupleSet.addTupleSet(condTupleNode);
5342
5343       if (needToGenerateInterLoc(newImplicitTupleSet)) {
5344         // need to create an intermediate node for the GLB of conditional
5345         // locations & implicit flows
5346
5347         NTuple<Descriptor> interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
5348         for (Iterator<NTuple<Descriptor>> idxIter = newImplicitTupleSet.iterator(); idxIter
5349             .hasNext();) {
5350           NTuple<Descriptor> tuple = idxIter.next();
5351           addFlowGraphEdge(md, tuple, interTuple);
5352         }
5353         newImplicitTupleSet.clear();
5354         newImplicitTupleSet.addTuple(interTuple);
5355
5356       }
5357
5358       // ///////////
5359       // NTuple<Descriptor> interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
5360       //
5361       // for (Iterator<NTuple<Descriptor>> idxIter = condTupleNode.iterator(); idxIter.hasNext();) {
5362       // NTuple<Descriptor> tuple = idxIter.next();
5363       // addFlowGraphEdge(md, tuple, interTuple);
5364       // }
5365       //
5366       // for (Iterator<NTuple<Descriptor>> idxIter = implicitFlowTupleSet.iterator(); idxIter
5367       // .hasNext();) {
5368       // NTuple<Descriptor> tuple = idxIter.next();
5369       // addFlowGraphEdge(md, tuple, interTuple);
5370       // }
5371       //
5372       // NodeTupleSet newImplicitSet = new NodeTupleSet();
5373       // newImplicitSet.addTuple(interTuple);
5374       analyzeFlowBlockNode(md, bn.getVarTable(), ln.getUpdate(), newImplicitTupleSet);
5375       analyzeFlowBlockNode(md, bn.getVarTable(), ln.getBody(), newImplicitTupleSet);
5376       // ///////////
5377
5378       // condTupleNode.addTupleSet(implicitFlowTupleSet);
5379       //
5380       // analyzeFlowBlockNode(md, bn.getVarTable(), ln.getUpdate(),
5381       // condTupleNode);
5382       // analyzeFlowBlockNode(md, bn.getVarTable(), ln.getBody(),
5383       // condTupleNode);
5384
5385     }
5386
5387   }
5388
5389   private void analyzeFlowIfStatementNode(MethodDescriptor md, SymbolTable nametable,
5390       IfStatementNode isn, NodeTupleSet implicitFlowTupleSet) {
5391
5392     // System.out.println("analyzeFlowIfStatementNode=" + isn.printNode(0));
5393
5394     NodeTupleSet condTupleNode = new NodeTupleSet();
5395     analyzeFlowExpressionNode(md, nametable, isn.getCondition(), condTupleNode, null,
5396         implicitFlowTupleSet, false);
5397
5398     NodeTupleSet newImplicitTupleSet = new NodeTupleSet();
5399
5400     newImplicitTupleSet.addTupleSet(implicitFlowTupleSet);
5401     newImplicitTupleSet.addTupleSet(condTupleNode);
5402
5403     // System.out.println("$$$GGGcondTupleNode=" + condTupleNode.getGlobalLocTupleSet());
5404     // System.out.println("-condTupleNode=" + condTupleNode);
5405     // System.out.println("-implicitFlowTupleSet=" + implicitFlowTupleSet);
5406     // System.out.println("-newImplicitTupleSet=" + newImplicitTupleSet);
5407
5408     if (needToGenerateInterLoc(newImplicitTupleSet)) {
5409
5410       // need to create an intermediate node for the GLB of conditional locations & implicit flows
5411       NTuple<Descriptor> interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
5412       for (Iterator<NTuple<Descriptor>> idxIter = newImplicitTupleSet.iterator(); idxIter.hasNext();) {
5413         NTuple<Descriptor> tuple = idxIter.next();
5414         addFlowGraphEdge(md, tuple, interTuple);
5415       }
5416       newImplicitTupleSet.clear();
5417       newImplicitTupleSet.addTuple(interTuple);
5418     }
5419
5420     // GlobalFlowGraph globalFlowGraph = getSubGlobalFlowGraph(md);
5421     // for (Iterator<NTuple<Location>> iterator = condTupleNode.globalIterator();
5422     // iterator.hasNext();) {
5423     // NTuple<Location> calleeReturnLocTuple = iterator.next();
5424     // for (Iterator<NTuple<Descriptor>> iter2 = newImplicitTupleSet.iterator(); iter2.hasNext();) {
5425     // NTuple<Descriptor> callerImplicitTuple = iter2.next();
5426     // globalFlowGraph.addValueFlowEdge(calleeReturnLocTuple,
5427     // translateToLocTuple(md, callerImplicitTuple));
5428     // }
5429     // }
5430     newImplicitTupleSet.addGlobalFlowTupleSet(condTupleNode.getGlobalLocTupleSet());
5431
5432     analyzeFlowBlockNode(md, nametable, isn.getTrueBlock(), newImplicitTupleSet);
5433
5434     if (isn.getFalseBlock() != null) {
5435       analyzeFlowBlockNode(md, nametable, isn.getFalseBlock(), newImplicitTupleSet);
5436     }
5437
5438   }
5439
5440   private void analyzeFlowDeclarationNode(MethodDescriptor md, SymbolTable nametable,
5441       DeclarationNode dn, NodeTupleSet implicitFlowTupleSet) {
5442
5443     VarDescriptor vd = dn.getVarDescriptor();
5444     mapDescToDefinitionLine.put(vd, dn.getNumLine());
5445     NTuple<Descriptor> tupleLHS = new NTuple<Descriptor>();
5446     tupleLHS.add(vd);
5447     FlowNode fn = getFlowGraph(md).createNewFlowNode(tupleLHS);
5448     fn.setDeclarationNode();
5449
5450     if (dn.getExpression() != null) {
5451       // System.out.println("-analyzeFlowDeclarationNode=" + dn.printNode(0));
5452
5453       NodeTupleSet nodeSetRHS = new NodeTupleSet();
5454       analyzeFlowExpressionNode(md, nametable, dn.getExpression(), nodeSetRHS, null,
5455           implicitFlowTupleSet, false);
5456
5457       // creates edges from RHS to LHS
5458       NTuple<Descriptor> interTuple = null;
5459       if (needToGenerateInterLoc(nodeSetRHS)) {
5460         interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
5461       }
5462
5463       for (Iterator<NTuple<Descriptor>> iter = nodeSetRHS.iterator(); iter.hasNext();) {
5464         NTuple<Descriptor> fromTuple = iter.next();
5465         // System.out.println("fromTuple=" + fromTuple + "  interTuple=" + interTuple + " tupleLSH="
5466         // + tupleLHS);
5467         addFlowGraphEdge(md, fromTuple, interTuple, tupleLHS);
5468       }
5469
5470       // creates edges from implicitFlowTupleSet to LHS
5471       for (Iterator<NTuple<Descriptor>> iter = implicitFlowTupleSet.iterator(); iter.hasNext();) {
5472         NTuple<Descriptor> implicitTuple = iter.next();
5473         addFlowGraphEdge(md, implicitTuple, tupleLHS);
5474       }
5475
5476       GlobalFlowGraph globalFlowGraph = getSubGlobalFlowGraph(md);
5477       for (Iterator<NTuple<Location>> iterator = nodeSetRHS.globalIterator(); iterator.hasNext();) {
5478         NTuple<Location> calleeReturnLocTuple = iterator.next();
5479
5480         globalFlowGraph.addValueFlowEdge(calleeReturnLocTuple, translateToLocTuple(md, tupleLHS));
5481       }
5482
5483       for (Iterator<NTuple<Location>> iterator = implicitFlowTupleSet.globalIterator(); iterator
5484           .hasNext();) {
5485         NTuple<Location> implicitGlobalTuple = iterator.next();
5486
5487         globalFlowGraph.addValueFlowEdge(implicitGlobalTuple, translateToLocTuple(md, tupleLHS));
5488       }
5489
5490       // System.out.println("-nodeSetRHS=" + nodeSetRHS);
5491       // System.out.println("-implicitFlowTupleSet=" + implicitFlowTupleSet);
5492
5493     }
5494
5495   }
5496
5497   private void analyzeBlockExpressionNode(MethodDescriptor md, SymbolTable nametable,
5498       BlockExpressionNode ben, NodeTupleSet implicitFlowTupleSet) {
5499     analyzeFlowExpressionNode(md, nametable, ben.getExpression(), null, null, implicitFlowTupleSet,
5500         false);
5501   }
5502
5503   private NTuple<Descriptor> analyzeFlowExpressionNode(MethodDescriptor md, SymbolTable nametable,
5504       ExpressionNode en, NodeTupleSet nodeSet, boolean isLHS) {
5505     return analyzeFlowExpressionNode(md, nametable, en, nodeSet, null, new NodeTupleSet(), isLHS);
5506   }
5507
5508   private NTuple<Descriptor> analyzeFlowExpressionNode(MethodDescriptor md, SymbolTable nametable,
5509       ExpressionNode en, NodeTupleSet nodeSet, NTuple<Descriptor> base,
5510       NodeTupleSet implicitFlowTupleSet, boolean isLHS) {
5511
5512     // System.out.println("en=" + en.printNode(0) + "   class=" + en.getClass());
5513
5514     // note that expression node can create more than one flow node
5515     // nodeSet contains of flow nodes
5516     // base is always assigned to null except the case of a name node!
5517     NTuple<Descriptor> flowTuple;
5518     switch (en.kind()) {
5519     case Kind.AssignmentNode:
5520       analyzeFlowAssignmentNode(md, nametable, (AssignmentNode) en, nodeSet, base,
5521           implicitFlowTupleSet);
5522       break;
5523
5524     case Kind.FieldAccessNode:
5525       flowTuple =
5526           analyzeFlowFieldAccessNode(md, nametable, (FieldAccessNode) en, nodeSet, base,
5527               implicitFlowTupleSet, isLHS);
5528       if (flowTuple != null) {
5529         nodeSet.addTuple(flowTuple);
5530       }
5531       return flowTuple;
5532
5533     case Kind.NameNode:
5534       NodeTupleSet nameNodeSet = new NodeTupleSet();
5535       flowTuple =
5536           analyzeFlowNameNode(md, nametable, (NameNode) en, nameNodeSet, base, implicitFlowTupleSet);
5537       if (flowTuple != null) {
5538         nodeSet.addTuple(flowTuple);
5539       }
5540       return flowTuple;
5541
5542     case Kind.OpNode:
5543       analyzeFlowOpNode(md, nametable, (OpNode) en, nodeSet, implicitFlowTupleSet);
5544       break;
5545
5546     case Kind.CreateObjectNode:
5547       analyzeCreateObjectNode(md, nametable, (CreateObjectNode) en, nodeSet, implicitFlowTupleSet);
5548       break;
5549
5550     case Kind.ArrayAccessNode:
5551       analyzeFlowArrayAccessNode(md, nametable, (ArrayAccessNode) en, nodeSet, isLHS);
5552       break;
5553
5554     case Kind.LiteralNode:
5555       analyzeFlowLiteralNode(md, nametable, (LiteralNode) en, nodeSet);
5556       break;
5557
5558     case Kind.MethodInvokeNode:
5559       analyzeFlowMethodInvokeNode(md, nametable, (MethodInvokeNode) en, nodeSet,
5560           implicitFlowTupleSet);
5561       break;
5562
5563     case Kind.TertiaryNode:
5564       analyzeFlowTertiaryNode(md, nametable, (TertiaryNode) en, nodeSet, implicitFlowTupleSet);
5565       break;
5566
5567     case Kind.CastNode:
5568       analyzeFlowCastNode(md, nametable, (CastNode) en, nodeSet, base, implicitFlowTupleSet);
5569       break;
5570     // case Kind.InstanceOfNode:
5571     // checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
5572     // return null;
5573
5574     // case Kind.ArrayInitializerNode:
5575     // checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en,
5576     // td);
5577     // return null;
5578
5579     // case Kind.ClassTypeNode:
5580     // checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
5581     // return null;
5582
5583     // case Kind.OffsetNode:
5584     // checkOffsetNode(md, nametable, (OffsetNode)en, td);
5585     // return null;
5586
5587     }
5588
5589     return null;
5590
5591   }
5592
5593   private void analyzeFlowCastNode(MethodDescriptor md, SymbolTable nametable, CastNode cn,
5594       NodeTupleSet nodeSet, NTuple<Descriptor> base, NodeTupleSet implicitFlowTupleSet) {
5595
5596     analyzeFlowExpressionNode(md, nametable, cn.getExpression(), nodeSet, base,
5597         implicitFlowTupleSet, false);
5598
5599   }
5600
5601   private void analyzeFlowTertiaryNode(MethodDescriptor md, SymbolTable nametable, TertiaryNode tn,
5602       NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
5603
5604     // System.out.println("analyzeFlowTertiaryNode=" + tn.printNode(0));
5605
5606     NodeTupleSet tertiaryTupleNode = new NodeTupleSet();
5607     analyzeFlowExpressionNode(md, nametable, tn.getCond(), tertiaryTupleNode, null,
5608         implicitFlowTupleSet, false);
5609
5610     NodeTupleSet newImplicitTupleSet = new NodeTupleSet();
5611     newImplicitTupleSet.addTupleSet(implicitFlowTupleSet);
5612     newImplicitTupleSet.addTupleSet(tertiaryTupleNode);
5613
5614     // System.out.println("$$$GGGcondTupleNode=" + tertiaryTupleNode.getGlobalLocTupleSet());
5615     // System.out.println("-tertiaryTupleNode=" + tertiaryTupleNode);
5616     // System.out.println("-implicitFlowTupleSet=" + implicitFlowTupleSet);
5617     // System.out.println("-newImplicitTupleSet=" + newImplicitTupleSet);
5618
5619     if (needToGenerateInterLoc(newImplicitTupleSet)) {
5620       // need to create an intermediate node for the GLB of conditional locations & implicit flows
5621       NTuple<Descriptor> interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
5622       for (Iterator<NTuple<Descriptor>> idxIter = newImplicitTupleSet.iterator(); idxIter.hasNext();) {
5623         NTuple<Descriptor> tuple = idxIter.next();
5624         addFlowGraphEdge(md, tuple, interTuple);
5625       }
5626       newImplicitTupleSet.clear();
5627       newImplicitTupleSet.addTuple(interTuple);
5628     }
5629
5630     newImplicitTupleSet.addGlobalFlowTupleSet(tertiaryTupleNode.getGlobalLocTupleSet());
5631
5632     // System.out.println("---------newImplicitTupleSet=" + newImplicitTupleSet);
5633
5634     // add edges from tertiaryTupleNode to all nodes of conditional nodes
5635     // tertiaryTupleNode.addTupleSet(implicitFlowTupleSet);
5636     analyzeFlowExpressionNode(md, nametable, tn.getTrueExpr(), tertiaryTupleNode, null,
5637         newImplicitTupleSet, false);
5638
5639     analyzeFlowExpressionNode(md, nametable, tn.getFalseExpr(), tertiaryTupleNode, null,
5640         newImplicitTupleSet, false);
5641
5642     nodeSet.addGlobalFlowTupleSet(tertiaryTupleNode.getGlobalLocTupleSet());
5643     nodeSet.addTupleSet(tertiaryTupleNode);
5644
5645     // System.out.println("#tertiary node set=" + nodeSet);
5646   }
5647
5648   private void addMapCallerMethodDescToMethodInvokeNodeSet(MethodDescriptor caller,
5649       MethodInvokeNode min) {
5650     Set<MethodInvokeNode> set = mapMethodDescriptorToMethodInvokeNodeSet.get(caller);
5651     if (set == null) {
5652       set = new HashSet<MethodInvokeNode>();
5653       mapMethodDescriptorToMethodInvokeNodeSet.put(caller, set);
5654     }
5655     set.add(min);
5656   }
5657
5658   private void addParamNodeFlowingToReturnValue(MethodDescriptor md, FlowNode fn) {
5659
5660     if (!mapMethodDescToParamNodeFlowsToReturnValue.containsKey(md)) {
5661       mapMethodDescToParamNodeFlowsToReturnValue.put(md, new HashSet<FlowNode>());
5662     }
5663     mapMethodDescToParamNodeFlowsToReturnValue.get(md).add(fn);
5664   }
5665
5666   private Set<FlowNode> getParamNodeFlowingToReturnValue(MethodDescriptor md) {
5667
5668     if (!mapMethodDescToParamNodeFlowsToReturnValue.containsKey(md)) {
5669       mapMethodDescToParamNodeFlowsToReturnValue.put(md, new HashSet<FlowNode>());
5670     }
5671
5672     return mapMethodDescToParamNodeFlowsToReturnValue.get(md);
5673   }
5674
5675   private Set<NTuple<Location>> getPCLocTupleSet(MethodInvokeNode min) {
5676     if (!mapMethodInvokeNodeToPCLocTupleSet.containsKey(min)) {
5677       mapMethodInvokeNodeToPCLocTupleSet.put(min, new HashSet<NTuple<Location>>());
5678     }
5679     return mapMethodInvokeNodeToPCLocTupleSet.get(min);
5680   }
5681
5682   private void analyzeFlowMethodInvokeNode(MethodDescriptor mdCaller, SymbolTable nametable,
5683       MethodInvokeNode min, NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
5684
5685     // System.out.println("analyzeFlowMethodInvokeNode=" + min.printNode(0));
5686
5687     if (!toanalyze_methodDescList.contains(min.getMethod())) {
5688       return;
5689     }
5690
5691     addMapMethodDescToMethodInvokeNodeSet(min);
5692
5693     Set<NTuple<Location>> pcLocTupleSet = getPCLocTupleSet(min);
5694     for (Iterator iterator = implicitFlowTupleSet.iterator(); iterator.hasNext();) {
5695       NTuple<Descriptor> pcDescTuple = (NTuple<Descriptor>) iterator.next();
5696       if (!pcDescTuple.get(0).equals(LITERALDESC)) {
5697         // here we don't need to add the literal value as a PC location
5698         pcLocTupleSet.add(translateToLocTuple(mdCaller, pcDescTuple));
5699       }
5700     }
5701
5702     mapMethodInvokeNodeToArgIdxMap.put(min, new HashMap<Integer, NTuple<Descriptor>>());
5703
5704     if (nodeSet == null) {
5705       nodeSet = new NodeTupleSet();
5706     }
5707
5708     MethodDescriptor mdCallee = min.getMethod();
5709
5710     NameDescriptor baseName = min.getBaseName();
5711     boolean isSystemout = false;
5712     if (baseName != null) {
5713       isSystemout = baseName.getSymbol().equals("System.out");
5714     }
5715
5716     if (!ssjava.isSSJavaUtil(mdCallee.getClassDesc()) && !ssjava.isTrustMethod(mdCallee)
5717         && !isSystemout) {
5718
5719       addMapCallerMethodDescToMethodInvokeNodeSet(mdCaller, min);
5720
5721       FlowGraph calleeFlowGraph = getFlowGraph(mdCallee);
5722       // System.out.println("mdCallee=" + mdCallee + " calleeFlowGraph=" + calleeFlowGraph);
5723       Set<FlowNode> calleeReturnSet = calleeFlowGraph.getReturnNodeSet();
5724
5725       // System.out.println("---calleeReturnSet=" + calleeReturnSet);
5726
5727       NodeTupleSet tupleSet = new NodeTupleSet();
5728
5729       if (min.getExpression() != null) {
5730
5731         NodeTupleSet baseNodeSet = new NodeTupleSet();
5732         analyzeFlowExpressionNode(mdCaller, nametable, min.getExpression(), baseNodeSet, null,
5733             implicitFlowTupleSet, false);
5734         // System.out.println("baseNodeSet=" + baseNodeSet);
5735
5736         assert (baseNodeSet.size() == 1);
5737         NTuple<Descriptor> baseTuple = baseNodeSet.iterator().next();
5738         if (baseTuple.get(0) instanceof InterDescriptor) {
5739           if (baseTuple.size() > 1) {
5740             throw new Error();
5741           }
5742           FlowNode interNode = getFlowGraph(mdCaller).getFlowNode(baseTuple);
5743           baseTuple = translateBaseTuple(interNode, baseTuple);
5744         }
5745         mapMethodInvokeNodeToBaseTuple.put(min, baseTuple);
5746
5747         if (!min.getMethod().isStatic()) {
5748           addArgIdxMap(min, 0, baseTuple);
5749
5750           for (Iterator iterator = calleeReturnSet.iterator(); iterator.hasNext();) {
5751             FlowNode returnNode = (FlowNode) iterator.next();
5752             NTuple<Descriptor> returnDescTuple = returnNode.getDescTuple();
5753             if (returnDescTuple.startsWith(mdCallee.getThis())) {
5754               // the location type of the return value is started with 'this'
5755               // reference
5756               NTuple<Descriptor> inFlowTuple = new NTuple<Descriptor>(baseTuple.getList());
5757
5758               if (inFlowTuple.get(0) instanceof InterDescriptor) {
5759                 // min.getExpression()
5760               } else {
5761
5762               }
5763
5764               inFlowTuple.addAll(returnDescTuple.subList(1, returnDescTuple.size()));
5765               // nodeSet.addTuple(inFlowTuple);
5766               // System.out.println("1CREATE A NEW TUPLE=" + inFlowTuple + "  from="
5767               // + mdCallee.getThis());
5768               // tupleSet.addTuple(inFlowTuple);
5769               tupleSet.addTuple(baseTuple);
5770             } else {
5771               // TODO
5772               // System.out.println("returnNode=" + returnNode);
5773               Set<FlowNode> inFlowSet = calleeFlowGraph.getIncomingFlowNodeSet(returnNode);
5774               // System.out.println("inFlowSet=" + inFlowSet + "   from retrunNode=" + returnNode);
5775               for (Iterator iterator2 = inFlowSet.iterator(); iterator2.hasNext();) {
5776                 FlowNode inFlowNode = (FlowNode) iterator2.next();
5777                 if (inFlowNode.getDescTuple().startsWith(mdCallee.getThis())) {
5778                   // nodeSet.addTupleSet(baseNodeSet);
5779                   // System.out.println("2CREATE A NEW TUPLE=" + baseNodeSet + "  from="
5780                   // + mdCallee.getThis());
5781                   tupleSet.addTupleSet(baseNodeSet);
5782                 }
5783               }
5784             }
5785           }
5786         }
5787
5788       }
5789       // analyze parameter flows
5790
5791       if (min.numArgs() > 0) {
5792
5793         int offset;
5794         if (min.getMethod().isStatic()) {
5795           offset = 0;
5796         } else {
5797           offset = 1;
5798         }
5799
5800         for (int i = 0; i < min.numArgs(); i++) {
5801           ExpressionNode en = min.getArg(i);
5802           int idx = i + offset;
5803           NodeTupleSet argTupleSet = new NodeTupleSet();
5804           analyzeFlowExpressionNode(mdCaller, nametable, en, argTupleSet, false);
5805           // if argument is liternal node, argTuple is set to NULL
5806           // System.out.println("---arg idx=" + idx + "   argTupleSet=" + argTupleSet);
5807           NTuple<Descriptor> argTuple = generateArgTuple(mdCaller, argTupleSet);
5808
5809           // if an argument is literal value,
5810           // we need to create an itermediate node so that we could assign a composite location to
5811           // that node if needed
5812           if (argTuple.size() > 0
5813               && (argTuple.get(0).equals(GLOBALDESC) || argTuple.get(0).equals(LITERALDESC))) {
5814             /*
5815              * System.out.println("***GLOBAL ARG TUPLE CASE=" + argTuple); System.out.println("8");
5816              * 
5817              * NTuple<Descriptor> interTuple =
5818              * getFlowGraph(mdCaller).createIntermediateNode().getDescTuple(); ((InterDescriptor)
5819              * interTuple.get(0)).setMethodArgIdxPair(min, idx); addFlowGraphEdge(mdCaller,
5820              * argTuple, interTuple); argTuple = interTuple; addArgIdxMap(min, idx, argTuple);
5821              * System.out.println("new min mapping i=" + idx + "  ->" + argTuple);
5822              */
5823             argTuple = new NTuple<Descriptor>();
5824           }
5825
5826           addArgIdxMap(min, idx, argTuple);
5827
5828           FlowNode paramNode = calleeFlowGraph.getParamFlowNode(idx);
5829
5830           // check whether a param node in the callee graph has incoming flows
5831           // if it has incoming flows, the corresponding arg should be lower than the current PC
5832           // Descriptor prefix = paramNode.getDescTuple().get(0);
5833           // if (calleeFlowGraph.getIncomingNodeSetByPrefix(prefix).size() > 0) {
5834           // for (Iterator<NTuple<Descriptor>> iterator = implicitFlowTupleSet.iterator(); iterator
5835           // .hasNext();) {
5836           // NTuple<Descriptor> pcTuple = iterator.next();
5837           // System.out.println("add edge pcTuple =" + pcTuple + " -> " + argTuple);
5838           // addFlowGraphEdge(md, pcTuple, argTuple);
5839           // }
5840           // }
5841
5842           // System.out.println("paramNode=" + paramNode + "  calleeReturnSet=" + calleeReturnSet);
5843           if (hasInFlowTo(calleeFlowGraph, paramNode, calleeReturnSet)
5844               || mdCallee.getModifiers().isNative()) {
5845             addParamNodeFlowingToReturnValue(mdCallee, paramNode);
5846             // nodeSet.addTupleSet(argTupleSet);
5847             // System.out.println("3CREATE A NEW TUPLE=" + argTupleSet + "  from=" + paramNode);
5848             tupleSet.addTupleSet(argTupleSet);
5849           }
5850         }
5851
5852       }
5853
5854       if (mdCallee.getReturnType() != null && !mdCallee.getReturnType().isVoid()) {
5855         FlowReturnNode returnHolderNode = getFlowGraph(mdCaller).createReturnNode(min);
5856
5857         if (needToGenerateInterLoc(tupleSet)) {
5858           FlowGraph fg = getFlowGraph(mdCaller);
5859           FlowNode interNode = fg.createIntermediateNode();
5860           interNode.setFormHolder(true);
5861
5862           NTuple<Descriptor> interTuple = interNode.getDescTuple();
5863
5864           for (Iterator iterator = tupleSet.iterator(); iterator.hasNext();) {
5865             NTuple<Descriptor> tuple = (NTuple<Descriptor>) iterator.next();
5866
5867             Set<NTuple<Descriptor>> addSet = new HashSet<NTuple<Descriptor>>();
5868             FlowNode node = fg.getFlowNode(tuple);
5869             if (node instanceof FlowReturnNode) {
5870               addSet.addAll(fg.getReturnTupleSet(((FlowReturnNode) node).getReturnTupleSet()));
5871             } else {
5872               addSet.add(tuple);
5873             }
5874             for (Iterator iterator2 = addSet.iterator(); iterator2.hasNext();) {
5875               NTuple<Descriptor> higher = (NTuple<Descriptor>) iterator2.next();
5876               addFlowGraphEdge(mdCaller, higher, interTuple);
5877             }
5878           }
5879
5880           returnHolderNode.addTuple(interTuple);
5881
5882           nodeSet.addTuple(interTuple);
5883           // System.out.println("ADD TUPLESET=" + interTuple + " to returnnode=" +
5884           // returnHolderNode);
5885
5886         } else {
5887           returnHolderNode.addTupleSet(tupleSet);
5888           // System.out.println("ADD TUPLESET=" + tupleSet + " to returnnode=" + returnHolderNode);
5889         }
5890         // setNode.addTupleSet(tupleSet);
5891         // NodeTupleSet setFromReturnNode=new NodeTupleSet();
5892         // setFromReturnNode.addTuple(tuple);
5893
5894         NodeTupleSet holderTupleSet =
5895             getNodeTupleSetFromReturnNode(getFlowGraph(mdCaller), returnHolderNode);
5896
5897         // System.out.println("HOLDER TUPLE SET=" + holderTupleSet);
5898         nodeSet.addTupleSet(holderTupleSet);
5899
5900         nodeSet.addTuple(returnHolderNode.getDescTuple());
5901       }
5902
5903       // propagateFlowsFromCallee(min, md, min.getMethod());
5904
5905       // when generating the global flow graph,
5906       // we need to add ordering relations from the set of callee return loc tuple to LHS of the
5907       // caller assignment
5908       for (Iterator iterator = calleeReturnSet.iterator(); iterator.hasNext();) {
5909         FlowNode calleeReturnNode = (FlowNode) iterator.next();
5910         NTuple<Location> calleeReturnLocTuple =
5911             translateToLocTuple(mdCallee, calleeReturnNode.getDescTuple());
5912         // System.out.println("calleeReturnLocTuple=" + calleeReturnLocTuple);
5913         NTuple<Location> transaltedToCaller =
5914             translateToCallerLocTuple(min, mdCallee, mdCaller, calleeReturnLocTuple);
5915         // System.out.println("translateToCallerLocTuple="
5916         // + translateToCallerLocTuple(min, mdCallee, mdCaller, calleeReturnLocTuple));
5917         if (transaltedToCaller.size() > 0) {
5918           nodeSet.addGlobalFlowTuple(translateToCallerLocTuple(min, mdCallee, mdCaller,
5919               calleeReturnLocTuple));
5920         }
5921       }
5922
5923       // System.out.println("min nodeSet=" + nodeSet);
5924
5925     }
5926
5927   }
5928
5929   private NodeTupleSet getNodeTupleSetFromReturnNode(FlowGraph fg, FlowReturnNode node) {
5930     NodeTupleSet nts = new NodeTupleSet();
5931
5932     Set<NTuple<Descriptor>> returnSet = node.getReturnTupleSet();
5933
5934     for (Iterator iterator = returnSet.iterator(); iterator.hasNext();) {
5935       NTuple<Descriptor> tuple = (NTuple<Descriptor>) iterator.next();
5936       FlowNode flowNode = fg.getFlowNode(tuple);
5937       if (flowNode instanceof FlowReturnNode) {
5938         returnSet.addAll(recurGetNode(fg, (FlowReturnNode) flowNode));
5939       } else {
5940         returnSet.add(tuple);
5941       }
5942     }
5943
5944     for (Iterator iterator = returnSet.iterator(); iterator.hasNext();) {
5945       NTuple<Descriptor> nTuple = (NTuple<Descriptor>) iterator.next();
5946       nts.addTuple(nTuple);
5947     }
5948
5949     return nts;
5950
5951   }
5952
5953   private Set<NTuple<Descriptor>> recurGetNode(FlowGraph fg, FlowReturnNode rnode) {
5954
5955     Set<NTuple<Descriptor>> tupleSet = new HashSet<NTuple<Descriptor>>();
5956
5957     Set<NTuple<Descriptor>> returnSet = rnode.getReturnTupleSet();
5958     for (Iterator iterator = returnSet.iterator(); iterator.hasNext();) {
5959       NTuple<Descriptor> tuple = (NTuple<Descriptor>) iterator.next();
5960       FlowNode flowNode = fg.getFlowNode(tuple);
5961       if (flowNode instanceof FlowReturnNode) {
5962         tupleSet.addAll(recurGetNode(fg, (FlowReturnNode) flowNode));
5963       }
5964       tupleSet.add(tuple);
5965     }
5966
5967     return tupleSet;
5968   }
5969
5970   private NTuple<Descriptor> generateArgTuple(MethodDescriptor mdCaller, NodeTupleSet argTupleSet) {
5971
5972     int size = 0;
5973
5974     // if argTupleSet is empty, it comes from the top location
5975     if (argTupleSet.size() == 0) {
5976       NTuple<Descriptor> descTuple = new NTuple<Descriptor>();
5977       descTuple.add(LITERALDESC);
5978       return descTuple;
5979     }
5980
5981     Set<NTuple<Descriptor>> argTupleSetNonLiteral = new HashSet<NTuple<Descriptor>>();
5982
5983     for (Iterator<NTuple<Descriptor>> iter = argTupleSet.iterator(); iter.hasNext();) {
5984       NTuple<Descriptor> descTuple = iter.next();
5985       if (!descTuple.get(0).equals(LITERALDESC)) {
5986         argTupleSetNonLiteral.add(descTuple);
5987       }
5988     }
5989
5990     if (argTupleSetNonLiteral.size() > 1) {
5991
5992       NTuple<Descriptor> interTuple =
5993           getFlowGraph(mdCaller).createIntermediateNode().getDescTuple();
5994       for (Iterator<NTuple<Descriptor>> idxIter = argTupleSet.iterator(); idxIter.hasNext();) {
5995         NTuple<Descriptor> tuple = idxIter.next();
5996         addFlowGraphEdge(mdCaller, tuple, interTuple);
5997       }
5998       return interTuple;
5999     } else if (argTupleSetNonLiteral.size() == 1) {
6000       return argTupleSetNonLiteral.iterator().next();
6001     } else {
6002       return argTupleSet.iterator().next();
6003     }
6004
6005   }
6006
6007   private boolean hasInFlowTo(FlowGraph fg, FlowNode inNode, Set<FlowNode> nodeSet) {
6008     // return true if inNode has in-flows to nodeSet
6009
6010     if (nodeSet.contains(inNode)) {
6011       // in this case, the method directly returns a parameter variable.
6012       return true;
6013     }
6014     // Set<FlowNode> reachableSet = fg.getReachFlowNodeSetFrom(inNode);
6015     Set<FlowNode> reachableSet = fg.getReachableSetFrom(inNode.getDescTuple());
6016     // System.out.println("inNode=" + inNode + "  reachalbeSet=" + reachableSet);
6017
6018     for (Iterator iterator = reachableSet.iterator(); iterator.hasNext();) {
6019       FlowNode fn = (FlowNode) iterator.next();
6020       if (nodeSet.contains(fn)) {
6021         return true;
6022       }
6023     }
6024     return false;
6025   }
6026
6027   private NTuple<Descriptor> getNodeTupleByArgIdx(MethodInvokeNode min, int idx) {
6028     return mapMethodInvokeNodeToArgIdxMap.get(min).get(new Integer(idx));
6029   }
6030
6031   private void addArgIdxMap(MethodInvokeNode min, int idx, NTuple<Descriptor> argTuple /*
6032                                                                                         * NodeTupleSet
6033                                                                                         * tupleSet
6034                                                                                         */) {
6035     Map<Integer, NTuple<Descriptor>> mapIdxToTuple = mapMethodInvokeNodeToArgIdxMap.get(min);
6036     if (mapIdxToTuple == null) {
6037       mapIdxToTuple = new HashMap<Integer, NTuple<Descriptor>>();
6038       mapMethodInvokeNodeToArgIdxMap.put(min, mapIdxToTuple);
6039     }
6040     mapIdxToTuple.put(new Integer(idx), argTuple);
6041   }
6042
6043   private void analyzeFlowLiteralNode(MethodDescriptor md, SymbolTable nametable, LiteralNode en,
6044       NodeTupleSet nodeSet) {
6045     NTuple<Descriptor> tuple = new NTuple<Descriptor>();
6046     tuple.add(LITERALDESC);
6047     nodeSet.addTuple(tuple);
6048   }
6049
6050   private void analyzeFlowArrayAccessNode(MethodDescriptor md, SymbolTable nametable,
6051       ArrayAccessNode aan, NodeTupleSet nodeSet, boolean isLHS) {
6052
6053     // System.out.println("analyzeFlowArrayAccessNode aan=" + aan.printNode(0));
6054     String currentArrayAccessNodeExpStr = aan.printNode(0);
6055     arrayAccessNodeStack.push(aan.printNode(0));
6056
6057     NodeTupleSet expNodeTupleSet = new NodeTupleSet();
6058     NTuple<Descriptor> base =
6059         analyzeFlowExpressionNode(md, nametable, aan.getExpression(), expNodeTupleSet, isLHS);
6060     // System.out.println("-base=" + base);
6061
6062     nodeSet.setMethodInvokeBaseDescTuple(base);
6063     NodeTupleSet idxNodeTupleSet = new NodeTupleSet();
6064     analyzeFlowExpressionNode(md, nametable, aan.getIndex(), idxNodeTupleSet, isLHS);
6065
6066     arrayAccessNodeStack.pop();
6067
6068     if (isLHS) {
6069       // need to create an edge from idx to array
6070       for (Iterator<NTuple<Descriptor>> idxIter = idxNodeTupleSet.iterator(); idxIter.hasNext();) {
6071         NTuple<Descriptor> idxTuple = idxIter.next();
6072         for (Iterator<NTuple<Descriptor>> arrIter = expNodeTupleSet.iterator(); arrIter.hasNext();) {
6073           NTuple<Descriptor> arrTuple = arrIter.next();
6074           getFlowGraph(md).addValueFlowEdge(idxTuple, arrTuple);
6075         }
6076       }
6077
6078       GlobalFlowGraph globalFlowGraph = getSubGlobalFlowGraph(md);
6079       for (Iterator<NTuple<Location>> iterator = idxNodeTupleSet.globalIterator(); iterator
6080           .hasNext();) {
6081         NTuple<Location> calleeReturnLocTuple = iterator.next();
6082         for (Iterator<NTuple<Descriptor>> arrIter = expNodeTupleSet.iterator(); arrIter.hasNext();) {
6083           NTuple<Descriptor> arrTuple = arrIter.next();
6084
6085           globalFlowGraph.addValueFlowEdge(calleeReturnLocTuple, translateToLocTuple(md, arrTuple));
6086         }
6087       }
6088
6089       nodeSet.addTupleSet(expNodeTupleSet);
6090     } else {
6091
6092       NodeTupleSet nodeSetArrayAccessExp = new NodeTupleSet();
6093
6094       nodeSetArrayAccessExp.addTupleSet(expNodeTupleSet);
6095       nodeSetArrayAccessExp.addTupleSet(idxNodeTupleSet);
6096
6097       if (arrayAccessNodeStack.isEmpty()
6098           || !arrayAccessNodeStack.peek().startsWith(currentArrayAccessNodeExpStr)) {
6099
6100         if (needToGenerateInterLoc(nodeSetArrayAccessExp)) {
6101           FlowNode interNode = getFlowGraph(md).createIntermediateNode();
6102           NTuple<Descriptor> interTuple = interNode.getDescTuple();
6103
6104           for (Iterator<NTuple<Descriptor>> iter = nodeSetArrayAccessExp.iterator(); iter.hasNext();) {
6105             NTuple<Descriptor> higherTuple = iter.next();
6106             addFlowGraphEdge(md, higherTuple, interTuple);
6107           }
6108           nodeSetArrayAccessExp.clear();
6109           nodeSetArrayAccessExp.addTuple(interTuple);
6110           FlowGraph fg = getFlowGraph(md);
6111
6112           // System.out.println("base=" + base);
6113           if (base != null) {
6114             fg.addMapInterLocNodeToEnclosingDescriptor(interTuple.get(0),
6115                 getClassTypeDescriptor(base.get(base.size() - 1)));
6116             interNode.setBaseTuple(base);
6117           }
6118         }
6119       }
6120
6121       nodeSet.addGlobalFlowTupleSet(idxNodeTupleSet.getGlobalLocTupleSet());
6122       nodeSet.addTupleSet(nodeSetArrayAccessExp);
6123
6124     }
6125
6126   }
6127
6128   private void analyzeCreateObjectNode(MethodDescriptor md, SymbolTable nametable,
6129       CreateObjectNode en, NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
6130     // System.out.println("#analyzeCreateObjectNode=" + en.printNode(0));
6131     int numArgs = en.numArgs();
6132     NodeTupleSet argSet = new NodeTupleSet();
6133
6134     for (int i = 0; i < numArgs; i++) {
6135       analyzeFlowExpressionNode(md, nametable, en.getArg(i), argSet, null, implicitFlowTupleSet,
6136           false);
6137     }
6138
6139     // System.out.println("###argSet=" + argSet);
6140     nodeSet.addTupleSet(argSet);
6141
6142   }
6143
6144   private void analyzeFlowOpNode(MethodDescriptor md, SymbolTable nametable, OpNode on,
6145       NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
6146
6147     NodeTupleSet leftOpSet = new NodeTupleSet();
6148     NodeTupleSet rightOpSet = new NodeTupleSet();
6149
6150     // System.out.println("analyzeFlowOpNode=" + on.printNode(0));
6151
6152     // left operand
6153     analyzeFlowExpressionNode(md, nametable, on.getLeft(), leftOpSet, null, implicitFlowTupleSet,
6154         false);
6155
6156     if (on.getRight() != null) {
6157       // right operand
6158       analyzeFlowExpressionNode(md, nametable, on.getRight(), rightOpSet, null,
6159           implicitFlowTupleSet, false);
6160     }
6161
6162     Operation op = on.getOp();
6163
6164     switch (op.getOp()) {
6165
6166     case Operation.UNARYPLUS:
6167     case Operation.UNARYMINUS:
6168     case Operation.LOGIC_NOT:
6169       // single operand
6170       nodeSet.addTupleSet(leftOpSet);
6171       break;
6172
6173     case Operation.LOGIC_OR:
6174     case Operation.LOGIC_AND:
6175     case Operation.COMP:
6176     case Operation.BIT_OR:
6177     case Operation.BIT_XOR:
6178     case Operation.BIT_AND:
6179     case Operation.ISAVAILABLE:
6180     case Operation.EQUAL:
6181     case Operation.NOTEQUAL:
6182     case Operation.LT:
6183     case Operation.GT:
6184     case Operation.LTE:
6185     case Operation.GTE:
6186     case Operation.ADD:
6187     case Operation.SUB:
6188     case Operation.MULT:
6189     case Operation.DIV:
6190     case Operation.MOD:
6191     case Operation.LEFTSHIFT:
6192     case Operation.RIGHTSHIFT:
6193     case Operation.URIGHTSHIFT:
6194
6195       // there are two operands
6196       nodeSet.addTupleSet(leftOpSet);
6197       nodeSet.addTupleSet(rightOpSet);
6198
6199       nodeSet.addGlobalFlowTupleSet(leftOpSet.getGlobalLocTupleSet());
6200       nodeSet.addGlobalFlowTupleSet(rightOpSet.getGlobalLocTupleSet());
6201
6202       break;
6203
6204     default:
6205       throw new Error(op.toString());
6206     }
6207
6208   }
6209
6210   private NTuple<Descriptor> analyzeFlowNameNode(MethodDescriptor md, SymbolTable nametable,
6211       NameNode nn, NodeTupleSet nodeSet, NTuple<Descriptor> base, NodeTupleSet implicitFlowTupleSet) {
6212
6213     if (base == null) {
6214       base = new NTuple<Descriptor>();
6215     }
6216
6217     NameDescriptor nd = nn.getName();
6218
6219     if (nd.getBase() != null) {
6220       base =
6221           analyzeFlowExpressionNode(md, nametable, nn.getExpression(), nodeSet, base,
6222               implicitFlowTupleSet, false);
6223       if (base == null) {
6224         // base node has the top location
6225         return base;
6226       }
6227     } else {
6228       String varname = nd.toString();
6229       if (varname.equals("this")) {
6230         // 'this' itself!
6231         base.add(md.getThis());
6232         return base;
6233       }
6234
6235       Descriptor d = (Descriptor) nametable.get(varname);
6236
6237       if (d instanceof VarDescriptor) {
6238         VarDescriptor vd = (VarDescriptor) d;
6239         base.add(vd);
6240       } else if (d instanceof FieldDescriptor) {
6241         // the type of field descriptor has a location!
6242         FieldDescriptor fd = (FieldDescriptor) d;
6243         if (fd.isStatic()) {
6244           if (fd.isFinal()) {
6245             // if it is 'static final', no need to have flow node for the TOP
6246             // location
6247             return null;
6248           } else {
6249             // if 'static', assign the default GLOBAL LOCATION to the first
6250             // element of the tuple
6251             base.add(GLOBALDESC);
6252           }
6253         } else {
6254           // the location of field access starts from this, followed by field
6255           // location
6256           base.add(md.getThis());
6257         }
6258
6259         base.add(fd);
6260       } else if (d == null) {
6261         // access static field
6262         base.add(GLOBALDESC);
6263         base.add(nn.getField());
6264         return base;
6265
6266         // FieldDescriptor fd = nn.getField();addFlowGraphEdge
6267         //
6268         // MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
6269         // String globalLocId = localLattice.getGlobalLoc();
6270         // if (globalLocId == null) {
6271         // throw new
6272         // Error("Method lattice does not define global variable location at "
6273         // + generateErrorMessage(md.getClassDesc(), nn));
6274         // }
6275         // loc.addLocation(new Location(md, globalLocId));
6276         //
6277         // Location fieldLoc = (Location) fd.getType().getExtension();
6278         // loc.addLocation(fieldLoc);
6279         //
6280         // return loc;
6281
6282       }
6283     }
6284     getFlowGraph(md).createNewFlowNode(base);
6285
6286     return base;
6287
6288   }
6289
6290   private NTuple<Descriptor> analyzeFlowFieldAccessNode(MethodDescriptor md, SymbolTable nametable,
6291       FieldAccessNode fan, NodeTupleSet nodeSet, NTuple<Descriptor> base,
6292       NodeTupleSet implicitFlowTupleSet, boolean isLHS) {
6293     // System.out.println("analyzeFlowFieldAccessNode=" + fan.printNode(0));
6294
6295     String currentArrayAccessNodeExpStr = null;
6296     ExpressionNode left = fan.getExpression();
6297     TypeDescriptor ltd = left.getType();
6298     FieldDescriptor fd = fan.getField();
6299     ArrayAccessNode aan = null;
6300
6301     String varName = null;
6302     if (left.kind() == Kind.NameNode) {
6303       NameDescriptor nd = ((NameNode) left).getName();
6304       varName = nd.toString();
6305     }
6306
6307     if (ltd.isClassNameRef() || (varName != null && varName.equals("this"))) {
6308       // using a class name directly or access using this
6309       if (fd.isStatic() && fd.isFinal()) {
6310         return null;
6311       }
6312     }
6313
6314     NodeTupleSet idxNodeTupleSet = new NodeTupleSet();
6315
6316     boolean isArrayCase = false;
6317     if (left instanceof ArrayAccessNode) {
6318
6319       isArrayCase = true;
6320       aan = (ArrayAccessNode) left;
6321
6322       currentArrayAccessNodeExpStr = aan.printNode(0);
6323       arrayAccessNodeStack.push(currentArrayAccessNodeExpStr);
6324
6325       left = aan.getExpression();
6326       analyzeFlowExpressionNode(md, nametable, aan.getIndex(), idxNodeTupleSet, base,
6327           implicitFlowTupleSet, isLHS);
6328
6329     }
6330     base =
6331         analyzeFlowExpressionNode(md, nametable, left, nodeSet, base, implicitFlowTupleSet, isLHS);
6332
6333     if (base == null) {
6334       // in this case, field is TOP location
6335       return null;
6336     } else {
6337
6338       NTuple<Descriptor> flowFieldTuple = new NTuple<Descriptor>(base.toList());
6339
6340       if (!left.getType().isPrimitive()) {
6341         if (!fd.getSymbol().equals("length")) {
6342           // array.length access, just have the location of the array
6343           flowFieldTuple.add(fd);
6344           nodeSet.removeTuple(base);
6345         }
6346       }
6347       getFlowGraph(md).createNewFlowNode(flowFieldTuple);
6348
6349       if (isLHS) {
6350         for (Iterator<NTuple<Descriptor>> idxIter = idxNodeTupleSet.iterator(); idxIter.hasNext();) {
6351           NTuple<Descriptor> idxTuple = idxIter.next();
6352           getFlowGraph(md).addValueFlowEdge(idxTuple, flowFieldTuple);
6353         }
6354
6355         GlobalFlowGraph globalFlowGraph = getSubGlobalFlowGraph(md);
6356         for (Iterator<NTuple<Location>> iterator = idxNodeTupleSet.globalIterator(); iterator
6357             .hasNext();) {
6358           NTuple<Location> calleeReturnLocTuple = iterator.next();
6359
6360           globalFlowGraph.addValueFlowEdge(calleeReturnLocTuple,
6361               translateToLocTuple(md, flowFieldTuple));
6362         }
6363
6364       } else {
6365         nodeSet.addTupleSet(idxNodeTupleSet);
6366
6367         // if it is the array case and not the LHS case
6368         if (isArrayCase) {
6369           arrayAccessNodeStack.pop();
6370
6371           if (arrayAccessNodeStack.isEmpty()
6372               || !arrayAccessNodeStack.peek().startsWith(currentArrayAccessNodeExpStr)) {
6373             NodeTupleSet nodeSetArrayAccessExp = new NodeTupleSet();
6374
6375             nodeSetArrayAccessExp.addTuple(flowFieldTuple);
6376             nodeSetArrayAccessExp.addTupleSet(idxNodeTupleSet);
6377             nodeSetArrayAccessExp.addTupleSet(nodeSet);
6378
6379             if (needToGenerateInterLoc(nodeSetArrayAccessExp)) {
6380               // System.out.println("nodeSetArrayAccessExp=" + nodeSetArrayAccessExp);
6381               // System.out.println("idxNodeTupleSet.getGlobalLocTupleSet()="
6382               // + idxNodeTupleSet.getGlobalLocTupleSet());
6383
6384               NTuple<Descriptor> interTuple =
6385                   getFlowGraph(md).createIntermediateNode().getDescTuple();
6386
6387               for (Iterator<NTuple<Descriptor>> iter = nodeSetArrayAccessExp.iterator(); iter
6388                   .hasNext();) {
6389                 NTuple<Descriptor> higherTuple = iter.next();
6390                 addFlowGraphEdge(md, higherTuple, interTuple);
6391               }
6392
6393               FlowGraph fg = getFlowGraph(md);
6394               fg.addMapInterLocNodeToEnclosingDescriptor(interTuple.get(0),
6395                   getClassTypeDescriptor(base.get(base.size() - 1)));
6396
6397               nodeSet.clear();
6398               flowFieldTuple = interTuple;
6399             }
6400             nodeSet.addGlobalFlowTupleSet(idxNodeTupleSet.getGlobalLocTupleSet());
6401           }
6402
6403         }
6404
6405       }
6406       return flowFieldTuple;
6407     }
6408
6409   }
6410
6411   private void debug_printTreeNode(TreeNode tn) {
6412
6413     System.out.println("DEBUG: " + tn.printNode(0) + "                line#=" + tn.getNumLine());
6414
6415   }
6416
6417   private void analyzeFlowAssignmentNode(MethodDescriptor md, SymbolTable nametable,
6418       AssignmentNode an, NodeTupleSet nodeSet, NTuple<Descriptor> base,
6419       NodeTupleSet implicitFlowTupleSet) {
6420
6421     NodeTupleSet nodeSetRHS = new NodeTupleSet();
6422     NodeTupleSet nodeSetLHS = new NodeTupleSet();
6423
6424     boolean postinc = true;
6425     if (an.getOperation().getBaseOp() == null
6426         || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
6427             .getBaseOp().getOp() != Operation.POSTDEC)) {
6428       postinc = false;
6429     }
6430     // if LHS is array access node, need to capture value flows between an array
6431     // and its index value
6432     analyzeFlowExpressionNode(md, nametable, an.getDest(), nodeSetLHS, null, implicitFlowTupleSet,
6433         true);
6434
6435     if (!postinc) {
6436       // analyze value flows of rhs expression
6437       analyzeFlowExpressionNode(md, nametable, an.getSrc(), nodeSetRHS, null, implicitFlowTupleSet,
6438           false);
6439
6440       // System.out.println("-analyzeFlowAssignmentNode=" + an.printNode(0));
6441       // System.out.println("-nodeSetLHS=" + nodeSetLHS);
6442       // System.out.println("-nodeSetRHS=" + nodeSetRHS);
6443       // System.out.println("-implicitFlowTupleSet=" + implicitFlowTupleSet);
6444       // System.out.println("-");
6445
6446       if (an.getOperation().getOp() >= 2 && an.getOperation().getOp() <= 12) {
6447         // if assignment contains OP+EQ operator, creates edges from LHS to LHS
6448
6449         for (Iterator<NTuple<Descriptor>> iter = nodeSetLHS.iterator(); iter.hasNext();) {
6450           NTuple<Descriptor> fromTuple = iter.next();
6451           for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
6452             NTuple<Descriptor> toTuple = iter2.next();
6453             addFlowGraphEdge(md, fromTuple, toTuple);
6454           }
6455         }
6456       }
6457
6458       // creates edges from RHS to LHS
6459       NTuple<Descriptor> interTuple = null;
6460       if (needToGenerateInterLoc(nodeSetRHS)) {
6461         interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
6462       }
6463
6464       for (Iterator<NTuple<Descriptor>> iter = nodeSetRHS.iterator(); iter.hasNext();) {
6465         NTuple<Descriptor> fromTuple = iter.next();
6466         for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
6467           NTuple<Descriptor> toTuple = iter2.next();
6468           addFlowGraphEdge(md, fromTuple, interTuple, toTuple);
6469         }
6470       }
6471
6472       // creates edges from implicitFlowTupleSet to LHS
6473       for (Iterator<NTuple<Descriptor>> iter = implicitFlowTupleSet.iterator(); iter.hasNext();) {
6474         NTuple<Descriptor> fromTuple = iter.next();
6475         for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
6476           NTuple<Descriptor> toTuple = iter2.next();
6477           addFlowGraphEdge(md, fromTuple, toTuple);
6478         }
6479       }
6480
6481       // create global flow edges if the callee gives return value flows to the caller
6482       GlobalFlowGraph globalFlowGraph = getSubGlobalFlowGraph(md);
6483       for (Iterator<NTuple<Location>> iterator = nodeSetRHS.globalIterator(); iterator.hasNext();) {
6484         NTuple<Location> calleeReturnLocTuple = iterator.next();
6485         for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
6486           NTuple<Descriptor> callerLHSTuple = iter2.next();
6487           // System.out.println("$$$ GLOBAL FLOW ADD=" + calleeReturnLocTuple + " -> "
6488           // + translateToLocTuple(md, callerLHSTuple));
6489
6490           globalFlowGraph.addValueFlowEdge(calleeReturnLocTuple,
6491               translateToLocTuple(md, callerLHSTuple));
6492         }
6493       }
6494
6495       for (Iterator<NTuple<Location>> iterator = implicitFlowTupleSet.globalIterator(); iterator
6496           .hasNext();) {
6497         NTuple<Location> calleeReturnLocTuple = iterator.next();
6498         for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
6499           NTuple<Descriptor> callerLHSTuple = iter2.next();
6500
6501           globalFlowGraph.addValueFlowEdge(calleeReturnLocTuple,
6502               translateToLocTuple(md, callerLHSTuple));
6503           // System.out.println("$$$ GLOBAL FLOW PCLOC ADD=" + calleeReturnLocTuple + " -> "
6504           // + translateToLocTuple(md, callerLHSTuple));
6505         }
6506       }
6507
6508     } else {
6509       // postinc case
6510
6511       for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
6512         NTuple<Descriptor> tuple = iter2.next();
6513         addFlowGraphEdge(md, tuple, tuple);
6514       }
6515
6516       // creates edges from implicitFlowTupleSet to LHS
6517       for (Iterator<NTuple<Descriptor>> iter = implicitFlowTupleSet.iterator(); iter.hasNext();) {
6518         NTuple<Descriptor> fromTuple = iter.next();
6519         for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
6520           NTuple<Descriptor> toTuple = iter2.next();
6521           addFlowGraphEdge(md, fromTuple, toTuple);
6522         }
6523       }
6524
6525       GlobalFlowGraph globalFlowGraph = getSubGlobalFlowGraph(md);
6526       for (Iterator<NTuple<Location>> iterator = implicitFlowTupleSet.globalIterator(); iterator
6527           .hasNext();) {
6528         NTuple<Location> calleeReturnLocTuple = iterator.next();
6529         for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
6530           NTuple<Descriptor> callerLHSTuple = iter2.next();
6531           globalFlowGraph.addValueFlowEdge(calleeReturnLocTuple,
6532               translateToLocTuple(md, callerLHSTuple));
6533           // System.out.println("$$$ GLOBAL FLOW PC ADD=" + calleeReturnLocTuple + " -> "
6534           // + translateToLocTuple(md, callerLHSTuple));
6535         }
6536       }
6537
6538     }
6539
6540     if (nodeSet != null) {
6541       nodeSet.addTupleSet(nodeSetLHS);
6542       nodeSet.addGlobalFlowTupleSet(nodeSetLHS.getGlobalLocTupleSet());
6543     }
6544   }
6545
6546   public FlowGraph getFlowGraph(MethodDescriptor md) {
6547     return mapMethodDescriptorToFlowGraph.get(md);
6548   }
6549
6550   private boolean addFlowGraphEdge(MethodDescriptor md, NTuple<Descriptor> from,
6551       NTuple<Descriptor> to) {
6552     FlowGraph graph = getFlowGraph(md);
6553     graph.addValueFlowEdge(from, to);
6554     return true;
6555   }
6556
6557   private void addFlowGraphEdge(MethodDescriptor md, NTuple<Descriptor> from,
6558       NTuple<Descriptor> inter, NTuple<Descriptor> to) {
6559
6560     FlowGraph graph = getFlowGraph(md);
6561
6562     if (inter != null) {
6563       graph.addValueFlowEdge(from, inter);
6564       graph.addValueFlowEdge(inter, to);
6565     } else {
6566       graph.addValueFlowEdge(from, to);
6567     }
6568
6569   }
6570
6571   public void writeInferredLatticeDotFile(ClassDescriptor cd, HierarchyGraph simpleHierarchyGraph,
6572       SSJavaLattice<String> locOrder, String nameSuffix) {
6573     // System.out.println("@cd=" + cd);
6574     // System.out.println("@sharedLoc=" + locOrder.getSharedLocSet());
6575     writeInferredLatticeDotFile(cd, null, simpleHierarchyGraph, locOrder, nameSuffix);
6576   }
6577
6578   public void writeInferredLatticeDotFile(ClassDescriptor cd, MethodDescriptor md,
6579       HierarchyGraph simpleHierarchyGraph, SSJavaLattice<String> locOrder, String nameSuffix) {
6580
6581     String fileName = "lattice_";
6582     if (md != null) {
6583       fileName +=
6584           cd.getSymbol().replaceAll("[\\W_]", "") + "_" + md.toString().replaceAll("[\\W_]", "");
6585     } else {
6586       fileName += cd.getSymbol().replaceAll("[\\W_]", "");
6587     }
6588
6589     fileName += nameSuffix;
6590
6591     System.out.println("***lattice=" + fileName + "    setsize=" + locOrder.getKeySet().size());
6592
6593     Set<Pair<String, String>> pairSet = locOrder.getOrderingPairSet();
6594
6595     Set<String> addedLocSet = new HashSet<String>();
6596
6597     if (pairSet.size() > 0) {
6598       try {
6599         BufferedWriter bw = new BufferedWriter(new FileWriter(fileName + ".dot"));
6600
6601         bw.write("digraph " + fileName + " {\n");
6602
6603         for (Iterator iterator = pairSet.iterator(); iterator.hasNext();) {
6604           // pair is in the form of <higher, lower>
6605           Pair<String, String> pair = (Pair<String, String>) iterator.next();
6606
6607           String highLocId = pair.getFirst();
6608           String lowLocId = pair.getSecond();
6609           if (!addedLocSet.contains(highLocId)) {
6610             addedLocSet.add(highLocId);
6611             drawNode(bw, locOrder, simpleHierarchyGraph, highLocId);
6612           }
6613
6614           if (!addedLocSet.contains(lowLocId)) {
6615             addedLocSet.add(lowLocId);
6616             drawNode(bw, locOrder, simpleHierarchyGraph, lowLocId);
6617           }
6618
6619           bw.write(highLocId + " -> " + lowLocId + ";\n");
6620         }
6621         bw.write("}\n");
6622         bw.close();
6623
6624       } catch (IOException e) {
6625         e.printStackTrace();
6626       }
6627
6628     }
6629
6630   }
6631
6632   private String convertMergeSetToString(HierarchyGraph graph, Set<HNode> mergeSet) {
6633     String str = "";
6634     for (Iterator iterator = mergeSet.iterator(); iterator.hasNext();) {
6635       HNode merged = (HNode) iterator.next();
6636       if (merged.isMergeNode()) {
6637         str += convertMergeSetToString(graph, graph.getMapHNodetoMergeSet().get(merged));
6638       } else {
6639         str += " " + merged.getName();
6640       }
6641     }
6642     return str;
6643   }
6644
6645   private void drawNode(BufferedWriter bw, SSJavaLattice<String> lattice, HierarchyGraph graph,
6646       String locName) throws IOException {
6647
6648     String prettyStr;
6649     if (lattice.isSharedLoc(locName)) {
6650       prettyStr = locName + "*";
6651     } else {
6652       prettyStr = locName;
6653     }
6654     // HNode node = graph.getHNode(locName);
6655     // if (node != null && node.isMergeNode()) {
6656     // Set<HNode> mergeSet = graph.getMapHNodetoMergeSet().get(node);
6657     // prettyStr += ":" + convertMergeSetToString(graph, mergeSet);
6658     // }
6659     bw.write(locName + " [label=\"" + prettyStr + "\"]" + ";\n");
6660   }
6661
6662   public void _debug_writeFlowGraph() {
6663     Set<MethodDescriptor> keySet = mapMethodDescriptorToFlowGraph.keySet();
6664
6665     for (Iterator<MethodDescriptor> iterator = keySet.iterator(); iterator.hasNext();) {
6666       MethodDescriptor md = (MethodDescriptor) iterator.next();
6667       FlowGraph fg = mapMethodDescriptorToFlowGraph.get(md);
6668       GlobalFlowGraph subGlobalFlowGraph = getSubGlobalFlowGraph(md);
6669       try {
6670         fg.writeGraph();
6671         subGlobalFlowGraph.writeGraph("_SUBGLOBAL");
6672       } catch (IOException e) {
6673         e.printStackTrace();
6674       }
6675     }
6676
6677   }
6678
6679 }
6680
6681 class CyclicFlowException extends Exception {
6682
6683 }
6684
6685 class InterDescriptor extends Descriptor {
6686
6687   Pair<MethodInvokeNode, Integer> minArgIdxPair;
6688
6689   public InterDescriptor(String name) {
6690     super(name);
6691   }
6692
6693   public void setMethodArgIdxPair(MethodInvokeNode min, int idx) {
6694     minArgIdxPair = new Pair<MethodInvokeNode, Integer>(min, new Integer(idx));
6695   }
6696
6697   public Pair<MethodInvokeNode, Integer> getMethodArgIdxPair() {
6698     return minArgIdxPair;
6699   }
6700
6701 }