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