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