changes.
[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.VarDescriptor;
31 import IR.Tree.ArrayAccessNode;
32 import IR.Tree.AssignmentNode;
33 import IR.Tree.BlockExpressionNode;
34 import IR.Tree.BlockNode;
35 import IR.Tree.BlockStatementNode;
36 import IR.Tree.CastNode;
37 import IR.Tree.CreateObjectNode;
38 import IR.Tree.DeclarationNode;
39 import IR.Tree.ExpressionNode;
40 import IR.Tree.FieldAccessNode;
41 import IR.Tree.IfStatementNode;
42 import IR.Tree.Kind;
43 import IR.Tree.LiteralNode;
44 import IR.Tree.LoopNode;
45 import IR.Tree.MethodInvokeNode;
46 import IR.Tree.NameNode;
47 import IR.Tree.OpNode;
48 import IR.Tree.ReturnNode;
49 import IR.Tree.SubBlockNode;
50 import IR.Tree.SwitchBlockNode;
51 import IR.Tree.SwitchStatementNode;
52 import IR.Tree.TertiaryNode;
53 import IR.Tree.TreeNode;
54 import Util.Pair;
55
56 public class LocationInference {
57
58   State state;
59   SSJavaAnalysis ssjava;
60
61   List<ClassDescriptor> temp_toanalyzeList;
62   List<MethodDescriptor> temp_toanalyzeMethodList;
63   Map<MethodDescriptor, FlowGraph> mapMethodDescriptorToFlowGraph;
64
65   LinkedList<MethodDescriptor> toanalyze_methodDescList;
66
67   // map a method descriptor to its set of parameter descriptors
68   Map<MethodDescriptor, Set<Descriptor>> mapMethodDescriptorToParamDescSet;
69
70   // keep current descriptors to visit in fixed-point interprocedural analysis,
71   private Stack<MethodDescriptor> methodDescriptorsToVisitStack;
72
73   // map a class descriptor to a field lattice
74   private Map<ClassDescriptor, SSJavaLattice<String>> cd2lattice;
75
76   // map a method descriptor to a method lattice
77   private Map<MethodDescriptor, SSJavaLattice<String>> md2lattice;
78
79   // map a method/class descriptor to a hierarchy graph
80   private Map<Descriptor, HierarchyGraph> mapDescriptorToHierarchyGraph;
81
82   // map a method/class descriptor to a skeleton hierarchy graph
83   private Map<Descriptor, HierarchyGraph> mapDescriptorToSkeletonHierarchyGraph;
84
85   private Map<Descriptor, HierarchyGraph> mapDescriptorToSimpleHierarchyGraph;
86
87   // map a method/class descriptor to a skeleton hierarchy graph with combination nodes
88   private Map<Descriptor, HierarchyGraph> mapDescriptorToCombineSkeletonHierarchyGraph;
89
90   // map a descriptor to a simple lattice
91   private Map<Descriptor, SSJavaLattice<String>> mapDescriptorToSimpleLattice;
92
93   // map a method descriptor to the set of method invocation nodes which are
94   // invoked by the method descriptor
95   private Map<MethodDescriptor, Set<MethodInvokeNode>> mapMethodDescriptorToMethodInvokeNodeSet;
96
97   private Map<MethodInvokeNode, Map<Integer, NTuple<Descriptor>>> mapMethodInvokeNodeToArgIdxMap;
98
99   private Map<MethodInvokeNode, NTuple<Descriptor>> mapMethodInvokeNodeToBaseTuple;
100
101   private Map<MethodDescriptor, MethodLocationInfo> mapMethodDescToMethodLocationInfo;
102
103   private Map<ClassDescriptor, LocationInfo> mapClassToLocationInfo;
104
105   private Map<MethodDescriptor, Set<MethodDescriptor>> mapMethodToCalleeSet;
106
107   private Map<MethodDescriptor, Set<FlowNode>> mapMethodDescToParamNodeFlowsToReturnValue;
108
109   private Map<String, Vector<String>> mapFileNameToLineVector;
110
111   private Map<Descriptor, Integer> mapDescToDefinitionLine;
112
113   private Map<Descriptor, LocationSummary> mapDescToLocationSummary;
114
115   // maps a method descriptor to a sub global flow graph that captures all value flows caused by the
116   // set of callees reachable from the method
117   private Map<MethodDescriptor, GlobalFlowGraph> mapMethodDescriptorToSubGlobalFlowGraph;
118
119   private Map<MethodInvokeNode, Map<NTuple<Descriptor>, NTuple<Descriptor>>> mapMethodInvokeNodeToMapCallerArgToCalleeArg;
120
121   public static final String GLOBALLOC = "GLOBALLOC";
122
123   public static final String TOPLOC = "TOPLOC";
124
125   public static final String INTERLOC = "INTERLOC";
126
127   public static final String PCLOC = "PCLOC";
128
129   public static final Descriptor GLOBALDESC = new NameDescriptor(GLOBALLOC);
130
131   public static final Descriptor TOPDESC = new NameDescriptor(TOPLOC);
132
133   public static String newline = System.getProperty("line.separator");
134
135   LocationInfo curMethodInfo;
136
137   boolean debug = true;
138
139   private static int locSeed = 0;
140
141   public LocationInference(SSJavaAnalysis ssjava, State state) {
142     this.ssjava = ssjava;
143     this.state = state;
144     this.temp_toanalyzeList = new ArrayList<ClassDescriptor>();
145     this.temp_toanalyzeMethodList = new ArrayList<MethodDescriptor>();
146     this.mapMethodDescriptorToFlowGraph = new HashMap<MethodDescriptor, FlowGraph>();
147     this.cd2lattice = new HashMap<ClassDescriptor, SSJavaLattice<String>>();
148     this.md2lattice = new HashMap<MethodDescriptor, SSJavaLattice<String>>();
149     this.methodDescriptorsToVisitStack = new Stack<MethodDescriptor>();
150     this.mapMethodDescriptorToMethodInvokeNodeSet =
151         new HashMap<MethodDescriptor, Set<MethodInvokeNode>>();
152     this.mapMethodInvokeNodeToArgIdxMap =
153         new HashMap<MethodInvokeNode, Map<Integer, NTuple<Descriptor>>>();
154     this.mapMethodDescToMethodLocationInfo = new HashMap<MethodDescriptor, MethodLocationInfo>();
155     this.mapMethodToCalleeSet = new HashMap<MethodDescriptor, Set<MethodDescriptor>>();
156     this.mapClassToLocationInfo = new HashMap<ClassDescriptor, LocationInfo>();
157
158     this.mapFileNameToLineVector = new HashMap<String, Vector<String>>();
159     this.mapDescToDefinitionLine = new HashMap<Descriptor, Integer>();
160     this.mapMethodDescToParamNodeFlowsToReturnValue =
161         new HashMap<MethodDescriptor, Set<FlowNode>>();
162
163     this.mapDescriptorToHierarchyGraph = new HashMap<Descriptor, HierarchyGraph>();
164     this.mapMethodInvokeNodeToBaseTuple = new HashMap<MethodInvokeNode, NTuple<Descriptor>>();
165
166     this.mapDescriptorToSkeletonHierarchyGraph = new HashMap<Descriptor, HierarchyGraph>();
167     this.mapDescriptorToCombineSkeletonHierarchyGraph = new HashMap<Descriptor, HierarchyGraph>();
168     this.mapDescriptorToSimpleHierarchyGraph = new HashMap<Descriptor, HierarchyGraph>();
169
170     this.mapDescriptorToSimpleLattice = new HashMap<Descriptor, SSJavaLattice<String>>();
171
172     this.mapDescToLocationSummary = new HashMap<Descriptor, LocationSummary>();
173
174     this.mapMethodDescriptorToSubGlobalFlowGraph = new HashMap<MethodDescriptor, GlobalFlowGraph>();
175
176     this.mapMethodInvokeNodeToMapCallerArgToCalleeArg =
177         new HashMap<MethodInvokeNode, Map<NTuple<Descriptor>, NTuple<Descriptor>>>();
178
179   }
180
181   public void setupToAnalyze() {
182     SymbolTable classtable = state.getClassSymbolTable();
183     temp_toanalyzeList.clear();
184     temp_toanalyzeList.addAll(classtable.getValueSet());
185     // Collections.sort(toanalyzeList, new Comparator<ClassDescriptor>() {
186     // public int compare(ClassDescriptor o1, ClassDescriptor o2) {
187     // return o1.getClassName().compareToIgnoreCase(o2.getClassName());
188     // }
189     // });
190   }
191
192   public void setupToAnalazeMethod(ClassDescriptor cd) {
193
194     SymbolTable methodtable = cd.getMethodTable();
195     temp_toanalyzeMethodList.clear();
196     temp_toanalyzeMethodList.addAll(methodtable.getValueSet());
197     Collections.sort(temp_toanalyzeMethodList, new Comparator<MethodDescriptor>() {
198       public int compare(MethodDescriptor o1, MethodDescriptor o2) {
199         return o1.getSymbol().compareToIgnoreCase(o2.getSymbol());
200       }
201     });
202   }
203
204   public boolean toAnalyzeMethodIsEmpty() {
205     return temp_toanalyzeMethodList.isEmpty();
206   }
207
208   public boolean toAnalyzeIsEmpty() {
209     return temp_toanalyzeList.isEmpty();
210   }
211
212   public ClassDescriptor toAnalyzeNext() {
213     return temp_toanalyzeList.remove(0);
214   }
215
216   public MethodDescriptor toAnalyzeMethodNext() {
217     return temp_toanalyzeMethodList.remove(0);
218   }
219
220   public void inference() {
221
222     // 1) construct value flow graph
223     constructFlowGraph();
224
225     assignCompositeLocation();
226
227     // constructGlobalFlowGraph();
228
229     constructHierarchyGraph();
230
231     debug_writeHierarchyDotFiles();
232
233     // calculate RETURNLOC,PCLOC
234     calculateExtraLocations();
235
236     simplifyHierarchyGraph();
237
238     debug_writeSimpleHierarchyDotFiles();
239
240     constructSkeletonHierarchyGraph();
241
242     debug_writeSkeletonHierarchyDotFiles();
243
244     insertCombinationNodes();
245
246     debug_writeSkeletonCombinationHierarchyDotFiles();
247
248     // System.exit(0);
249
250     buildLattice();
251
252     debug_writeLattices();
253
254     updateCompositeLocationAssignments();
255
256     generateMethodSummary();
257
258     System.exit(0);
259
260     // 2) construct lattices
261     // inferLattices();
262     // simplifyLattices();
263     // 3) check properties
264     // checkLattices();
265
266     // calculate RETURNLOC,PCLOC
267     calculateExtraLocations();
268
269     debug_writeLatticeDotFile();
270
271     // 4) generate annotated source codes
272     generateAnnoatedCode();
273
274   }
275
276   public Map<NTuple<Descriptor>, NTuple<Descriptor>> getMapCallerArgToCalleeParam(
277       MethodInvokeNode min) {
278
279     if (!mapMethodInvokeNodeToMapCallerArgToCalleeArg.containsKey(min)) {
280       mapMethodInvokeNodeToMapCallerArgToCalleeArg.put(min,
281           new HashMap<NTuple<Descriptor>, NTuple<Descriptor>>());
282     }
283
284     return mapMethodInvokeNodeToMapCallerArgToCalleeArg.get(min);
285   }
286
287   public void addMapCallerArgToCalleeParam(MethodInvokeNode min, NTuple<Descriptor> callerArg,
288       NTuple<Descriptor> calleeParam) {
289     getMapCallerArgToCalleeParam(min).put(callerArg, calleeParam);
290   }
291
292   private void assignCompositeLocation() {
293     calculateGlobalValueFlowCompositeLocation();
294     translateCompositeLocationAssignmentToFlowGraph();
295   }
296
297   private void translateCompositeLocationAssignmentToFlowGraph() {
298     MethodDescriptor methodEventLoopDesc = ssjava.getMethodContainingSSJavaLoop();
299     translateCompositeLocationAssignmentToFlowGraph(methodEventLoopDesc);
300     _debug_printGraph();
301   }
302
303   private void updateCompositeLocationAssignments() {
304
305     LinkedList<MethodDescriptor> methodDescList =
306         (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
307
308     while (!methodDescList.isEmpty()) {
309       MethodDescriptor md = methodDescList.removeLast();
310       GlobalFlowGraph globalFlowGraph = getSubGlobalFlowGraph(md);
311       FlowGraph flowGraph = getFlowGraph(md);
312
313       Set<FlowNode> nodeSet = flowGraph.getNodeSet();
314       for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
315         FlowNode node = (FlowNode) iterator.next();
316         if (node.getCompositeLocation() != null) {
317           CompositeLocation compLoc = node.getCompositeLocation();
318           CompositeLocation updatedCompLoc = updateCompositeLocation(compLoc);
319           node.setCompositeLocation(updatedCompLoc);
320         } else {
321           NTuple<Descriptor> descTuple = node.getDescTuple();
322           CompositeLocation compLoc = convertToCompositeLocation(md, descTuple);
323           node.setCompositeLocation(compLoc);
324         }
325       }
326
327     }
328
329   }
330
331   private CompositeLocation updateCompositeLocation(CompositeLocation compLoc) {
332     CompositeLocation updatedCompLoc = new CompositeLocation();
333     for (int i = 0; i < compLoc.getSize(); i++) {
334       Location loc = compLoc.get(i);
335       String nodeIdentifier = loc.getLocIdentifier();
336       Descriptor enclosingDesc = loc.getDescriptor();
337       LocationSummary locSummary = getLocationSummary(enclosingDesc);
338       String locName = locSummary.getLocationName(nodeIdentifier);
339       Location updatedLoc = new Location(enclosingDesc, locName);
340       updatedCompLoc.addLocation(updatedLoc);
341     }
342
343     return updatedCompLoc;
344   }
345
346   private void translateCompositeLocationAssignmentToFlowGraph(MethodDescriptor mdCaller) {
347
348     System.out.println("\n#translateCompositeLocationAssignmentToFlowGraph=" + mdCaller);
349
350     // First, assign a composite location to a node in the flow graph
351     GlobalFlowGraph callerGlobalFlowGraph = getSubGlobalFlowGraph(mdCaller);
352
353     FlowGraph callerFlowGraph = getFlowGraph(mdCaller);
354     Map<Location, CompositeLocation> callerMapLocToCompLoc =
355         callerGlobalFlowGraph.getMapLocationToInferCompositeLocation();
356     System.out.println("---callerMapLocToCompLoc=" + callerMapLocToCompLoc);
357     Set<Location> methodLocSet = callerMapLocToCompLoc.keySet();
358     for (Iterator iterator = methodLocSet.iterator(); iterator.hasNext();) {
359       Location methodLoc = (Location) iterator.next();
360       if (methodLoc.getDescriptor().equals(mdCaller)) {
361         CompositeLocation inferCompLoc = callerMapLocToCompLoc.get(methodLoc);
362         assignCompositeLocationToFlowGraph(callerFlowGraph, methodLoc, inferCompLoc);
363       }
364     }
365
366     Set<MethodInvokeNode> minSet = mapMethodDescriptorToMethodInvokeNodeSet.get(mdCaller);
367
368     Set<MethodDescriptor> calleeSet = new HashSet<MethodDescriptor>();
369     for (Iterator iterator = minSet.iterator(); iterator.hasNext();) {
370       MethodInvokeNode min = (MethodInvokeNode) iterator.next();
371       // need to translate a composite location that is started with the base
372       // tuple of 'min'.
373       if (mapMethodInvokeNodeToBaseTuple.get(min) != null) {
374         // if mapMethodInvokeNodeToBaseTuple doesn't have a mapping
375         // it means that the corresponding callee method does not cause any
376         // flows
377         translateMapLocationToInferCompositeLocationToCalleeGraph(callerGlobalFlowGraph, min);
378       }
379       calleeSet.add(min.getMethod());
380     }
381
382     for (Iterator iterator = calleeSet.iterator(); iterator.hasNext();) {
383       MethodDescriptor callee = (MethodDescriptor) iterator.next();
384       translateCompositeLocationAssignmentToFlowGraph(callee);
385     }
386
387   }
388
389   public void assignCompositeLocationToFlowGraph(FlowGraph flowGraph, Location loc,
390       CompositeLocation inferCompLoc) {
391     Descriptor localDesc = loc.getLocDescriptor();
392
393     Set<FlowNode> nodeSet = flowGraph.getNodeSet();
394     for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
395       FlowNode node = (FlowNode) iterator.next();
396       if (node.getDescTuple().startsWith(localDesc)) {
397         // need to assign the inferred composite location to this node
398         CompositeLocation newCompLoc = generateCompositeLocation(node.getDescTuple(), inferCompLoc);
399         node.setCompositeLocation(newCompLoc);
400         System.out.println("SET Node=" + node + "  inferCompLoc=" + newCompLoc);
401       }
402     }
403   }
404
405   private CompositeLocation generateCompositeLocation(NTuple<Descriptor> nodeDescTuple,
406       CompositeLocation inferCompLoc) {
407
408     System.out.println("generateCompositeLocation=" + nodeDescTuple + " with inferCompLoc="
409         + inferCompLoc);
410
411     CompositeLocation newCompLoc = new CompositeLocation();
412     for (int i = 0; i < inferCompLoc.getSize(); i++) {
413       newCompLoc.addLocation(inferCompLoc.get(i));
414     }
415
416     Descriptor lastDescOfPrefix = nodeDescTuple.get(0);
417     Descriptor enclosingDescriptor;
418     if (lastDescOfPrefix instanceof InterDescriptor) {
419       enclosingDescriptor = null;
420     } else {
421       enclosingDescriptor = ((VarDescriptor) lastDescOfPrefix).getType().getClassDesc();
422     }
423
424     for (int i = 1; i < nodeDescTuple.size(); i++) {
425       Descriptor desc = nodeDescTuple.get(i);
426       Location locElement = new Location(enclosingDescriptor, desc);
427       newCompLoc.addLocation(locElement);
428
429       enclosingDescriptor = ((FieldDescriptor) desc).getClassDescriptor();
430     }
431
432     return newCompLoc;
433   }
434
435   private void translateMapLocationToInferCompositeLocationToCalleeGraph(
436       GlobalFlowGraph callerGraph, MethodInvokeNode min) {
437
438     MethodDescriptor mdCallee = min.getMethod();
439     MethodDescriptor mdCaller = callerGraph.getMethodDescriptor();
440     Map<Location, CompositeLocation> callerMapLocToCompLoc =
441         callerGraph.getMapLocationToInferCompositeLocation();
442
443     FlowGraph calleeFlowGraph = getFlowGraph(mdCallee);
444     GlobalFlowGraph calleeGlobalGraph = getSubGlobalFlowGraph(mdCallee);
445
446     NTuple<Location> baseLocTuple =
447         translateToLocTuple(mdCaller, mapMethodInvokeNodeToBaseTuple.get(min));
448
449     System.out.println("\n-translate caller infer composite loc to callee=" + mdCallee
450         + " baseLocTuple=" + baseLocTuple);
451     Set<Location> keySet = callerMapLocToCompLoc.keySet();
452     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
453       Location key = (Location) iterator.next();
454       CompositeLocation callerCompLoc = callerMapLocToCompLoc.get(key);
455
456       if (!key.getDescriptor().equals(mdCaller)) {
457         System.out.println("--- caller key=" + key + "  callerCompLoc=" + callerCompLoc);
458
459         // && callerCompLoc.getTuple().startsWith(baseLocTuple)) {
460         // need to translate to the callee side
461
462         // TODO
463         CompositeLocation newCalleeCompLoc;
464         if (callerCompLoc.getTuple().startsWith(baseLocTuple)) {
465           System.out.println("---need to translate callerCompLoc=" + callerCompLoc
466               + " with baseTuple=" + baseLocTuple);
467           newCalleeCompLoc =
468               translateCompositeLocationToCallee(callerCompLoc, baseLocTuple, mdCallee);
469
470           calleeGlobalGraph.addMapLocationToInferCompositeLocation(key, newCalleeCompLoc);
471           System.out.println("---callee loc=" + key + "  newCalleeCompLoc=" + newCalleeCompLoc);
472         } else {
473           // newCalleeCompLoc = callerCompLoc.clone();
474         }
475
476       }
477     }
478
479     // If the location of an argument has a composite location
480     // need to assign a proper composite location to the corresponding callee parameter
481     System.out.println("\n-translate arg composite location to callee param. min="
482         + min.printNode(0));
483     Map<Integer, NTuple<Descriptor>> mapIdxToArgTuple = mapMethodInvokeNodeToArgIdxMap.get(min);
484     Set<Integer> idxSet = mapIdxToArgTuple.keySet();
485     for (Iterator iterator = idxSet.iterator(); iterator.hasNext();) {
486       Integer idx = (Integer) iterator.next();
487
488       if (idx == 0 && !min.getMethod().isStatic()) {
489         continue;
490       }
491
492       NTuple<Descriptor> argTuple = mapIdxToArgTuple.get(idx);
493       if (argTuple.size() > 0) {
494         // check if an arg tuple has been already assigned to a composite location
495         NTuple<Location> argLocTuple = translateToLocTuple(mdCaller, argTuple);
496         Location argLocalLoc = argLocTuple.get(0);
497
498         // if (!isPrimitiveType(argTuple)) {
499         if (callerMapLocToCompLoc.containsKey(argLocalLoc)) {
500
501           CompositeLocation callerCompLoc = callerMapLocToCompLoc.get(argLocalLoc);
502           for (int i = 1; i < argLocTuple.size(); i++) {
503             callerCompLoc.addLocation(argLocTuple.get(i));
504           }
505
506           if (callerCompLoc.getTuple().startsWith(baseLocTuple)) {
507
508             FlowNode calleeParamFlowNode = calleeFlowGraph.getParamFlowNode(idx);
509             NTuple<Descriptor> calleeParamDescTuple = calleeParamFlowNode.getDescTuple();
510             NTuple<Location> calleeParamLocTuple =
511                 translateToLocTuple(mdCallee, calleeParamDescTuple);
512
513             System.out.println("---need to translate callerCompLoc=" + callerCompLoc
514                 + " with baseTuple=" + baseLocTuple + "   calleeParamLocTuple="
515                 + calleeParamLocTuple);
516
517             CompositeLocation newCalleeCompLoc =
518                 translateCompositeLocationToCallee(callerCompLoc, baseLocTuple, mdCallee);
519
520             calleeGlobalGraph.addMapLocationToInferCompositeLocation(calleeParamLocTuple.get(0),
521                 newCalleeCompLoc);
522
523             System.out.println("---callee loc=" + calleeParamLocTuple.get(0)
524                 + "  newCalleeCompLoc=" + newCalleeCompLoc);
525
526             // System.out.println("###need to assign composite location to=" + calleeParamDescTuple
527             // + " with baseTuple=" + baseLocTuple);
528           }
529
530         }
531       }
532
533     }
534
535   }
536
537   private boolean isPrimitiveType(NTuple<Descriptor> argTuple) {
538
539     Descriptor lastDesc = argTuple.get(argTuple.size() - 1);
540
541     if (lastDesc instanceof FieldDescriptor) {
542       return ((FieldDescriptor) lastDesc).getType().isPrimitive();
543     } else if (lastDesc instanceof VarDescriptor) {
544       return ((VarDescriptor) lastDesc).getType().isPrimitive();
545     }
546
547     return true;
548   }
549
550   private CompositeLocation translateCompositeLocationToCallee(CompositeLocation callerCompLoc,
551       NTuple<Location> baseLocTuple, MethodDescriptor mdCallee) {
552
553     CompositeLocation newCalleeCompLoc = new CompositeLocation();
554
555     Location calleeThisLoc = new Location(mdCallee, mdCallee.getThis());
556     newCalleeCompLoc.addLocation(calleeThisLoc);
557
558     // remove the base tuple from the caller
559     // ex; In the method invoation foo.bar.methodA(), the callee will have the composite location
560     // ,which is relative to the 'this' variable, <THIS,...>
561     for (int i = baseLocTuple.size(); i < callerCompLoc.getSize(); i++) {
562       newCalleeCompLoc.addLocation(callerCompLoc.get(i));
563     }
564
565     return newCalleeCompLoc;
566
567   }
568
569   private void constructGlobalFlowGraph() {
570
571     System.out.println("");
572     LinkedList<MethodDescriptor> methodDescList =
573         (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
574
575     System.out.println("@@@methodDescList=" + methodDescList);
576     // System.exit(0);
577
578     while (!methodDescList.isEmpty()) {
579       MethodDescriptor md = methodDescList.removeLast();
580       if (state.SSJAVADEBUG) {
581         System.out.println();
582         System.out.println("SSJAVA: Constructing a global flow graph: " + md);
583
584         FlowGraph flowGraph = getFlowGraph(md);
585         FlowGraph subGlobalFlowGraph = flowGraph.clone();
586
587         // mapMethodDescriptorToSubGlobalFlowGraph.put(md, subGlobalFlowGraph);
588
589         // addValueFlowsFromCalleeSubGlobalFlowGraph(md, subGlobalFlowGraph);
590
591         // try {
592         // subGlobalFlowGraph.writeGraph("_SUBGLOBAL");
593         // } catch (IOException e) {
594         // e.printStackTrace();
595         // }
596         // FlowGraph fg = new FlowGraph(md, mapParamDescToIdx);
597         // mapMethodDescriptorToFlowGraph.put(md, fg);
598         // analyzeMethodBody(md.getClassDesc(), md);
599       }
600
601     }
602
603     // DEBUG: write a global flow graph
604     MethodDescriptor mdContainingSSJavaLoop = ssjava.getMethodContainingSSJavaLoop();
605     // FlowGraph globalFlowGraph =
606     // getSubGlobalFlowGraph(mdContainingSSJavaLoop);
607     // System.out.println("GLOBAL NODE SET=" + globalFlowGraph.getNodeSet());
608     // assignCompositeLocation(globalFlowGraph);
609     // try {
610     // globalFlowGraph.writeGraph("_GLOBAL");
611     // } catch (IOException e) {
612     // e.printStackTrace();
613     // }
614     // _debug_printGraph();
615
616   }
617
618   private void calculateGlobalValueFlowCompositeLocation() {
619
620     System.out.println("SSJAVA: Calculate composite locations in the global value flow graph");
621     MethodDescriptor methodDescEventLoop = ssjava.getMethodContainingSSJavaLoop();
622     GlobalFlowGraph globalFlowGraph = getSubGlobalFlowGraph(methodDescEventLoop);
623
624     Set<Location> calculatedPrefixSet = new HashSet<Location>();
625
626     Set<GlobalFlowNode> nodeSet = globalFlowGraph.getNodeSet();
627
628     next: for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
629       GlobalFlowNode node = (GlobalFlowNode) iterator.next();
630
631       Location prefixLoc = node.getLocTuple().get(0);
632
633       if (calculatedPrefixSet.contains(prefixLoc)) {
634         // the prefix loc has been already assigned to a composite location
635         continue;
636       }
637
638       calculatedPrefixSet.add(prefixLoc);
639
640       // Set<GlobalFlowNode> incomingNodeSet = globalFlowGraph.getIncomingNodeSet(node);
641       List<NTuple<Location>> prefixList = calculatePrefixList(globalFlowGraph, node);
642
643       Set<GlobalFlowNode> reachableNodeSet =
644           globalFlowGraph.getReachableNodeSetByPrefix(node.getLocTuple().get(0));
645       // Set<GlobalFlowNode> reachNodeSet = globalFlowGraph.getReachableNodeSetFrom(node);
646
647       // System.out.println("node=" + node + "    prefixList=" + prefixList + "   reachableNodeSet="
648       // + reachableNodeSet);
649
650       for (int i = 0; i < prefixList.size(); i++) {
651         NTuple<Location> curPrefix = prefixList.get(i);
652         Set<NTuple<Location>> reachableCommonPrefixSet = new HashSet<NTuple<Location>>();
653
654         for (Iterator iterator2 = reachableNodeSet.iterator(); iterator2.hasNext();) {
655           GlobalFlowNode reachNode = (GlobalFlowNode) iterator2.next();
656           if (reachNode.getLocTuple().startsWith(curPrefix)) {
657             reachableCommonPrefixSet.add(reachNode.getLocTuple());
658           }
659         }
660
661         if (!reachableCommonPrefixSet.isEmpty()) {
662
663           MethodDescriptor curPrefixFirstElementMethodDesc =
664               (MethodDescriptor) curPrefix.get(0).getDescriptor();
665
666           MethodDescriptor nodePrefixLocFirstElementMethodDesc =
667               (MethodDescriptor) prefixLoc.getDescriptor();
668
669           if (curPrefixFirstElementMethodDesc.equals(nodePrefixLocFirstElementMethodDesc)
670               || isTransitivelyCalledFrom(nodePrefixLocFirstElementMethodDesc,
671                   curPrefixFirstElementMethodDesc)) {
672
673             // TODO
674             // if (!node.getLocTuple().startsWith(curPrefix.get(0))) {
675
676             Location curPrefixLocalLoc = curPrefix.get(0);
677             if (globalFlowGraph.mapLocationToInferCompositeLocation.containsKey(curPrefixLocalLoc)) {
678               // in this case, the local variable of the current prefix has already got a composite
679               // location
680               // so we just ignore the current composite location.
681
682               // System.out.println("HERE WE DO NOT ASSIGN A COMPOSITE LOCATION TO =" + node
683               // + " DUE TO " + curPrefix);
684
685               continue next;
686             }
687
688             Location targetLocalLoc = node.getLocTuple().get(0);
689             // CompositeLocation curCompLoc = globalFlowGraph.getCompositeLocation(targetLocalLoc);
690             // if ((curPrefix.size() + 1) > curCompLoc.getSize()) {
691
692             CompositeLocation newCompLoc = generateCompositeLocation(curPrefix);
693             System.out.println("NEED TO ASSIGN COMP LOC TO " + node + " with prefix=" + curPrefix);
694             System.out.println("- newCompLoc=" + newCompLoc);
695             globalFlowGraph.addMapLocationToInferCompositeLocation(targetLocalLoc, newCompLoc);
696             // }
697
698             continue next;
699             // }
700
701           }
702
703         }
704
705       }
706
707     }
708     // Set<GlobalFlowNode> inNodeSet =
709     // graph.getIncomingNodeSetWithPrefix(prefix);
710     // System.out.println("inNodeSet=" + inNodeSet + "  from=" + node);
711   }
712
713   private void assignCompositeLocation(CompositeLocation compLocPrefix, GlobalFlowNode node) {
714     CompositeLocation newCompLoc = compLocPrefix.clone();
715     NTuple<Location> locTuple = node.getLocTuple();
716     for (int i = 1; i < locTuple.size(); i++) {
717       newCompLoc.addLocation(locTuple.get(i));
718     }
719     node.setInferCompositeLocation(newCompLoc);
720   }
721
722   private List<NTuple<Location>> calculatePrefixList(GlobalFlowGraph graph, GlobalFlowNode node) {
723
724     System.out.println("\n##### calculatePrefixList node=" + node);
725
726     MethodDescriptor md = graph.getMethodDescriptor();
727
728     Set<GlobalFlowNode> incomingNodeSetPrefix =
729         graph.getIncomingNodeSetByPrefix(node.getLocTuple().get(0));
730     // System.out.println("incomingNodeSetPrefix=" + incomingNodeSetPrefix);
731     //
732     // Set<GlobalFlowNode> reachableNodeSetPrefix =
733     // graph.getReachableNodeSetByPrefix(node.getLocTuple().get(0));
734     // System.out.println("reachableNodeSetPrefix=" + reachableNodeSetPrefix);
735
736     List<NTuple<Location>> prefixList = new ArrayList<NTuple<Location>>();
737
738     for (Iterator iterator = incomingNodeSetPrefix.iterator(); iterator.hasNext();) {
739       GlobalFlowNode inNode = (GlobalFlowNode) iterator.next();
740       NTuple<Location> inNodeTuple = inNode.getLocTuple();
741
742       for (int i = 1; i < inNodeTuple.size(); i++) {
743         NTuple<Location> prefix = inNodeTuple.subList(0, i);
744         if (!prefixList.contains(prefix)) {
745           prefixList.add(prefix);
746         }
747       }
748     }
749
750     Collections.sort(prefixList, new Comparator<NTuple<Location>>() {
751       public int compare(NTuple<Location> arg0, NTuple<Location> arg1) {
752         int s0 = arg0.size();
753         int s1 = arg1.size();
754         if (s0 > s1) {
755           return -1;
756         } else if (s0 == s1) {
757           return 0;
758         } else {
759           return 1;
760         }
761       }
762     });
763     return prefixList;
764
765     // List<NTuple<Location>> prefixList = new ArrayList<NTuple<Location>>();
766     //
767     // for (Iterator iterator = incomingNodeSet.iterator(); iterator.hasNext();) {
768     // GlobalFlowNode inNode = (GlobalFlowNode) iterator.next();
769     // NTuple<Location> inNodeTuple = inNode.getLocTuple();
770     //
771     // for (int i = 1; i < inNodeTuple.size(); i++) {
772     // NTuple<Location> prefix = inNodeTuple.subList(0, i);
773     // if (!prefixList.contains(prefix)) {
774     // prefixList.add(prefix);
775     // }
776     // }
777     // }
778     //
779     // Collections.sort(prefixList, new Comparator<NTuple<Location>>() {
780     // public int compare(NTuple<Location> arg0, NTuple<Location> arg1) {
781     // int s0 = arg0.size();
782     // int s1 = arg1.size();
783     // if (s0 > s1) {
784     // return -1;
785     // } else if (s0 == s1) {
786     // return 0;
787     // } else {
788     // return 1;
789     // }
790     // }
791     // });
792     // return prefixList;
793   }
794
795   private GlobalFlowGraph constructSubGlobalFlowGraph(FlowGraph flowGraph) {
796
797     MethodDescriptor md = flowGraph.getMethodDescriptor();
798
799     GlobalFlowGraph globalGraph = new GlobalFlowGraph(md);
800
801     // Set<FlowNode> nodeSet = flowGraph.getNodeSet();
802     Set<FlowEdge> edgeSet = flowGraph.getEdgeSet();
803
804     for (Iterator iterator = edgeSet.iterator(); iterator.hasNext();) {
805
806       FlowEdge edge = (FlowEdge) iterator.next();
807       NTuple<Descriptor> srcDescTuple = edge.getInitTuple();
808       NTuple<Descriptor> dstDescTuple = edge.getEndTuple();
809
810       // here only keep the first element(method location) of the descriptor
811       // tuple
812       NTuple<Location> srcLocTuple = translateToLocTuple(md, srcDescTuple);
813       // Location srcMethodLoc = srcLocTuple.get(0);
814       // Descriptor srcVarDesc = srcMethodLoc.getLocDescriptor();
815       // // if (flowGraph.isParamDesc(srcVarDesc) &&
816       // (!srcVarDesc.equals(md.getThis()))) {
817       // if (!srcVarDesc.equals(md.getThis())) {
818       // srcLocTuple = new NTuple<Location>();
819       // Location loc = new Location(md, srcVarDesc);
820       // srcLocTuple.add(loc);
821       // }
822       //
823       NTuple<Location> dstLocTuple = translateToLocTuple(md, dstDescTuple);
824       // Location dstMethodLoc = dstLocTuple.get(0);
825       // Descriptor dstVarDesc = dstMethodLoc.getLocDescriptor();
826       // if (!dstVarDesc.equals(md.getThis())) {
827       // dstLocTuple = new NTuple<Location>();
828       // Location loc = new Location(md, dstVarDesc);
829       // dstLocTuple.add(loc);
830       // }
831
832       globalGraph.addValueFlowEdge(srcLocTuple, dstLocTuple);
833
834     }
835
836     return globalGraph;
837   }
838
839   private NTuple<Location> translateToLocTuple(MethodDescriptor md, NTuple<Descriptor> descTuple) {
840
841     NTuple<Location> locTuple = new NTuple<Location>();
842
843     Descriptor enclosingDesc = md;
844     // System.out.println("md=" + md + "  descTuple=" + descTuple);
845     for (int i = 0; i < descTuple.size(); i++) {
846       Descriptor desc = descTuple.get(i);
847
848       Location loc = new Location(enclosingDesc, desc);
849       locTuple.add(loc);
850
851       if (desc instanceof VarDescriptor) {
852         enclosingDesc = ((VarDescriptor) desc).getType().getClassDesc();
853       } else if (desc instanceof FieldDescriptor) {
854         enclosingDesc = ((FieldDescriptor) desc).getType().getClassDesc();
855       } else {
856         // TODO: inter descriptor case
857         enclosingDesc = desc;
858       }
859
860     }
861
862     return locTuple;
863
864   }
865
866   private void addValueFlowsFromCalleeSubGlobalFlowGraph(MethodDescriptor mdCaller,
867       GlobalFlowGraph subGlobalFlowGraph) {
868
869     // the transformation for a call site propagates flows through parameters
870     // if the method is virtual, it also grab all relations from any possible
871     // callees
872
873     Set<MethodInvokeNode> setMethodInvokeNode = getMethodInvokeNodeSet(mdCaller);
874
875     for (Iterator iterator = setMethodInvokeNode.iterator(); iterator.hasNext();) {
876       MethodInvokeNode min = (MethodInvokeNode) iterator.next();
877       MethodDescriptor mdCallee = min.getMethod();
878       Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
879       if (mdCallee.isStatic()) {
880         setPossibleCallees.add(mdCallee);
881       } else {
882         Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getMethods(mdCallee);
883         // removes method descriptors that are not invoked by the caller
884         calleeSet.retainAll(mapMethodToCalleeSet.get(mdCaller));
885         setPossibleCallees.addAll(calleeSet);
886       }
887
888       for (Iterator iterator2 = setPossibleCallees.iterator(); iterator2.hasNext();) {
889         MethodDescriptor possibleMdCallee = (MethodDescriptor) iterator2.next();
890         propagateValueFlowsToCallerFromSubGlobalFlowGraph(min, mdCaller, possibleMdCallee);
891       }
892
893     }
894
895   }
896
897   private void propagateValueFlowsToCallerFromSubGlobalFlowGraph(MethodInvokeNode min,
898       MethodDescriptor mdCaller, MethodDescriptor possibleMdCallee) {
899
900     System.out.println("propagateValueFlowsToCallerFromSubGlobalFlowGraph=" + min.printNode(0)
901         + " by caller=" + mdCaller);
902     FlowGraph calleeFlowGraph = getFlowGraph(possibleMdCallee);
903     Map<Integer, NTuple<Descriptor>> mapIdxToArg = mapMethodInvokeNodeToArgIdxMap.get(min);
904
905     System.out.println("mapMethodInvokeNodeToArgIdxMap.get(min)="
906         + mapMethodInvokeNodeToArgIdxMap.get(min));
907     Set<Integer> keySet = mapIdxToArg.keySet();
908     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
909       Integer idx = (Integer) iterator.next();
910       NTuple<Descriptor> argDescTuple = mapIdxToArg.get(idx);
911       if (argDescTuple.size() > 0) {
912         NTuple<Location> argLocTuple = translateToLocTuple(mdCaller, argDescTuple);
913         NTuple<Descriptor> paramDescTuple = calleeFlowGraph.getParamFlowNode(idx).getDescTuple();
914         NTuple<Location> paramLocTuple = translateToLocTuple(possibleMdCallee, paramDescTuple);
915         addMapCallerArgToCalleeParam(min, argDescTuple, paramDescTuple);
916       }
917
918     }
919
920     NTuple<Descriptor> baseTuple = mapMethodInvokeNodeToBaseTuple.get(min);
921     GlobalFlowGraph calleeSubGlobalGraph = getSubGlobalFlowGraph(possibleMdCallee);
922     Set<GlobalFlowNode> calleeNodeSet = calleeSubGlobalGraph.getNodeSet();
923     System.out.println("#calleeNodeSet=" + calleeNodeSet);
924     for (Iterator iterator = calleeNodeSet.iterator(); iterator.hasNext();) {
925       GlobalFlowNode calleeNode = (GlobalFlowNode) iterator.next();
926       addValueFlowFromCalleeNode(min, mdCaller, possibleMdCallee, calleeNode);
927     }
928
929     // int numParam = calleeFlowGraph.getNumParameters();
930     // for (int idx = 0; idx < numParam; idx++) {
931     //
932     // FlowNode paramNode = calleeFlowGraph.getParamFlowNode(idx);
933     //
934     // NTuple<Location> paramLocTuple =
935     // translateToLocTuple(possibleMdCallee, paramNode.getCurrentDescTuple());
936     //
937     // GlobalFlowNode globalParamNode =
938     // calleeSubGlobalGraph.getFlowNode(paramLocTuple);
939     //
940     // NTuple<Descriptor> argTuple =
941     // mapMethodInvokeNodeToArgIdxMap.get(min).get(idx);
942     //
943     // NTuple<Location> argLocTuple = translateToLocTuple(mdCaller, argTuple);
944     //
945     // System.out.println("argTupleSet=" + argLocTuple + "   param=" +
946     // paramLocTuple);
947     // // here, it adds all value flows reachable from the paramNode in the
948     // callee's flow graph
949     //
950     // addValueFlowsFromCalleeParam(mdCaller, argLocTuple, baseLocTuple,
951     // possibleMdCallee,
952     // globalParamNode);
953     // }
954     //
955     // // TODO
956     // // FlowGraph callerSubGlobalGraph = getSubGlobalFlowGraph(mdCaller);
957     // // FlowGraph calleeSubGlobalGraph =
958     // getSubGlobalFlowGraph(possibleMdCallee);
959     // //
960     // // int numParam = calleeSubGlobalGraph.getNumParameters();
961     // // for (int idx = 0; idx < numParam; idx++) {
962     // // FlowNode paramNode = calleeSubGlobalGraph.getParamFlowNode(idx);
963     // // NTuple<Descriptor> argTuple =
964     // mapMethodInvokeNodeToArgIdxMap.get(min).get(idx);
965     // // System.out.println("argTupleSet=" + argTuple + "   param=" +
966     // paramNode);
967     // // // here, it adds all value flows reachable from the paramNode in the
968     // callee's flow graph
969     // // addValueFlowsFromCalleeParam(min, calleeSubGlobalGraph, paramNode,
970     // callerSubGlobalGraph,
971     // // argTuple, baseTuple);
972     // // }
973
974   }
975
976   private void addValueFlowFromCalleeNode(MethodInvokeNode min, MethodDescriptor mdCaller,
977       MethodDescriptor mdCallee, GlobalFlowNode calleeSrcNode) {
978
979     GlobalFlowGraph calleeSubGlobalGraph = getSubGlobalFlowGraph(mdCallee);
980     GlobalFlowGraph callerSubGlobalGraph = getSubGlobalFlowGraph(mdCaller);
981
982     NTuple<Location> callerSrcNodeLocTuple =
983         translateToCallerLocTuple(min, mdCallee, mdCaller, calleeSrcNode.getLocTuple());
984
985     if (callerSrcNodeLocTuple != null) {
986       Set<GlobalFlowNode> outNodeSet = calleeSubGlobalGraph.getOutNodeSet(calleeSrcNode);
987
988       for (Iterator iterator = outNodeSet.iterator(); iterator.hasNext();) {
989         GlobalFlowNode outNode = (GlobalFlowNode) iterator.next();
990         NTuple<Location> callerDstNodeLocTuple =
991             translateToCallerLocTuple(min, mdCallee, mdCaller, outNode.getLocTuple());
992         if (callerDstNodeLocTuple != null) {
993           callerSubGlobalGraph.addValueFlowEdge(callerSrcNodeLocTuple, callerDstNodeLocTuple);
994         }
995       }
996     }
997
998   }
999
1000   private NTuple<Location> translateToCallerLocTuple(MethodInvokeNode min,
1001       MethodDescriptor mdCallee, MethodDescriptor mdCaller, NTuple<Location> nodeLocTuple) {
1002     // this method will return NULL if the corresponding argument is literal
1003     // value.
1004     // assumes that we don't need to propagate callee flows to the argument
1005     // which is literal.
1006
1007     System.out.println("---translateToCallerLocTuple=" + min.printNode(0)
1008         + "  callee nodeLocTuple=" + nodeLocTuple);
1009
1010     FlowGraph calleeFlowGraph = getFlowGraph(mdCallee);
1011
1012     NTuple<Descriptor> nodeDescTuple = translateToDescTuple(nodeLocTuple);
1013     if (calleeFlowGraph.isParameter(nodeDescTuple)) {
1014       int paramIdx = calleeFlowGraph.getParamIdx(nodeDescTuple);
1015       NTuple<Descriptor> argDescTuple = mapMethodInvokeNodeToArgIdxMap.get(min).get(paramIdx);
1016       // System.out.println(" mapMethodInvokeNodeToArgIdxMap.get(min)="
1017       // + mapMethodInvokeNodeToArgIdxMap.get(min));
1018
1019       if (argDescTuple.size() == 0) {
1020         // argument is literal
1021         return null;
1022       }
1023       NTuple<Location> argLocTuple = translateToLocTuple(mdCaller, argDescTuple);
1024
1025       NTuple<Location> callerLocTuple = new NTuple<Location>();
1026
1027       callerLocTuple.addAll(argLocTuple);
1028       for (int i = 1; i < nodeLocTuple.size(); i++) {
1029         callerLocTuple.add(nodeLocTuple.get(i));
1030       }
1031       return callerLocTuple;
1032     } else {
1033       return nodeLocTuple.clone();
1034     }
1035
1036   }
1037
1038   private NTuple<Descriptor> translateToDescTuple(NTuple<Location> locTuple) {
1039
1040     NTuple<Descriptor> descTuple = new NTuple<Descriptor>();
1041     for (int i = 0; i < locTuple.size(); i++) {
1042       descTuple.add(locTuple.get(i).getLocDescriptor());
1043     }
1044     return descTuple;
1045
1046   }
1047
1048   private void addValueFlowsFromCalleeParam(MethodDescriptor mdCaller,
1049       NTuple<Location> argLocTuple, NTuple<Location> baseLocTuple, MethodDescriptor mdCallee,
1050       GlobalFlowNode globalParamNode) {
1051
1052     Set<GlobalFlowNode> visited = new HashSet<GlobalFlowNode>();
1053     visited.add(globalParamNode);
1054     recurAddValueFlowsFromCalleeParam(mdCaller, argLocTuple, baseLocTuple, mdCallee,
1055         globalParamNode);
1056
1057   }
1058
1059   private void recurAddValueFlowsFromCalleeParam(MethodDescriptor mdCaller,
1060       NTuple<Location> argLocTuple, NTuple<Location> baseLocTuple, MethodDescriptor mdCallee,
1061       GlobalFlowNode calleeCurNode) {
1062
1063     // FlowGraph calleeFlowGraph = getFlowGraph(mdCallee);
1064     // GlobalFlowGraph calleeSubGlobalGraph = getSubGlobalFlowGraph(mdCallee);
1065     //
1066     // NTuple<Location> curNodeLocTuple = calleeCurNode.getLocTuple();
1067     // NTuple<Descriptor> curNodeDescTuple = calleeCurNode.getDescTuple();
1068     // if (calleeFlowGraph.isParameter(curNodeDescTuple)) {
1069     // curNodeLocTuple = translateToCaller(argLocTuple, curNodeLocTuple);
1070     // }
1071     //
1072     // Set<GlobalFlowNode> outNodeSet =
1073     // calleeSubGlobalGraph.getOutNodeSet(calleeCurNode);
1074     // for (Iterator iterator = outNodeSet.iterator(); iterator.hasNext();) {
1075     // GlobalFlowNode outNode = (GlobalFlowNode) iterator.next();
1076     //
1077     // NTuple<Location> curNodeLocTuple = calleeCurNode.getLocTuple();
1078     // NTuple<Descriptor> curNodeDescTuple = calleeCurNode.getDescTuple();
1079     // if (calleeFlowGraph.isParameter(curNodeDescTuple)) {
1080     // curNodeLocTuple = translateToCaller(argLocTuple, curNodeLocTuple);
1081     // }
1082     //
1083     // outNode.getDescTuple();
1084     //
1085     // if (calleeFlowGraph.is)
1086     //
1087     // if (calleeSubGlobalGraph.isParameter(srcDescTuple)) {
1088     // // destination node is started with 'parameter'
1089     // // need to translate it in terms of the caller's a node
1090     // srcDescTuple =
1091     // translateToCaller(min, calleeSubGlobalGraph.getParamIdx(srcDescTuple),
1092     // srcDescTuple);
1093     // }
1094     //
1095     // }
1096     //
1097     // Set<FlowEdge> edgeSet =
1098     // calleeSubGlobalGraph.getOutEdgeSetStartingFrom(calleeSrcNode);
1099     // for (Iterator iterator = edgeSet.iterator(); iterator.hasNext();) {
1100     // FlowEdge flowEdge = (FlowEdge) iterator.next();
1101     //
1102     // NTuple<Descriptor> srcDescTuple = flowEdge.getInitTuple();
1103     // NTuple<Descriptor> dstDescTuple = flowEdge.getEndTuple();
1104     //
1105     // FlowNode dstNode = calleeSubGlobalGraph.getFlowNode(dstDescTuple);
1106     //
1107     // if (calleeSubGlobalGraph.isParameter(srcDescTuple)) {
1108     // // destination node is started with 'parameter'
1109     // // need to translate it in terms of the caller's a node
1110     // srcDescTuple =
1111     // translateToCaller(min, calleeSubGlobalGraph.getParamIdx(srcDescTuple),
1112     // srcDescTuple);
1113     // }
1114     //
1115     // if (calleeSubGlobalGraph.isParameter(dstDescTuple)) {
1116     // // destination node is started with 'parameter'
1117     // // need to translate it in terms of the caller's a node
1118     // dstDescTuple =
1119     // translateToCaller(min, calleeSubGlobalGraph.getParamIdx(dstDescTuple),
1120     // dstDescTuple);
1121     // }
1122     //
1123     // callerSubGlobalGraph.addValueFlowEdge(srcDescTuple, dstDescTuple);
1124     //
1125     // if (!visited.contains(dstNode)) {
1126     // visited.add(dstNode);
1127     // recurAddValueFlowsFromCalleeParam(min, calleeSubGlobalGraph, dstNode,
1128     // callerSubGlobalGraph,
1129     // dstDescTuple, visited, baseTuple);
1130     // }
1131     //
1132     // }
1133
1134   }
1135
1136   private NTuple<Location> translateToCaller(NTuple<Location> argLocTuple,
1137       NTuple<Location> curNodeLocTuple) {
1138
1139     NTuple<Location> callerLocTuple = new NTuple<Location>();
1140
1141     callerLocTuple.addAll(argLocTuple);
1142     for (int i = 1; i < curNodeLocTuple.size(); i++) {
1143       callerLocTuple.add(curNodeLocTuple.get(i));
1144     }
1145
1146     return callerLocTuple;
1147   }
1148
1149   private void recurAddValueFlowsFromCalleeParam(MethodInvokeNode min,
1150       FlowGraph calleeSubGlobalGraph, FlowNode calleeSrcNode, FlowGraph callerSubGlobalGraph,
1151       NTuple<Descriptor> callerSrcTuple, Set<FlowNode> visited, NTuple<Descriptor> baseTuple) {
1152
1153     MethodDescriptor mdCallee = calleeSubGlobalGraph.getMethodDescriptor();
1154
1155     // Set<FlowEdge> edgeSet =
1156     // calleeSubGlobalGraph.getOutEdgeSet(calleeSrcNode);
1157     Set<FlowEdge> edgeSet = calleeSubGlobalGraph.getOutEdgeSetStartingFrom(calleeSrcNode);
1158     for (Iterator iterator = edgeSet.iterator(); iterator.hasNext();) {
1159       FlowEdge flowEdge = (FlowEdge) iterator.next();
1160
1161       NTuple<Descriptor> srcDescTuple = flowEdge.getInitTuple();
1162       NTuple<Descriptor> dstDescTuple = flowEdge.getEndTuple();
1163
1164       FlowNode dstNode = calleeSubGlobalGraph.getFlowNode(dstDescTuple);
1165
1166       if (calleeSubGlobalGraph.isParameter(srcDescTuple)) {
1167         // destination node is started with 'parameter'
1168         // need to translate it in terms of the caller's a node
1169         srcDescTuple =
1170             translateToCaller(min, calleeSubGlobalGraph.getParamIdx(srcDescTuple), srcDescTuple);
1171       }
1172
1173       if (calleeSubGlobalGraph.isParameter(dstDescTuple)) {
1174         // destination node is started with 'parameter'
1175         // need to translate it in terms of the caller's a node
1176         dstDescTuple =
1177             translateToCaller(min, calleeSubGlobalGraph.getParamIdx(dstDescTuple), dstDescTuple);
1178       }
1179
1180       callerSubGlobalGraph.addValueFlowEdge(srcDescTuple, dstDescTuple);
1181
1182       if (!visited.contains(dstNode)) {
1183         visited.add(dstNode);
1184         recurAddValueFlowsFromCalleeParam(min, calleeSubGlobalGraph, dstNode, callerSubGlobalGraph,
1185             dstDescTuple, visited, baseTuple);
1186       }
1187
1188     }
1189
1190   }
1191
1192   private NTuple<Descriptor> translateToCaller(MethodInvokeNode min, int paramIdx,
1193       NTuple<Descriptor> srcDescTuple) {
1194
1195     NTuple<Descriptor> callerTuple = new NTuple<Descriptor>();
1196
1197     NTuple<Descriptor> argTuple = mapMethodInvokeNodeToArgIdxMap.get(min).get(paramIdx);
1198
1199     for (int i = 0; i < argTuple.size(); i++) {
1200       callerTuple.add(argTuple.get(i));
1201     }
1202
1203     for (int i = 1; i < srcDescTuple.size(); i++) {
1204       callerTuple.add(srcDescTuple.get(i));
1205     }
1206
1207     return callerTuple;
1208   }
1209
1210   private NTuple<Descriptor> traslateToCalleeParamTupleToCallerArgTuple(
1211       NTuple<Descriptor> calleeInitTuple, NTuple<Descriptor> callerSrcTuple) {
1212
1213     NTuple<Descriptor> callerInitTuple = new NTuple<Descriptor>();
1214
1215     for (int i = 0; i < callerSrcTuple.size(); i++) {
1216       callerInitTuple.add(callerSrcTuple.get(i));
1217     }
1218
1219     for (int i = 1; i < calleeInitTuple.size(); i++) {
1220       callerInitTuple.add(calleeInitTuple.get(i));
1221     }
1222
1223     return callerInitTuple;
1224   }
1225
1226   public LocationSummary getLocationSummary(Descriptor d) {
1227     if (!mapDescToLocationSummary.containsKey(d)) {
1228       if (d instanceof MethodDescriptor) {
1229         mapDescToLocationSummary.put(d, new MethodSummary((MethodDescriptor) d));
1230       } else if (d instanceof ClassDescriptor) {
1231         mapDescToLocationSummary.put(d, new FieldSummary());
1232       }
1233     }
1234     return mapDescToLocationSummary.get(d);
1235   }
1236
1237   private void generateMethodSummary() {
1238
1239     Set<MethodDescriptor> keySet = md2lattice.keySet();
1240     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1241       MethodDescriptor md = (MethodDescriptor) iterator.next();
1242
1243       System.out.println("\nSSJAVA: generate method summary: " + md);
1244
1245       FlowGraph flowGraph = getFlowGraph(md);
1246       MethodSummary methodSummary = getMethodSummary(md);
1247
1248       // construct a parameter mapping that maps a parameter descriptor to an
1249       // inferred composite
1250       // location
1251
1252       for (int paramIdx = 0; paramIdx < flowGraph.getNumParameters(); paramIdx++) {
1253         FlowNode flowNode = flowGraph.getParamFlowNode(paramIdx);
1254         CompositeLocation inferredCompLoc = flowNode.getCompositeLocation();
1255         // NTuple<Descriptor> descTuple = flowNode.getDescTuple();
1256         //
1257         // CompositeLocation assignedCompLoc = flowNode.getCompositeLocation();
1258         // CompositeLocation inferredCompLoc;
1259         // if (assignedCompLoc != null) {
1260         // inferredCompLoc = translateCompositeLocation(assignedCompLoc);
1261         // } else {
1262         // Descriptor locDesc = descTuple.get(0);
1263         // Location loc = new Location(md, locDesc.getSymbol());
1264         // loc.setLocDescriptor(locDesc);
1265         // inferredCompLoc = new CompositeLocation(loc);
1266         // }
1267         System.out.println("-paramIdx=" + paramIdx + "   infer=" + inferredCompLoc);
1268         System.out.println("-flowNode inferLoc=" + flowNode.getCompositeLocation());
1269         methodSummary.addMapParamIdxToInferLoc(paramIdx, inferredCompLoc);
1270       }
1271
1272     }
1273
1274   }
1275
1276   private boolean hasOrderingRelation(NTuple<Location> locTuple1, NTuple<Location> locTuple2) {
1277
1278     int size = locTuple1.size() >= locTuple2.size() ? locTuple2.size() : locTuple1.size();
1279
1280     for (int idx = 0; idx < size; idx++) {
1281       Location loc1 = locTuple1.get(idx);
1282       Location loc2 = locTuple2.get(idx);
1283
1284       Descriptor desc1 = loc1.getDescriptor();
1285       Descriptor desc2 = loc2.getDescriptor();
1286
1287       if (!desc1.equals(desc2)) {
1288         throw new Error("Fail to compare " + locTuple1 + " and " + locTuple2);
1289       }
1290
1291       Descriptor locDesc1 = loc1.getLocDescriptor();
1292       Descriptor locDesc2 = loc2.getLocDescriptor();
1293
1294       HierarchyGraph hierarchyGraph = getHierarchyGraph(desc1);
1295
1296       HNode node1 = hierarchyGraph.getHNode(locDesc1);
1297       HNode node2 = hierarchyGraph.getHNode(locDesc2);
1298
1299       System.out.println("---node1=" + node1 + "  node2=" + node2);
1300       System.out.println("---hierarchyGraph.getIncomingNodeSet(node2)="
1301           + hierarchyGraph.getIncomingNodeSet(node2));
1302
1303       if (locDesc1.equals(locDesc2)) {
1304         continue;
1305       } else if (!hierarchyGraph.getIncomingNodeSet(node2).contains(node1)
1306           && !hierarchyGraph.getIncomingNodeSet(node1).contains(node2)) {
1307         return false;
1308       } else {
1309         return true;
1310       }
1311
1312     }
1313
1314     return false;
1315
1316   }
1317
1318   private boolean isHigherThan(NTuple<Location> locTuple1, NTuple<Location> locTuple2) {
1319
1320     int size = locTuple1.size() >= locTuple2.size() ? locTuple2.size() : locTuple1.size();
1321
1322     for (int idx = 0; idx < size; idx++) {
1323       Location loc1 = locTuple1.get(idx);
1324       Location loc2 = locTuple2.get(idx);
1325
1326       Descriptor desc1 = loc1.getDescriptor();
1327       Descriptor desc2 = loc2.getDescriptor();
1328
1329       if (!desc1.equals(desc2)) {
1330         throw new Error("Fail to compare " + locTuple1 + " and " + locTuple2);
1331       }
1332
1333       Descriptor locDesc1 = loc1.getLocDescriptor();
1334       Descriptor locDesc2 = loc2.getLocDescriptor();
1335
1336       HierarchyGraph hierarchyGraph = getHierarchyGraph(desc1);
1337
1338       HNode node1 = hierarchyGraph.getHNode(locDesc1);
1339       HNode node2 = hierarchyGraph.getHNode(locDesc2);
1340
1341       System.out.println("---node1=" + node1 + "  node2=" + node2);
1342       System.out.println("---hierarchyGraph.getIncomingNodeSet(node2)="
1343           + hierarchyGraph.getIncomingNodeSet(node2));
1344
1345       if (locDesc1.equals(locDesc2)) {
1346         continue;
1347       } else if (hierarchyGraph.getIncomingNodeSet(node2).contains(node1)) {
1348         return true;
1349       } else {
1350         return false;
1351       }
1352
1353     }
1354
1355     return false;
1356   }
1357
1358   private CompositeLocation translateCompositeLocation(CompositeLocation compLoc) {
1359     CompositeLocation newCompLoc = new CompositeLocation();
1360
1361     // System.out.println("compLoc=" + compLoc);
1362     for (int i = 0; i < compLoc.getSize(); i++) {
1363       Location loc = compLoc.get(i);
1364       Descriptor enclosingDescriptor = loc.getDescriptor();
1365       Descriptor locDescriptor = loc.getLocDescriptor();
1366
1367       HNode hnode = getHierarchyGraph(enclosingDescriptor).getHNode(locDescriptor);
1368       // System.out.println("-hnode=" + hnode + "    from=" + locDescriptor +
1369       // " enclosingDescriptor="
1370       // + enclosingDescriptor);
1371       // System.out.println("-getLocationSummary(enclosingDescriptor)="
1372       // + getLocationSummary(enclosingDescriptor));
1373       String locName = getLocationSummary(enclosingDescriptor).getLocationName(hnode.getName());
1374       // System.out.println("-locName=" + locName);
1375       Location newLoc = new Location(enclosingDescriptor, locName);
1376       newLoc.setLocDescriptor(locDescriptor);
1377       newCompLoc.addLocation(newLoc);
1378     }
1379
1380     return newCompLoc;
1381   }
1382
1383   private void debug_writeLattices() {
1384
1385     Set<Descriptor> keySet = mapDescriptorToSimpleLattice.keySet();
1386     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1387       Descriptor key = (Descriptor) iterator.next();
1388       SSJavaLattice<String> simpleLattice = mapDescriptorToSimpleLattice.get(key);
1389       // HierarchyGraph simpleHierarchyGraph = getSimpleHierarchyGraph(key);
1390       HierarchyGraph scHierarchyGraph = getSkeletonCombinationHierarchyGraph(key);
1391       if (key instanceof ClassDescriptor) {
1392         writeInferredLatticeDotFile((ClassDescriptor) key, scHierarchyGraph, simpleLattice,
1393             "_SIMPLE");
1394       } else if (key instanceof MethodDescriptor) {
1395         MethodDescriptor md = (MethodDescriptor) key;
1396         writeInferredLatticeDotFile(md.getClassDesc(), md, scHierarchyGraph, simpleLattice,
1397             "_SIMPLE");
1398       }
1399
1400       LocationSummary ls = getLocationSummary(key);
1401       System.out.println("####LOC SUMMARY=" + key + "\n" + ls.getMapHNodeNameToLocationName());
1402     }
1403
1404     Set<ClassDescriptor> cdKeySet = cd2lattice.keySet();
1405     for (Iterator iterator = cdKeySet.iterator(); iterator.hasNext();) {
1406       ClassDescriptor cd = (ClassDescriptor) iterator.next();
1407       writeInferredLatticeDotFile((ClassDescriptor) cd, getSkeletonCombinationHierarchyGraph(cd),
1408           cd2lattice.get(cd), "");
1409     }
1410
1411     Set<MethodDescriptor> mdKeySet = md2lattice.keySet();
1412     for (Iterator iterator = mdKeySet.iterator(); iterator.hasNext();) {
1413       MethodDescriptor md = (MethodDescriptor) iterator.next();
1414       writeInferredLatticeDotFile(md.getClassDesc(), md, getSkeletonCombinationHierarchyGraph(md),
1415           md2lattice.get(md), "");
1416     }
1417
1418   }
1419
1420   private void buildLattice() {
1421
1422     BuildLattice buildLattice = new BuildLattice(this);
1423
1424     Set<Descriptor> keySet = mapDescriptorToCombineSkeletonHierarchyGraph.keySet();
1425     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1426       Descriptor desc = (Descriptor) iterator.next();
1427
1428       SSJavaLattice<String> simpleLattice = buildLattice.buildLattice(desc);
1429
1430       addMapDescToSimpleLattice(desc, simpleLattice);
1431
1432       HierarchyGraph simpleHierarchyGraph = getSimpleHierarchyGraph(desc);
1433       System.out.println("\n## insertIntermediateNodesToStraightLine:"
1434           + simpleHierarchyGraph.getName());
1435       SSJavaLattice<String> lattice =
1436           buildLattice.insertIntermediateNodesToStraightLine(desc, simpleLattice);
1437       lattice.removeRedundantEdges();
1438
1439       if (desc instanceof ClassDescriptor) {
1440         // field lattice
1441         cd2lattice.put((ClassDescriptor) desc, lattice);
1442         // ssjava.writeLatticeDotFile((ClassDescriptor) desc, null, lattice);
1443       } else if (desc instanceof MethodDescriptor) {
1444         // method lattice
1445         md2lattice.put((MethodDescriptor) desc, lattice);
1446         MethodDescriptor md = (MethodDescriptor) desc;
1447         ClassDescriptor cd = md.getClassDesc();
1448         // ssjava.writeLatticeDotFile(cd, md, lattice);
1449       }
1450
1451       // System.out.println("\nSSJAVA: Insering Combination Nodes:" + desc);
1452       // HierarchyGraph skeletonGraph = getSkeletonHierarchyGraph(desc);
1453       // HierarchyGraph skeletonGraphWithCombinationNode =
1454       // skeletonGraph.clone();
1455       // skeletonGraphWithCombinationNode.setName(desc + "_SC");
1456       //
1457       // HierarchyGraph simpleHierarchyGraph = getSimpleHierarchyGraph(desc);
1458       // System.out.println("Identifying Combination Nodes:");
1459       // skeletonGraphWithCombinationNode.insertCombinationNodesToGraph(simpleHierarchyGraph);
1460       // skeletonGraphWithCombinationNode.simplifySkeletonCombinationHierarchyGraph();
1461       // mapDescriptorToCombineSkeletonHierarchyGraph.put(desc,
1462       // skeletonGraphWithCombinationNode);
1463     }
1464
1465   }
1466
1467   public void addMapDescToSimpleLattice(Descriptor desc, SSJavaLattice<String> lattice) {
1468     mapDescriptorToSimpleLattice.put(desc, lattice);
1469   }
1470
1471   public SSJavaLattice<String> getSimpleLattice(Descriptor desc) {
1472     return mapDescriptorToSimpleLattice.get(desc);
1473   }
1474
1475   private void simplifyHierarchyGraph() {
1476     Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
1477     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1478       Descriptor desc = (Descriptor) iterator.next();
1479       HierarchyGraph simpleHierarchyGraph = getHierarchyGraph(desc).clone();
1480       simpleHierarchyGraph.setName(desc + "_SIMPLE");
1481       simpleHierarchyGraph.removeRedundantEdges();
1482       // simpleHierarchyGraph.simplifyHierarchyGraph();
1483       mapDescriptorToSimpleHierarchyGraph.put(desc, simpleHierarchyGraph);
1484     }
1485   }
1486
1487   private void insertCombinationNodes() {
1488     Set<Descriptor> keySet = mapDescriptorToSkeletonHierarchyGraph.keySet();
1489     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1490       Descriptor desc = (Descriptor) iterator.next();
1491       System.out.println("\nSSJAVA: Insering Combination Nodes:" + desc);
1492       HierarchyGraph skeletonGraph = getSkeletonHierarchyGraph(desc);
1493       HierarchyGraph skeletonGraphWithCombinationNode = skeletonGraph.clone();
1494       skeletonGraphWithCombinationNode.setName(desc + "_SC");
1495
1496       HierarchyGraph simpleHierarchyGraph = getSimpleHierarchyGraph(desc);
1497       System.out.println("Identifying Combination Nodes:");
1498       skeletonGraphWithCombinationNode.insertCombinationNodesToGraph(simpleHierarchyGraph);
1499       skeletonGraphWithCombinationNode.simplifySkeletonCombinationHierarchyGraph();
1500       mapDescriptorToCombineSkeletonHierarchyGraph.put(desc, skeletonGraphWithCombinationNode);
1501     }
1502   }
1503
1504   private void constructSkeletonHierarchyGraph() {
1505     Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
1506     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1507       Descriptor desc = (Descriptor) iterator.next();
1508       HierarchyGraph simpleGraph = getSimpleHierarchyGraph(desc);
1509       HierarchyGraph skeletonGraph = simpleGraph.generateSkeletonGraph();
1510       skeletonGraph.setMapDescToHNode(simpleGraph.getMapDescToHNode());
1511       skeletonGraph.setMapHNodeToDescSet(simpleGraph.getMapHNodeToDescSet());
1512       skeletonGraph.simplifyHierarchyGraph();
1513       // skeletonGraph.combineRedundantNodes(false);
1514       // skeletonGraph.removeRedundantEdges();
1515       mapDescriptorToSkeletonHierarchyGraph.put(desc, skeletonGraph);
1516     }
1517   }
1518
1519   private void debug_writeHierarchyDotFiles() {
1520
1521     Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
1522     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1523       Descriptor desc = (Descriptor) iterator.next();
1524       getHierarchyGraph(desc).writeGraph();
1525     }
1526
1527   }
1528
1529   private void debug_writeSimpleHierarchyDotFiles() {
1530
1531     Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
1532     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1533       Descriptor desc = (Descriptor) iterator.next();
1534       getHierarchyGraph(desc).writeGraph();
1535       getSimpleHierarchyGraph(desc).writeGraph();
1536     }
1537
1538   }
1539
1540   private void debug_writeSkeletonHierarchyDotFiles() {
1541
1542     Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
1543     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1544       Descriptor desc = (Descriptor) iterator.next();
1545       getSkeletonHierarchyGraph(desc).writeGraph();
1546     }
1547
1548   }
1549
1550   private void debug_writeSkeletonCombinationHierarchyDotFiles() {
1551
1552     Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
1553     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1554       Descriptor desc = (Descriptor) iterator.next();
1555       getSkeletonCombinationHierarchyGraph(desc).writeGraph();
1556     }
1557
1558   }
1559
1560   public HierarchyGraph getSimpleHierarchyGraph(Descriptor d) {
1561     return mapDescriptorToSimpleHierarchyGraph.get(d);
1562   }
1563
1564   private HierarchyGraph getSkeletonHierarchyGraph(Descriptor d) {
1565     if (!mapDescriptorToSkeletonHierarchyGraph.containsKey(d)) {
1566       mapDescriptorToSkeletonHierarchyGraph.put(d, new HierarchyGraph(d));
1567     }
1568     return mapDescriptorToSkeletonHierarchyGraph.get(d);
1569   }
1570
1571   public HierarchyGraph getSkeletonCombinationHierarchyGraph(Descriptor d) {
1572     if (!mapDescriptorToCombineSkeletonHierarchyGraph.containsKey(d)) {
1573       mapDescriptorToCombineSkeletonHierarchyGraph.put(d, new HierarchyGraph(d));
1574     }
1575     return mapDescriptorToCombineSkeletonHierarchyGraph.get(d);
1576   }
1577
1578   private void constructHierarchyGraph() {
1579
1580     // do fixed-point analysis
1581
1582     ssjava.init();
1583     LinkedList<MethodDescriptor> descriptorListToAnalyze = ssjava.getSortedDescriptors();
1584
1585     // Collections.sort(descriptorListToAnalyze, new
1586     // Comparator<MethodDescriptor>() {
1587     // public int compare(MethodDescriptor o1, MethodDescriptor o2) {
1588     // return o1.getSymbol().compareToIgnoreCase(o2.getSymbol());
1589     // }
1590     // });
1591
1592     // current descriptors to visit in fixed-point interprocedural analysis,
1593     // prioritized by dependency in the call graph
1594     methodDescriptorsToVisitStack.clear();
1595
1596     Set<MethodDescriptor> methodDescriptorToVistSet = new HashSet<MethodDescriptor>();
1597     methodDescriptorToVistSet.addAll(descriptorListToAnalyze);
1598
1599     while (!descriptorListToAnalyze.isEmpty()) {
1600       MethodDescriptor md = descriptorListToAnalyze.removeFirst();
1601       methodDescriptorsToVisitStack.add(md);
1602     }
1603
1604     // analyze scheduled methods until there are no more to visit
1605     while (!methodDescriptorsToVisitStack.isEmpty()) {
1606       // start to analyze leaf node
1607       MethodDescriptor md = methodDescriptorsToVisitStack.pop();
1608
1609       HierarchyGraph hierarchyGraph = new HierarchyGraph(md);
1610       // MethodSummary methodSummary = new MethodSummary(md);
1611
1612       // MethodLocationInfo methodInfo = new MethodLocationInfo(md);
1613       // curMethodInfo = methodInfo;
1614
1615       System.out.println();
1616       System.out.println("SSJAVA: Construcing the hierarchy graph from " + md);
1617
1618       constructHierarchyGraph(md, hierarchyGraph);
1619
1620       HierarchyGraph prevHierarchyGraph = getHierarchyGraph(md);
1621       // MethodSummary prevMethodSummary = getMethodSummary(md);
1622
1623       if (!hierarchyGraph.equals(prevHierarchyGraph)) {
1624
1625         mapDescriptorToHierarchyGraph.put(md, hierarchyGraph);
1626         // mapDescToLocationSummary.put(md, methodSummary);
1627
1628         // results for callee changed, so enqueue dependents caller for
1629         // further analysis
1630         Iterator<MethodDescriptor> depsItr = ssjava.getDependents(md).iterator();
1631         while (depsItr.hasNext()) {
1632           MethodDescriptor methodNext = depsItr.next();
1633           if (!methodDescriptorsToVisitStack.contains(methodNext)
1634               && methodDescriptorToVistSet.contains(methodNext)) {
1635             methodDescriptorsToVisitStack.add(methodNext);
1636           }
1637         }
1638
1639       }
1640
1641     }
1642
1643   }
1644
1645   private HierarchyGraph getHierarchyGraph(Descriptor d) {
1646     if (!mapDescriptorToHierarchyGraph.containsKey(d)) {
1647       mapDescriptorToHierarchyGraph.put(d, new HierarchyGraph(d));
1648     }
1649     return mapDescriptorToHierarchyGraph.get(d);
1650   }
1651
1652   private void constructHierarchyGraph(MethodDescriptor md, HierarchyGraph methodGraph) {
1653
1654     // visit each node of method flow graph
1655     FlowGraph fg = getFlowGraph(md);
1656     Set<FlowNode> nodeSet = fg.getNodeSet();
1657
1658     Set<Descriptor> paramDescSet = fg.getMapParamDescToIdx().keySet();
1659     for (Iterator iterator = paramDescSet.iterator(); iterator.hasNext();) {
1660       Descriptor desc = (Descriptor) iterator.next();
1661       methodGraph.getHNode(desc).setSkeleton(true);
1662     }
1663
1664     // for the method lattice, we need to look at the first element of
1665     // NTuple<Descriptor>
1666     for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
1667       FlowNode srcNode = (FlowNode) iterator.next();
1668
1669       Set<FlowEdge> outEdgeSet = fg.getOutEdgeSet(srcNode);
1670       for (Iterator iterator2 = outEdgeSet.iterator(); iterator2.hasNext();) {
1671         FlowEdge outEdge = (FlowEdge) iterator2.next();
1672         FlowNode dstNode = outEdge.getDst();
1673
1674         NTuple<Descriptor> srcNodeTuple = srcNode.getDescTuple();
1675         NTuple<Descriptor> dstNodeTuple = dstNode.getDescTuple();
1676
1677         if (outEdge.getInitTuple().equals(srcNodeTuple)
1678             && outEdge.getEndTuple().equals(dstNodeTuple)) {
1679
1680           NTuple<Descriptor> srcCurTuple = srcNode.getCurrentDescTuple();
1681           NTuple<Descriptor> dstCurTuple = dstNode.getCurrentDescTuple();
1682
1683           if ((srcCurTuple.size() > 1 && dstCurTuple.size() > 1)
1684               && srcCurTuple.get(0).equals(dstCurTuple.get(0))) {
1685
1686             // value flows between fields
1687             Descriptor desc = srcCurTuple.get(0);
1688             ClassDescriptor classDesc;
1689
1690             if (desc.equals(GLOBALDESC)) {
1691               classDesc = md.getClassDesc();
1692             } else {
1693               VarDescriptor varDesc = (VarDescriptor) srcCurTuple.get(0);
1694               classDesc = varDesc.getType().getClassDesc();
1695             }
1696             extractFlowsBetweenFields(classDesc, srcNode, dstNode, 1);
1697
1698           } else {
1699             // value flow between local var - local var or local var - field
1700
1701             Descriptor srcDesc = srcCurTuple.get(0);
1702             Descriptor dstDesc = dstCurTuple.get(0);
1703
1704             methodGraph.addEdge(srcDesc, dstDesc);
1705
1706             if (fg.isParamDesc(srcDesc)) {
1707               methodGraph.setParamHNode(srcDesc);
1708             }
1709             if (fg.isParamDesc(dstDesc)) {
1710               methodGraph.setParamHNode(dstDesc);
1711             }
1712
1713           }
1714
1715         }
1716       }
1717     }
1718
1719   }
1720
1721   private MethodSummary getMethodSummary(MethodDescriptor md) {
1722     if (!mapDescToLocationSummary.containsKey(md)) {
1723       mapDescToLocationSummary.put(md, new MethodSummary(md));
1724     }
1725     return (MethodSummary) mapDescToLocationSummary.get(md);
1726   }
1727
1728   private void addMapClassDefinitionToLineNum(ClassDescriptor cd, String strLine, int lineNum) {
1729
1730     String classSymbol = cd.getSymbol();
1731     int idx = classSymbol.lastIndexOf("$");
1732     if (idx != -1) {
1733       classSymbol = classSymbol.substring(idx + 1);
1734     }
1735
1736     String pattern = "class " + classSymbol + " ";
1737     if (strLine.indexOf(pattern) != -1) {
1738       mapDescToDefinitionLine.put(cd, lineNum);
1739     }
1740   }
1741
1742   private void addMapMethodDefinitionToLineNum(Set<MethodDescriptor> methodSet, String strLine,
1743       int lineNum) {
1744     for (Iterator iterator = methodSet.iterator(); iterator.hasNext();) {
1745       MethodDescriptor md = (MethodDescriptor) iterator.next();
1746       String pattern = md.getMethodDeclaration();
1747       if (strLine.indexOf(pattern) != -1) {
1748         mapDescToDefinitionLine.put(md, lineNum);
1749         methodSet.remove(md);
1750         return;
1751       }
1752     }
1753
1754   }
1755
1756   private void readOriginalSourceFiles() {
1757
1758     SymbolTable classtable = state.getClassSymbolTable();
1759
1760     Set<ClassDescriptor> classDescSet = new HashSet<ClassDescriptor>();
1761     classDescSet.addAll(classtable.getValueSet());
1762
1763     try {
1764       // inefficient implement. it may re-visit the same file if the file
1765       // contains more than one class definitions.
1766       for (Iterator iterator = classDescSet.iterator(); iterator.hasNext();) {
1767         ClassDescriptor cd = (ClassDescriptor) iterator.next();
1768
1769         Set<MethodDescriptor> methodSet = new HashSet<MethodDescriptor>();
1770         methodSet.addAll(cd.getMethodTable().getValueSet());
1771
1772         String sourceFileName = cd.getSourceFileName();
1773         Vector<String> lineVec = new Vector<String>();
1774
1775         mapFileNameToLineVector.put(sourceFileName, lineVec);
1776
1777         BufferedReader in = new BufferedReader(new FileReader(sourceFileName));
1778         String strLine;
1779         int lineNum = 1;
1780         lineVec.add(""); // the index is started from 1.
1781         while ((strLine = in.readLine()) != null) {
1782           lineVec.add(lineNum, strLine);
1783           addMapClassDefinitionToLineNum(cd, strLine, lineNum);
1784           addMapMethodDefinitionToLineNum(methodSet, strLine, lineNum);
1785           lineNum++;
1786         }
1787
1788       }
1789
1790     } catch (IOException e) {
1791       e.printStackTrace();
1792     }
1793
1794   }
1795
1796   private String generateLatticeDefinition(Descriptor desc) {
1797
1798     Set<String> sharedLocSet = new HashSet<String>();
1799
1800     SSJavaLattice<String> lattice = getLattice(desc);
1801     String rtr = "@LATTICE(\"";
1802
1803     Map<String, Set<String>> map = lattice.getTable();
1804     Set<String> keySet = map.keySet();
1805     boolean first = true;
1806     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1807       String key = (String) iterator.next();
1808       if (!key.equals(lattice.getTopItem())) {
1809         Set<String> connectedSet = map.get(key);
1810
1811         if (connectedSet.size() == 1) {
1812           if (connectedSet.iterator().next().equals(lattice.getBottomItem())) {
1813             if (!first) {
1814               rtr += ",";
1815             } else {
1816               rtr += "LOC,";
1817               first = false;
1818             }
1819             rtr += key;
1820             if (lattice.isSharedLoc(key)) {
1821               rtr += "," + key + "*";
1822             }
1823           }
1824         }
1825
1826         for (Iterator iterator2 = connectedSet.iterator(); iterator2.hasNext();) {
1827           String loc = (String) iterator2.next();
1828           if (!loc.equals(lattice.getBottomItem())) {
1829             if (!first) {
1830               rtr += ",";
1831             } else {
1832               rtr += "LOC,";
1833               first = false;
1834             }
1835             rtr += loc + "<" + key;
1836             if (lattice.isSharedLoc(key) && (!sharedLocSet.contains(key))) {
1837               rtr += "," + key + "*";
1838               sharedLocSet.add(key);
1839             }
1840             if (lattice.isSharedLoc(loc) && (!sharedLocSet.contains(loc))) {
1841               rtr += "," + loc + "*";
1842               sharedLocSet.add(loc);
1843             }
1844
1845           }
1846         }
1847       }
1848     }
1849
1850     rtr += "\")";
1851
1852     if (desc instanceof MethodDescriptor) {
1853       TypeDescriptor returnType = ((MethodDescriptor) desc).getReturnType();
1854
1855       MethodLocationInfo methodLocInfo = getMethodLocationInfo((MethodDescriptor) desc);
1856
1857       if (returnType != null && (!returnType.isVoid())) {
1858         rtr +=
1859             "\n@RETURNLOC(\"" + generateLocationAnnoatation(methodLocInfo.getReturnLoc()) + "\")";
1860       }
1861
1862       rtr += "\n@THISLOC(\"this\")";
1863       rtr += "\n@GLOBALLOC(\"GLOBALLOC\")";
1864
1865       CompositeLocation pcLoc = methodLocInfo.getPCLoc();
1866       if ((pcLoc != null) && (!pcLoc.get(0).isTop())) {
1867         rtr += "\n@PCLOC(\"" + generateLocationAnnoatation(pcLoc) + "\")";
1868       }
1869
1870     }
1871
1872     return rtr;
1873   }
1874
1875   private void generateAnnoatedCode() {
1876
1877     readOriginalSourceFiles();
1878
1879     setupToAnalyze();
1880     while (!toAnalyzeIsEmpty()) {
1881       ClassDescriptor cd = toAnalyzeNext();
1882
1883       setupToAnalazeMethod(cd);
1884
1885       LocationInfo locInfo = mapClassToLocationInfo.get(cd);
1886       String sourceFileName = cd.getSourceFileName();
1887
1888       if (cd.isInterface()) {
1889         continue;
1890       }
1891
1892       int classDefLine = mapDescToDefinitionLine.get(cd);
1893       Vector<String> sourceVec = mapFileNameToLineVector.get(sourceFileName);
1894
1895       if (locInfo == null) {
1896         locInfo = getLocationInfo(cd);
1897       }
1898
1899       for (Iterator iter = cd.getFields(); iter.hasNext();) {
1900         FieldDescriptor fieldDesc = (FieldDescriptor) iter.next();
1901         if (!(fieldDesc.isStatic() && fieldDesc.isFinal())) {
1902           String locIdentifier = locInfo.getFieldInferLocation(fieldDesc).getLocIdentifier();
1903           if (!getLattice(cd).getElementSet().contains(locIdentifier)) {
1904             getLattice(cd).put(locIdentifier);
1905           }
1906         }
1907       }
1908
1909       String fieldLatticeDefStr = generateLatticeDefinition(cd);
1910       String annoatedSrc = fieldLatticeDefStr + newline + sourceVec.get(classDefLine);
1911       sourceVec.set(classDefLine, annoatedSrc);
1912
1913       // generate annotations for field declarations
1914       LocationInfo fieldLocInfo = getLocationInfo(cd);
1915       Map<Descriptor, CompositeLocation> inferLocMap = fieldLocInfo.getMapDescToInferLocation();
1916
1917       for (Iterator iter = cd.getFields(); iter.hasNext();) {
1918         FieldDescriptor fd = (FieldDescriptor) iter.next();
1919
1920         String locAnnotationStr;
1921         CompositeLocation inferLoc = inferLocMap.get(fd);
1922
1923         if (inferLoc != null) {
1924           // infer loc is null if the corresponding field is static and final
1925           locAnnotationStr = "@LOC(\"" + generateLocationAnnoatation(inferLoc) + "\")";
1926           int fdLineNum = fd.getLineNum();
1927           String orgFieldDeclarationStr = sourceVec.get(fdLineNum);
1928           String fieldDeclaration = fd.toString();
1929           fieldDeclaration = fieldDeclaration.substring(0, fieldDeclaration.length() - 1);
1930           String annoatedStr = locAnnotationStr + " " + orgFieldDeclarationStr;
1931           sourceVec.set(fdLineNum, annoatedStr);
1932         }
1933
1934       }
1935
1936       while (!toAnalyzeMethodIsEmpty()) {
1937         MethodDescriptor md = toAnalyzeMethodNext();
1938
1939         if (!ssjava.needTobeAnnotated(md)) {
1940           continue;
1941         }
1942
1943         SSJavaLattice<String> methodLattice = md2lattice.get(md);
1944         if (methodLattice != null) {
1945
1946           int methodDefLine = md.getLineNum();
1947
1948           MethodLocationInfo methodLocInfo = getMethodLocationInfo(md);
1949
1950           Map<Descriptor, CompositeLocation> methodInferLocMap =
1951               methodLocInfo.getMapDescToInferLocation();
1952           Set<Descriptor> localVarDescSet = methodInferLocMap.keySet();
1953
1954           Set<String> localLocElementSet = methodLattice.getElementSet();
1955
1956           for (Iterator iterator = localVarDescSet.iterator(); iterator.hasNext();) {
1957             Descriptor localVarDesc = (Descriptor) iterator.next();
1958             CompositeLocation inferLoc = methodInferLocMap.get(localVarDesc);
1959
1960             String localLocIdentifier = inferLoc.get(0).getLocIdentifier();
1961             if (!localLocElementSet.contains(localLocIdentifier)) {
1962               methodLattice.put(localLocIdentifier);
1963             }
1964
1965             String locAnnotationStr = "@LOC(\"" + generateLocationAnnoatation(inferLoc) + "\")";
1966
1967             if (!isParameter(md, localVarDesc)) {
1968               if (mapDescToDefinitionLine.containsKey(localVarDesc)) {
1969                 int varLineNum = mapDescToDefinitionLine.get(localVarDesc);
1970                 String orgSourceLine = sourceVec.get(varLineNum);
1971                 int idx =
1972                     orgSourceLine.indexOf(generateVarDeclaration((VarDescriptor) localVarDesc));
1973                 assert (idx != -1);
1974                 String annoatedStr =
1975                     orgSourceLine.substring(0, idx) + locAnnotationStr + " "
1976                         + orgSourceLine.substring(idx);
1977                 sourceVec.set(varLineNum, annoatedStr);
1978               }
1979             } else {
1980               String methodDefStr = sourceVec.get(methodDefLine);
1981
1982               int idx =
1983                   getParamLocation(methodDefStr,
1984                       generateVarDeclaration((VarDescriptor) localVarDesc));
1985
1986               assert (idx != -1);
1987
1988               String annoatedStr =
1989                   methodDefStr.substring(0, idx) + locAnnotationStr + " "
1990                       + methodDefStr.substring(idx);
1991               sourceVec.set(methodDefLine, annoatedStr);
1992             }
1993
1994           }
1995
1996           // check if the lattice has to have the location type for the this
1997           // reference...
1998
1999           // boolean needToAddthisRef = hasThisReference(md);
2000           if (localLocElementSet.contains("this")) {
2001             methodLattice.put("this");
2002           }
2003
2004           String methodLatticeDefStr = generateLatticeDefinition(md);
2005           String annoatedStr = methodLatticeDefStr + newline + sourceVec.get(methodDefLine);
2006           sourceVec.set(methodDefLine, annoatedStr);
2007
2008         }
2009       }
2010
2011     }
2012
2013     codeGen();
2014   }
2015
2016   private boolean hasThisReference(MethodDescriptor md) {
2017
2018     FlowGraph fg = getFlowGraph(md);
2019     Set<FlowNode> nodeSet = fg.getNodeSet();
2020     for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
2021       FlowNode flowNode = (FlowNode) iterator.next();
2022       if (flowNode.getDescTuple().get(0).equals(md.getThis())) {
2023         return true;
2024       }
2025     }
2026
2027     return false;
2028   }
2029
2030   private int getParamLocation(String methodStr, String paramStr) {
2031
2032     String pattern = paramStr + ",";
2033
2034     int idx = methodStr.indexOf(pattern);
2035     if (idx != -1) {
2036       return idx;
2037     } else {
2038       pattern = paramStr + ")";
2039       return methodStr.indexOf(pattern);
2040     }
2041
2042   }
2043
2044   private String generateVarDeclaration(VarDescriptor varDesc) {
2045
2046     TypeDescriptor td = varDesc.getType();
2047     String rtr = td.toString();
2048     if (td.isArray()) {
2049       for (int i = 0; i < td.getArrayCount(); i++) {
2050         rtr += "[]";
2051       }
2052     }
2053     rtr += " " + varDesc.getName();
2054     return rtr;
2055
2056   }
2057
2058   private String generateLocationAnnoatation(CompositeLocation loc) {
2059     String rtr = "";
2060     // method location
2061     Location methodLoc = loc.get(0);
2062     rtr += methodLoc.getLocIdentifier();
2063
2064     for (int i = 1; i < loc.getSize(); i++) {
2065       Location element = loc.get(i);
2066       rtr += "," + element.getDescriptor().getSymbol() + "." + element.getLocIdentifier();
2067     }
2068
2069     return rtr;
2070   }
2071
2072   private boolean isParameter(MethodDescriptor md, Descriptor localVarDesc) {
2073     return getFlowGraph(md).isParamDesc(localVarDesc);
2074   }
2075
2076   private String extractFileName(String fileName) {
2077     int idx = fileName.lastIndexOf("/");
2078     if (idx == -1) {
2079       return fileName;
2080     } else {
2081       return fileName.substring(idx + 1);
2082     }
2083
2084   }
2085
2086   private void codeGen() {
2087
2088     Set<String> originalFileNameSet = mapFileNameToLineVector.keySet();
2089     for (Iterator iterator = originalFileNameSet.iterator(); iterator.hasNext();) {
2090       String orgFileName = (String) iterator.next();
2091       String outputFileName = extractFileName(orgFileName);
2092
2093       Vector<String> sourceVec = mapFileNameToLineVector.get(orgFileName);
2094
2095       try {
2096
2097         FileWriter fileWriter = new FileWriter("./infer/" + outputFileName);
2098         BufferedWriter out = new BufferedWriter(fileWriter);
2099
2100         for (int i = 0; i < sourceVec.size(); i++) {
2101           out.write(sourceVec.get(i));
2102           out.newLine();
2103         }
2104         out.close();
2105       } catch (IOException e) {
2106         e.printStackTrace();
2107       }
2108
2109     }
2110
2111   }
2112
2113   private void checkLattices() {
2114
2115     LinkedList<MethodDescriptor> descriptorListToAnalyze = ssjava.getSortedDescriptors();
2116
2117     // current descriptors to visit in fixed-point interprocedural analysis,
2118     // prioritized by
2119     // dependency in the call graph
2120     methodDescriptorsToVisitStack.clear();
2121
2122     // descriptorListToAnalyze.removeFirst();
2123
2124     Set<MethodDescriptor> methodDescriptorToVistSet = new HashSet<MethodDescriptor>();
2125     methodDescriptorToVistSet.addAll(descriptorListToAnalyze);
2126
2127     while (!descriptorListToAnalyze.isEmpty()) {
2128       MethodDescriptor md = descriptorListToAnalyze.removeFirst();
2129       checkLatticesOfVirtualMethods(md);
2130     }
2131
2132   }
2133
2134   private void debug_writeLatticeDotFile() {
2135     // generate lattice dot file
2136
2137     setupToAnalyze();
2138
2139     while (!toAnalyzeIsEmpty()) {
2140       ClassDescriptor cd = toAnalyzeNext();
2141
2142       setupToAnalazeMethod(cd);
2143
2144       SSJavaLattice<String> classLattice = cd2lattice.get(cd);
2145       if (classLattice != null) {
2146         ssjava.writeLatticeDotFile(cd, null, classLattice);
2147         debug_printDescriptorToLocNameMapping(cd);
2148       }
2149
2150       while (!toAnalyzeMethodIsEmpty()) {
2151         MethodDescriptor md = toAnalyzeMethodNext();
2152         SSJavaLattice<String> methodLattice = md2lattice.get(md);
2153         if (methodLattice != null) {
2154           ssjava.writeLatticeDotFile(cd, md, methodLattice);
2155           debug_printDescriptorToLocNameMapping(md);
2156         }
2157       }
2158     }
2159
2160   }
2161
2162   private void debug_printDescriptorToLocNameMapping(Descriptor desc) {
2163
2164     LocationInfo info = getLocationInfo(desc);
2165     System.out.println("## " + desc + " ##");
2166     System.out.println(info.getMapDescToInferLocation());
2167     LocationInfo locInfo = getLocationInfo(desc);
2168     System.out.println("mapping=" + locInfo.getMapLocSymbolToDescSet());
2169     System.out.println("###################");
2170
2171   }
2172
2173   private void inferLattices() {
2174   }
2175
2176   private void calculateExtraLocations() {
2177     LinkedList<MethodDescriptor> descriptorListToAnalyze = ssjava.getSortedDescriptors();
2178     for (Iterator iterator = descriptorListToAnalyze.iterator(); iterator.hasNext();) {
2179       MethodDescriptor md = (MethodDescriptor) iterator.next();
2180       calculateExtraLocations(md);
2181     }
2182   }
2183
2184   private void calculateExtraLocations2() {
2185     LinkedList<MethodDescriptor> descriptorListToAnalyze = ssjava.getSortedDescriptors();
2186     for (Iterator iterator = descriptorListToAnalyze.iterator(); iterator.hasNext();) {
2187       MethodDescriptor md = (MethodDescriptor) iterator.next();
2188       calculateExtraLocations(md);
2189     }
2190   }
2191
2192   private void setMethodLocInfo(MethodDescriptor md, MethodLocationInfo methodInfo) {
2193     mapMethodDescToMethodLocationInfo.put(md, methodInfo);
2194   }
2195
2196   private void checkLatticesOfVirtualMethods(MethodDescriptor md) {
2197
2198     if (!md.isStatic()) {
2199       Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
2200       setPossibleCallees.addAll(ssjava.getCallGraph().getMethods(md));
2201
2202       for (Iterator iterator = setPossibleCallees.iterator(); iterator.hasNext();) {
2203         MethodDescriptor mdCallee = (MethodDescriptor) iterator.next();
2204         if (!md.equals(mdCallee)) {
2205           checkConsistency(md, mdCallee);
2206         }
2207       }
2208
2209     }
2210
2211   }
2212
2213   private void checkConsistency(MethodDescriptor md1, MethodDescriptor md2) {
2214
2215     // check that two lattice have the same relations between parameters(+PC
2216     // LOC, GLOBAL_LOC RETURN LOC)
2217
2218     List<CompositeLocation> list1 = new ArrayList<CompositeLocation>();
2219     List<CompositeLocation> list2 = new ArrayList<CompositeLocation>();
2220
2221     MethodLocationInfo locInfo1 = getMethodLocationInfo(md1);
2222     MethodLocationInfo locInfo2 = getMethodLocationInfo(md2);
2223
2224     Map<Integer, CompositeLocation> paramMap1 = locInfo1.getMapParamIdxToInferLoc();
2225     Map<Integer, CompositeLocation> paramMap2 = locInfo2.getMapParamIdxToInferLoc();
2226
2227     int numParam = locInfo1.getMapParamIdxToInferLoc().keySet().size();
2228
2229     // add location types of paramters
2230     for (int idx = 0; idx < numParam; idx++) {
2231       list1.add(paramMap1.get(Integer.valueOf(idx)));
2232       list2.add(paramMap2.get(Integer.valueOf(idx)));
2233     }
2234
2235     // add program counter location
2236     list1.add(locInfo1.getPCLoc());
2237     list2.add(locInfo2.getPCLoc());
2238
2239     if (!md1.getReturnType().isVoid()) {
2240       // add return value location
2241       CompositeLocation rtrLoc1 = getMethodLocationInfo(md1).getReturnLoc();
2242       CompositeLocation rtrLoc2 = getMethodLocationInfo(md2).getReturnLoc();
2243       list1.add(rtrLoc1);
2244       list2.add(rtrLoc2);
2245     }
2246
2247     // add global location type
2248     if (md1.isStatic()) {
2249       CompositeLocation globalLoc1 =
2250           new CompositeLocation(new Location(md1, locInfo1.getGlobalLocName()));
2251       CompositeLocation globalLoc2 =
2252           new CompositeLocation(new Location(md2, locInfo2.getGlobalLocName()));
2253       list1.add(globalLoc1);
2254       list2.add(globalLoc2);
2255     }
2256
2257     for (int i = 0; i < list1.size(); i++) {
2258       CompositeLocation locA1 = list1.get(i);
2259       CompositeLocation locA2 = list2.get(i);
2260       for (int k = 0; k < list1.size(); k++) {
2261         if (i != k) {
2262           CompositeLocation locB1 = list1.get(k);
2263           CompositeLocation locB2 = list2.get(k);
2264           boolean r1 = isGreaterThan(getLattice(md1), locA1, locB1);
2265
2266           boolean r2 = isGreaterThan(getLattice(md1), locA2, locB2);
2267
2268           if (r1 != r2) {
2269             throw new Error("The method " + md1 + " is not consistent with the method " + md2
2270                 + ".:: They have a different ordering relation between locations (" + locA1 + ","
2271                 + locB1 + ") and (" + locA2 + "," + locB2 + ").");
2272           }
2273         }
2274       }
2275     }
2276
2277   }
2278
2279   private String getSymbol(int idx, FlowNode node) {
2280     Descriptor desc = node.getDescTuple().get(idx);
2281     return desc.getSymbol();
2282   }
2283
2284   private Descriptor getDescriptor(int idx, FlowNode node) {
2285     Descriptor desc = node.getDescTuple().get(idx);
2286     return desc;
2287   }
2288
2289   private void calculateExtraLocations(MethodDescriptor md) {
2290     // calcualte pcloc, returnloc,...
2291
2292     System.out.println("\nSSJAVA:Calculate extra locations: " + md);
2293
2294     SSJavaLattice<String> methodLattice = getMethodLattice(md);
2295
2296     MethodSummary methodSummary = getMethodSummary(md);
2297
2298     FlowGraph fg = getFlowGraph(md);
2299     Set<FlowNode> nodeSet = fg.getNodeSet();
2300
2301     // for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
2302     // FlowNode flowNode = (FlowNode) iterator.next();
2303     // if (flowNode.isDeclaratonNode()) {
2304     // CompositeLocation inferLoc = methodInfo.getInferLocation(flowNode.getDescTuple().get(0));
2305     // String locIdentifier = inferLoc.get(0).getLocIdentifier();
2306     // if (!methodLattice.containsKey(locIdentifier)) {
2307     // methodLattice.put(locIdentifier);
2308     // }
2309     // }
2310     // }
2311     MethodLocationInfo methodInfo = getMethodLocationInfo(md);
2312
2313     Map<Integer, CompositeLocation> mapParamToLoc = methodSummary.getMapParamIdxToInferLoc();
2314     Set<Integer> paramIdxSet = mapParamToLoc.keySet();
2315
2316     if (!ssjava.getMethodContainingSSJavaLoop().equals(md)) {
2317       // calculate the initial program counter location
2318       // PC location is higher than location types of parameters which has incoming flows.
2319       String pcLocSymbol = "PCLOC";
2320
2321       Set<NTuple<Location>> paramLocTupleHavingInFlowSet = new HashSet<NTuple<Location>>();
2322
2323       int numParams = fg.getNumParameters();
2324       for (int i = 0; i < numParams; i++) {
2325         FlowNode paramFlowNode = fg.getParamFlowNode(i);
2326
2327         Descriptor prefix = paramFlowNode.getDescTuple().get(0);
2328
2329         // if (fg.getIncomingFlowNodeSet(paramFlowNode).size() > 0) {
2330         if (fg.getIncomingNodeSetByPrefix(prefix).size() > 0) {
2331           // parameter has in-value flows
2332           NTuple<Descriptor> paramDescTuple = paramFlowNode.getCurrentDescTuple();
2333           NTuple<Location> paramLocTuple = translateToLocTuple(md, paramDescTuple);
2334
2335           paramLocTupleHavingInFlowSet.add(paramLocTuple);
2336           // CompositeLocation inferLoc = mapParamToLoc.get(paramIdx);
2337           // paramInFlowSet.add(inferLoc);
2338         }
2339       }
2340
2341       System.out.println("paramLocTupleHavingInFlowSet=" + paramLocTupleHavingInFlowSet);
2342
2343       int numParamsWithIncomingValue = paramLocTupleHavingInFlowSet.size();
2344
2345       if (paramLocTupleHavingInFlowSet.size() > 0
2346           && numParamsWithIncomingValue == fg.getNumParameters()) {
2347         // If the PC loc is going to be higher than all paramters, we dont' need to do anything
2348
2349         // Generates a location in the method lattice that is higher than the
2350         // paramLocTupleHavingInFlowSet
2351         NTuple<Location> pcLocTuple = generateLocTupleHigherThan(md, paramLocTupleHavingInFlowSet);
2352
2353         int pcLocTupleIdx = pcLocTuple.size() - 1;
2354         Location pcLoc = pcLocTuple.get(pcLocTupleIdx);
2355         Descriptor pcDesc = pcLoc.getLocDescriptor();
2356         Descriptor enclosingDesc = pcLocTuple.get(pcLocTupleIdx).getDescriptor();
2357
2358         HierarchyGraph hierarchyGraph = getHierarchyGraph(enclosingDesc);
2359         HNode pcNode = hierarchyGraph.getHNode(pcDesc);
2360         pcNode.setSkeleton(true);
2361
2362         for (Iterator iterator = paramLocTupleHavingInFlowSet.iterator(); iterator.hasNext();) {
2363           NTuple<Location> paramLocTuple = (NTuple<Location>) iterator.next();
2364           Descriptor lowerDesc = paramLocTuple.get(pcLocTupleIdx).getLocDescriptor();
2365           hierarchyGraph.addEdge(pcDesc, lowerDesc);
2366         }
2367
2368       }
2369
2370     }
2371
2372     // calculate a return location
2373     // the return location type is lower than all parameters and location
2374     // types of return values
2375     if (!md.getReturnType().isVoid()) {
2376       // first, generate the set of return value location types that starts
2377       // with 'this' reference
2378
2379       Set<CompositeLocation> inferFieldReturnLocSet = new HashSet<CompositeLocation>();
2380
2381       Set<FlowNode> paramFlowNodeFlowingToReturnValueSet = getParamNodeFlowingToReturnValue(md);
2382       Set<CompositeLocation> inferParamLocSet = new HashSet<CompositeLocation>();
2383       for (Iterator iterator = paramFlowNodeFlowingToReturnValueSet.iterator(); iterator.hasNext();) {
2384         FlowNode fn = (FlowNode) iterator.next();
2385         CompositeLocation inferLoc =
2386             generateInferredCompositeLocation(methodInfo, getFlowGraph(md).getLocationTuple(fn));
2387         inferParamLocSet.add(inferLoc);
2388       }
2389
2390       Set<FlowNode> returnNodeSet = fg.getReturnNodeSet();
2391
2392       skip: for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
2393         FlowNode returnNode = (FlowNode) iterator.next();
2394         CompositeLocation inferReturnLoc =
2395             generateInferredCompositeLocation(methodInfo, fg.getLocationTuple(returnNode));
2396         if (inferReturnLoc.get(0).getLocIdentifier().equals("this")) {
2397           // if the location type of the return value matches "this" reference
2398           // then, check whether this return value is equal to/lower than all
2399           // of parameters that possibly flow into the return values
2400           for (Iterator iterator2 = inferParamLocSet.iterator(); iterator2.hasNext();) {
2401             CompositeLocation paramInferLoc = (CompositeLocation) iterator2.next();
2402
2403             if ((!paramInferLoc.equals(inferReturnLoc))
2404                 && !isGreaterThan(methodLattice, paramInferLoc, inferReturnLoc)) {
2405               continue skip;
2406             }
2407           }
2408           inferFieldReturnLocSet.add(inferReturnLoc);
2409
2410         }
2411       }
2412
2413       if (inferFieldReturnLocSet.size() > 0) {
2414
2415         CompositeLocation returnLoc = getLowest(methodLattice, inferFieldReturnLocSet);
2416         if (returnLoc == null) {
2417           // in this case, assign <'this',bottom> to the RETURNLOC
2418           returnLoc = new CompositeLocation(new Location(md, md.getThis().getSymbol()));
2419           returnLoc.addLocation(new Location(md.getClassDesc(), getLattice(md.getClassDesc())
2420               .getBottomItem()));
2421         }
2422         methodInfo.setReturnLoc(returnLoc);
2423
2424       } else {
2425         String returnLocSymbol = "RETURNLOC";
2426         CompositeLocation returnLocInferLoc =
2427             new CompositeLocation(new Location(md, returnLocSymbol));
2428         methodInfo.setReturnLoc(returnLocInferLoc);
2429
2430         for (Iterator iterator = paramIdxSet.iterator(); iterator.hasNext();) {
2431           Integer paramIdx = (Integer) iterator.next();
2432           CompositeLocation inferLoc = mapParamToLoc.get(paramIdx);
2433           String paramLocLocalSymbol = inferLoc.get(0).getLocIdentifier();
2434           if (!methodLattice.isGreaterThan(paramLocLocalSymbol, returnLocSymbol)) {
2435             // TODO
2436             // addRelationHigherToLower(methodLattice, methodInfo,
2437             // paramLocLocalSymbol,
2438             // returnLocSymbol);
2439           }
2440         }
2441
2442         for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
2443           FlowNode returnNode = (FlowNode) iterator.next();
2444           CompositeLocation inferLoc =
2445               generateInferredCompositeLocation(methodInfo, fg.getLocationTuple(returnNode));
2446           if (!isGreaterThan(methodLattice, inferLoc, returnLocInferLoc)) {
2447             // TODO
2448             // addRelation(methodLattice, methodInfo, inferLoc,
2449             // returnLocInferLoc);
2450           }
2451         }
2452
2453       }
2454
2455     }
2456   }
2457
2458   private NTuple<Location> generateLocTupleHigherThan(MethodDescriptor md,
2459       Set<NTuple<Location>> paramLocTupleHavingInFlowSet) {
2460
2461     System.out.println("-generateLocTupleHigherThan=" + paramLocTupleHavingInFlowSet);
2462
2463     NTuple<Location> higherLocTuple = new NTuple<Location>();
2464
2465     VarDescriptor thisVarDesc = md.getThis();
2466     // check if all paramter loc tuple is started with 'this' reference
2467     boolean hasParamNotStartedWithThisRef = false;
2468
2469     int maxSize = 0;
2470
2471     Set<NTuple<Location>> paramLocTupleStartedWithThis = new HashSet<NTuple<Location>>();
2472
2473     for (Iterator iterator = paramLocTupleHavingInFlowSet.iterator(); iterator.hasNext();) {
2474       NTuple<Location> paramLocTuple = (NTuple<Location>) iterator.next();
2475       if (!paramLocTuple.get(0).getLocDescriptor().equals(thisVarDesc)) {
2476         hasParamNotStartedWithThisRef = true;
2477       } else if (paramLocTuple.size() > 1) {
2478         paramLocTupleStartedWithThis.add(paramLocTuple);
2479         if (maxSize < paramLocTuple.size()) {
2480           maxSize = paramLocTuple.size();
2481         }
2482       }
2483     }
2484
2485     Descriptor enclosingDesc = md;
2486     if (hasParamNotStartedWithThisRef) {
2487       // in this case, PCLOC will be the local location
2488     } else {
2489       // all parameter is started with 'this', so PCLOC will be set relative to the composite
2490       // location started with 'this'.
2491       for (int idx = 0; idx < maxSize - 1; idx++) {
2492         Set<Descriptor> locDescSet = new HashSet<Descriptor>();
2493         Location curLoc = null;
2494         for (Iterator iterator = paramLocTupleHavingInFlowSet.iterator(); iterator.hasNext();) {
2495           NTuple<Location> paramLocTuple = (NTuple<Location>) iterator.next();
2496           curLoc = paramLocTuple.get(idx);
2497           Descriptor locDesc = curLoc.getLocDescriptor();
2498           locDescSet.add(locDesc);
2499         }
2500         System.out.println("locDescSet=" + locDescSet + " idx=" + idx);
2501         if (locDescSet.size() != 1) {
2502           break;
2503         }
2504         Location newLocElement = new Location(curLoc.getDescriptor(), curLoc.getLocDescriptor());
2505         higherLocTuple.add(newLocElement);
2506         enclosingDesc = getClassTypeDescriptor(curLoc.getLocDescriptor());
2507       }
2508
2509     }
2510
2511     String pcLocIdentifier = PCLOC + (locSeed++);
2512     NameDescriptor pcLocDesc = new NameDescriptor(pcLocIdentifier);
2513     Location newLoc = new Location(enclosingDesc, pcLocDesc);
2514     higherLocTuple.add(newLoc);
2515
2516     System.out.println("---higherLocTuple=" + higherLocTuple);
2517
2518     return higherLocTuple;
2519
2520   }
2521
2522   public ClassDescriptor getClassTypeDescriptor(Descriptor in) {
2523
2524     if (in instanceof VarDescriptor) {
2525       return ((VarDescriptor) in).getType().getClassDesc();
2526     } else {/* if (desc instanceof FieldDescriptor) { */
2527       return ((FieldDescriptor) in).getType().getClassDesc();
2528     }
2529
2530   }
2531
2532   private Set<NTuple<Location>> calculateHighestLocTupleSet(
2533       Set<NTuple<Location>> paramLocTupleHavingInFlowSet) {
2534
2535     Set<NTuple<Location>> highestSet = new HashSet<NTuple<Location>>();
2536
2537     Iterator<NTuple<Location>> iterator = paramLocTupleHavingInFlowSet.iterator();
2538     NTuple<Location> highest = iterator.next();
2539
2540     for (; iterator.hasNext();) {
2541       NTuple<Location> curLocTuple = (NTuple<Location>) iterator.next();
2542       if (isHigherThan(curLocTuple, highest)) {
2543         System.out.println(curLocTuple + " is greater than " + highest);
2544         highest = curLocTuple;
2545       }
2546     }
2547
2548     highestSet.add(highest);
2549
2550     MethodDescriptor md = (MethodDescriptor) highest.get(0).getDescriptor();
2551     VarDescriptor thisVarDesc = md.getThis();
2552
2553     System.out.println("highest=" + highest);
2554
2555     for (Iterator<NTuple<Location>> iter = paramLocTupleHavingInFlowSet.iterator(); iter.hasNext();) {
2556       NTuple<Location> curLocTuple = iter.next();
2557
2558       if (!curLocTuple.equals(highest) && !hasOrderingRelation(highest, curLocTuple)) {
2559
2560         System.out.println("add it to the highest set=" + curLocTuple);
2561         highestSet.add(curLocTuple);
2562
2563       }
2564     }
2565
2566     return highestSet;
2567
2568   }
2569
2570   private void calculateExtraLocations2(MethodDescriptor md) {
2571     // calcualte pcloc, returnloc,...
2572
2573     SSJavaLattice<String> methodLattice = getMethodLattice(md);
2574     MethodLocationInfo methodInfo = getMethodLocationInfo(md);
2575     FlowGraph fg = getFlowGraph(md);
2576     Set<FlowNode> nodeSet = fg.getNodeSet();
2577
2578     for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
2579       FlowNode flowNode = (FlowNode) iterator.next();
2580       if (flowNode.isDeclaratonNode()) {
2581         CompositeLocation inferLoc = methodInfo.getInferLocation(flowNode.getDescTuple().get(0));
2582         String locIdentifier = inferLoc.get(0).getLocIdentifier();
2583         if (!methodLattice.containsKey(locIdentifier)) {
2584           methodLattice.put(locIdentifier);
2585         }
2586
2587       }
2588     }
2589
2590     Map<Integer, CompositeLocation> mapParamToLoc = methodInfo.getMapParamIdxToInferLoc();
2591     Set<Integer> paramIdxSet = mapParamToLoc.keySet();
2592
2593     if (!ssjava.getMethodContainingSSJavaLoop().equals(md)) {
2594       // calculate the initial program counter location
2595       // PC location is higher than location types of all parameters
2596       String pcLocSymbol = "PCLOC";
2597
2598       Set<CompositeLocation> paramInFlowSet = new HashSet<CompositeLocation>();
2599
2600       for (Iterator iterator = paramIdxSet.iterator(); iterator.hasNext();) {
2601         Integer paramIdx = (Integer) iterator.next();
2602
2603         FlowNode paramFlowNode = fg.getParamFlowNode(paramIdx);
2604
2605         if (fg.getIncomingFlowNodeSet(paramFlowNode).size() > 0) {
2606           // parameter has in-value flows
2607           CompositeLocation inferLoc = mapParamToLoc.get(paramIdx);
2608           paramInFlowSet.add(inferLoc);
2609         }
2610       }
2611
2612       if (paramInFlowSet.size() > 0) {
2613         CompositeLocation lowestLoc = getLowest(methodLattice, paramInFlowSet);
2614         assert (lowestLoc != null);
2615         methodInfo.setPCLoc(lowestLoc);
2616       }
2617
2618     }
2619
2620     // calculate a return location
2621     // the return location type is lower than all parameters and location
2622     // types
2623     // of return values
2624     if (!md.getReturnType().isVoid()) {
2625       // first, generate the set of return value location types that starts
2626       // with
2627       // 'this' reference
2628
2629       Set<CompositeLocation> inferFieldReturnLocSet = new HashSet<CompositeLocation>();
2630
2631       Set<FlowNode> paramFlowNode = getParamNodeFlowingToReturnValue(md);
2632       Set<CompositeLocation> inferParamLocSet = new HashSet<CompositeLocation>();
2633       if (paramFlowNode != null) {
2634         for (Iterator iterator = paramFlowNode.iterator(); iterator.hasNext();) {
2635           FlowNode fn = (FlowNode) iterator.next();
2636           CompositeLocation inferLoc =
2637               generateInferredCompositeLocation(methodInfo, getFlowGraph(md).getLocationTuple(fn));
2638           inferParamLocSet.add(inferLoc);
2639         }
2640       }
2641
2642       Set<FlowNode> returnNodeSet = fg.getReturnNodeSet();
2643
2644       skip: for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
2645         FlowNode returnNode = (FlowNode) iterator.next();
2646         CompositeLocation inferReturnLoc =
2647             generateInferredCompositeLocation(methodInfo, fg.getLocationTuple(returnNode));
2648         if (inferReturnLoc.get(0).getLocIdentifier().equals("this")) {
2649           // if the location type of the return value matches "this" reference
2650           // then, check whether this return value is equal to/lower than all
2651           // of
2652           // parameters that possibly flow into the return values
2653           for (Iterator iterator2 = inferParamLocSet.iterator(); iterator2.hasNext();) {
2654             CompositeLocation paramInferLoc = (CompositeLocation) iterator2.next();
2655
2656             if ((!paramInferLoc.equals(inferReturnLoc))
2657                 && !isGreaterThan(methodLattice, paramInferLoc, inferReturnLoc)) {
2658               continue skip;
2659             }
2660           }
2661           inferFieldReturnLocSet.add(inferReturnLoc);
2662
2663         }
2664       }
2665
2666       if (inferFieldReturnLocSet.size() > 0) {
2667
2668         CompositeLocation returnLoc = getLowest(methodLattice, inferFieldReturnLocSet);
2669         if (returnLoc == null) {
2670           // in this case, assign <'this',bottom> to the RETURNLOC
2671           returnLoc = new CompositeLocation(new Location(md, md.getThis().getSymbol()));
2672           returnLoc.addLocation(new Location(md.getClassDesc(), getLattice(md.getClassDesc())
2673               .getBottomItem()));
2674         }
2675         methodInfo.setReturnLoc(returnLoc);
2676
2677       } else {
2678         String returnLocSymbol = "RETURNLOC";
2679         CompositeLocation returnLocInferLoc =
2680             new CompositeLocation(new Location(md, returnLocSymbol));
2681         methodInfo.setReturnLoc(returnLocInferLoc);
2682
2683         for (Iterator iterator = paramIdxSet.iterator(); iterator.hasNext();) {
2684           Integer paramIdx = (Integer) iterator.next();
2685           CompositeLocation inferLoc = mapParamToLoc.get(paramIdx);
2686           String paramLocLocalSymbol = inferLoc.get(0).getLocIdentifier();
2687           if (!methodLattice.isGreaterThan(paramLocLocalSymbol, returnLocSymbol)) {
2688             // TODO
2689             // addRelationHigherToLower(methodLattice, methodInfo,
2690             // paramLocLocalSymbol,
2691             // returnLocSymbol);
2692           }
2693         }
2694
2695         for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
2696           FlowNode returnNode = (FlowNode) iterator.next();
2697           CompositeLocation inferLoc =
2698               generateInferredCompositeLocation(methodInfo, fg.getLocationTuple(returnNode));
2699           if (!isGreaterThan(methodLattice, inferLoc, returnLocInferLoc)) {
2700             // TODO
2701             // addRelation(methodLattice, methodInfo, inferLoc,
2702             // returnLocInferLoc);
2703           }
2704         }
2705
2706       }
2707
2708     }
2709   }
2710
2711   private Set<String> getHigherLocSymbolThan(SSJavaLattice<String> lattice, String loc) {
2712     Set<String> higherLocSet = new HashSet<String>();
2713
2714     Set<String> locSet = lattice.getTable().keySet();
2715     for (Iterator iterator = locSet.iterator(); iterator.hasNext();) {
2716       String element = (String) iterator.next();
2717       if (lattice.isGreaterThan(element, loc) && (!element.equals(lattice.getTopItem()))) {
2718         higherLocSet.add(element);
2719       }
2720     }
2721     return higherLocSet;
2722   }
2723
2724   private CompositeLocation getLowest(SSJavaLattice<String> methodLattice,
2725       Set<CompositeLocation> set) {
2726
2727     CompositeLocation lowest = set.iterator().next();
2728
2729     if (set.size() == 1) {
2730       return lowest;
2731     }
2732
2733     for (Iterator iterator = set.iterator(); iterator.hasNext();) {
2734       CompositeLocation loc = (CompositeLocation) iterator.next();
2735
2736       if ((!loc.equals(lowest)) && (!isComparable(methodLattice, lowest, loc))) {
2737         // if there is a case where composite locations are incomparable, just
2738         // return null
2739         return null;
2740       }
2741
2742       if ((!loc.equals(lowest)) && isGreaterThan(methodLattice, lowest, loc)) {
2743         lowest = loc;
2744       }
2745     }
2746     return lowest;
2747   }
2748
2749   private boolean isComparable(SSJavaLattice<String> methodLattice, CompositeLocation comp1,
2750       CompositeLocation comp2) {
2751
2752     int size = comp1.getSize() >= comp2.getSize() ? comp2.getSize() : comp1.getSize();
2753
2754     for (int idx = 0; idx < size; idx++) {
2755       Location loc1 = comp1.get(idx);
2756       Location loc2 = comp2.get(idx);
2757
2758       Descriptor desc1 = loc1.getDescriptor();
2759       Descriptor desc2 = loc2.getDescriptor();
2760
2761       if (!desc1.equals(desc2)) {
2762         throw new Error("Fail to compare " + comp1 + " and " + comp2);
2763       }
2764
2765       String symbol1 = loc1.getLocIdentifier();
2766       String symbol2 = loc2.getLocIdentifier();
2767
2768       SSJavaLattice<String> lattice;
2769       if (idx == 0) {
2770         lattice = methodLattice;
2771       } else {
2772         lattice = getLattice(desc1);
2773       }
2774
2775       if (symbol1.equals(symbol2)) {
2776         continue;
2777       } else if (!lattice.isComparable(symbol1, symbol2)) {
2778         return false;
2779       }
2780
2781     }
2782
2783     return true;
2784   }
2785
2786   private boolean isGreaterThan(SSJavaLattice<String> methodLattice, CompositeLocation comp1,
2787       CompositeLocation comp2) {
2788
2789     int size = comp1.getSize() >= comp2.getSize() ? comp2.getSize() : comp1.getSize();
2790
2791     for (int idx = 0; idx < size; idx++) {
2792       Location loc1 = comp1.get(idx);
2793       Location loc2 = comp2.get(idx);
2794
2795       Descriptor desc1 = loc1.getDescriptor();
2796       Descriptor desc2 = loc2.getDescriptor();
2797
2798       if (!desc1.equals(desc2)) {
2799         throw new Error("Fail to compare " + comp1 + " and " + comp2);
2800       }
2801
2802       String symbol1 = loc1.getLocIdentifier();
2803       String symbol2 = loc2.getLocIdentifier();
2804
2805       SSJavaLattice<String> lattice;
2806       if (idx == 0) {
2807         lattice = methodLattice;
2808       } else {
2809         lattice = getLattice(desc1);
2810       }
2811
2812       if (symbol1.equals(symbol2)) {
2813         continue;
2814       } else if (lattice.isGreaterThan(symbol1, symbol2)) {
2815         return true;
2816       } else {
2817         return false;
2818       }
2819
2820     }
2821
2822     return false;
2823   }
2824
2825   private void contributeCalleeFlows(MethodInvokeNode min, MethodDescriptor mdCaller,
2826       MethodDescriptor mdCallee) {
2827
2828     System.out.println("\n##contributeCalleeFlows callee=" + mdCallee + "TO caller=" + mdCaller);
2829
2830     getSubGlobalFlowGraph(mdCallee);
2831
2832   }
2833
2834   private GlobalFlowGraph getSubGlobalFlowGraph(MethodDescriptor md) {
2835     return mapMethodDescriptorToSubGlobalFlowGraph.get(md);
2836   }
2837
2838   private void propagateFlowsToCallerWithNoCompositeLocation(MethodInvokeNode min,
2839       MethodDescriptor mdCaller, MethodDescriptor mdCallee) {
2840
2841     System.out.println("\n##PROPAGATE callee=" + mdCallee + "TO caller=" + mdCaller);
2842
2843     // if the parameter A reaches to the parameter B
2844     // then, add an edge the argument A -> the argument B to the caller's flow
2845     // graph
2846
2847     FlowGraph calleeFlowGraph = getFlowGraph(mdCallee);
2848     FlowGraph callerFlowGraph = getFlowGraph(mdCaller);
2849     int numParam = calleeFlowGraph.getNumParameters();
2850
2851     for (int i = 0; i < numParam; i++) {
2852       for (int k = 0; k < numParam; k++) {
2853
2854         if (i != k) {
2855
2856           FlowNode paramNode1 = calleeFlowGraph.getParamFlowNode(i);
2857           FlowNode paramNode2 = calleeFlowGraph.getParamFlowNode(k);
2858
2859           NTuple<Descriptor> arg1Tuple = getNodeTupleByArgIdx(min, i);
2860           NTuple<Descriptor> arg2Tuple = getNodeTupleByArgIdx(min, k);
2861
2862           // check if the callee propagates an ordering constraints through
2863           // parameters
2864
2865           Set<FlowNode> localReachSet = calleeFlowGraph.getLocalReachFlowNodeSetFrom(paramNode1);
2866           System.out.println("-param1=" + paramNode1 + " is higher than param2=" + paramNode2);
2867           System.out.println("-- localReachSet from param1=" + localReachSet);
2868
2869           if (arg1Tuple.size() > 0 && arg2Tuple.size() > 0 && localReachSet.contains(paramNode2)) {
2870             // need to propagate an ordering relation s.t. arg1 is higher
2871             // than arg2
2872
2873             System.out
2874                 .println("-arg1Tuple=" + arg1Tuple + " is higher than arg2Tuple=" + arg2Tuple);
2875
2876             // otherwise, flows between method/field locations...
2877             callerFlowGraph.addValueFlowEdge(arg1Tuple, arg2Tuple);
2878             System.out.println("arg1=" + arg1Tuple + "   arg2=" + arg2Tuple);
2879
2880           }
2881
2882           System.out.println();
2883         }
2884       }
2885     }
2886     System.out.println("##\n");
2887
2888   }
2889
2890   private void propagateFlowsToCaller(MethodInvokeNode min, MethodDescriptor mdCaller,
2891       MethodDescriptor mdCallee) {
2892
2893     System.out.println("\n##PROPAGATE callee=" + mdCallee + "TO caller=" + mdCaller);
2894
2895     // if the parameter A reaches to the parameter B
2896     // then, add an edge the argument A -> the argument B to the caller's flow
2897     // graph
2898
2899     // TODO
2900     // also if a parameter is a composite location and is started with "this"
2901     // reference,
2902     // need to make sure that the corresponding argument is higher than the
2903     // translated location of
2904     // the parameter.
2905
2906     FlowGraph calleeFlowGraph = getFlowGraph(mdCallee);
2907     FlowGraph callerFlowGraph = getFlowGraph(mdCaller);
2908     int numParam = calleeFlowGraph.getNumParameters();
2909
2910     for (int i = 0; i < numParam; i++) {
2911       for (int k = 0; k < numParam; k++) {
2912
2913         if (i != k) {
2914
2915           FlowNode paramNode1 = calleeFlowGraph.getParamFlowNode(i);
2916           FlowNode paramNode2 = calleeFlowGraph.getParamFlowNode(k);
2917
2918           System.out.println("param1=" + paramNode1 + " curDescTuple="
2919               + paramNode1.getCurrentDescTuple());
2920           System.out.println("param2=" + paramNode2 + " curDescTuple="
2921               + paramNode2.getCurrentDescTuple());
2922
2923           // TODO: deprecated method
2924           // NodeTupleSet tupleSetArg1 = getNodeTupleSetByArgIdx(min, i);
2925           // NodeTupleSet tupleSetArg2 = getNodeTupleSetByArgIdx(min, k);
2926           NodeTupleSet tupleSetArg1 = null;
2927           NodeTupleSet tupleSetArg2 = null;
2928
2929           for (Iterator<NTuple<Descriptor>> iter1 = tupleSetArg1.iterator(); iter1.hasNext();) {
2930             NTuple<Descriptor> arg1Tuple = iter1.next();
2931
2932             for (Iterator<NTuple<Descriptor>> iter2 = tupleSetArg2.iterator(); iter2.hasNext();) {
2933               NTuple<Descriptor> arg2Tuple = iter2.next();
2934
2935               // check if the callee propagates an ordering constraints through
2936               // parameters
2937
2938               Set<FlowNode> localReachSet =
2939                   calleeFlowGraph.getLocalReachFlowNodeSetFrom(paramNode1);
2940
2941               if (localReachSet.contains(paramNode2)) {
2942                 // need to propagate an ordering relation s.t. arg1 is higher
2943                 // than arg2
2944
2945                 System.out
2946                     .println("-param1=" + paramNode1 + " is higher than param2=" + paramNode2);
2947                 System.out.println("-arg1Tuple=" + arg1Tuple + " is higher than arg2Tuple="
2948                     + arg2Tuple);
2949
2950                 if (!min.getMethod().isStatic()) {
2951                   // check if this is the case that values flow to/from the
2952                   // current object reference 'this'
2953
2954                   NTuple<Descriptor> baseTuple = mapMethodInvokeNodeToBaseTuple.get(min);
2955                   Descriptor baseRef = baseTuple.get(baseTuple.size() - 1);
2956
2957                   System.out.println("paramNode1.getCurrentDescTuple()="
2958                       + paramNode1.getCurrentDescTuple());
2959                   // calculate the prefix of the argument
2960
2961                   if (arg2Tuple.size() == 1 && arg2Tuple.get(0).equals(baseRef)) {
2962                     // in this case, the callee flow causes a caller flow to the
2963                     // object whose method
2964                     // is invoked.
2965
2966                     if (!paramNode1.getCurrentDescTuple().startsWith(mdCallee.getThis())) {
2967                       // check whether ???
2968
2969                       NTuple<Descriptor> param1Prefix =
2970                           calculatePrefixForParam(callerFlowGraph, calleeFlowGraph, min, arg1Tuple,
2971                               paramNode1);
2972
2973                       if (param1Prefix != null && param1Prefix.startsWith(mdCallee.getThis())) {
2974                         // in this case, we need to create a new edge
2975                         // 'this.FIELD'->'this'
2976                         // but we couldn't... instead we assign a new composite
2977                         // location started
2978                         // with 'this' reference to the corresponding parameter
2979
2980                         CompositeLocation compLocForParam1 =
2981                             generateCompositeLocation(mdCallee, param1Prefix);
2982
2983                         System.out
2984                             .println("set comp loc=" + compLocForParam1 + " to " + paramNode1);
2985                         paramNode1.setCompositeLocation(compLocForParam1);
2986
2987                         // then, we need to make sure that the corresponding
2988                         // argument in the caller
2989                         // is required to be higher than or equal to the
2990                         // translated parameter
2991                         // location
2992
2993                         NTuple<Descriptor> translatedParamTuple =
2994                             translateCompositeLocationToCaller(min, compLocForParam1);
2995
2996                         // TODO : check if the arg >= the tranlated parameter
2997
2998                         System.out.println("add a flow edge= " + arg1Tuple + "->"
2999                             + translatedParamTuple);
3000                         callerFlowGraph.addValueFlowEdge(arg1Tuple, translatedParamTuple);
3001
3002                         continue;
3003
3004                       }
3005
3006                     } else {
3007                       // param1 has already been assigned a composite location
3008
3009                       System.out.println("--param1 has already been assigned a composite location");
3010                       CompositeLocation compLocForParam1 = paramNode1.getCompositeLocation();
3011                       NTuple<Descriptor> translatedParamTuple =
3012                           translateCompositeLocationToCaller(min, compLocForParam1);
3013
3014                       // TODO : check if the arg >= the tranlated parameter
3015
3016                       System.out.println("add a flow edge= " + arg1Tuple + "->"
3017                           + translatedParamTuple);
3018                       callerFlowGraph.addValueFlowEdge(arg1Tuple, translatedParamTuple);
3019
3020                       continue;
3021
3022                     }
3023
3024                   } else if (arg1Tuple.size() == 1 && arg1Tuple.get(0).equals(baseRef)) {
3025                     // in this case, the callee flow causes a caller flow
3026                     // originated from the object
3027                     // whose
3028                     // method is invoked.
3029
3030                     System.out.println("###FROM CASE");
3031
3032                     if (!paramNode2.getCurrentDescTuple().startsWith(mdCallee.getThis())) {
3033
3034                       NTuple<Descriptor> param2Prefix =
3035                           calculatePrefixForParam(callerFlowGraph, calleeFlowGraph, min, arg2Tuple,
3036                               paramNode2);
3037
3038                       if (param2Prefix != null && param2Prefix.startsWith(mdCallee.getThis())) {
3039                         // in this case, we need to create a new edge 'this' ->
3040                         // 'this.FIELD' but we couldn't... instead we assign the
3041                         // corresponding
3042                         // parameter a new composite location started with
3043                         // 'this' reference
3044
3045                         CompositeLocation compLocForParam2 =
3046                             generateCompositeLocation(mdCallee, param2Prefix);
3047
3048                         // System.out.println("set comp loc=" + compLocForParam2
3049                         // +
3050                         // " to " + paramNode2);
3051                         paramNode1.setCompositeLocation(compLocForParam2);
3052                         continue;
3053                       }
3054                     }
3055
3056                   }
3057                 }
3058
3059                 // otherwise, flows between method/field locations...
3060                 callerFlowGraph.addValueFlowEdge(arg1Tuple, arg2Tuple);
3061                 System.out.println("arg1=" + arg1Tuple + "   arg2=" + arg2Tuple);
3062
3063               }
3064
3065             }
3066
3067           }
3068           System.out.println();
3069         }
3070       }
3071     }
3072     System.out.println("##\n");
3073   }
3074
3075   private NTuple<Descriptor> translateCompositeLocationToCaller(MethodInvokeNode min,
3076       CompositeLocation compLocForParam1) {
3077     NTuple<Descriptor> baseTuple = mapMethodInvokeNodeToBaseTuple.get(min);
3078
3079     NTuple<Descriptor> tuple = new NTuple<Descriptor>();
3080
3081     for (int i = 0; i < baseTuple.size(); i++) {
3082       tuple.add(baseTuple.get(i));
3083     }
3084
3085     for (int i = 1; i < compLocForParam1.getSize(); i++) {
3086       Location loc = compLocForParam1.get(i);
3087       tuple.add(loc.getLocDescriptor());
3088     }
3089
3090     return tuple;
3091   }
3092
3093   private CompositeLocation generateCompositeLocation(NTuple<Location> prefixLocTuple) {
3094
3095     System.out.println("generateCompositeLocation=" + prefixLocTuple);
3096
3097     CompositeLocation newCompLoc = new CompositeLocation();
3098     for (int i = 0; i < prefixLocTuple.size(); i++) {
3099       newCompLoc.addLocation(prefixLocTuple.get(i));
3100     }
3101
3102     Descriptor lastDescOfPrefix = prefixLocTuple.get(prefixLocTuple.size() - 1).getLocDescriptor();
3103
3104     ClassDescriptor enclosingDescriptor;
3105     if (lastDescOfPrefix instanceof FieldDescriptor) {
3106       enclosingDescriptor = ((FieldDescriptor) lastDescOfPrefix).getType().getClassDesc();
3107       // System.out.println("enclosingDescriptor0=" + enclosingDescriptor);
3108     } else {
3109       // var descriptor case
3110       enclosingDescriptor = ((VarDescriptor) lastDescOfPrefix).getType().getClassDesc();
3111     }
3112     // System.out.println("enclosingDescriptor=" + enclosingDescriptor);
3113
3114     LocationDescriptor newLocDescriptor = generateNewLocationDescriptor();
3115     newLocDescriptor.setEnclosingClassDesc(enclosingDescriptor);
3116
3117     Location newLoc = new Location(enclosingDescriptor, newLocDescriptor.getSymbol());
3118     newLoc.setLocDescriptor(newLocDescriptor);
3119     newCompLoc.addLocation(newLoc);
3120
3121     // System.out.println("--newCompLoc=" + newCompLoc);
3122     return newCompLoc;
3123   }
3124
3125   private CompositeLocation generateCompositeLocation(MethodDescriptor md,
3126       NTuple<Descriptor> paramPrefix) {
3127
3128     System.out.println("generateCompositeLocation=" + paramPrefix);
3129
3130     CompositeLocation newCompLoc = convertToCompositeLocation(md, paramPrefix);
3131
3132     Descriptor lastDescOfPrefix = paramPrefix.get(paramPrefix.size() - 1);
3133     // System.out.println("lastDescOfPrefix=" + lastDescOfPrefix + "  kind="
3134     // + lastDescOfPrefix.getClass());
3135     ClassDescriptor enclosingDescriptor;
3136     if (lastDescOfPrefix instanceof FieldDescriptor) {
3137       enclosingDescriptor = ((FieldDescriptor) lastDescOfPrefix).getType().getClassDesc();
3138       // System.out.println("enclosingDescriptor0=" + enclosingDescriptor);
3139     } else {
3140       // var descriptor case
3141       enclosingDescriptor = ((VarDescriptor) lastDescOfPrefix).getType().getClassDesc();
3142     }
3143     // System.out.println("enclosingDescriptor=" + enclosingDescriptor);
3144
3145     LocationDescriptor newLocDescriptor = generateNewLocationDescriptor();
3146     newLocDescriptor.setEnclosingClassDesc(enclosingDescriptor);
3147
3148     Location newLoc = new Location(enclosingDescriptor, newLocDescriptor.getSymbol());
3149     newLoc.setLocDescriptor(newLocDescriptor);
3150     newCompLoc.addLocation(newLoc);
3151
3152     // System.out.println("--newCompLoc=" + newCompLoc);
3153     return newCompLoc;
3154   }
3155
3156   private NTuple<Descriptor> calculatePrefixForParam(FlowGraph callerFlowGraph,
3157       FlowGraph calleeFlowGraph, MethodInvokeNode min, NTuple<Descriptor> arg1Tuple,
3158       FlowNode paramNode1) {
3159
3160     NTuple<Descriptor> baseTuple = mapMethodInvokeNodeToBaseTuple.get(min);
3161     Descriptor baseRef = baseTuple.get(baseTuple.size() - 1);
3162     System.out.println("baseRef=" + baseRef);
3163
3164     FlowNode flowNodeArg1 = callerFlowGraph.getFlowNode(arg1Tuple);
3165     List<NTuple<Descriptor>> callerPrefixList = calculatePrefixList(callerFlowGraph, flowNodeArg1);
3166     System.out.println("callerPrefixList=" + callerPrefixList);
3167
3168     List<NTuple<Descriptor>> prefixList = calculatePrefixList(calleeFlowGraph, paramNode1);
3169     System.out.println("###prefixList from node=" + paramNode1 + " =" + prefixList);
3170
3171     List<NTuple<Descriptor>> calleePrefixList =
3172         translatePrefixListToCallee(baseRef, min.getMethod(), callerPrefixList);
3173
3174     System.out.println("calleePrefixList=" + calleePrefixList);
3175
3176     Set<FlowNode> reachNodeSetFromParam1 = calleeFlowGraph.getReachFlowNodeSetFrom(paramNode1);
3177     System.out.println("reachNodeSetFromParam1=" + reachNodeSetFromParam1);
3178
3179     for (int i = 0; i < calleePrefixList.size(); i++) {
3180       NTuple<Descriptor> curPrefix = calleePrefixList.get(i);
3181       Set<NTuple<Descriptor>> reachableCommonPrefixSet = new HashSet<NTuple<Descriptor>>();
3182
3183       for (Iterator iterator2 = reachNodeSetFromParam1.iterator(); iterator2.hasNext();) {
3184         FlowNode reachNode = (FlowNode) iterator2.next();
3185         if (reachNode.getCurrentDescTuple().startsWith(curPrefix)) {
3186           reachableCommonPrefixSet.add(reachNode.getCurrentDescTuple());
3187         }
3188       }
3189
3190       if (!reachableCommonPrefixSet.isEmpty()) {
3191         System.out.println("###REACHABLECOMONPREFIX=" + reachableCommonPrefixSet
3192             + " with curPreFix=" + curPrefix);
3193         return curPrefix;
3194       }
3195
3196     }
3197
3198     return null;
3199   }
3200
3201   private List<NTuple<Descriptor>> translatePrefixListToCallee(Descriptor baseRef,
3202       MethodDescriptor mdCallee, List<NTuple<Descriptor>> callerPrefixList) {
3203
3204     List<NTuple<Descriptor>> calleePrefixList = new ArrayList<NTuple<Descriptor>>();
3205
3206     for (int i = 0; i < callerPrefixList.size(); i++) {
3207       NTuple<Descriptor> prefix = callerPrefixList.get(i);
3208       if (prefix.startsWith(baseRef)) {
3209         NTuple<Descriptor> calleePrefix = new NTuple<Descriptor>();
3210         calleePrefix.add(mdCallee.getThis());
3211         for (int k = 1; k < prefix.size(); k++) {
3212           calleePrefix.add(prefix.get(k));
3213         }
3214         calleePrefixList.add(calleePrefix);
3215       }
3216     }
3217
3218     return calleePrefixList;
3219
3220   }
3221
3222   private List<NTuple<Descriptor>> calculatePrefixList(FlowGraph flowGraph, FlowNode flowNode) {
3223
3224     System.out.println("\n##### calculatePrefixList=" + flowNode);
3225
3226     Set<FlowNode> inNodeSet = flowGraph.getIncomingFlowNodeSet(flowNode);
3227     inNodeSet.add(flowNode);
3228
3229     System.out.println("inNodeSet=" + inNodeSet);
3230
3231     List<NTuple<Descriptor>> prefixList = new ArrayList<NTuple<Descriptor>>();
3232
3233     for (Iterator iterator = inNodeSet.iterator(); iterator.hasNext();) {
3234       FlowNode inNode = (FlowNode) iterator.next();
3235
3236       NTuple<Descriptor> inNodeTuple = inNode.getCurrentDescTuple();
3237
3238       // CompositeLocation inNodeInferredLoc =
3239       // generateInferredCompositeLocation(methodInfo, inNodeTuple);
3240       // NTuple<Location> inNodeInferredLocTuple = inNodeInferredLoc.getTuple();
3241
3242       for (int i = 1; i < inNodeTuple.size(); i++) {
3243         NTuple<Descriptor> prefix = inNodeTuple.subList(0, i);
3244         if (!prefixList.contains(prefix)) {
3245           prefixList.add(prefix);
3246         }
3247       }
3248     }
3249
3250     Collections.sort(prefixList, new Comparator<NTuple<Descriptor>>() {
3251       public int compare(NTuple<Descriptor> arg0, NTuple<Descriptor> arg1) {
3252         int s0 = arg0.size();
3253         int s1 = arg1.size();
3254         if (s0 > s1) {
3255           return -1;
3256         } else if (s0 == s1) {
3257           return 0;
3258         } else {
3259           return 1;
3260         }
3261       }
3262     });
3263
3264     return prefixList;
3265
3266   }
3267
3268   public CompositeLocation convertToCompositeLocation(MethodDescriptor md, NTuple<Descriptor> tuple) {
3269
3270     CompositeLocation compLoc = new CompositeLocation();
3271
3272     Descriptor enclosingDescriptor = md;
3273
3274     for (int i = 0; i < tuple.size(); i++) {
3275       Descriptor curDescriptor = tuple.get(i);
3276       Location locElement = new Location(enclosingDescriptor, curDescriptor.getSymbol());
3277       locElement.setLocDescriptor(curDescriptor);
3278       compLoc.addLocation(locElement);
3279
3280       if (curDescriptor instanceof VarDescriptor) {
3281         enclosingDescriptor = md.getClassDesc();
3282       } else if (curDescriptor instanceof NameDescriptor) {
3283         // it is "GLOBAL LOC" case!
3284         enclosingDescriptor = GLOBALDESC;
3285       } else if (curDescriptor instanceof InterDescriptor) {
3286         enclosingDescriptor = null;
3287       } else {
3288         enclosingDescriptor = ((FieldDescriptor) curDescriptor).getClassDescriptor();
3289       }
3290
3291     }
3292
3293     return compLoc;
3294   }
3295
3296   private LocationDescriptor generateNewLocationDescriptor() {
3297     return new LocationDescriptor("Loc" + (locSeed++));
3298   }
3299
3300   private int getPrefixIndex(NTuple<Descriptor> tuple1, NTuple<Descriptor> tuple2) {
3301
3302     // return the index where the prefix shared by tuple1 and tuple2 is ended
3303     // if there is no prefix shared by both of them, return -1
3304
3305     int minSize = tuple1.size();
3306     if (minSize > tuple2.size()) {
3307       minSize = tuple2.size();
3308     }
3309
3310     int idx = -1;
3311     for (int i = 0; i < minSize; i++) {
3312       if (!tuple1.get(i).equals(tuple2.get(i))) {
3313         break;
3314       } else {
3315         idx++;
3316       }
3317     }
3318
3319     return idx;
3320   }
3321
3322   private CompositeLocation generateInferredCompositeLocation(MethodLocationInfo methodInfo,
3323       NTuple<Location> tuple) {
3324
3325     // first, retrieve inferred location by the local var descriptor
3326     CompositeLocation inferLoc = new CompositeLocation();
3327
3328     CompositeLocation localVarInferLoc =
3329         methodInfo.getInferLocation(tuple.get(0).getLocDescriptor());
3330
3331     localVarInferLoc.get(0).setLocDescriptor(tuple.get(0).getLocDescriptor());
3332
3333     for (int i = 0; i < localVarInferLoc.getSize(); i++) {
3334       inferLoc.addLocation(localVarInferLoc.get(i));
3335     }
3336
3337     for (int i = 1; i < tuple.size(); i++) {
3338       Location cur = tuple.get(i);
3339       Descriptor enclosingDesc = cur.getDescriptor();
3340       Descriptor curDesc = cur.getLocDescriptor();
3341
3342       Location inferLocElement;
3343       if (curDesc == null) {
3344         // in this case, we have a newly generated location.
3345         inferLocElement = new Location(enclosingDesc, cur.getLocIdentifier());
3346       } else {
3347         String fieldLocSymbol =
3348             getLocationInfo(enclosingDesc).getInferLocation(curDesc).get(0).getLocIdentifier();
3349         inferLocElement = new Location(enclosingDesc, fieldLocSymbol);
3350         inferLocElement.setLocDescriptor(curDesc);
3351       }
3352
3353       inferLoc.addLocation(inferLocElement);
3354
3355     }
3356
3357     assert (inferLoc.get(0).getLocDescriptor().getSymbol() == inferLoc.get(0).getLocIdentifier());
3358     return inferLoc;
3359   }
3360
3361   public LocationInfo getLocationInfo(Descriptor d) {
3362     if (d instanceof MethodDescriptor) {
3363       return getMethodLocationInfo((MethodDescriptor) d);
3364     } else {
3365       return getFieldLocationInfo((ClassDescriptor) d);
3366     }
3367   }
3368
3369   private MethodLocationInfo getMethodLocationInfo(MethodDescriptor md) {
3370
3371     if (!mapMethodDescToMethodLocationInfo.containsKey(md)) {
3372       mapMethodDescToMethodLocationInfo.put(md, new MethodLocationInfo(md));
3373     }
3374
3375     return mapMethodDescToMethodLocationInfo.get(md);
3376
3377   }
3378
3379   private LocationInfo getFieldLocationInfo(ClassDescriptor cd) {
3380
3381     if (!mapClassToLocationInfo.containsKey(cd)) {
3382       mapClassToLocationInfo.put(cd, new LocationInfo(cd));
3383     }
3384
3385     return mapClassToLocationInfo.get(cd);
3386
3387   }
3388
3389   private void addPrefixMapping(Map<NTuple<Location>, Set<NTuple<Location>>> map,
3390       NTuple<Location> prefix, NTuple<Location> element) {
3391
3392     if (!map.containsKey(prefix)) {
3393       map.put(prefix, new HashSet<NTuple<Location>>());
3394     }
3395     map.get(prefix).add(element);
3396   }
3397
3398   private boolean containsNonPrimitiveElement(Set<Descriptor> descSet) {
3399     for (Iterator iterator = descSet.iterator(); iterator.hasNext();) {
3400       Descriptor desc = (Descriptor) iterator.next();
3401
3402       if (desc.equals(LocationInference.GLOBALDESC)) {
3403         return true;
3404       } else if (desc instanceof VarDescriptor) {
3405         if (!((VarDescriptor) desc).getType().isPrimitive()) {
3406           return true;
3407         }
3408       } else if (desc instanceof FieldDescriptor) {
3409         if (!((FieldDescriptor) desc).getType().isPrimitive()) {
3410           return true;
3411         }
3412       }
3413
3414     }
3415     return false;
3416   }
3417
3418   private SSJavaLattice<String> getLattice(Descriptor d) {
3419     if (d instanceof MethodDescriptor) {
3420       return getMethodLattice((MethodDescriptor) d);
3421     } else {
3422       return getFieldLattice((ClassDescriptor) d);
3423     }
3424   }
3425
3426   private SSJavaLattice<String> getMethodLattice(MethodDescriptor md) {
3427     if (!md2lattice.containsKey(md)) {
3428       md2lattice.put(md, new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM));
3429     }
3430     return md2lattice.get(md);
3431   }
3432
3433   private void setMethodLattice(MethodDescriptor md, SSJavaLattice<String> lattice) {
3434     md2lattice.put(md, lattice);
3435   }
3436
3437   private void extractFlowsBetweenFields(ClassDescriptor cd, FlowNode srcNode, FlowNode dstNode,
3438       int idx) {
3439
3440     NTuple<Descriptor> srcCurTuple = srcNode.getCurrentDescTuple();
3441     NTuple<Descriptor> dstCurTuple = dstNode.getCurrentDescTuple();
3442
3443     if (srcCurTuple.get(idx).equals(dstCurTuple.get(idx)) && srcCurTuple.size() > (idx + 1)
3444         && dstCurTuple.size() > (idx + 1)) {
3445       // value flow between fields: we don't need to add a binary relation
3446       // for this case
3447
3448       Descriptor desc = srcCurTuple.get(idx);
3449       ClassDescriptor classDesc;
3450
3451       if (idx == 0) {
3452         classDesc = ((VarDescriptor) desc).getType().getClassDesc();
3453       } else {
3454         if (desc instanceof FieldDescriptor) {
3455           classDesc = ((FieldDescriptor) desc).getType().getClassDesc();
3456         } else {
3457           // this case is that the local variable has a composite location assignment
3458           // the following element after the composite location to the local variable
3459           // has the enclosing descriptor of the local variable
3460           Descriptor localDesc = srcNode.getDescTuple().get(0);
3461           classDesc = ((VarDescriptor) localDesc).getType().getClassDesc();
3462         }
3463       }
3464       extractFlowsBetweenFields(classDesc, srcNode, dstNode, idx + 1);
3465
3466     } else {
3467
3468       Descriptor srcFieldDesc = srcCurTuple.get(idx);
3469       Descriptor dstFieldDesc = dstCurTuple.get(idx);
3470
3471       // add a new edge
3472       getHierarchyGraph(cd).addEdge(srcFieldDesc, dstFieldDesc);
3473
3474     }
3475
3476   }
3477
3478   public SSJavaLattice<String> getFieldLattice(ClassDescriptor cd) {
3479     if (!cd2lattice.containsKey(cd)) {
3480       cd2lattice.put(cd, new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM));
3481     }
3482     return cd2lattice.get(cd);
3483   }
3484
3485   public LinkedList<MethodDescriptor> computeMethodList() {
3486
3487     Set<MethodDescriptor> toSort = new HashSet<MethodDescriptor>();
3488
3489     setupToAnalyze();
3490
3491     Set<MethodDescriptor> visited = new HashSet<MethodDescriptor>();
3492     Set<MethodDescriptor> reachableCallee = new HashSet<MethodDescriptor>();
3493
3494     while (!toAnalyzeIsEmpty()) {
3495       ClassDescriptor cd = toAnalyzeNext();
3496
3497       setupToAnalazeMethod(cd);
3498       temp_toanalyzeMethodList.removeAll(visited);
3499
3500       while (!toAnalyzeMethodIsEmpty()) {
3501         MethodDescriptor md = toAnalyzeMethodNext();
3502         if ((!visited.contains(md))
3503             && (ssjava.needTobeAnnotated(md) || reachableCallee.contains(md))) {
3504
3505           // creates a mapping from a method descriptor to virtual methods
3506           Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
3507           if (md.isStatic()) {
3508             setPossibleCallees.add(md);
3509           } else {
3510             setPossibleCallees.addAll(ssjava.getCallGraph().getMethods(md));
3511           }
3512
3513           Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getCalleeSet(md);
3514           Set<MethodDescriptor> needToAnalyzeCalleeSet = new HashSet<MethodDescriptor>();
3515
3516           for (Iterator iterator = calleeSet.iterator(); iterator.hasNext();) {
3517             MethodDescriptor calleemd = (MethodDescriptor) iterator.next();
3518             if ((!ssjava.isTrustMethod(calleemd))
3519                 && (!ssjava.isSSJavaUtil(calleemd.getClassDesc()))) {
3520               if (!visited.contains(calleemd)) {
3521                 temp_toanalyzeMethodList.add(calleemd);
3522               }
3523               reachableCallee.add(calleemd);
3524               needToAnalyzeCalleeSet.add(calleemd);
3525             }
3526           }
3527
3528           mapMethodToCalleeSet.put(md, needToAnalyzeCalleeSet);
3529
3530           visited.add(md);
3531
3532           toSort.add(md);
3533         }
3534       }
3535     }
3536
3537     return ssjava.topologicalSort(toSort);
3538
3539   }
3540
3541   public boolean isTransitivelyCalledFrom(MethodDescriptor callee, MethodDescriptor caller) {
3542     // if the callee is transitively invoked from the caller
3543     // return true;
3544
3545     int callerIdx = toanalyze_methodDescList.indexOf(caller);
3546     int calleeIdx = toanalyze_methodDescList.indexOf(callee);
3547
3548     if (callerIdx < calleeIdx) {
3549       return true;
3550     }
3551
3552     return false;
3553
3554   }
3555
3556   public void constructFlowGraph() {
3557
3558     System.out.println("");
3559     toanalyze_methodDescList = computeMethodList();
3560
3561     LinkedList<MethodDescriptor> methodDescList =
3562         (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
3563
3564     System.out.println("@@@methodDescList=" + methodDescList);
3565     // System.exit(0);
3566
3567     while (!methodDescList.isEmpty()) {
3568       MethodDescriptor md = methodDescList.removeLast();
3569       if (state.SSJAVADEBUG) {
3570         System.out.println();
3571         System.out.println("SSJAVA: Constructing a flow graph: " + md);
3572
3573         // creates a mapping from a parameter descriptor to its index
3574         Map<Descriptor, Integer> mapParamDescToIdx = new HashMap<Descriptor, Integer>();
3575         int offset = 0;
3576         if (!md.isStatic()) {
3577           offset = 1;
3578           mapParamDescToIdx.put(md.getThis(), 0);
3579         }
3580
3581         for (int i = 0; i < md.numParameters(); i++) {
3582           Descriptor paramDesc = (Descriptor) md.getParameter(i);
3583           mapParamDescToIdx.put(paramDesc, new Integer(i + offset));
3584         }
3585
3586         FlowGraph fg = new FlowGraph(md, mapParamDescToIdx);
3587         mapMethodDescriptorToFlowGraph.put(md, fg);
3588
3589         analyzeMethodBody(md.getClassDesc(), md);
3590
3591         // System.out.println("##constructSubGlobalFlowGraph");
3592         // GlobalFlowGraph subGlobalFlowGraph = constructSubGlobalFlowGraph(fg);
3593         // mapMethodDescriptorToSubGlobalFlowGraph.put(md, subGlobalFlowGraph);
3594         //
3595         // // TODO
3596         // System.out.println("##addValueFlowsFromCalleeSubGlobalFlowGraph");
3597         // addValueFlowsFromCalleeSubGlobalFlowGraph(md, subGlobalFlowGraph);
3598         // subGlobalFlowGraph.writeGraph("_SUBGLOBAL");
3599         //
3600         // propagateFlowsFromCalleesWithNoCompositeLocation(md);
3601
3602       }
3603     }
3604     // _debug_printGraph();
3605
3606     methodDescList = (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
3607
3608     while (!methodDescList.isEmpty()) {
3609       MethodDescriptor md = methodDescList.removeLast();
3610       if (state.SSJAVADEBUG) {
3611         System.out.println();
3612         System.out.println("SSJAVA: Constructing a flow graph2: " + md);
3613
3614         System.out.println("##constructSubGlobalFlowGraph");
3615         GlobalFlowGraph subGlobalFlowGraph = constructSubGlobalFlowGraph(getFlowGraph(md));
3616         mapMethodDescriptorToSubGlobalFlowGraph.put(md, subGlobalFlowGraph);
3617
3618         // TODO
3619         System.out.println("##addValueFlowsFromCalleeSubGlobalFlowGraph");
3620         addValueFlowsFromCalleeSubGlobalFlowGraph(md, subGlobalFlowGraph);
3621         subGlobalFlowGraph.writeGraph("_SUBGLOBAL");
3622
3623         propagateFlowsFromCalleesWithNoCompositeLocation(md);
3624
3625       }
3626     }
3627
3628   }
3629
3630   private Set<MethodInvokeNode> getMethodInvokeNodeSet(MethodDescriptor md) {
3631     if (!mapMethodDescriptorToMethodInvokeNodeSet.containsKey(md)) {
3632       mapMethodDescriptorToMethodInvokeNodeSet.put(md, new HashSet<MethodInvokeNode>());
3633     }
3634     return mapMethodDescriptorToMethodInvokeNodeSet.get(md);
3635   }
3636
3637   private void constructSubGlobalFlowGraph(MethodDescriptor md) {
3638
3639     FlowGraph flowGraph = getFlowGraph(md);
3640
3641     Set<MethodInvokeNode> setMethodInvokeNode = getMethodInvokeNodeSet(md);
3642
3643     for (Iterator<MethodInvokeNode> iter = setMethodInvokeNode.iterator(); iter.hasNext();) {
3644       MethodInvokeNode min = iter.next();
3645       propagateFlowsFromMethodInvokeNode(md, min);
3646     }
3647
3648   }
3649
3650   private void propagateFlowsFromMethodInvokeNode(MethodDescriptor mdCaller, MethodInvokeNode min) {
3651     // the transformation for a call site propagates flows through parameters
3652     // if the method is virtual, it also grab all relations from any possible
3653     // callees
3654
3655     MethodDescriptor mdCallee = min.getMethod();
3656     Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
3657     if (mdCallee.isStatic()) {
3658       setPossibleCallees.add(mdCallee);
3659     } else {
3660       Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getMethods(mdCallee);
3661       // removes method descriptors that are not invoked by the caller
3662       calleeSet.retainAll(mapMethodToCalleeSet.get(mdCaller));
3663       setPossibleCallees.addAll(calleeSet);
3664     }
3665
3666     for (Iterator iterator2 = setPossibleCallees.iterator(); iterator2.hasNext();) {
3667       MethodDescriptor possibleMdCallee = (MethodDescriptor) iterator2.next();
3668       contributeCalleeFlows(min, mdCaller, possibleMdCallee);
3669     }
3670
3671   }
3672
3673   private void assignCompositeLocation(MethodDescriptor md) {
3674
3675     FlowGraph flowGraph = getFlowGraph(md);
3676
3677     Set<FlowNode> nodeSet = flowGraph.getNodeSet();
3678
3679     next: for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
3680       FlowNode flowNode = (FlowNode) iterator.next();
3681
3682       // assign a composite location only to the local variable
3683       if (flowNode.getCurrentDescTuple().size() == 1) {
3684
3685         List<NTuple<Descriptor>> prefixList = calculatePrefixList(flowGraph, flowNode);
3686         Set<FlowNode> reachSet = flowGraph.getReachFlowNodeSetFrom(flowNode);
3687
3688         for (int i = 0; i < prefixList.size(); i++) {
3689           NTuple<Descriptor> curPrefix = prefixList.get(i);
3690           Set<NTuple<Descriptor>> reachableCommonPrefixSet = new HashSet<NTuple<Descriptor>>();
3691
3692           for (Iterator iterator2 = reachSet.iterator(); iterator2.hasNext();) {
3693             FlowNode reachNode = (FlowNode) iterator2.next();
3694             if (reachNode.getCurrentDescTuple().startsWith(curPrefix)) {
3695               reachableCommonPrefixSet.add(reachNode.getCurrentDescTuple());
3696             }
3697           }
3698
3699           if (!reachableCommonPrefixSet.isEmpty()) {
3700             System.out.println("NEED TO ASSIGN COMP LOC TO " + flowNode + " with prefix="
3701                 + curPrefix);
3702             CompositeLocation newCompLoc = generateCompositeLocation(md, curPrefix);
3703             flowNode.setCompositeLocation(newCompLoc);
3704             continue next;
3705           }
3706
3707         }
3708       }
3709
3710     }
3711
3712   }
3713
3714   private void propagateFlowsFromCalleesWithNoCompositeLocation(MethodDescriptor mdCaller) {
3715
3716     // the transformation for a call site propagates flows through parameters
3717     // if the method is virtual, it also grab all relations from any possible
3718     // callees
3719
3720     Set<MethodInvokeNode> setMethodInvokeNode =
3721         mapMethodDescriptorToMethodInvokeNodeSet.get(mdCaller);
3722
3723     if (setMethodInvokeNode != null) {
3724
3725       for (Iterator iterator = setMethodInvokeNode.iterator(); iterator.hasNext();) {
3726         MethodInvokeNode min = (MethodInvokeNode) iterator.next();
3727         MethodDescriptor mdCallee = min.getMethod();
3728         Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
3729         if (mdCallee.isStatic()) {
3730           setPossibleCallees.add(mdCallee);
3731         } else {
3732           Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getMethods(mdCallee);
3733           // removes method descriptors that are not invoked by the caller
3734           calleeSet.retainAll(mapMethodToCalleeSet.get(mdCaller));
3735           setPossibleCallees.addAll(calleeSet);
3736         }
3737
3738         for (Iterator iterator2 = setPossibleCallees.iterator(); iterator2.hasNext();) {
3739           MethodDescriptor possibleMdCallee = (MethodDescriptor) iterator2.next();
3740           propagateFlowsToCallerWithNoCompositeLocation(min, mdCaller, possibleMdCallee);
3741         }
3742
3743       }
3744     }
3745
3746   }
3747
3748   private void propagateFlowsFromCallees(MethodDescriptor mdCaller) {
3749
3750     // the transformation for a call site propagates flows through parameters
3751     // if the method is virtual, it also grab all relations from any possible
3752     // callees
3753
3754     Set<MethodInvokeNode> setMethodInvokeNode =
3755         mapMethodDescriptorToMethodInvokeNodeSet.get(mdCaller);
3756
3757     if (setMethodInvokeNode != null) {
3758
3759       for (Iterator iterator = setMethodInvokeNode.iterator(); iterator.hasNext();) {
3760         MethodInvokeNode min = (MethodInvokeNode) iterator.next();
3761         MethodDescriptor mdCallee = min.getMethod();
3762         Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
3763         if (mdCallee.isStatic()) {
3764           setPossibleCallees.add(mdCallee);
3765         } else {
3766           Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getMethods(mdCallee);
3767           // removes method descriptors that are not invoked by the caller
3768           calleeSet.retainAll(mapMethodToCalleeSet.get(mdCaller));
3769           setPossibleCallees.addAll(calleeSet);
3770         }
3771
3772         for (Iterator iterator2 = setPossibleCallees.iterator(); iterator2.hasNext();) {
3773           MethodDescriptor possibleMdCallee = (MethodDescriptor) iterator2.next();
3774           propagateFlowsToCaller(min, mdCaller, possibleMdCallee);
3775         }
3776
3777       }
3778     }
3779
3780   }
3781
3782   private void analyzeMethodBody(ClassDescriptor cd, MethodDescriptor md) {
3783     BlockNode bn = state.getMethodBody(md);
3784     NodeTupleSet implicitFlowTupleSet = new NodeTupleSet();
3785     analyzeFlowBlockNode(md, md.getParameterTable(), bn, implicitFlowTupleSet);
3786   }
3787
3788   private void analyzeFlowBlockNode(MethodDescriptor md, SymbolTable nametable, BlockNode bn,
3789       NodeTupleSet implicitFlowTupleSet) {
3790
3791     bn.getVarTable().setParent(nametable);
3792     for (int i = 0; i < bn.size(); i++) {
3793       BlockStatementNode bsn = bn.get(i);
3794       analyzeBlockStatementNode(md, bn.getVarTable(), bsn, implicitFlowTupleSet);
3795     }
3796
3797   }
3798
3799   private void analyzeBlockStatementNode(MethodDescriptor md, SymbolTable nametable,
3800       BlockStatementNode bsn, NodeTupleSet implicitFlowTupleSet) {
3801
3802     switch (bsn.kind()) {
3803     case Kind.BlockExpressionNode:
3804       analyzeBlockExpressionNode(md, nametable, (BlockExpressionNode) bsn, implicitFlowTupleSet);
3805       break;
3806
3807     case Kind.DeclarationNode:
3808       analyzeFlowDeclarationNode(md, nametable, (DeclarationNode) bsn, implicitFlowTupleSet);
3809       break;
3810
3811     case Kind.IfStatementNode:
3812       analyzeFlowIfStatementNode(md, nametable, (IfStatementNode) bsn, implicitFlowTupleSet);
3813       break;
3814
3815     case Kind.LoopNode:
3816       analyzeFlowLoopNode(md, nametable, (LoopNode) bsn, implicitFlowTupleSet);
3817       break;
3818
3819     case Kind.ReturnNode:
3820       analyzeFlowReturnNode(md, nametable, (ReturnNode) bsn, implicitFlowTupleSet);
3821       break;
3822
3823     case Kind.SubBlockNode:
3824       analyzeFlowSubBlockNode(md, nametable, (SubBlockNode) bsn, implicitFlowTupleSet);
3825       break;
3826
3827     case Kind.ContinueBreakNode:
3828       break;
3829
3830     case Kind.SwitchStatementNode:
3831       analyzeSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn, implicitFlowTupleSet);
3832       break;
3833
3834     }
3835
3836   }
3837
3838   private void analyzeSwitchBlockNode(MethodDescriptor md, SymbolTable nametable,
3839       SwitchBlockNode sbn, NodeTupleSet implicitFlowTupleSet) {
3840
3841     analyzeFlowBlockNode(md, nametable, sbn.getSwitchBlockStatement(), implicitFlowTupleSet);
3842
3843   }
3844
3845   private void analyzeSwitchStatementNode(MethodDescriptor md, SymbolTable nametable,
3846       SwitchStatementNode ssn, NodeTupleSet implicitFlowTupleSet) {
3847
3848     NodeTupleSet condTupleNode = new NodeTupleSet();
3849     analyzeFlowExpressionNode(md, nametable, ssn.getCondition(), condTupleNode, null,
3850         implicitFlowTupleSet, false);
3851
3852     NodeTupleSet newImplicitTupleSet = new NodeTupleSet();
3853
3854     newImplicitTupleSet.addTupleSet(implicitFlowTupleSet);
3855     newImplicitTupleSet.addTupleSet(condTupleNode);
3856
3857     if (newImplicitTupleSet.size() > 1) {
3858       // need to create an intermediate node for the GLB of conditional
3859       // locations & implicit flows
3860       NTuple<Descriptor> interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
3861       for (Iterator<NTuple<Descriptor>> idxIter = newImplicitTupleSet.iterator(); idxIter.hasNext();) {
3862         NTuple<Descriptor> tuple = idxIter.next();
3863         addFlowGraphEdge(md, tuple, interTuple);
3864       }
3865       newImplicitTupleSet.clear();
3866       newImplicitTupleSet.addTuple(interTuple);
3867     }
3868
3869     BlockNode sbn = ssn.getSwitchBody();
3870     for (int i = 0; i < sbn.size(); i++) {
3871       analyzeSwitchBlockNode(md, nametable, (SwitchBlockNode) sbn.get(i), newImplicitTupleSet);
3872     }
3873
3874   }
3875
3876   private void analyzeFlowSubBlockNode(MethodDescriptor md, SymbolTable nametable,
3877       SubBlockNode sbn, NodeTupleSet implicitFlowTupleSet) {
3878     analyzeFlowBlockNode(md, nametable, sbn.getBlockNode(), implicitFlowTupleSet);
3879   }
3880
3881   private void analyzeFlowReturnNode(MethodDescriptor md, SymbolTable nametable, ReturnNode rn,
3882       NodeTupleSet implicitFlowTupleSet) {
3883
3884     ExpressionNode returnExp = rn.getReturnExpression();
3885
3886     if (returnExp != null) {
3887       NodeTupleSet nodeSet = new NodeTupleSet();
3888       // if a return expression returns a literal value, nodeSet is empty
3889       analyzeFlowExpressionNode(md, nametable, returnExp, nodeSet, false);
3890       FlowGraph fg = getFlowGraph(md);
3891
3892       // if (implicitFlowTupleSet.size() == 1
3893       // &&
3894       // fg.getFlowNode(implicitFlowTupleSet.iterator().next()).isIntermediate())
3895       // {
3896       //
3897       // // since there is already an intermediate node for the GLB of implicit
3898       // flows
3899       // // we don't need to create another intermediate node.
3900       // // just re-use the intermediate node for implicit flows.
3901       //
3902       // FlowNode meetNode =
3903       // fg.getFlowNode(implicitFlowTupleSet.iterator().next());
3904       //
3905       // for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
3906       // NTuple<Descriptor> returnNodeTuple = (NTuple<Descriptor>)
3907       // iterator.next();
3908       // fg.addValueFlowEdge(returnNodeTuple, meetNode.getDescTuple());
3909       // }
3910       //
3911       // }
3912
3913       NodeTupleSet currentFlowTupleSet = new NodeTupleSet();
3914
3915       // add tuples from return node
3916       currentFlowTupleSet.addTupleSet(nodeSet);
3917
3918       // add tuples corresponding to the current implicit flows
3919       currentFlowTupleSet.addTupleSet(implicitFlowTupleSet);
3920
3921       if (currentFlowTupleSet.size() > 1) {
3922         FlowNode meetNode = fg.createIntermediateNode();
3923         for (Iterator iterator = currentFlowTupleSet.iterator(); iterator.hasNext();) {
3924           NTuple<Descriptor> currentFlowTuple = (NTuple<Descriptor>) iterator.next();
3925           fg.addValueFlowEdge(currentFlowTuple, meetNode.getDescTuple());
3926         }
3927         fg.addReturnFlowNode(meetNode.getDescTuple());
3928       } else if (currentFlowTupleSet.size() == 1) {
3929         NTuple<Descriptor> tuple = currentFlowTupleSet.iterator().next();
3930         fg.addReturnFlowNode(tuple);
3931       }
3932
3933     }
3934
3935   }
3936
3937   private void analyzeFlowLoopNode(MethodDescriptor md, SymbolTable nametable, LoopNode ln,
3938       NodeTupleSet implicitFlowTupleSet) {
3939
3940     if (ln.getType() == LoopNode.WHILELOOP || ln.getType() == LoopNode.DOWHILELOOP) {
3941
3942       NodeTupleSet condTupleNode = new NodeTupleSet();
3943       analyzeFlowExpressionNode(md, nametable, ln.getCondition(), condTupleNode, null,
3944           implicitFlowTupleSet, false);
3945
3946       NodeTupleSet newImplicitTupleSet = new NodeTupleSet();
3947
3948       newImplicitTupleSet.addTupleSet(implicitFlowTupleSet);
3949       newImplicitTupleSet.addTupleSet(condTupleNode);
3950
3951       if (newImplicitTupleSet.size() > 1) {
3952         // need to create an intermediate node for the GLB of conditional
3953         // locations & implicit flows
3954         NTuple<Descriptor> interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
3955         for (Iterator<NTuple<Descriptor>> idxIter = newImplicitTupleSet.iterator(); idxIter
3956             .hasNext();) {
3957           NTuple<Descriptor> tuple = idxIter.next();
3958           addFlowGraphEdge(md, tuple, interTuple);
3959         }
3960         newImplicitTupleSet.clear();
3961         newImplicitTupleSet.addTuple(interTuple);
3962
3963       }
3964
3965       // ///////////
3966       // System.out.println("condTupleNode="+condTupleNode);
3967       // NTuple<Descriptor> interTuple =
3968       // getFlowGraph(md).createIntermediateNode().getDescTuple();
3969       //
3970       // for (Iterator<NTuple<Descriptor>> idxIter = condTupleNode.iterator();
3971       // idxIter.hasNext();) {
3972       // NTuple<Descriptor> tuple = idxIter.next();
3973       // addFlowGraphEdge(md, tuple, interTuple);
3974       // }
3975
3976       // for (Iterator<NTuple<Descriptor>> idxIter =
3977       // implicitFlowTupleSet.iterator(); idxIter
3978       // .hasNext();) {
3979       // NTuple<Descriptor> tuple = idxIter.next();
3980       // addFlowGraphEdge(md, tuple, interTuple);
3981       // }
3982
3983       // NodeTupleSet newImplicitSet = new NodeTupleSet();
3984       // newImplicitSet.addTuple(interTuple);
3985       analyzeFlowBlockNode(md, nametable, ln.getBody(), newImplicitTupleSet);
3986       // ///////////
3987
3988       // condTupleNode.addTupleSet(implicitFlowTupleSet);
3989
3990       // add edges from condNodeTupleSet to all nodes of conditional nodes
3991       // analyzeFlowBlockNode(md, nametable, ln.getBody(), condTupleNode);
3992
3993     } else {
3994       // check 'for loop' case
3995       BlockNode bn = ln.getInitializer();
3996       bn.getVarTable().setParent(nametable);
3997       for (int i = 0; i < bn.size(); i++) {
3998         BlockStatementNode bsn = bn.get(i);
3999         analyzeBlockStatementNode(md, bn.getVarTable(), bsn, implicitFlowTupleSet);
4000       }
4001
4002       NodeTupleSet condTupleNode = new NodeTupleSet();
4003       analyzeFlowExpressionNode(md, bn.getVarTable(), ln.getCondition(), condTupleNode, null,
4004           implicitFlowTupleSet, false);
4005
4006       // ///////////
4007       NTuple<Descriptor> interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
4008
4009       for (Iterator<NTuple<Descriptor>> idxIter = condTupleNode.iterator(); idxIter.hasNext();) {
4010         NTuple<Descriptor> tuple = idxIter.next();
4011         addFlowGraphEdge(md, tuple, interTuple);
4012       }
4013
4014       for (Iterator<NTuple<Descriptor>> idxIter = implicitFlowTupleSet.iterator(); idxIter
4015           .hasNext();) {
4016         NTuple<Descriptor> tuple = idxIter.next();
4017         addFlowGraphEdge(md, tuple, interTuple);
4018       }
4019
4020       NodeTupleSet newImplicitSet = new NodeTupleSet();
4021       newImplicitSet.addTuple(interTuple);
4022       analyzeFlowBlockNode(md, bn.getVarTable(), ln.getUpdate(), newImplicitSet);
4023       analyzeFlowBlockNode(md, bn.getVarTable(), ln.getBody(), newImplicitSet);
4024       // ///////////
4025
4026       // condTupleNode.addTupleSet(implicitFlowTupleSet);
4027       //
4028       // analyzeFlowBlockNode(md, bn.getVarTable(), ln.getUpdate(),
4029       // condTupleNode);
4030       // analyzeFlowBlockNode(md, bn.getVarTable(), ln.getBody(),
4031       // condTupleNode);
4032
4033     }
4034
4035   }
4036
4037   private void analyzeFlowIfStatementNode(MethodDescriptor md, SymbolTable nametable,
4038       IfStatementNode isn, NodeTupleSet implicitFlowTupleSet) {
4039
4040     System.out.println("analyzeFlowIfStatementNode=" + isn.printNode(0));
4041
4042     NodeTupleSet condTupleNode = new NodeTupleSet();
4043     analyzeFlowExpressionNode(md, nametable, isn.getCondition(), condTupleNode, null,
4044         implicitFlowTupleSet, false);
4045
4046     NodeTupleSet newImplicitTupleSet = new NodeTupleSet();
4047
4048     newImplicitTupleSet.addTupleSet(implicitFlowTupleSet);
4049     newImplicitTupleSet.addTupleSet(condTupleNode);
4050
4051     System.out.println("condTupleNode=" + condTupleNode);
4052     System.out.println("implicitFlowTupleSet=" + implicitFlowTupleSet);
4053     System.out.println("newImplicitTupleSet=" + newImplicitTupleSet);
4054
4055     if (newImplicitTupleSet.size() > 1) {
4056
4057       // need to create an intermediate node for the GLB of conditional locations & implicit flows
4058       NTuple<Descriptor> interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
4059       for (Iterator<NTuple<Descriptor>> idxIter = newImplicitTupleSet.iterator(); idxIter.hasNext();) {
4060         NTuple<Descriptor> tuple = idxIter.next();
4061         addFlowGraphEdge(md, tuple, interTuple);
4062       }
4063       newImplicitTupleSet.clear();
4064       newImplicitTupleSet.addTuple(interTuple);
4065     }
4066
4067     analyzeFlowBlockNode(md, nametable, isn.getTrueBlock(), newImplicitTupleSet);
4068
4069     if (isn.getFalseBlock() != null) {
4070       analyzeFlowBlockNode(md, nametable, isn.getFalseBlock(), newImplicitTupleSet);
4071     }
4072
4073   }
4074
4075   private void analyzeFlowDeclarationNode(MethodDescriptor md, SymbolTable nametable,
4076       DeclarationNode dn, NodeTupleSet implicitFlowTupleSet) {
4077
4078     VarDescriptor vd = dn.getVarDescriptor();
4079     mapDescToDefinitionLine.put(vd, dn.getNumLine());
4080     NTuple<Descriptor> tupleLHS = new NTuple<Descriptor>();
4081     tupleLHS.add(vd);
4082     FlowNode fn = getFlowGraph(md).createNewFlowNode(tupleLHS);
4083     fn.setDeclarationNode();
4084
4085     if (dn.getExpression() != null) {
4086
4087       NodeTupleSet nodeSetRHS = new NodeTupleSet();
4088       analyzeFlowExpressionNode(md, nametable, dn.getExpression(), nodeSetRHS, null,
4089           implicitFlowTupleSet, false);
4090
4091       // creates edges from RHS to LHS
4092       NTuple<Descriptor> interTuple = null;
4093       if (nodeSetRHS.size() > 1) {
4094         interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
4095       }
4096
4097       for (Iterator<NTuple<Descriptor>> iter = nodeSetRHS.iterator(); iter.hasNext();) {
4098         NTuple<Descriptor> fromTuple = iter.next();
4099         addFlowGraphEdge(md, fromTuple, interTuple, tupleLHS);
4100       }
4101
4102       // creates edges from implicitFlowTupleSet to LHS
4103       for (Iterator<NTuple<Descriptor>> iter = implicitFlowTupleSet.iterator(); iter.hasNext();) {
4104         NTuple<Descriptor> implicitTuple = iter.next();
4105         addFlowGraphEdge(md, implicitTuple, tupleLHS);
4106       }
4107
4108     }
4109
4110   }
4111
4112   private void analyzeBlockExpressionNode(MethodDescriptor md, SymbolTable nametable,
4113       BlockExpressionNode ben, NodeTupleSet implicitFlowTupleSet) {
4114     analyzeFlowExpressionNode(md, nametable, ben.getExpression(), null, null, implicitFlowTupleSet,
4115         false);
4116   }
4117
4118   private NTuple<Descriptor> analyzeFlowExpressionNode(MethodDescriptor md, SymbolTable nametable,
4119       ExpressionNode en, NodeTupleSet nodeSet, boolean isLHS) {
4120     return analyzeFlowExpressionNode(md, nametable, en, nodeSet, null, new NodeTupleSet(), isLHS);
4121   }
4122
4123   private NTuple<Descriptor> analyzeFlowExpressionNode(MethodDescriptor md, SymbolTable nametable,
4124       ExpressionNode en, NodeTupleSet nodeSet, NTuple<Descriptor> base,
4125       NodeTupleSet implicitFlowTupleSet, boolean isLHS) {
4126
4127     // note that expression node can create more than one flow node
4128     // nodeSet contains of flow nodes
4129     // base is always assigned to null except the case of a name node!
4130
4131     NTuple<Descriptor> flowTuple;
4132
4133     switch (en.kind()) {
4134
4135     case Kind.AssignmentNode:
4136       analyzeFlowAssignmentNode(md, nametable, (AssignmentNode) en, nodeSet, base,
4137           implicitFlowTupleSet);
4138       break;
4139
4140     case Kind.FieldAccessNode:
4141       flowTuple =
4142           analyzeFlowFieldAccessNode(md, nametable, (FieldAccessNode) en, nodeSet, base,
4143               implicitFlowTupleSet, isLHS);
4144       if (flowTuple != null) {
4145         nodeSet.addTuple(flowTuple);
4146       }
4147       return flowTuple;
4148
4149     case Kind.NameNode:
4150       NodeTupleSet nameNodeSet = new NodeTupleSet();
4151       flowTuple =
4152           analyzeFlowNameNode(md, nametable, (NameNode) en, nameNodeSet, base, implicitFlowTupleSet);
4153       if (flowTuple != null) {
4154         nodeSet.addTuple(flowTuple);
4155       }
4156       return flowTuple;
4157
4158     case Kind.OpNode:
4159       analyzeFlowOpNode(md, nametable, (OpNode) en, nodeSet, implicitFlowTupleSet);
4160       break;
4161
4162     case Kind.CreateObjectNode:
4163       analyzeCreateObjectNode(md, nametable, (CreateObjectNode) en);
4164       break;
4165
4166     case Kind.ArrayAccessNode:
4167       analyzeFlowArrayAccessNode(md, nametable, (ArrayAccessNode) en, nodeSet, isLHS);
4168       break;
4169
4170     case Kind.LiteralNode:
4171       analyzeLiteralNode(md, nametable, (LiteralNode) en);
4172       break;
4173
4174     case Kind.MethodInvokeNode:
4175       analyzeFlowMethodInvokeNode(md, nametable, (MethodInvokeNode) en, nodeSet,
4176           implicitFlowTupleSet);
4177       break;
4178
4179     case Kind.TertiaryNode:
4180       analyzeFlowTertiaryNode(md, nametable, (TertiaryNode) en, nodeSet, implicitFlowTupleSet);
4181       break;
4182
4183     case Kind.CastNode:
4184       analyzeFlowCastNode(md, nametable, (CastNode) en, nodeSet, base, implicitFlowTupleSet);
4185       break;
4186     // case Kind.InstanceOfNode:
4187     // checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
4188     // return null;
4189
4190     // case Kind.ArrayInitializerNode:
4191     // checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en,
4192     // td);
4193     // return null;
4194
4195     // case Kind.ClassTypeNode:
4196     // checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
4197     // return null;
4198
4199     // case Kind.OffsetNode:
4200     // checkOffsetNode(md, nametable, (OffsetNode)en, td);
4201     // return null;
4202
4203     }
4204     return null;
4205
4206   }
4207
4208   private void analyzeFlowCastNode(MethodDescriptor md, SymbolTable nametable, CastNode cn,
4209       NodeTupleSet nodeSet, NTuple<Descriptor> base, NodeTupleSet implicitFlowTupleSet) {
4210
4211     analyzeFlowExpressionNode(md, nametable, cn.getExpression(), nodeSet, base,
4212         implicitFlowTupleSet, false);
4213
4214   }
4215
4216   private void analyzeFlowTertiaryNode(MethodDescriptor md, SymbolTable nametable, TertiaryNode tn,
4217       NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
4218
4219     NodeTupleSet tertiaryTupleNode = new NodeTupleSet();
4220     analyzeFlowExpressionNode(md, nametable, tn.getCond(), tertiaryTupleNode, null,
4221         implicitFlowTupleSet, false);
4222
4223     // add edges from tertiaryTupleNode to all nodes of conditional nodes
4224     tertiaryTupleNode.addTupleSet(implicitFlowTupleSet);
4225     analyzeFlowExpressionNode(md, nametable, tn.getTrueExpr(), tertiaryTupleNode, null,
4226         implicitFlowTupleSet, false);
4227
4228     analyzeFlowExpressionNode(md, nametable, tn.getFalseExpr(), tertiaryTupleNode, null,
4229         implicitFlowTupleSet, false);
4230
4231     nodeSet.addTupleSet(tertiaryTupleNode);
4232
4233   }
4234
4235   private void addMapCallerMethodDescToMethodInvokeNodeSet(MethodDescriptor caller,
4236       MethodInvokeNode min) {
4237     Set<MethodInvokeNode> set = mapMethodDescriptorToMethodInvokeNodeSet.get(caller);
4238     if (set == null) {
4239       set = new HashSet<MethodInvokeNode>();
4240       mapMethodDescriptorToMethodInvokeNodeSet.put(caller, set);
4241     }
4242     set.add(min);
4243   }
4244
4245   private void addParamNodeFlowingToReturnValue(MethodDescriptor md, FlowNode fn) {
4246
4247     if (!mapMethodDescToParamNodeFlowsToReturnValue.containsKey(md)) {
4248       mapMethodDescToParamNodeFlowsToReturnValue.put(md, new HashSet<FlowNode>());
4249     }
4250     mapMethodDescToParamNodeFlowsToReturnValue.get(md).add(fn);
4251   }
4252
4253   private Set<FlowNode> getParamNodeFlowingToReturnValue(MethodDescriptor md) {
4254
4255     if (!mapMethodDescToParamNodeFlowsToReturnValue.containsKey(md)) {
4256       mapMethodDescToParamNodeFlowsToReturnValue.put(md, new HashSet<FlowNode>());
4257     }
4258
4259     return mapMethodDescToParamNodeFlowsToReturnValue.get(md);
4260   }
4261
4262   private void analyzeFlowMethodInvokeNode(MethodDescriptor md, SymbolTable nametable,
4263       MethodInvokeNode min, NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
4264
4265     System.out.println("analyzeFlowMethodInvokeNode=" + min.printNode(0));
4266
4267     mapMethodInvokeNodeToArgIdxMap.put(min, new HashMap<Integer, NTuple<Descriptor>>());
4268
4269     if (nodeSet == null) {
4270       nodeSet = new NodeTupleSet();
4271     }
4272
4273     MethodDescriptor calleeMethodDesc = min.getMethod();
4274
4275     NameDescriptor baseName = min.getBaseName();
4276     boolean isSystemout = false;
4277     if (baseName != null) {
4278       isSystemout = baseName.getSymbol().equals("System.out");
4279     }
4280
4281     if (!ssjava.isSSJavaUtil(calleeMethodDesc.getClassDesc())
4282         && !ssjava.isTrustMethod(calleeMethodDesc) && !isSystemout) {
4283
4284       addMapCallerMethodDescToMethodInvokeNodeSet(md, min);
4285
4286       FlowGraph calleeFlowGraph = getFlowGraph(calleeMethodDesc);
4287       Set<FlowNode> calleeReturnSet = calleeFlowGraph.getReturnNodeSet();
4288
4289       if (min.getExpression() != null) {
4290
4291         NodeTupleSet baseNodeSet = new NodeTupleSet();
4292         analyzeFlowExpressionNode(md, nametable, min.getExpression(), baseNodeSet, null,
4293             implicitFlowTupleSet, false);
4294
4295         assert (baseNodeSet.size() == 1);
4296         NTuple<Descriptor> baseTuple = baseNodeSet.iterator().next();
4297         mapMethodInvokeNodeToBaseTuple.put(min, baseTuple);
4298
4299         if (!min.getMethod().isStatic()) {
4300           addArgIdxMap(min, 0, baseTuple);
4301
4302           for (Iterator iterator = calleeReturnSet.iterator(); iterator.hasNext();) {
4303             FlowNode returnNode = (FlowNode) iterator.next();
4304             NTuple<Descriptor> returnDescTuple = returnNode.getDescTuple();
4305             if (returnDescTuple.startsWith(calleeMethodDesc.getThis())) {
4306               // the location type of the return value is started with 'this'
4307               // reference
4308               NTuple<Descriptor> inFlowTuple = new NTuple<Descriptor>(baseTuple.getList());
4309               inFlowTuple.addAll(returnDescTuple.subList(1, returnDescTuple.size()));
4310               nodeSet.addTuple(inFlowTuple);
4311             } else {
4312               // TODO
4313               Set<FlowNode> inFlowSet = calleeFlowGraph.getIncomingFlowNodeSet(returnNode);
4314               System.out.println("inFlowSet=" + inFlowSet + "   from retrunNode=" + returnNode);
4315               for (Iterator iterator2 = inFlowSet.iterator(); iterator2.hasNext();) {
4316                 FlowNode inFlowNode = (FlowNode) iterator2.next();
4317                 if (inFlowNode.getDescTuple().startsWith(calleeMethodDesc.getThis())) {
4318                   nodeSet.addTupleSet(baseNodeSet);
4319                 }
4320               }
4321             }
4322           }
4323         }
4324
4325       }
4326
4327       // analyze parameter flows
4328
4329       if (min.numArgs() > 0) {
4330
4331         int offset;
4332         if (min.getMethod().isStatic()) {
4333           offset = 0;
4334         } else {
4335           offset = 1;
4336         }
4337
4338         for (int i = 0; i < min.numArgs(); i++) {
4339           ExpressionNode en = min.getArg(i);
4340           int idx = i + offset;
4341           NodeTupleSet argTupleSet = new NodeTupleSet();
4342           analyzeFlowExpressionNode(md, nametable, en, argTupleSet, false);
4343           // if argument is liternal node, argTuple is set to NULL
4344
4345           NTuple<Descriptor> argTuple = new NTuple<Descriptor>();
4346           System.out.println("-argTupleSet=" + argTupleSet + "  from en=" + en.printNode(0));
4347           if (argTupleSet.size() > 1) {
4348             NTuple<Descriptor> interTuple =
4349                 getFlowGraph(md).createIntermediateNode().getDescTuple();
4350             for (Iterator<NTuple<Descriptor>> idxIter = argTupleSet.iterator(); idxIter.hasNext();) {
4351               NTuple<Descriptor> tuple = idxIter.next();
4352               addFlowGraphEdge(md, tuple, interTuple);
4353             }
4354             argTuple = interTuple;
4355           } else if (argTupleSet.size() == 1) {
4356             argTuple = argTupleSet.iterator().next();
4357           } else {
4358             argTuple = new NTuple<Descriptor>();
4359           }
4360
4361           addArgIdxMap(min, idx, argTuple);
4362
4363           FlowNode paramNode = calleeFlowGraph.getParamFlowNode(idx);
4364           if (hasInFlowTo(calleeFlowGraph, paramNode, calleeReturnSet)
4365               || calleeMethodDesc.getModifiers().isNative()) {
4366             addParamNodeFlowingToReturnValue(calleeMethodDesc, paramNode);
4367             nodeSet.addTupleSet(argTupleSet);
4368           }
4369         }
4370
4371       }
4372
4373       // propagateFlowsFromCallee(min, md, min.getMethod());
4374
4375       System.out.println("min nodeSet=" + nodeSet);
4376     }
4377
4378   }
4379
4380   private boolean hasInFlowTo(FlowGraph fg, FlowNode inNode, Set<FlowNode> nodeSet) {
4381     // return true if inNode has in-flows to nodeSet
4382
4383     // Set<FlowNode> reachableSet = fg.getReachFlowNodeSetFrom(inNode);
4384     Set<FlowNode> reachableSet = fg.getReachableSetFrom(inNode.getDescTuple());
4385     System.out.println("inNode=" + inNode + "  reachalbeSet=" + reachableSet);
4386
4387     for (Iterator iterator = reachableSet.iterator(); iterator.hasNext();) {
4388       FlowNode fn = (FlowNode) iterator.next();
4389       if (nodeSet.contains(fn)) {
4390         return true;
4391       }
4392     }
4393     return false;
4394   }
4395
4396   private NTuple<Descriptor> getNodeTupleByArgIdx(MethodInvokeNode min, int idx) {
4397     return mapMethodInvokeNodeToArgIdxMap.get(min).get(new Integer(idx));
4398   }
4399
4400   private void addArgIdxMap(MethodInvokeNode min, int idx, NTuple<Descriptor> argTuple /*
4401                                                                                         * NodeTupleSet
4402                                                                                         * tupleSet
4403                                                                                         */) {
4404     Map<Integer, NTuple<Descriptor>> mapIdxToTuple = mapMethodInvokeNodeToArgIdxMap.get(min);
4405     if (mapIdxToTuple == null) {
4406       mapIdxToTuple = new HashMap<Integer, NTuple<Descriptor>>();
4407       mapMethodInvokeNodeToArgIdxMap.put(min, mapIdxToTuple);
4408     }
4409     mapIdxToTuple.put(new Integer(idx), argTuple);
4410   }
4411
4412   private void analyzeLiteralNode(MethodDescriptor md, SymbolTable nametable, LiteralNode en) {
4413
4414   }
4415
4416   private void analyzeFlowArrayAccessNode(MethodDescriptor md, SymbolTable nametable,
4417       ArrayAccessNode aan, NodeTupleSet nodeSet, boolean isLHS) {
4418
4419     NodeTupleSet expNodeTupleSet = new NodeTupleSet();
4420     NTuple<Descriptor> base =
4421         analyzeFlowExpressionNode(md, nametable, aan.getExpression(), expNodeTupleSet, isLHS);
4422
4423     NodeTupleSet idxNodeTupleSet = new NodeTupleSet();
4424     analyzeFlowExpressionNode(md, nametable, aan.getIndex(), idxNodeTupleSet, isLHS);
4425
4426     if (isLHS) {
4427       // need to create an edge from idx to array
4428       for (Iterator<NTuple<Descriptor>> idxIter = idxNodeTupleSet.iterator(); idxIter.hasNext();) {
4429         NTuple<Descriptor> idxTuple = idxIter.next();
4430         for (Iterator<NTuple<Descriptor>> arrIter = expNodeTupleSet.iterator(); arrIter.hasNext();) {
4431           NTuple<Descriptor> arrTuple = arrIter.next();
4432           getFlowGraph(md).addValueFlowEdge(idxTuple, arrTuple);
4433         }
4434       }
4435
4436       nodeSet.addTupleSet(expNodeTupleSet);
4437     } else {
4438       nodeSet.addTupleSet(expNodeTupleSet);
4439       nodeSet.addTupleSet(idxNodeTupleSet);
4440     }
4441   }
4442
4443   private void analyzeCreateObjectNode(MethodDescriptor md, SymbolTable nametable,
4444       CreateObjectNode en) {
4445     // TODO Auto-generated method stub
4446
4447   }
4448
4449   private void analyzeFlowOpNode(MethodDescriptor md, SymbolTable nametable, OpNode on,
4450       NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
4451
4452     NodeTupleSet leftOpSet = new NodeTupleSet();
4453     NodeTupleSet rightOpSet = new NodeTupleSet();
4454
4455     // left operand
4456     analyzeFlowExpressionNode(md, nametable, on.getLeft(), leftOpSet, null, implicitFlowTupleSet,
4457         false);
4458
4459     if (on.getRight() != null) {
4460       // right operand
4461       analyzeFlowExpressionNode(md, nametable, on.getRight(), rightOpSet, null,
4462           implicitFlowTupleSet, false);
4463     }
4464
4465     Operation op = on.getOp();
4466
4467     switch (op.getOp()) {
4468
4469     case Operation.UNARYPLUS:
4470     case Operation.UNARYMINUS:
4471     case Operation.LOGIC_NOT:
4472       // single operand
4473       nodeSet.addTupleSet(leftOpSet);
4474       break;
4475
4476     case Operation.LOGIC_OR:
4477     case Operation.LOGIC_AND:
4478     case Operation.COMP:
4479     case Operation.BIT_OR:
4480     case Operation.BIT_XOR:
4481     case Operation.BIT_AND:
4482     case Operation.ISAVAILABLE:
4483     case Operation.EQUAL:
4484     case Operation.NOTEQUAL:
4485     case Operation.LT:
4486     case Operation.GT:
4487     case Operation.LTE:
4488     case Operation.GTE:
4489     case Operation.ADD:
4490     case Operation.SUB:
4491     case Operation.MULT:
4492     case Operation.DIV:
4493     case Operation.MOD:
4494     case Operation.LEFTSHIFT:
4495     case Operation.RIGHTSHIFT:
4496     case Operation.URIGHTSHIFT:
4497
4498       // there are two operands
4499       nodeSet.addTupleSet(leftOpSet);
4500       nodeSet.addTupleSet(rightOpSet);
4501       break;
4502
4503     default:
4504       throw new Error(op.toString());
4505     }
4506
4507   }
4508
4509   private NTuple<Descriptor> analyzeFlowNameNode(MethodDescriptor md, SymbolTable nametable,
4510       NameNode nn, NodeTupleSet nodeSet, NTuple<Descriptor> base, NodeTupleSet implicitFlowTupleSet) {
4511
4512     // System.out.println("analyzeFlowNameNode=" + nn.printNode(0));
4513
4514     if (base == null) {
4515       base = new NTuple<Descriptor>();
4516     }
4517
4518     NameDescriptor nd = nn.getName();
4519
4520     if (nd.getBase() != null) {
4521       base =
4522           analyzeFlowExpressionNode(md, nametable, nn.getExpression(), nodeSet, base,
4523               implicitFlowTupleSet, false);
4524       if (base == null) {
4525         // base node has the top location
4526         return base;
4527       }
4528     } else {
4529       String varname = nd.toString();
4530       if (varname.equals("this")) {
4531         // 'this' itself!
4532         base.add(md.getThis());
4533         return base;
4534       }
4535
4536       Descriptor d = (Descriptor) nametable.get(varname);
4537
4538       if (d instanceof VarDescriptor) {
4539         VarDescriptor vd = (VarDescriptor) d;
4540         base.add(vd);
4541       } else if (d instanceof FieldDescriptor) {
4542         // the type of field descriptor has a location!
4543         FieldDescriptor fd = (FieldDescriptor) d;
4544         if (fd.isStatic()) {
4545           if (fd.isFinal()) {
4546             // if it is 'static final', no need to have flow node for the TOP
4547             // location
4548             return null;
4549           } else {
4550             // if 'static', assign the default GLOBAL LOCATION to the first
4551             // element of the tuple
4552             base.add(GLOBALDESC);
4553           }
4554         } else {
4555           // the location of field access starts from this, followed by field
4556           // location
4557           base.add(md.getThis());
4558         }
4559
4560         base.add(fd);
4561       } else if (d == null) {
4562         // access static field
4563         base.add(GLOBALDESC);
4564         base.add(nn.getField());
4565         return base;
4566
4567         // FieldDescriptor fd = nn.getField();addFlowGraphEdge
4568         //
4569         // MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
4570         // String globalLocId = localLattice.getGlobalLoc();
4571         // if (globalLocId == null) {
4572         // throw new
4573         // Error("Method lattice does not define global variable location at "
4574         // + generateErrorMessage(md.getClassDesc(), nn));
4575         // }
4576         // loc.addLocation(new Location(md, globalLocId));
4577         //
4578         // Location fieldLoc = (Location) fd.getType().getExtension();
4579         // loc.addLocation(fieldLoc);
4580         //
4581         // return loc;
4582
4583       }
4584     }
4585     getFlowGraph(md).createNewFlowNode(base);
4586
4587     return base;
4588
4589   }
4590
4591   private NTuple<Descriptor> analyzeFlowFieldAccessNode(MethodDescriptor md, SymbolTable nametable,
4592       FieldAccessNode fan, NodeTupleSet nodeSet, NTuple<Descriptor> base,
4593       NodeTupleSet implicitFlowTupleSet, boolean isLHS) {
4594
4595     ExpressionNode left = fan.getExpression();
4596     TypeDescriptor ltd = left.getType();
4597     FieldDescriptor fd = fan.getField();
4598
4599     String varName = null;
4600     if (left.kind() == Kind.NameNode) {
4601       NameDescriptor nd = ((NameNode) left).getName();
4602       varName = nd.toString();
4603     }
4604
4605     if (ltd.isClassNameRef() || (varName != null && varName.equals("this"))) {
4606       // using a class name directly or access using this
4607       if (fd.isStatic() && fd.isFinal()) {
4608         return null;
4609       }
4610     }
4611
4612     NodeTupleSet idxNodeTupleSet = new NodeTupleSet();
4613
4614     if (left instanceof ArrayAccessNode) {
4615
4616       ArrayAccessNode aan = (ArrayAccessNode) left;
4617       left = aan.getExpression();
4618       analyzeFlowExpressionNode(md, nametable, aan.getIndex(), idxNodeTupleSet, base,
4619           implicitFlowTupleSet, isLHS);
4620
4621       nodeSet.addTupleSet(idxNodeTupleSet);
4622     }
4623     base =
4624         analyzeFlowExpressionNode(md, nametable, left, nodeSet, base, implicitFlowTupleSet, isLHS);
4625
4626     if (base == null) {
4627       // in this case, field is TOP location
4628       return null;
4629     } else {
4630
4631       NTuple<Descriptor> flowFieldTuple = new NTuple<Descriptor>(base.toList());
4632
4633       if (!left.getType().isPrimitive()) {
4634
4635         if (!fd.getSymbol().equals("length")) {
4636           // array.length access, just have the location of the array
4637           flowFieldTuple.add(fd);
4638           nodeSet.removeTuple(base);
4639         }
4640
4641       }
4642       getFlowGraph(md).createNewFlowNode(flowFieldTuple);
4643
4644       if (isLHS) {
4645         for (Iterator<NTuple<Descriptor>> idxIter = idxNodeTupleSet.iterator(); idxIter.hasNext();) {
4646           NTuple<Descriptor> idxTuple = idxIter.next();
4647           getFlowGraph(md).addValueFlowEdge(idxTuple, flowFieldTuple);
4648         }
4649       }
4650       return flowFieldTuple;
4651
4652     }
4653
4654   }
4655
4656   private void debug_printTreeNode(TreeNode tn) {
4657
4658     System.out.println("DEBUG: " + tn.printNode(0) + "                line#=" + tn.getNumLine());
4659
4660   }
4661
4662   private void analyzeFlowAssignmentNode(MethodDescriptor md, SymbolTable nametable,
4663       AssignmentNode an, NodeTupleSet nodeSet, NTuple<Descriptor> base,
4664       NodeTupleSet implicitFlowTupleSet) {
4665
4666     NodeTupleSet nodeSetRHS = new NodeTupleSet();
4667     NodeTupleSet nodeSetLHS = new NodeTupleSet();
4668
4669     boolean postinc = true;
4670     if (an.getOperation().getBaseOp() == null
4671         || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
4672             .getBaseOp().getOp() != Operation.POSTDEC)) {
4673       postinc = false;
4674     }
4675     // if LHS is array access node, need to capture value flows between an array
4676     // and its index value
4677     analyzeFlowExpressionNode(md, nametable, an.getDest(), nodeSetLHS, null, implicitFlowTupleSet,
4678         true);
4679
4680     if (!postinc) {
4681       // analyze value flows of rhs expression
4682       analyzeFlowExpressionNode(md, nametable, an.getSrc(), nodeSetRHS, null, implicitFlowTupleSet,
4683           false);
4684
4685       // System.out.println("-analyzeFlowAssignmentNode=" + an.printNode(0));
4686       // System.out.println("-nodeSetLHS=" + nodeSetLHS);
4687       // System.out.println("-nodeSetRHS=" + nodeSetRHS);
4688       // System.out.println("-implicitFlowTupleSet=" + implicitFlowTupleSet);
4689       // System.out.println("-");
4690
4691       if (an.getOperation().getOp() >= 2 && an.getOperation().getOp() <= 12) {
4692         // if assignment contains OP+EQ operator, creates edges from LHS to LHS
4693
4694         for (Iterator<NTuple<Descriptor>> iter = nodeSetLHS.iterator(); iter.hasNext();) {
4695           NTuple<Descriptor> fromTuple = iter.next();
4696           for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
4697             NTuple<Descriptor> toTuple = iter2.next();
4698             addFlowGraphEdge(md, fromTuple, toTuple);
4699           }
4700         }
4701       }
4702
4703       // creates edges from RHS to LHS
4704       NTuple<Descriptor> interTuple = null;
4705       if (nodeSetRHS.size() > 1) {
4706         interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
4707       }
4708
4709       for (Iterator<NTuple<Descriptor>> iter = nodeSetRHS.iterator(); iter.hasNext();) {
4710         NTuple<Descriptor> fromTuple = iter.next();
4711         for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
4712           NTuple<Descriptor> toTuple = iter2.next();
4713           addFlowGraphEdge(md, fromTuple, interTuple, toTuple);
4714         }
4715       }
4716
4717       // creates edges from implicitFlowTupleSet to LHS
4718       for (Iterator<NTuple<Descriptor>> iter = implicitFlowTupleSet.iterator(); iter.hasNext();) {
4719         NTuple<Descriptor> fromTuple = iter.next();
4720         for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
4721           NTuple<Descriptor> toTuple = iter2.next();
4722           addFlowGraphEdge(md, fromTuple, toTuple);
4723         }
4724       }
4725
4726     } else {
4727       // postinc case
4728
4729       for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
4730         NTuple<Descriptor> tuple = iter2.next();
4731         addFlowGraphEdge(md, tuple, tuple);
4732       }
4733
4734       // creates edges from implicitFlowTupleSet to LHS
4735       for (Iterator<NTuple<Descriptor>> iter = implicitFlowTupleSet.iterator(); iter.hasNext();) {
4736         NTuple<Descriptor> fromTuple = iter.next();
4737         for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
4738           NTuple<Descriptor> toTuple = iter2.next();
4739           addFlowGraphEdge(md, fromTuple, toTuple);
4740         }
4741       }
4742
4743     }
4744
4745     if (nodeSet != null) {
4746       nodeSet.addTupleSet(nodeSetLHS);
4747     }
4748   }
4749
4750   public FlowGraph getFlowGraph(MethodDescriptor md) {
4751     return mapMethodDescriptorToFlowGraph.get(md);
4752   }
4753
4754   private boolean addFlowGraphEdge(MethodDescriptor md, NTuple<Descriptor> from,
4755       NTuple<Descriptor> to) {
4756     FlowGraph graph = getFlowGraph(md);
4757     graph.addValueFlowEdge(from, to);
4758     return true;
4759   }
4760
4761   private void addFlowGraphEdge(MethodDescriptor md, NTuple<Descriptor> from,
4762       NTuple<Descriptor> inter, NTuple<Descriptor> to) {
4763
4764     FlowGraph graph = getFlowGraph(md);
4765
4766     if (inter != null) {
4767       graph.addValueFlowEdge(from, inter);
4768       graph.addValueFlowEdge(inter, to);
4769     } else {
4770       graph.addValueFlowEdge(from, to);
4771     }
4772
4773   }
4774
4775   public void writeInferredLatticeDotFile(ClassDescriptor cd, HierarchyGraph simpleHierarchyGraph,
4776       SSJavaLattice<String> locOrder, String nameSuffix) {
4777     writeInferredLatticeDotFile(cd, null, simpleHierarchyGraph, locOrder, nameSuffix);
4778   }
4779
4780   public void writeInferredLatticeDotFile(ClassDescriptor cd, MethodDescriptor md,
4781       HierarchyGraph simpleHierarchyGraph, SSJavaLattice<String> locOrder, String nameSuffix) {
4782
4783     String fileName = "lattice_";
4784     if (md != null) {
4785       fileName +=
4786           cd.getSymbol().replaceAll("[\\W_]", "") + "_" + md.toString().replaceAll("[\\W_]", "");
4787     } else {
4788       fileName += cd.getSymbol().replaceAll("[\\W_]", "");
4789     }
4790
4791     fileName += nameSuffix;
4792
4793     Set<Pair<String, String>> pairSet = locOrder.getOrderingPairSet();
4794
4795     Set<String> addedLocSet = new HashSet<String>();
4796
4797     if (pairSet.size() > 0) {
4798       try {
4799         BufferedWriter bw = new BufferedWriter(new FileWriter(fileName + ".dot"));
4800
4801         bw.write("digraph " + fileName + " {\n");
4802
4803         for (Iterator iterator = pairSet.iterator(); iterator.hasNext();) {
4804           // pair is in the form of <higher, lower>
4805           Pair<String, String> pair = (Pair<String, String>) iterator.next();
4806
4807           String highLocId = pair.getFirst();
4808           String lowLocId = pair.getSecond();
4809
4810           if (!addedLocSet.contains(highLocId)) {
4811             addedLocSet.add(highLocId);
4812             drawNode(bw, locOrder, simpleHierarchyGraph, highLocId);
4813           }
4814
4815           if (!addedLocSet.contains(lowLocId)) {
4816             addedLocSet.add(lowLocId);
4817             drawNode(bw, locOrder, simpleHierarchyGraph, lowLocId);
4818           }
4819
4820           bw.write(highLocId + " -> " + lowLocId + ";\n");
4821         }
4822         bw.write("}\n");
4823         bw.close();
4824
4825       } catch (IOException e) {
4826         e.printStackTrace();
4827       }
4828
4829     }
4830
4831   }
4832
4833   private String convertMergeSetToString(HierarchyGraph graph, Set<HNode> mergeSet) {
4834     String str = "";
4835     for (Iterator iterator = mergeSet.iterator(); iterator.hasNext();) {
4836       HNode merged = (HNode) iterator.next();
4837       if (merged.isMergeNode()) {
4838         str += convertMergeSetToString(graph, graph.getMapHNodetoMergeSet().get(merged));
4839       } else {
4840         str += " " + merged.getName();
4841       }
4842     }
4843     return str;
4844   }
4845
4846   private void drawNode(BufferedWriter bw, SSJavaLattice<String> lattice, HierarchyGraph graph,
4847       String locName) throws IOException {
4848
4849     HNode node = graph.getHNode(locName);
4850
4851     if (node == null) {
4852       return;
4853     }
4854
4855     String prettyStr;
4856     if (lattice.isSharedLoc(locName)) {
4857       prettyStr = locName + "*";
4858     } else {
4859       prettyStr = locName;
4860     }
4861
4862     if (node.isMergeNode()) {
4863       Set<HNode> mergeSet = graph.getMapHNodetoMergeSet().get(node);
4864       prettyStr += ":" + convertMergeSetToString(graph, mergeSet);
4865     }
4866     bw.write(locName + " [label=\"" + prettyStr + "\"]" + ";\n");
4867   }
4868
4869   public void _debug_printGraph() {
4870     Set<MethodDescriptor> keySet = mapMethodDescriptorToFlowGraph.keySet();
4871
4872     for (Iterator<MethodDescriptor> iterator = keySet.iterator(); iterator.hasNext();) {
4873       MethodDescriptor md = (MethodDescriptor) iterator.next();
4874       FlowGraph fg = mapMethodDescriptorToFlowGraph.get(md);
4875       try {
4876         fg.writeGraph();
4877       } catch (IOException e) {
4878         e.printStackTrace();
4879       }
4880     }
4881
4882   }
4883
4884 }
4885
4886 class CyclicFlowException extends Exception {
4887
4888 }
4889
4890 class InterDescriptor extends Descriptor {
4891
4892   public InterDescriptor(String name) {
4893     super(name);
4894   }
4895
4896 }