fix problems of shared loc extension
[IRC.git] / Robust / src / Analysis / SSJava / DefinitelyWrittenCheck.java
1 package Analysis.SSJava;
2
3 import java.io.BufferedWriter;
4 import java.io.FileWriter;
5 import java.io.IOException;
6 import java.util.Enumeration;
7 import java.util.HashSet;
8 import java.util.Hashtable;
9 import java.util.Iterator;
10 import java.util.LinkedList;
11 import java.util.Set;
12 import java.util.Stack;
13
14 import Analysis.CallGraph.CallGraph;
15 import Analysis.Loops.LoopFinder;
16 import IR.Descriptor;
17 import IR.FieldDescriptor;
18 import IR.MethodDescriptor;
19 import IR.Operation;
20 import IR.State;
21 import IR.TypeDescriptor;
22 import IR.TypeExtension;
23 import IR.Flat.FKind;
24 import IR.Flat.FlatCall;
25 import IR.Flat.FlatElementNode;
26 import IR.Flat.FlatFieldNode;
27 import IR.Flat.FlatLiteralNode;
28 import IR.Flat.FlatMethod;
29 import IR.Flat.FlatNode;
30 import IR.Flat.FlatOpNode;
31 import IR.Flat.FlatSetElementNode;
32 import IR.Flat.FlatSetFieldNode;
33 import IR.Flat.TempDescriptor;
34 import IR.Tree.Modifiers;
35 import Util.Pair;
36
37 public class DefinitelyWrittenCheck {
38
39   SSJavaAnalysis ssjava;
40   State state;
41   CallGraph callGraph;
42
43   int debugcount = 0;
44
45   // maps a descriptor to its known dependents: namely
46   // methods or tasks that call the descriptor's method
47   // AND are part of this analysis (reachable from main)
48   private Hashtable<Descriptor, Set<MethodDescriptor>> mapDescriptorToSetDependents;
49
50   // maps a flat node to its WrittenSet: this keeps all heap path overwritten
51   // previously.
52   private Hashtable<FlatNode, Set<NTuple<Descriptor>>> mapFlatNodeToMustWriteSet;
53
54   // maps a temp descriptor to its heap path
55   // each temp descriptor has a unique heap path since we do not allow any
56   // alias.
57   private Hashtable<Descriptor, NTuple<Descriptor>> mapHeapPath;
58
59   // maps a temp descriptor to its composite location
60   private Hashtable<TempDescriptor, NTuple<Location>> mapDescriptorToLocationPath;
61
62   // maps a flat method to the READ that is the set of heap path that is
63   // expected to be written before method invocation
64   private Hashtable<FlatMethod, Set<NTuple<Descriptor>>> mapFlatMethodToReadSet;
65
66   // maps a flat method to the must-write set that is the set of heap path that
67   // is overwritten on every possible path during method invocation
68   private Hashtable<FlatMethod, Set<NTuple<Descriptor>>> mapFlatMethodToMustWriteSet;
69
70   // maps a flat method to the DELETE SET that is a set of heap path to shared
71   // locations that are
72   // written to but not overwritten by the higher value
73   private Hashtable<FlatMethod, SharedLocMap> mapFlatMethodToDeleteSet;
74
75   // maps a flat method to the S SET that is a set of heap path to shared
76   // locations that are overwritten by the higher value
77   private Hashtable<FlatMethod, SharedLocMap> mapFlatMethodToSharedLocMap;
78
79   // maps a flat method to the may-wirte set that is the set of heap path that
80   // might be written to
81   private Hashtable<FlatMethod, Set<NTuple<Descriptor>>> mapFlatMethodToMayWriteSet;
82
83   // maps a call site to the read set contributed by all callees
84   private Hashtable<FlatNode, Set<NTuple<Descriptor>>> mapFlatNodeToBoundReadSet;
85
86   // maps a call site to the must write set contributed by all callees
87   private Hashtable<FlatNode, Set<NTuple<Descriptor>>> mapFlatNodeToBoundMustWriteSet;
88
89   // maps a call site to the may read set contributed by all callees
90   private Hashtable<FlatNode, Set<NTuple<Descriptor>>> mapFlatNodeToBoundMayWriteSet;
91
92   // points to method containing SSJAVA Loop
93   private MethodDescriptor methodContainingSSJavaLoop;
94
95   // maps a flatnode to definitely written analysis mapping M
96   private Hashtable<FlatNode, Hashtable<NTuple<Descriptor>, Set<WriteAge>>> mapFlatNodetoEventLoopMap;
97
98   // maps a method descriptor to its current summary during the analysis
99   // then analysis reaches fixed-point, this mapping will have the final summary
100   // for each method descriptor
101   private Hashtable<MethodDescriptor, ClearingSummary> mapMethodDescriptorToCompleteClearingSummary;
102
103   // maps a method descriptor to the merged incoming caller's current
104   // overwritten status
105   private Hashtable<MethodDescriptor, ClearingSummary> mapMethodDescriptorToInitialClearingSummary;
106
107   // maps a flat node to current partial results
108   private Hashtable<FlatNode, ClearingSummary> mapFlatNodeToClearingSummary;
109
110   // maps shared location to the set of descriptors which belong to the shared
111   // location
112
113   // keep current descriptors to visit in fixed-point interprocedural analysis,
114   private Stack<MethodDescriptor> methodDescriptorsToVisitStack;
115
116   // when analyzing flatcall, need to re-schedule set of callee
117   private Set<MethodDescriptor> calleesToEnqueue;
118
119   private Set<ReadSummary> possibleCalleeReadSummarySetToCaller;
120
121   public static final String arrayElementFieldName = "___element_";
122   static protected Hashtable<TypeDescriptor, FieldDescriptor> mapTypeToArrayField;
123
124   private Set<ClearingSummary> possibleCalleeCompleteSummarySetToCaller;
125
126   // maps a method descriptor to the merged incoming caller's current
127   // reading status
128   // it is for setting clearance flag when all read set is overwritten
129   private Hashtable<MethodDescriptor, ReadSummary> mapMethodDescriptorToReadSummary;
130
131   private MultiSourceMap<Location, Descriptor> mapLocationPathToMayWrittenSet;
132
133   private Hashtable<MethodDescriptor, MultiSourceMap<Location, Descriptor>> mapMethodToSharedWriteMapping;
134
135   private Hashtable<FlatNode, SharedLocMap> mapFlatNodeToSharedLocMapping;
136   private Hashtable<FlatNode, SharedLocMap> mapFlatNodeToDeleteSet;
137
138   private Hashtable<Location, Set<Descriptor>> mapSharedLocationToCoverSet;
139
140   private LinkedList<MethodDescriptor> sortedDescriptors;
141
142   private FlatNode ssjavaLoopEntrance;
143   private LoopFinder ssjavaLoop;
144   private Set<FlatNode> loopIncElements;
145
146   private Set<NTuple<Descriptor>> calleeUnionBoundReadSet;
147   private Set<NTuple<Descriptor>> calleeIntersectBoundMustWriteSet;
148   private Set<NTuple<Descriptor>> calleeUnionBoundMayWriteSet;
149   private SharedLocMap calleeUnionBoundDeleteSet;
150   private SharedLocMap calleeIntersectBoundSharedSet;
151
152   private Hashtable<Descriptor, Location> mapDescToLocation;
153
154   private TempDescriptor LOCAL;
155
156   public static int MAXAGE = 1;
157
158   public DefinitelyWrittenCheck(SSJavaAnalysis ssjava, State state) {
159     this.state = state;
160     this.ssjava = ssjava;
161     this.callGraph = ssjava.getCallGraph();
162     this.mapFlatNodeToMustWriteSet = new Hashtable<FlatNode, Set<NTuple<Descriptor>>>();
163     this.mapDescriptorToSetDependents = new Hashtable<Descriptor, Set<MethodDescriptor>>();
164     this.mapHeapPath = new Hashtable<Descriptor, NTuple<Descriptor>>();
165     this.mapDescriptorToLocationPath = new Hashtable<TempDescriptor, NTuple<Location>>();
166     this.mapFlatMethodToReadSet = new Hashtable<FlatMethod, Set<NTuple<Descriptor>>>();
167     this.mapFlatMethodToMustWriteSet = new Hashtable<FlatMethod, Set<NTuple<Descriptor>>>();
168     this.mapFlatMethodToMayWriteSet = new Hashtable<FlatMethod, Set<NTuple<Descriptor>>>();
169     this.mapFlatNodetoEventLoopMap =
170         new Hashtable<FlatNode, Hashtable<NTuple<Descriptor>, Set<WriteAge>>>();
171     this.calleeUnionBoundReadSet = new HashSet<NTuple<Descriptor>>();
172     this.calleeIntersectBoundMustWriteSet = new HashSet<NTuple<Descriptor>>();
173     this.calleeUnionBoundMayWriteSet = new HashSet<NTuple<Descriptor>>();
174
175     this.mapMethodDescriptorToCompleteClearingSummary =
176         new Hashtable<MethodDescriptor, ClearingSummary>();
177     this.mapMethodDescriptorToInitialClearingSummary =
178         new Hashtable<MethodDescriptor, ClearingSummary>();
179     this.methodDescriptorsToVisitStack = new Stack<MethodDescriptor>();
180     this.calleesToEnqueue = new HashSet<MethodDescriptor>();
181     this.possibleCalleeCompleteSummarySetToCaller = new HashSet<ClearingSummary>();
182     this.mapTypeToArrayField = new Hashtable<TypeDescriptor, FieldDescriptor>();
183     this.LOCAL = new TempDescriptor("LOCAL");
184     this.mapDescToLocation = new Hashtable<Descriptor, Location>();
185     this.possibleCalleeReadSummarySetToCaller = new HashSet<ReadSummary>();
186     this.mapMethodDescriptorToReadSummary = new Hashtable<MethodDescriptor, ReadSummary>();
187     this.mapFlatNodeToBoundReadSet = new Hashtable<FlatNode, Set<NTuple<Descriptor>>>();
188     this.mapFlatNodeToBoundMustWriteSet = new Hashtable<FlatNode, Set<NTuple<Descriptor>>>();
189     this.mapFlatNodeToBoundMayWriteSet = new Hashtable<FlatNode, Set<NTuple<Descriptor>>>();
190     this.mapSharedLocationToCoverSet = new Hashtable<Location, Set<Descriptor>>();
191     this.mapFlatNodeToSharedLocMapping = new Hashtable<FlatNode, SharedLocMap>();
192     this.mapFlatMethodToDeleteSet = new Hashtable<FlatMethod, SharedLocMap>();
193     this.calleeUnionBoundDeleteSet = new SharedLocMap();
194     this.calleeIntersectBoundSharedSet = new SharedLocMap();
195     this.mapFlatMethodToSharedLocMap = new Hashtable<FlatMethod, SharedLocMap>();
196     this.mapLocationPathToMayWrittenSet = new MultiSourceMap<Location, Descriptor>();
197     this.mapMethodToSharedWriteMapping =
198         new Hashtable<MethodDescriptor, MultiSourceMap<Location, Descriptor>>();
199     this.mapFlatNodeToDeleteSet = new Hashtable<FlatNode, SharedLocMap>();
200   }
201
202   public void definitelyWrittenCheck() {
203     if (!ssjava.getAnnotationRequireSet().isEmpty()) {
204       initialize();
205       computeSharedCoverSet();
206
207       // System.out.println("#");
208       // System.out.println(mapLocationPathToMayWrittenSet);
209
210       methodReadWriteSetAnalysis();
211       sharedLocAnalysis();
212
213       eventLoopAnalysis();
214
215     }
216   }
217
218   private void sharedLocAnalysis() {
219
220     // perform method READ/OVERWRITE analysis
221     LinkedList<MethodDescriptor> descriptorListToAnalyze =
222         (LinkedList<MethodDescriptor>) sortedDescriptors.clone();
223
224     // current descriptors to visit in fixed-point interprocedural analysis,
225     // prioritized by
226     // dependency in the call graph
227     methodDescriptorsToVisitStack.clear();
228
229     descriptorListToAnalyze.removeFirst();
230
231     Set<MethodDescriptor> methodDescriptorToVistSet = new HashSet<MethodDescriptor>();
232     methodDescriptorToVistSet.addAll(descriptorListToAnalyze);
233
234     while (!descriptorListToAnalyze.isEmpty()) {
235       MethodDescriptor md = descriptorListToAnalyze.removeFirst();
236       methodDescriptorsToVisitStack.add(md);
237     }
238
239     // analyze scheduled methods until there are no more to visit
240     while (!methodDescriptorsToVisitStack.isEmpty()) {
241       // start to analyze leaf node
242       MethodDescriptor md = methodDescriptorsToVisitStack.pop();
243       FlatMethod fm = state.getMethodFlat(md);
244
245       SharedLocMap sharedLocMap = new SharedLocMap();
246       SharedLocMap deleteSet = new SharedLocMap();
247
248       sharedLoc_analyzeMethod(fm, sharedLocMap, deleteSet);
249       SharedLocMap prevSharedLocMap = mapFlatMethodToSharedLocMap.get(fm);
250       SharedLocMap prevDeleteSet = mapFlatMethodToDeleteSet.get(fm);
251
252       if (!(deleteSet.equals(prevDeleteSet) && sharedLocMap.equals(prevSharedLocMap))) {
253         mapFlatMethodToSharedLocMap.put(fm, sharedLocMap);
254         mapFlatMethodToDeleteSet.put(fm, deleteSet);
255
256         // results for callee changed, so enqueue dependents caller for
257         // further
258         // analysis
259         Iterator<MethodDescriptor> depsItr = getDependents(md).iterator();
260         while (depsItr.hasNext()) {
261           MethodDescriptor methodNext = depsItr.next();
262           if (!methodDescriptorsToVisitStack.contains(methodNext)
263               && methodDescriptorToVistSet.contains(methodNext)) {
264             methodDescriptorsToVisitStack.add(methodNext);
265           }
266
267         }
268
269       }
270
271     }
272
273     sharedLoc_analyzeEventLoop();
274
275   }
276
277   private void sharedLoc_analyzeEventLoop() {
278     if (state.SSJAVADEBUG) {
279       System.out.println("SSJAVA: Definite clearance for shared locations Analyzing: eventloop");
280     }
281     SharedLocMap sharedLocMap = new SharedLocMap();
282     SharedLocMap deleteSet = new SharedLocMap();
283     sharedLoc_analyzeBody(state.getMethodFlat(methodContainingSSJavaLoop), ssjavaLoopEntrance,
284         sharedLocMap, deleteSet, true);
285   }
286
287   private void sharedLoc_analyzeMethod(FlatMethod fm, SharedLocMap sharedLocMap,
288       SharedLocMap deleteSet) {
289     if (state.SSJAVADEBUG) {
290       System.out.println("SSJAVA: Definite clearance for shared locations Analyzing: " + fm);
291     }
292
293     sharedLoc_analyzeBody(fm, fm, sharedLocMap, deleteSet, false);
294
295   }
296
297   private void sharedLoc_analyzeBody(FlatMethod fm, FlatNode startNode, SharedLocMap sharedLocMap,
298       SharedLocMap deleteSet, boolean isEventLoopBody) {
299
300     // intraprocedural analysis
301     Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
302     flatNodesToVisit.add(startNode);
303
304     while (!flatNodesToVisit.isEmpty()) {
305       FlatNode fn = flatNodesToVisit.iterator().next();
306       flatNodesToVisit.remove(fn);
307
308       SharedLocMap currSharedSet = new SharedLocMap();
309       SharedLocMap currDeleteSet = new SharedLocMap();
310
311       for (int i = 0; i < fn.numPrev(); i++) {
312         FlatNode prevFn = fn.getPrev(i);
313         SharedLocMap inSharedLoc = mapFlatNodeToSharedLocMapping.get(prevFn);
314         if (inSharedLoc != null) {
315           mergeSharedLocMap(currSharedSet, inSharedLoc);
316         }
317
318         SharedLocMap inDeleteLoc = mapFlatNodeToDeleteSet.get(prevFn);
319         if (inDeleteLoc != null) {
320           mergeDeleteSet(currDeleteSet, inDeleteLoc);
321         }
322       }
323
324       sharedLoc_nodeActions(fm, fn, currSharedSet, currDeleteSet, sharedLocMap, deleteSet,
325           isEventLoopBody);
326
327       SharedLocMap prevSharedSet = mapFlatNodeToSharedLocMapping.get(fn);
328       SharedLocMap prevDeleteSet = mapFlatNodeToDeleteSet.get(fn);
329
330       if (!(currSharedSet.equals(prevSharedSet) && currDeleteSet.equals(prevDeleteSet))) {
331         mapFlatNodeToSharedLocMapping.put(fn, currSharedSet);
332         mapFlatNodeToDeleteSet.put(fn, currDeleteSet);
333         for (int i = 0; i < fn.numNext(); i++) {
334           FlatNode nn = fn.getNext(i);
335           if ((!isEventLoopBody) || loopIncElements.contains(nn)) {
336             flatNodesToVisit.add(nn);
337           }
338
339         }
340       }
341
342     }
343
344   }
345
346   private void sharedLoc_nodeActions(FlatMethod fm, FlatNode fn, SharedLocMap curr,
347       SharedLocMap currDeleteSet, SharedLocMap sharedLocMap, SharedLocMap deleteSet,
348       boolean isEventLoopBody) {
349
350     SharedLocMap killSet = new SharedLocMap();
351     SharedLocMap genSet = new SharedLocMap();
352
353     TempDescriptor lhs;
354     TempDescriptor rhs;
355     FieldDescriptor fld;
356
357     switch (fn.kind()) {
358
359     case FKind.FlatOpNode: {
360
361       if (isEventLoopBody) {
362         FlatOpNode fon = (FlatOpNode) fn;
363
364         if (fon.getOp().getOp() == Operation.ASSIGN) {
365           lhs = fon.getDest();
366           rhs = fon.getLeft();
367
368           if (!lhs.getSymbol().startsWith("neverused") && rhs.getType().isImmutable()) {
369
370             Location dstLoc = getLocation(lhs);
371             if (dstLoc != null && ssjava.isSharedLocation(dstLoc)) {
372               NTuple<Descriptor> lhsHeapPath = computePath(lhs);
373               NTuple<Location> lhsLocTuple = mapDescriptorToLocationPath.get(lhs);
374
375               Location srcLoc = getLocation(lhs);
376
377               // computing gen/kill set
378               computeKILLSetForWrite(curr, killSet, lhsLocTuple, lhsHeapPath);
379               if (!dstLoc.equals(srcLoc)) {
380                 computeGENSetForHigherWrite(curr, killSet, lhsLocTuple, lhsHeapPath);
381                 updateDeleteSetForHigherWrite(currDeleteSet, lhsLocTuple, lhsHeapPath);
382               } else {
383                 computeGENSetForSameHeightWrite(curr, killSet, lhsLocTuple, lhsHeapPath);
384                 updateDeleteSetForSameHeightWrite(currDeleteSet, lhsLocTuple, lhsHeapPath);
385               }
386
387               // System.out.println("VAR WRITE:" + fn);
388               // System.out.println("lhsLocTuple=" + lhsLocTuple +
389               // " lhsHeapPath="
390               // + lhsHeapPath);
391               // System.out.println("dstLoc=" + dstLoc + " srcLoc=" + srcLoc);
392               // System.out.println("KILLSET=" + killSet);
393               // System.out.println("GENSet=" + genSet);
394               // System.out.println("DELETESET=" + currDeleteSet);
395
396             }
397
398           }
399         }
400
401       }
402
403     }
404       break;
405
406     case FKind.FlatSetFieldNode:
407     case FKind.FlatSetElementNode: {
408
409       if (fn.kind() == FKind.FlatSetFieldNode) {
410         FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
411         lhs = fsfn.getDst();
412         fld = fsfn.getField();
413         rhs = fsfn.getSrc();
414       } else {
415         FlatSetElementNode fsen = (FlatSetElementNode) fn;
416         lhs = fsen.getDst();
417         rhs = fsen.getSrc();
418         TypeDescriptor td = lhs.getType().dereference();
419         fld = getArrayField(td);
420       }
421
422       // shared loc extension
423       Location srcLoc = getLocation(rhs);
424       Location fieldLoc = (Location) fld.getType().getExtension();
425       if (ssjava.isSharedLocation(fieldLoc)) {
426         // only care the case that loc(f) is shared location
427         // write(field)
428
429         NTuple<Location> fieldLocTuple = new NTuple<Location>();
430         fieldLocTuple.addAll(mapDescriptorToLocationPath.get(lhs));
431         fieldLocTuple.add(fieldLoc);
432
433         NTuple<Descriptor> fldHeapPath = computePath(fld);
434
435         // computing gen/kill set
436         computeKILLSetForWrite(curr, killSet, fieldLocTuple, fldHeapPath);
437         if (!fieldLoc.equals(srcLoc)) {
438           computeGENSetForHigherWrite(curr, genSet, fieldLocTuple, fldHeapPath);
439           updateDeleteSetForHigherWrite(currDeleteSet, fieldLocTuple, fldHeapPath);
440         } else {
441           computeGENSetForSameHeightWrite(curr, genSet, fieldLocTuple, fldHeapPath);
442           updateDeleteSetForSameHeightWrite(currDeleteSet, fieldLocTuple, fldHeapPath);
443         }
444
445         // System.out.println("################");
446         // System.out.println("FIELD WRITE:" + fn);
447         // System.out.println("FldHeapPath=" + fldHeapPath);
448         // System.out.println("fieldLocTuple=" + fieldLocTuple + " srcLoc=" +
449         // srcLoc);
450         // System.out.println("KILLSET=" + killSet);
451         // System.out.println("GENSet=" + genSet);
452         // System.out.println("DELETESET=" + currDeleteSet);
453       }
454
455     }
456       break;
457
458     case FKind.FlatCall: {
459       FlatCall fc = (FlatCall) fn;
460
461       bindHeapPathCallerArgWithCaleeParamForSharedLoc(fm.getMethod(), fc);
462
463       // computing gen/kill set
464       generateKILLSetForFlatCall(curr, killSet);
465       generateGENSetForFlatCall(curr, genSet);
466
467       // System.out.println("#FLATCALL=" + fc);
468       // System.out.println("KILLSET=" + killSet);
469       // System.out.println("GENSet=" + genSet);
470       // System.out.println("bound DELETE Set=" + calleeUnionBoundDeleteSet);
471
472     }
473       break;
474
475     case FKind.FlatExit: {
476       // merge the current delete/shared loc mapping
477       mergeSharedLocMap(sharedLocMap, curr);
478       mergeDeleteSet(deleteSet, currDeleteSet);
479
480       // System.out.println("#FLATEXIT sharedLocMap=" + sharedLocMap);
481     }
482       break;
483
484     }
485
486     computeNewMapping(curr, killSet, genSet);
487     // System.out.println("#######" + curr);
488
489   }
490
491   private void generateGENSetForFlatCall(SharedLocMap curr, SharedLocMap genSet) {
492
493     Set<NTuple<Location>> locTupleSet = calleeIntersectBoundSharedSet.keySet();
494     for (Iterator iterator = locTupleSet.iterator(); iterator.hasNext();) {
495       NTuple<Location> locTupleKey = (NTuple<Location>) iterator.next();
496       genSet.addWrite(locTupleKey, curr.get(locTupleKey));
497       genSet.addWrite(locTupleKey, calleeIntersectBoundSharedSet.get(locTupleKey));
498
499       genSet.removeWriteAll(locTupleKey, calleeUnionBoundDeleteSet.get(locTupleKey));
500     }
501
502   }
503
504   private void generateKILLSetForFlatCall(SharedLocMap curr, SharedLocMap killSet) {
505
506     Set<NTuple<Location>> locTupleSet = calleeIntersectBoundSharedSet.keySet();
507     for (Iterator iterator = locTupleSet.iterator(); iterator.hasNext();) {
508       NTuple<Location> locTupleKey = (NTuple<Location>) iterator.next();
509       killSet.addWrite(locTupleKey, curr.get(locTupleKey));
510     }
511
512   }
513
514   private void mergeDeleteSet(SharedLocMap currDeleteSet, SharedLocMap inDeleteLoc) {
515
516     Set<NTuple<Location>> locTupleKeySet = inDeleteLoc.keySet();
517
518     for (Iterator iterator = locTupleKeySet.iterator(); iterator.hasNext();) {
519       NTuple<Location> locTupleKey = (NTuple<Location>) iterator.next();
520
521       Set<NTuple<Descriptor>> inSet = inDeleteLoc.get(locTupleKey);
522       currDeleteSet.addWrite(locTupleKey, inSet);
523
524     }
525   }
526
527   private void computeNewMapping(SharedLocMap curr, SharedLocMap killSet, SharedLocMap genSet) {
528     curr.kill(killSet);
529     curr.gen(genSet);
530   }
531
532   private void updateDeleteSetForHigherWrite(SharedLocMap currDeleteSet, NTuple<Location> locTuple,
533       NTuple<Descriptor> hp) {
534     currDeleteSet.removeWrite(locTuple, hp);
535   }
536
537   private void updateDeleteSetForSameHeightWrite(SharedLocMap currDeleteSet,
538       NTuple<Location> locTuple, NTuple<Descriptor> hp) {
539     currDeleteSet.addWrite(locTuple, hp);
540   }
541
542   private void computeGENSetForHigherWrite(SharedLocMap curr, SharedLocMap genSet,
543       NTuple<Location> locTuple, NTuple<Descriptor> hp) {
544     Set<NTuple<Descriptor>> currWriteSet = curr.get(locTuple);
545
546     if (currWriteSet != null) {
547       genSet.addWrite(locTuple, currWriteSet);
548     }
549
550     genSet.addWrite(locTuple, hp);
551   }
552
553   private void computeGENSetForSameHeightWrite(SharedLocMap curr, SharedLocMap genSet,
554       NTuple<Location> locTuple, NTuple<Descriptor> hp) {
555     Set<NTuple<Descriptor>> currWriteSet = curr.get(locTuple);
556
557     if (currWriteSet != null) {
558       genSet.addWrite(locTuple, currWriteSet);
559     }
560     genSet.removeWrite(locTuple, hp);
561   }
562
563   private void computeKILLSetForWrite(SharedLocMap curr, SharedLocMap killSet,
564       NTuple<Location> locTuple, NTuple<Descriptor> hp) {
565
566     Set<NTuple<Descriptor>> writeSet = curr.get(locTuple);
567     if (writeSet != null) {
568       killSet.addWrite(locTuple, writeSet);
569     }
570
571   }
572
573   private void mergeSharedLocMap(SharedLocMap currSharedSet, SharedLocMap in) {
574
575     Set<NTuple<Location>> locTupleKeySet = in.keySet();
576     for (Iterator iterator = locTupleKeySet.iterator(); iterator.hasNext();) {
577       NTuple<Location> locTupleKey = (NTuple<Location>) iterator.next();
578
579       Set<NTuple<Descriptor>> inSet = in.get(locTupleKey);
580       Set<NTuple<Descriptor>> currSet = currSharedSet.get(locTupleKey);
581       if (currSet == null) {
582         currSet = new HashSet<NTuple<Descriptor>>();
583         currSet.addAll(inSet);
584         currSharedSet.addWrite(locTupleKey, currSet);
585       }
586       currSet.retainAll(inSet);
587     }
588
589   }
590
591   private void checkSharedLocationResult() {
592
593     // mapping of method containing ssjava loop has the final result of
594     // shared location analysis
595
596     ClearingSummary result =
597         mapMethodDescriptorToCompleteClearingSummary.get(methodContainingSSJavaLoop);
598
599     String str = generateNotClearedResult(result);
600     if (str.length() > 0) {
601       throw new Error(
602           "Following concrete locations of the shared abstract location are not cleared at the same time:\n"
603               + str);
604     }
605
606   }
607
608   private String generateNotClearedResult(ClearingSummary result) {
609     Set<NTuple<Descriptor>> keySet = result.keySet();
610
611     StringBuffer str = new StringBuffer();
612     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
613       NTuple<Descriptor> hpKey = (NTuple<Descriptor>) iterator.next();
614       SharedStatus status = result.get(hpKey);
615       Hashtable<Location, Pair<Set<Descriptor>, Boolean>> map = status.getMap();
616       Set<Location> locKeySet = map.keySet();
617       for (Iterator iterator2 = locKeySet.iterator(); iterator2.hasNext();) {
618         Location locKey = (Location) iterator2.next();
619         if (status.haveWriteEffect(locKey)) {
620           Pair<Set<Descriptor>, Boolean> pair = map.get(locKey);
621           if (!pair.getSecond().booleanValue()) {
622             // not cleared!
623             str.append("- Concrete locations of the shared location '" + locKey
624                 + "' are not cleared out, which are reachable through the heap path '" + hpKey
625                 + ".\n");
626           }
627         }
628       }
629     }
630
631     return str.toString();
632
633   }
634
635   private void writeReadMapFile() {
636
637     String fileName = "SharedLocationReadMap";
638
639     try {
640       BufferedWriter bw = new BufferedWriter(new FileWriter(fileName + ".txt"));
641
642       Set<MethodDescriptor> keySet = mapMethodDescriptorToReadSummary.keySet();
643       for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
644         MethodDescriptor mdKey = (MethodDescriptor) iterator.next();
645         ReadSummary summary = mapMethodDescriptorToReadSummary.get(mdKey);
646         bw.write("Method " + mdKey + "::\n");
647         bw.write(summary + "\n\n");
648       }
649       bw.close();
650     } catch (IOException e) {
651       e.printStackTrace();
652     }
653
654   }
655
656   private void sharedLocationAnalysis() {
657     // verify that all concrete locations of shared location are cleared out at
658     // the same time once per the out-most loop
659
660     computeSharedCoverSet();
661
662     if (state.SSJAVADEBUG) {
663       writeReadMapFile();
664     }
665
666     // methodDescriptorsToVisitStack.clear();
667     // methodDescriptorsToVisitStack.add(sortedDescriptors.peekFirst());
668
669     LinkedList<MethodDescriptor> descriptorListToAnalyze =
670         (LinkedList<MethodDescriptor>) sortedDescriptors.clone();
671
672     // current descriptors to visit in fixed-point interprocedural analysis,
673     // prioritized by
674     // dependency in the call graph
675     methodDescriptorsToVisitStack.clear();
676
677     Set<MethodDescriptor> methodDescriptorToVistSet = new HashSet<MethodDescriptor>();
678     methodDescriptorToVistSet.addAll(descriptorListToAnalyze);
679
680     while (!descriptorListToAnalyze.isEmpty()) {
681       MethodDescriptor md = descriptorListToAnalyze.removeFirst();
682       methodDescriptorsToVisitStack.add(md);
683     }
684
685     // analyze scheduled methods until there are no more to visit
686     while (!methodDescriptorsToVisitStack.isEmpty()) {
687       MethodDescriptor md = methodDescriptorsToVisitStack.pop();
688
689       ClearingSummary completeSummary =
690           sharedLocation_analyzeMethod(md, (md.equals(methodContainingSSJavaLoop)));
691
692       ClearingSummary prevCompleteSummary = mapMethodDescriptorToCompleteClearingSummary.get(md);
693
694       if (!completeSummary.equals(prevCompleteSummary)) {
695
696         mapMethodDescriptorToCompleteClearingSummary.put(md, completeSummary);
697
698         // results for callee changed, so enqueue dependents caller for
699         // further analysis
700         Iterator<MethodDescriptor> depsItr = getDependents(md).iterator();
701         while (depsItr.hasNext()) {
702           MethodDescriptor methodNext = depsItr.next();
703           if (!methodDescriptorsToVisitStack.contains(methodNext)) {
704             methodDescriptorsToVisitStack.add(methodNext);
705           }
706         }
707
708         // if there is set of callee to be analyzed,
709         // add this set into the top of stack
710         Iterator<MethodDescriptor> calleeIter = calleesToEnqueue.iterator();
711         while (calleeIter.hasNext()) {
712           MethodDescriptor mdNext = calleeIter.next();
713           if (!methodDescriptorsToVisitStack.contains(mdNext)) {
714             methodDescriptorsToVisitStack.add(mdNext);
715           }
716         }
717         calleesToEnqueue.clear();
718
719       }
720
721     }
722
723   }
724
725   private ClearingSummary sharedLocation_analyzeMethod(MethodDescriptor md,
726       boolean onlyVisitSSJavaLoop) {
727
728     if (state.SSJAVADEBUG) {
729       System.out.println("SSJAVA: Definite clearance for shared locations Analyzing: " + md);
730     }
731
732     FlatMethod fm = state.getMethodFlat(md);
733
734     // intraprocedural analysis
735     Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
736
737     // start a new mapping of partial results for each flat node
738     mapFlatNodeToClearingSummary = new Hashtable<FlatNode, ClearingSummary>();
739
740     if (onlyVisitSSJavaLoop) {
741       flatNodesToVisit.add(ssjavaLoopEntrance);
742     } else {
743       flatNodesToVisit.add(fm);
744     }
745
746     Set<FlatNode> returnNodeSet = new HashSet<FlatNode>();
747
748     while (!flatNodesToVisit.isEmpty()) {
749       FlatNode fn = flatNodesToVisit.iterator().next();
750       flatNodesToVisit.remove(fn);
751
752       ClearingSummary curr = new ClearingSummary();
753
754       Set<ClearingSummary> prevSet = new HashSet<ClearingSummary>();
755       for (int i = 0; i < fn.numPrev(); i++) {
756         FlatNode prevFn = fn.getPrev(i);
757         ClearingSummary in = mapFlatNodeToClearingSummary.get(prevFn);
758         if (in != null) {
759           prevSet.add(in);
760         }
761       }
762       mergeSharedLocationAnaylsis(curr, prevSet);
763
764       sharedLocation_nodeActions(md, fn, curr, returnNodeSet, onlyVisitSSJavaLoop);
765       ClearingSummary clearingPrev = mapFlatNodeToClearingSummary.get(fn);
766
767       if (!curr.equals(clearingPrev)) {
768         mapFlatNodeToClearingSummary.put(fn, curr);
769
770         for (int i = 0; i < fn.numNext(); i++) {
771           FlatNode nn = fn.getNext(i);
772
773           if (!onlyVisitSSJavaLoop || (onlyVisitSSJavaLoop && loopIncElements.contains(nn))) {
774             flatNodesToVisit.add(nn);
775           }
776
777         }
778       }
779
780     }
781
782     ClearingSummary completeSummary = new ClearingSummary();
783     Set<ClearingSummary> summarySet = new HashSet<ClearingSummary>();
784
785     if (onlyVisitSSJavaLoop) {
786       // when analyzing ssjava loop,
787       // complete summary is merging of all previous nodes of ssjava loop
788       // entrance
789       for (int i = 0; i < ssjavaLoopEntrance.numPrev(); i++) {
790         ClearingSummary frnSummary =
791             mapFlatNodeToClearingSummary.get(ssjavaLoopEntrance.getPrev(i));
792         if (frnSummary != null) {
793           summarySet.add(frnSummary);
794         }
795       }
796     } else {
797       // merging all exit node summary into the complete summary
798       if (!returnNodeSet.isEmpty()) {
799         for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
800           FlatNode frn = (FlatNode) iterator.next();
801           ClearingSummary frnSummary = mapFlatNodeToClearingSummary.get(frn);
802           summarySet.add(frnSummary);
803         }
804       }
805     }
806     mergeSharedLocationAnaylsis(completeSummary, summarySet);
807
808     return completeSummary;
809   }
810
811   private void sharedLocation_nodeActions(MethodDescriptor md, FlatNode fn, ClearingSummary curr,
812       Set<FlatNode> returnNodeSet, boolean isSSJavaLoop) {
813
814     TempDescriptor lhs;
815     TempDescriptor rhs;
816     FieldDescriptor fld;
817     switch (fn.kind()) {
818
819     case FKind.FlatMethod: {
820       FlatMethod fm = (FlatMethod) fn;
821
822       ClearingSummary summaryFromCaller =
823           mapMethodDescriptorToInitialClearingSummary.get(fm.getMethod());
824
825       Set<ClearingSummary> inSet = new HashSet<ClearingSummary>();
826       if (summaryFromCaller != null) {
827         inSet.add(summaryFromCaller);
828         mergeSharedLocationAnaylsis(curr, inSet);
829       }
830
831     }
832       break;
833
834     case FKind.FlatOpNode: {
835       FlatOpNode fon = (FlatOpNode) fn;
836       lhs = fon.getDest();
837       rhs = fon.getLeft();
838
839       if (fon.getOp().getOp() == Operation.ASSIGN) {
840         if (rhs.getType().isImmutable() && isSSJavaLoop) {
841           // in ssjavaloop, we need to take care about reading local variables!
842           NTuple<Descriptor> rhsHeapPath = new NTuple<Descriptor>();
843           NTuple<Descriptor> lhsHeapPath = new NTuple<Descriptor>();
844           rhsHeapPath.add(LOCAL);
845           lhsHeapPath.add(LOCAL);
846           if (!lhs.getSymbol().startsWith("neverused")) {
847             readLocation(md, curr, rhsHeapPath, getLocation(rhs), rhs);
848             writeLocation(md, curr, lhsHeapPath, getLocation(lhs), lhs);
849           }
850         }
851       }
852
853     }
854       break;
855
856     case FKind.FlatSetFieldNode:
857     case FKind.FlatSetElementNode: {
858
859       // x.f=y
860
861       if (fn.kind() == FKind.FlatSetFieldNode) {
862         FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
863         lhs = fsfn.getDst();
864         fld = fsfn.getField();
865         rhs = fsfn.getSrc();
866       } else {
867         FlatSetElementNode fsen = (FlatSetElementNode) fn;
868         lhs = fsen.getDst();
869         rhs = fsen.getSrc();
870         TypeDescriptor td = lhs.getType().dereference();
871         fld = getArrayField(td);
872       }
873
874       // write(field)
875       NTuple<Descriptor> lhsHeapPath = computePath(lhs);
876       NTuple<Descriptor> fldHeapPath = new NTuple<Descriptor>(lhsHeapPath.getList());
877       if (fld.getType().isImmutable()) {
878
879         writeLocation(md, curr, fldHeapPath, getLocation(fld), fld);
880
881         Descriptor desc = fldHeapPath.get(fldHeapPath.size() - 1);
882         if (desc instanceof FieldDescriptor) {
883           NTuple<Descriptor> arrayPath = new NTuple<Descriptor>();
884           for (int i = 0; i < fldHeapPath.size() - 1; i++) {
885             arrayPath.add(fldHeapPath.get(i));
886           }
887           SharedStatus state = getState(curr, arrayPath);
888           state.setWriteEffect(getLocation(desc));
889         }
890
891       } else {
892         // updates reference field case:
893         fldHeapPath.add(fld);
894         updateWriteEffectOnReferenceField(curr, fldHeapPath);
895       }
896
897     }
898       break;
899
900     case FKind.FlatCall: {
901
902       FlatCall fc = (FlatCall) fn;
903
904       if (ssjava.isSSJavaUtil(fc.getMethod().getClassDesc())) {
905         // ssjava util case!
906         // have write effects on the first argument
907
908         if (fc.getArg(0).getType().isArray()) {
909           // updates reference field case:
910           // 2. if there exists a tuple t in sharing summary that starts with
911           // hp(x) then, set flag of tuple t to 'true'
912           NTuple<Descriptor> argHeapPath = computePath(fc.getArg(0));
913
914           Location loc = getLocation(fc.getArg(0));
915           NTuple<Descriptor> newHeapPath = new NTuple<Descriptor>();
916           for (int i = 0; i < argHeapPath.size() - 1; i++) {
917             newHeapPath.add(argHeapPath.get(i));
918           }
919           fld = (FieldDescriptor) argHeapPath.get(argHeapPath.size() - 1);
920           argHeapPath = newHeapPath;
921
922           writeLocation(md, curr, argHeapPath, loc, fld);
923         }
924
925       } else {
926         // find out the set of callees
927         MethodDescriptor mdCallee = fc.getMethod();
928         FlatMethod fmCallee = state.getMethodFlat(mdCallee);
929         Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
930         setPossibleCallees.addAll(callGraph.getMethods(mdCallee));
931
932         possibleCalleeCompleteSummarySetToCaller.clear();
933
934         for (Iterator iterator = setPossibleCallees.iterator(); iterator.hasNext();) {
935           MethodDescriptor mdPossibleCallee = (MethodDescriptor) iterator.next();
936           FlatMethod calleeFlatMethod = state.getMethodFlat(mdPossibleCallee);
937
938           addDependent(mdPossibleCallee, // callee
939               md); // caller
940
941           calleesToEnqueue.add(mdPossibleCallee);
942
943           // updates possible callee's initial summary using caller's current
944           // writing status
945           ClearingSummary prevCalleeInitSummary =
946               mapMethodDescriptorToInitialClearingSummary.get(mdPossibleCallee);
947
948           ClearingSummary calleeInitSummary =
949               bindHeapPathOfCalleeCallerEffects(fc, calleeFlatMethod, curr);
950
951           Set<ClearingSummary> inSet = new HashSet<ClearingSummary>();
952           if (prevCalleeInitSummary != null) {
953             inSet.add(prevCalleeInitSummary);
954             mergeSharedLocationAnaylsis(calleeInitSummary, inSet);
955           }
956
957           // if changes, update the init summary
958           // and reschedule the callee for analysis
959           if (!calleeInitSummary.equals(prevCalleeInitSummary)) {
960
961             if (!methodDescriptorsToVisitStack.contains(mdPossibleCallee)) {
962               methodDescriptorsToVisitStack.add(mdPossibleCallee);
963             }
964
965             mapMethodDescriptorToInitialClearingSummary.put(mdPossibleCallee, calleeInitSummary);
966           }
967
968         }
969
970         // contribute callee's writing effects to the caller
971         mergeSharedLocationAnaylsis(curr, possibleCalleeCompleteSummarySetToCaller);
972
973       }
974
975     }
976       break;
977
978     case FKind.FlatReturnNode: {
979       returnNodeSet.add(fn);
980     }
981       break;
982
983     }
984
985   }
986
987   private void updateWriteEffectOnReferenceField(ClearingSummary curr, NTuple<Descriptor> heapPath) {
988
989     // 2. if there exists a tuple t in sharing summary that starts with
990     // hp(x) then, set flag of tuple t to 'true'
991     Set<NTuple<Descriptor>> hpKeySet = curr.keySet();
992     for (Iterator iterator = hpKeySet.iterator(); iterator.hasNext();) {
993       NTuple<Descriptor> hpKey = (NTuple<Descriptor>) iterator.next();
994       if (hpKey.startsWith(heapPath)) {
995         curr.get(hpKey).updateFlag(true);
996       }
997     }
998
999   }
1000
1001   private ClearingSummary bindHeapPathOfCalleeCallerEffects(FlatCall fc,
1002       FlatMethod calleeFlatMethod, ClearingSummary curr) {
1003
1004     ClearingSummary boundSet = new ClearingSummary();
1005
1006     // create mapping from arg idx to its heap paths
1007     Hashtable<Integer, NTuple<Descriptor>> mapArgIdx2CallerArgHeapPath =
1008         new Hashtable<Integer, NTuple<Descriptor>>();
1009
1010     if (fc.getThis() != null) {
1011       // arg idx is starting from 'this' arg
1012       NTuple<Descriptor> thisHeapPath = mapHeapPath.get(fc.getThis());
1013       if (thisHeapPath == null) {
1014         // method is called without creating new flat node representing 'this'
1015         thisHeapPath = new NTuple<Descriptor>();
1016         thisHeapPath.add(fc.getThis());
1017       }
1018
1019       mapArgIdx2CallerArgHeapPath.put(Integer.valueOf(0), thisHeapPath);
1020     }
1021
1022     for (int i = 0; i < fc.numArgs(); i++) {
1023       TempDescriptor arg = fc.getArg(i);
1024       NTuple<Descriptor> argHeapPath = computePath(arg);
1025       mapArgIdx2CallerArgHeapPath.put(Integer.valueOf(i + 1), argHeapPath);
1026     }
1027
1028     Hashtable<Integer, TempDescriptor> mapParamIdx2ParamTempDesc =
1029         new Hashtable<Integer, TempDescriptor>();
1030     int offset = 0;
1031     if (calleeFlatMethod.getMethod().isStatic()) {
1032       // static method does not have implicit 'this' arg
1033       offset = 1;
1034     }
1035     for (int i = 0; i < calleeFlatMethod.numParameters(); i++) {
1036       TempDescriptor param = calleeFlatMethod.getParameter(i);
1037       mapParamIdx2ParamTempDesc.put(Integer.valueOf(i + offset), param);
1038     }
1039
1040     // binding caller's writing effects to callee's params
1041     for (int i = 0; i < calleeFlatMethod.numParameters(); i++) {
1042       NTuple<Descriptor> argHeapPath = mapArgIdx2CallerArgHeapPath.get(Integer.valueOf(i));
1043
1044       if (argHeapPath != null) {
1045         // if method is static, the first argument is nulll because static
1046         // method does not have implicit "THIS" arg
1047         TempDescriptor calleeParamHeapPath = mapParamIdx2ParamTempDesc.get(Integer.valueOf(i));
1048
1049         // iterate over caller's writing effect set
1050         Set<NTuple<Descriptor>> hpKeySet = curr.keySet();
1051         for (Iterator iterator = hpKeySet.iterator(); iterator.hasNext();) {
1052           NTuple<Descriptor> hpKey = (NTuple<Descriptor>) iterator.next();
1053           // current element is reachable caller's arg
1054           // so need to bind it to the caller's side and add it to the
1055           // callee's
1056           // init summary
1057           if (hpKey.startsWith(argHeapPath)) {
1058             NTuple<Descriptor> boundHeapPath = replace(hpKey, argHeapPath, calleeParamHeapPath);
1059             boundSet.put(boundHeapPath, curr.get(hpKey).clone());
1060           }
1061
1062         }
1063       }
1064
1065     }
1066
1067     // contribute callee's complete summary into the caller's current summary
1068     ClearingSummary calleeCompleteSummary =
1069         mapMethodDescriptorToCompleteClearingSummary.get(calleeFlatMethod.getMethod());
1070     if (calleeCompleteSummary != null) {
1071       ClearingSummary boundCalleeEfffects = new ClearingSummary();
1072       for (int i = 0; i < calleeFlatMethod.numParameters(); i++) {
1073         NTuple<Descriptor> argHeapPath = mapArgIdx2CallerArgHeapPath.get(Integer.valueOf(i));
1074
1075         if (argHeapPath != null) {
1076           // if method is static, the first argument is nulll because static
1077           // method does not have implicit "THIS" arg
1078           TempDescriptor calleeParamHeapPath = mapParamIdx2ParamTempDesc.get(Integer.valueOf(i));
1079
1080           // iterate over callee's writing effect set
1081           Set<NTuple<Descriptor>> hpKeySet = calleeCompleteSummary.keySet();
1082           for (Iterator iterator = hpKeySet.iterator(); iterator.hasNext();) {
1083             NTuple<Descriptor> hpKey = (NTuple<Descriptor>) iterator.next();
1084             // current element is reachable caller's arg
1085             // so need to bind it to the caller's side and add it to the
1086             // callee's
1087             // init summary
1088             if (hpKey.startsWith(calleeParamHeapPath)) {
1089
1090               NTuple<Descriptor> boundHeapPathForCaller = replace(hpKey, argHeapPath);
1091
1092               boundCalleeEfffects.put(boundHeapPathForCaller, calleeCompleteSummary.get(hpKey)
1093                   .clone());
1094
1095             }
1096           }
1097
1098         }
1099
1100       }
1101       possibleCalleeCompleteSummarySetToCaller.add(boundCalleeEfffects);
1102     }
1103
1104     return boundSet;
1105   }
1106
1107   private NTuple<Descriptor> replace(NTuple<Descriptor> hpKey, NTuple<Descriptor> argHeapPath) {
1108
1109     // replace the head of heap path with caller's arg path
1110     // for example, heap path 'param.a.b' in callee's side will be replaced with
1111     // (corresponding arg heap path).a.b for caller's side
1112
1113     NTuple<Descriptor> bound = new NTuple<Descriptor>();
1114
1115     for (int i = 0; i < argHeapPath.size(); i++) {
1116       bound.add(argHeapPath.get(i));
1117     }
1118
1119     for (int i = 1; i < hpKey.size(); i++) {
1120       bound.add(hpKey.get(i));
1121     }
1122
1123     return bound;
1124   }
1125
1126   private NTuple<Descriptor> replace(NTuple<Descriptor> effectHeapPath,
1127       NTuple<Descriptor> argHeapPath, TempDescriptor calleeParamHeapPath) {
1128     // replace the head of caller's heap path with callee's param heap path
1129
1130     NTuple<Descriptor> boundHeapPath = new NTuple<Descriptor>();
1131     boundHeapPath.add(calleeParamHeapPath);
1132
1133     for (int i = argHeapPath.size(); i < effectHeapPath.size(); i++) {
1134       boundHeapPath.add(effectHeapPath.get(i));
1135     }
1136
1137     return boundHeapPath;
1138   }
1139
1140   private void computeSharedCoverSet() {
1141     LinkedList<MethodDescriptor> descriptorListToAnalyze =
1142         (LinkedList<MethodDescriptor>) sortedDescriptors.clone();
1143
1144     // current descriptors to visit in fixed-point interprocedural analysis,
1145     // prioritized by
1146     // dependency in the call graph
1147     methodDescriptorsToVisitStack.clear();
1148
1149     descriptorListToAnalyze.removeFirst();
1150
1151     Set<MethodDescriptor> methodDescriptorToVistSet = new HashSet<MethodDescriptor>();
1152     methodDescriptorToVistSet.addAll(descriptorListToAnalyze);
1153
1154     while (!descriptorListToAnalyze.isEmpty()) {
1155       MethodDescriptor md = descriptorListToAnalyze.removeFirst();
1156       methodDescriptorsToVisitStack.add(md);
1157     }
1158
1159     // analyze scheduled methods until there are no more to visit
1160     while (!methodDescriptorsToVisitStack.isEmpty()) {
1161       MethodDescriptor md = methodDescriptorsToVisitStack.pop();
1162       FlatMethod fm = state.getMethodFlat(md);
1163       computeSharedCoverSet_analyzeMethod(fm, md.equals(methodContainingSSJavaLoop));
1164     }
1165
1166     computeSharedCoverSetForEventLoop();
1167
1168   }
1169
1170   private void computeSharedCoverSetForEventLoop() {
1171     computeSharedCoverSet_analyzeMethod(state.getMethodFlat(methodContainingSSJavaLoop), true);
1172   }
1173
1174   private void computeSharedCoverSet_analyzeMethod(FlatMethod fm, boolean onlyVisitSSJavaLoop) {
1175
1176     MethodDescriptor md = fm.getMethod();
1177     Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
1178
1179     Set<FlatNode> visited = new HashSet<FlatNode>();
1180
1181     if (onlyVisitSSJavaLoop) {
1182       flatNodesToVisit.add(ssjavaLoopEntrance);
1183     } else {
1184       flatNodesToVisit.add(fm);
1185     }
1186
1187     while (!flatNodesToVisit.isEmpty()) {
1188       FlatNode fn = flatNodesToVisit.iterator().next();
1189       flatNodesToVisit.remove(fn);
1190       visited.add(fn);
1191
1192       computeSharedCoverSet_nodeActions(md, fn);
1193
1194       for (int i = 0; i < fn.numNext(); i++) {
1195         FlatNode nn = fn.getNext(i);
1196
1197         if (!visited.contains(nn)) {
1198           if (!onlyVisitSSJavaLoop || (onlyVisitSSJavaLoop && loopIncElements.contains(nn))) {
1199             flatNodesToVisit.add(nn);
1200           }
1201         }
1202
1203       }
1204
1205     }
1206
1207   }
1208
1209   private void computeSharedCoverSet_nodeActions(MethodDescriptor md, FlatNode fn) {
1210     TempDescriptor lhs;
1211     TempDescriptor rhs;
1212     FieldDescriptor fld;
1213
1214     switch (fn.kind()) {
1215
1216     case FKind.FlatLiteralNode: {
1217       FlatLiteralNode fln = (FlatLiteralNode) fn;
1218       lhs = fln.getDst();
1219
1220       if (lhs.getType().isPrimitive() && !lhs.getSymbol().startsWith("neverused")
1221           && !lhs.getSymbol().startsWith("srctmp")) {
1222         // only need to care about composite location case here
1223         if (lhs.getType().getExtension() instanceof SSJavaType) {
1224           CompositeLocation compLoc = ((SSJavaType) lhs.getType().getExtension()).getCompLoc();
1225           Location lastLocElement = compLoc.get(compLoc.getSize() - 1);
1226           // check if the last one is shared loc
1227           if (ssjava.isSharedLocation(lastLocElement)) {
1228             addSharedLocDescriptor(lastLocElement, lhs);
1229           }
1230         }
1231       }
1232
1233     }
1234       break;
1235
1236     case FKind.FlatOpNode: {
1237       FlatOpNode fon = (FlatOpNode) fn;
1238       // for a normal assign node, need to propagate lhs's location path to
1239       // rhs
1240       if (fon.getOp().getOp() == Operation.ASSIGN) {
1241         rhs = fon.getLeft();
1242         lhs = fon.getDest();
1243
1244         if (lhs.getType().isPrimitive() && !lhs.getSymbol().startsWith("neverused")
1245             && !lhs.getSymbol().startsWith("srctmp") && !lhs.getSymbol().startsWith("leftop")
1246             && !lhs.getSymbol().startsWith("rightop")) {
1247
1248           NTuple<Location> lhsLocTuple = new NTuple<Location>();
1249           lhsLocTuple.addAll(deriveLocationTuple(md, rhs));
1250
1251           mapLocationPathToMayWrittenSet.put(lhsLocTuple, null, lhs);
1252           addMayWrittenSet(md, lhsLocTuple, lhs);
1253
1254         }
1255
1256         if (mapDescriptorToLocationPath.containsKey(rhs)) {
1257           mapDescriptorToLocationPath.put(lhs, mapDescriptorToLocationPath.get(rhs));
1258         } else {
1259           if (rhs.getType().getExtension() instanceof SSJavaType) {
1260             NTuple<Location> rhsLocTuple =
1261                 ((SSJavaType) rhs.getType().getExtension()).getCompLoc().getTuple();
1262
1263             NTuple<Location> lhsLocTuple = new NTuple<Location>();
1264             lhsLocTuple.addAll(rhsLocTuple);
1265
1266             mapDescriptorToLocationPath.put(rhs, rhsLocTuple);
1267             mapDescriptorToLocationPath.put(lhs, lhsLocTuple);
1268
1269           }
1270         }
1271
1272       }
1273     }
1274       break;
1275
1276     case FKind.FlatSetFieldNode:
1277     case FKind.FlatSetElementNode: {
1278
1279       // x.f=y;
1280
1281       if (fn.kind() == FKind.FlatSetFieldNode) {
1282         FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
1283         lhs = fsfn.getDst();
1284         fld = fsfn.getField();
1285         rhs = fsfn.getSrc();
1286       } else {
1287         FlatSetElementNode fsen = (FlatSetElementNode) fn;
1288         lhs = fsen.getDst();
1289         rhs = fsen.getSrc();
1290         TypeDescriptor td = lhs.getType().dereference();
1291         fld = getArrayField(td);
1292       }
1293
1294       Location fieldLocation = (Location) fld.getType().getExtension();
1295       if (ssjava.isSharedLocation(fieldLocation)) {
1296         addSharedLocDescriptor(fieldLocation, fld);
1297
1298         NTuple<Location> locTuple = new NTuple<Location>();
1299         locTuple.addAll(deriveLocationTuple(md, lhs));
1300         locTuple.add(fieldLocation);
1301
1302         // mapLocationPathToMayWrittenSet.put(locTuple, null, fld);
1303         addMayWrittenSet(md, locTuple, fld);
1304
1305       }
1306
1307     }
1308       break;
1309
1310     case FKind.FlatElementNode:
1311     case FKind.FlatFieldNode: {
1312
1313       // x=y.f;
1314
1315       if (fn.kind() == FKind.FlatFieldNode) {
1316         FlatFieldNode ffn = (FlatFieldNode) fn;
1317         lhs = ffn.getDst();
1318         rhs = ffn.getSrc();
1319         fld = ffn.getField();
1320       } else {
1321         FlatElementNode fen = (FlatElementNode) fn;
1322         lhs = fen.getDst();
1323         rhs = fen.getSrc();
1324         TypeDescriptor td = rhs.getType().dereference();
1325         fld = getArrayField(td);
1326       }
1327
1328       if (fld.isFinal()) {
1329         // if field is final no need to check
1330         break;
1331       }
1332
1333       NTuple<Location> locTuple = new NTuple<Location>();
1334       locTuple.addAll(deriveLocationTuple(md, rhs));
1335       locTuple.add((Location) fld.getType().getExtension());
1336
1337       mapDescriptorToLocationPath.put(lhs, locTuple);
1338
1339     }
1340       break;
1341
1342     case FKind.FlatCall: {
1343
1344       FlatCall fc = (FlatCall) fn;
1345       bindLocationPathCallerArgWithCalleeParam(md, fc);
1346
1347     }
1348       break;
1349
1350     }
1351   }
1352
1353   private void addMayWrittenSet(MethodDescriptor md, NTuple<Location> locTuple, Descriptor d) {
1354
1355     MultiSourceMap<Location, Descriptor> map = mapMethodToSharedWriteMapping.get(md);
1356     if (map == null) {
1357       map = new MultiSourceMap<Location, Descriptor>();
1358       mapMethodToSharedWriteMapping.put(md, map);
1359     }
1360
1361     Set<Descriptor> writeSet = map.get(locTuple);
1362     if (writeSet == null) {
1363       writeSet = new HashSet<Descriptor>();
1364       map.put(locTuple, writeSet);
1365     }
1366     writeSet.add(d);
1367
1368     // System.out.println("ADD WRITE DESC=" + d + " TO locTuple=" + locTuple);
1369   }
1370
1371   private void bindLocationPathCallerArgWithCalleeParam(MethodDescriptor mdCaller, FlatCall fc) {
1372
1373     if (ssjava.isSSJavaUtil(fc.getMethod().getClassDesc())) {
1374       // ssjava util case!
1375       // have write effects on the first argument
1376       TempDescriptor arg = fc.getArg(0);
1377       NTuple<Location> argLocationPath = deriveLocationTuple(mdCaller, arg);
1378       NTuple<Descriptor> argHeapPath = computePath(arg);
1379       mapLocationPathToMayWrittenSet.put(argLocationPath, null,
1380           argHeapPath.get(argHeapPath.size() - 1));
1381
1382     } else {
1383
1384       // if arg is not primitive type, we need to propagate maywritten set to
1385       // the caller's location path
1386
1387       MethodDescriptor mdCallee = fc.getMethod();
1388       Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
1389       setPossibleCallees.addAll(callGraph.getMethods(mdCallee));
1390
1391       // create mapping from arg idx to its heap paths
1392       Hashtable<Integer, NTuple<Location>> mapArgIdx2CallerAgLocationStrPath =
1393           new Hashtable<Integer, NTuple<Location>>();
1394
1395       // arg idx is starting from 'this' arg
1396       if (fc.getThis() != null) {
1397         NTuple<Location> thisLocationPath = deriveLocationTuple(mdCaller, fc.getThis());
1398         mapArgIdx2CallerAgLocationStrPath.put(Integer.valueOf(0), thisLocationPath);
1399       }
1400
1401       Hashtable<Integer, Set<Descriptor>> mapParamIdx2WriteSet =
1402           new Hashtable<Integer, Set<Descriptor>>();
1403
1404       for (int i = 0; i < fc.numArgs() + 1; i++) {
1405         mapParamIdx2WriteSet.put(Integer.valueOf(i), new HashSet<Descriptor>());
1406       }
1407
1408       for (int i = 0; i < fc.numArgs(); i++) {
1409         TempDescriptor arg = fc.getArg(i);
1410         NTuple<Location> argLocationPath = deriveLocationTuple(mdCaller, arg);
1411         mapArgIdx2CallerAgLocationStrPath.put(Integer.valueOf(i + 1), argLocationPath);
1412       }
1413
1414       for (Iterator iterator = setPossibleCallees.iterator(); iterator.hasNext();) {
1415         MethodDescriptor callee = (MethodDescriptor) iterator.next();
1416         FlatMethod calleeFlatMethod = state.getMethodFlat(callee);
1417
1418         // binding caller's args and callee's params
1419
1420         Hashtable<Integer, TempDescriptor> mapParamIdx2ParamTempDesc =
1421             new Hashtable<Integer, TempDescriptor>();
1422         int offset = 0;
1423         if (calleeFlatMethod.getMethod().isStatic()) {
1424           // static method does not have implicit 'this' arg
1425           offset = 1;
1426         }
1427         for (int i = 0; i < calleeFlatMethod.numParameters(); i++) {
1428           TempDescriptor param = calleeFlatMethod.getParameter(i);
1429           mapParamIdx2ParamTempDesc.put(Integer.valueOf(i + offset), param);
1430         }
1431
1432         Set<Integer> keySet = mapArgIdx2CallerAgLocationStrPath.keySet();
1433         for (Iterator iterator2 = keySet.iterator(); iterator2.hasNext();) {
1434           Integer idx = (Integer) iterator2.next();
1435           NTuple<Location> callerArgLocationStrPath = mapArgIdx2CallerAgLocationStrPath.get(idx);
1436
1437           TempDescriptor calleeParam = mapParamIdx2ParamTempDesc.get(idx);
1438           NTuple<Location> calleeLocationPath = deriveLocationTuple(mdCallee, calleeParam);
1439
1440           // System.out.println("#createNewMappingOfMayWrittenSet callee=" +
1441           // callee
1442           // + " callerArgLocationStrPath=" + callerArgLocationStrPath +
1443           // "calleeLocationPath="
1444           // + calleeLocationPath + " idx=" + idx + " writeset=" +
1445           // mapParamIdx2WriteSet.get(idx));
1446           createNewMappingOfMayWrittenSet(callee, callerArgLocationStrPath, calleeLocationPath,
1447               mapParamIdx2WriteSet.get(idx));
1448
1449         }
1450
1451       }
1452
1453     }
1454
1455   }
1456
1457   private void createNewMappingOfMayWrittenSet(MethodDescriptor callee,
1458       NTuple<Location> callerPath, NTuple<Location> calleeParamPath, Set<Descriptor> writeSet) {
1459
1460     // propagate may-written-set associated with the key that is started with
1461     // calleepath to the caller
1462     // 1) makes a new key by combining caller path and callee path(except local
1463     // loc element of param)
1464     // 2) create new mapping of may-written-set of callee path to caller path
1465
1466     // extract all may written effect accessed through callee param path
1467     MultiSourceMap<Location, Descriptor> mapping = mapMethodToSharedWriteMapping.get(callee);
1468
1469     if (mapping == null) {
1470       return;
1471     }
1472
1473     Hashtable<NTuple<Location>, Set<Descriptor>> paramMapping =
1474         mapping.getMappingByStartedWith(calleeParamPath);
1475
1476     Set<NTuple<Location>> calleeKeySet = mapping.keySet();
1477     for (Iterator iterator = calleeKeySet.iterator(); iterator.hasNext();) {
1478       NTuple<Location> calleeKey = (NTuple<Location>) iterator.next();
1479       Set<Descriptor> calleeMayWriteSet = paramMapping.get(calleeKey);
1480
1481       if (calleeMayWriteSet != null) {
1482         writeSet.addAll(calleeMayWriteSet);
1483
1484         NTuple<Location> newKey = new NTuple<Location>();
1485         newKey.addAll(callerPath);
1486         // need to replace the local location with the caller's path so skip the
1487         // local location of the parameter
1488         for (int i = 1; i < calleeKey.size(); i++) {
1489           newKey.add(calleeKey.get(i));
1490         }
1491
1492         mapLocationPathToMayWrittenSet.put(calleeKey, newKey, writeSet);
1493       }
1494
1495     }
1496
1497   }
1498
1499   private void addSharedLocDescriptor(Location sharedLoc, Descriptor desc) {
1500
1501     Set<Descriptor> descSet = mapSharedLocationToCoverSet.get(sharedLoc);
1502     if (descSet == null) {
1503       descSet = new HashSet<Descriptor>();
1504       mapSharedLocationToCoverSet.put(sharedLoc, descSet);
1505     }
1506
1507     descSet.add(desc);
1508
1509   }
1510
1511   private boolean hasReadingEffectOnSharedLocation(MethodDescriptor md, NTuple<Descriptor> hp,
1512       Location loc, Descriptor d) {
1513
1514     ReadSummary summary = mapMethodDescriptorToReadSummary.get(md);
1515
1516     if (summary != null) {
1517       Hashtable<Location, Set<Descriptor>> map = summary.get(hp);
1518       if (map != null) {
1519         Set<Descriptor> descSec = map.get(loc);
1520         if (descSec != null) {
1521           return descSec.contains(d);
1522         }
1523       }
1524     }
1525     return false;
1526
1527   }
1528
1529   private Location getLocation(Descriptor d) {
1530
1531     if (d instanceof FieldDescriptor) {
1532       TypeExtension te = ((FieldDescriptor) d).getType().getExtension();
1533       if (te != null) {
1534         return (Location) te;
1535       }
1536     } else {
1537       assert d instanceof TempDescriptor;
1538       TempDescriptor td = (TempDescriptor) d;
1539
1540       TypeExtension te = td.getType().getExtension();
1541       if (te != null) {
1542         if (te instanceof SSJavaType) {
1543           SSJavaType ssType = (SSJavaType) te;
1544           CompositeLocation comp = ssType.getCompLoc();
1545           return comp.get(comp.getSize() - 1);
1546         } else {
1547           return (Location) te;
1548         }
1549       }
1550     }
1551
1552     return mapDescToLocation.get(d);
1553   }
1554
1555   private void writeLocation(MethodDescriptor md, ClearingSummary curr, NTuple<Descriptor> hp,
1556       Location loc, Descriptor d) {
1557
1558     SharedStatus state = getState(curr, hp);
1559     if (loc != null && hasReadingEffectOnSharedLocation(md, hp, loc, d)) {
1560       // 1. add field x to the clearing set
1561
1562       state.addVar(loc, d);
1563
1564       // 3. if the set v contains all of variables belonging to the shared
1565       // location, set flag to true
1566       if (isOverWrittenAllDescsOfSharedLoc(md, hp, loc, state.getVarSet(loc))) {
1567         state.updateFlag(loc, true);
1568       }
1569     }
1570     state.setWriteEffect(loc);
1571
1572   }
1573
1574   private boolean isOverWrittenAllDescsOfSharedLoc(MethodDescriptor md, NTuple<Descriptor> hp,
1575       Location loc, Set<Descriptor> writtenSet) {
1576
1577     ReadSummary summary = mapMethodDescriptorToReadSummary.get(md);
1578
1579     if (summary != null) {
1580       Hashtable<Location, Set<Descriptor>> map = summary.get(hp);
1581       if (map != null) {
1582         Set<Descriptor> descSet = map.get(loc);
1583         if (descSet != null) {
1584           return writtenSet.containsAll(descSet);
1585         }
1586       }
1587     }
1588     return false;
1589   }
1590
1591   private void readLocation(MethodDescriptor md, ClearingSummary curr, NTuple<Descriptor> hp,
1592       Location loc, Descriptor d) {
1593     // remove reading var x from written set
1594     if (loc != null && hasReadingEffectOnSharedLocation(md, hp, loc, d)) {
1595       SharedStatus state = getState(curr, hp);
1596       state.removeVar(loc, d);
1597     }
1598   }
1599
1600   private SharedStatus getState(ClearingSummary curr, NTuple<Descriptor> hp) {
1601     SharedStatus state = curr.get(hp);
1602     if (state == null) {
1603       state = new SharedStatus();
1604       curr.put(hp, state);
1605     }
1606     return state;
1607   }
1608
1609   private void eventLoopAnalysis() {
1610     // perform second stage analysis: intraprocedural analysis ensure that
1611     // all
1612     // variables are definitely written in-between the same read
1613
1614     Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
1615     flatNodesToVisit.add(ssjavaLoopEntrance);
1616
1617     while (!flatNodesToVisit.isEmpty()) {
1618       FlatNode fn = (FlatNode) flatNodesToVisit.iterator().next();
1619       flatNodesToVisit.remove(fn);
1620
1621       Hashtable<NTuple<Descriptor>, Set<WriteAge>> prev = mapFlatNodetoEventLoopMap.get(fn);
1622
1623       Hashtable<NTuple<Descriptor>, Set<WriteAge>> curr =
1624           new Hashtable<NTuple<Descriptor>, Set<WriteAge>>();
1625       for (int i = 0; i < fn.numPrev(); i++) {
1626         FlatNode nn = fn.getPrev(i);
1627         Hashtable<NTuple<Descriptor>, Set<WriteAge>> in = mapFlatNodetoEventLoopMap.get(nn);
1628         if (in != null) {
1629           union(curr, in);
1630         }
1631       }
1632
1633       eventLoopAnalysis_nodeAction(fn, curr, ssjavaLoopEntrance);
1634
1635       // if a new result, schedule forward nodes for analysis
1636       if (!curr.equals(prev)) {
1637         mapFlatNodetoEventLoopMap.put(fn, curr);
1638
1639         for (int i = 0; i < fn.numNext(); i++) {
1640           FlatNode nn = fn.getNext(i);
1641           if (loopIncElements.contains(nn)) {
1642             flatNodesToVisit.add(nn);
1643           }
1644
1645         }
1646       }
1647     }
1648   }
1649
1650   private void union(Hashtable<NTuple<Descriptor>, Set<WriteAge>> curr,
1651       Hashtable<NTuple<Descriptor>, Set<WriteAge>> in) {
1652
1653     Set<NTuple<Descriptor>> inKeySet = in.keySet();
1654     for (Iterator iterator = inKeySet.iterator(); iterator.hasNext();) {
1655       NTuple<Descriptor> inKey = (NTuple<Descriptor>) iterator.next();
1656       Set<WriteAge> inSet = in.get(inKey);
1657
1658       Set<WriteAge> currSet = curr.get(inKey);
1659
1660       if (currSet == null) {
1661         currSet = new HashSet<WriteAge>();
1662         curr.put(inKey, currSet);
1663       }
1664       currSet.addAll(inSet);
1665     }
1666
1667   }
1668
1669   private void eventLoopAnalysis_nodeAction(FlatNode fn,
1670       Hashtable<NTuple<Descriptor>, Set<WriteAge>> curr, FlatNode loopEntrance) {
1671
1672     Hashtable<NTuple<Descriptor>, Set<WriteAge>> readWriteKillSet =
1673         new Hashtable<NTuple<Descriptor>, Set<WriteAge>>();
1674     Hashtable<NTuple<Descriptor>, Set<WriteAge>> readWriteGenSet =
1675         new Hashtable<NTuple<Descriptor>, Set<WriteAge>>();
1676
1677     if (fn.equals(loopEntrance)) {
1678       // it reaches loop entrance: changes all flag to true
1679       Set<NTuple<Descriptor>> keySet = curr.keySet();
1680       for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1681         NTuple<Descriptor> key = (NTuple<Descriptor>) iterator.next();
1682         Set<WriteAge> writeAgeSet = curr.get(key);
1683
1684         Set<WriteAge> incSet = new HashSet<WriteAge>();
1685         incSet.addAll(writeAgeSet);
1686         writeAgeSet.clear();
1687
1688         for (Iterator iterator2 = incSet.iterator(); iterator2.hasNext();) {
1689           WriteAge writeAge = (WriteAge) iterator2.next();
1690           WriteAge newWriteAge = writeAge.copy();
1691           newWriteAge.inc();
1692           writeAgeSet.add(newWriteAge);
1693         }
1694
1695       }
1696       // System.out.println("EVENT LOOP ENTRY=" + curr);
1697
1698     } else {
1699       TempDescriptor lhs;
1700       TempDescriptor rhs;
1701       FieldDescriptor fld;
1702
1703       switch (fn.kind()) {
1704
1705       case FKind.FlatOpNode: {
1706         FlatOpNode fon = (FlatOpNode) fn;
1707         lhs = fon.getDest();
1708         rhs = fon.getLeft();
1709
1710         if (!lhs.getSymbol().startsWith("neverused")) {
1711           NTuple<Descriptor> rhsHeapPath = computePath(rhs);
1712           if (!rhs.getType().isImmutable()) {
1713             mapHeapPath.put(lhs, rhsHeapPath);
1714           } else {
1715             // write(lhs)
1716             // NTuple<Descriptor> lhsHeapPath = computePath(lhs);
1717             NTuple<Descriptor> path = new NTuple<Descriptor>();
1718             path.add(lhs);
1719
1720             // System.out.println("WRITE VARIABLE=" + path + " from=" + lhs);
1721
1722             computeKILLSetForWrite(curr, path, readWriteKillSet);
1723             computeGENSetForWrite(path, readWriteGenSet);
1724
1725             // System.out.println("#VARIABLE WRITE:" + fn);
1726             // System.out.println("#KILLSET=" + KILLSet);
1727             // System.out.println("#GENSet=" + GENSet);
1728
1729           }
1730         }
1731
1732       }
1733         break;
1734
1735       case FKind.FlatFieldNode:
1736       case FKind.FlatElementNode: {
1737
1738         if (fn.kind() == FKind.FlatFieldNode) {
1739           FlatFieldNode ffn = (FlatFieldNode) fn;
1740           lhs = ffn.getDst();
1741           rhs = ffn.getSrc();
1742           fld = ffn.getField();
1743         } else {
1744           FlatElementNode fen = (FlatElementNode) fn;
1745           lhs = fen.getDst();
1746           rhs = fen.getSrc();
1747           TypeDescriptor td = rhs.getType().dereference();
1748           fld = getArrayField(td);
1749         }
1750
1751         // read field
1752         NTuple<Descriptor> srcHeapPath = mapHeapPath.get(rhs);
1753         NTuple<Descriptor> fldHeapPath;
1754         if (srcHeapPath != null) {
1755           fldHeapPath = new NTuple<Descriptor>(srcHeapPath.getList());
1756         } else {
1757           // if srcHeapPath is null, it is static reference
1758           fldHeapPath = new NTuple<Descriptor>();
1759           fldHeapPath.add(rhs);
1760         }
1761         fldHeapPath.add(fld);
1762
1763         Set<WriteAge> writeAgeSet = curr.get(fldHeapPath);
1764         checkWriteAgeSet(writeAgeSet, fldHeapPath, fn);
1765
1766       }
1767         break;
1768
1769       case FKind.FlatSetFieldNode:
1770       case FKind.FlatSetElementNode: {
1771
1772         if (fn.kind() == FKind.FlatSetFieldNode) {
1773           FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
1774           lhs = fsfn.getDst();
1775           fld = fsfn.getField();
1776         } else {
1777           FlatSetElementNode fsen = (FlatSetElementNode) fn;
1778           lhs = fsen.getDst();
1779           rhs = fsen.getSrc();
1780           TypeDescriptor td = lhs.getType().dereference();
1781           fld = getArrayField(td);
1782         }
1783
1784         // write(field)
1785         NTuple<Descriptor> lhsHeapPath = computePath(lhs);
1786         NTuple<Descriptor> fldHeapPath = new NTuple<Descriptor>(lhsHeapPath.getList());
1787         fldHeapPath.add(fld);
1788
1789         computeKILLSetForWrite(curr, fldHeapPath, readWriteKillSet);
1790         computeGENSetForWrite(fldHeapPath, readWriteGenSet);
1791
1792         // System.out.println("FIELD WRITE:" + fn);
1793         // System.out.println("KILLSET=" + KILLSet);
1794         // System.out.println("GENSet=" + GENSet);
1795
1796       }
1797         break;
1798
1799       case FKind.FlatCall: {
1800         FlatCall fc = (FlatCall) fn;
1801
1802         // System.out.println("FLATCALL:" + fn);
1803
1804         generateKILLSetForFlatCall(fc, curr, readWriteKillSet);
1805         generateGENSetForFlatCall(fc, readWriteGenSet);
1806
1807         checkManyRead(fc, curr);
1808
1809         // System.out.println("KILLSET=" + readWriteKillSet);
1810         // System.out.println("GENSet=" + readWriteGenSet);
1811
1812       }
1813         break;
1814
1815       }
1816
1817       computeNewMapping(curr, readWriteKillSet, readWriteGenSet);
1818       // System.out.println("#######" + curr);
1819
1820     }
1821
1822   }
1823
1824   private void checkManyRead(FlatCall fc, Hashtable<NTuple<Descriptor>, Set<WriteAge>> curr) {
1825
1826     Set<NTuple<Descriptor>> boundReadSet = mapFlatNodeToBoundReadSet.get(fc);
1827
1828     for (Iterator iterator = boundReadSet.iterator(); iterator.hasNext();) {
1829       NTuple<Descriptor> readHeapPath = (NTuple<Descriptor>) iterator.next();
1830       Set<WriteAge> writeAgeSet = curr.get(readHeapPath);
1831       checkWriteAgeSet(writeAgeSet, readHeapPath, fc);
1832     }
1833
1834   }
1835
1836   private void checkWriteAgeSet(Set<WriteAge> writeAgeSet, NTuple<Descriptor> path, FlatNode fn) {
1837     if (writeAgeSet != null) {
1838       for (Iterator iterator = writeAgeSet.iterator(); iterator.hasNext();) {
1839         WriteAge writeAge = (WriteAge) iterator.next();
1840         if (writeAge.getAge() >= MAXAGE) {
1841           throw new Error(
1842               "Memory location, which is reachable through references "
1843                   + path
1844                   + ", who comes back to the same read statement without being overwritten at the out-most iteration at "
1845                   + methodContainingSSJavaLoop.getClassDesc().getSourceFileName() + "::"
1846                   + fn.getNumLine());
1847         }
1848       }
1849     }
1850   }
1851
1852   private void generateGENSetForFlatCall(FlatCall fc,
1853       Hashtable<NTuple<Descriptor>, Set<WriteAge>> GENSet) {
1854
1855     Set<NTuple<Descriptor>> boundMayWriteSet = mapFlatNodeToBoundMayWriteSet.get(fc);
1856
1857     for (Iterator iterator = boundMayWriteSet.iterator(); iterator.hasNext();) {
1858       NTuple<Descriptor> key = (NTuple<Descriptor>) iterator.next();
1859       // TODO: shared location
1860       Set<WriteAge> set = new HashSet<WriteAge>();
1861       set.add(new WriteAge(0));
1862       GENSet.put(key, set);
1863     }
1864
1865   }
1866
1867   private void generateKILLSetForFlatCall(FlatCall fc,
1868       Hashtable<NTuple<Descriptor>, Set<WriteAge>> curr,
1869       Hashtable<NTuple<Descriptor>, Set<WriteAge>> KILLSet) {
1870
1871     Set<NTuple<Descriptor>> boundMustWriteSet = mapFlatNodeToBoundMustWriteSet.get(fc);
1872
1873     for (Iterator iterator = boundMustWriteSet.iterator(); iterator.hasNext();) {
1874       NTuple<Descriptor> key = (NTuple<Descriptor>) iterator.next();
1875       // TODO: shared location
1876       if (curr.get(key) != null) {
1877         KILLSet.put(key, curr.get(key));
1878       }
1879     }
1880
1881   }
1882
1883   private void computeNewMapping(Hashtable<NTuple<Descriptor>, Set<WriteAge>> curr,
1884       Hashtable<NTuple<Descriptor>, Set<WriteAge>> KILLSet,
1885       Hashtable<NTuple<Descriptor>, Set<WriteAge>> GENSet) {
1886
1887     for (Enumeration<NTuple<Descriptor>> e = KILLSet.keys(); e.hasMoreElements();) {
1888       NTuple<Descriptor> key = e.nextElement();
1889
1890       Set<WriteAge> writeAgeSet = curr.get(key);
1891       if (writeAgeSet == null) {
1892         writeAgeSet = new HashSet<WriteAge>();
1893         curr.put(key, writeAgeSet);
1894       }
1895       writeAgeSet.removeAll(KILLSet.get(key));
1896     }
1897
1898     for (Enumeration<NTuple<Descriptor>> e = GENSet.keys(); e.hasMoreElements();) {
1899       NTuple<Descriptor> key = e.nextElement();
1900
1901       Set<WriteAge> currWriteAgeSet = curr.get(key);
1902       if (currWriteAgeSet == null) {
1903         currWriteAgeSet = new HashSet<WriteAge>();
1904         curr.put(key, currWriteAgeSet);
1905       }
1906       currWriteAgeSet.addAll(GENSet.get(key));
1907     }
1908
1909   }
1910
1911   private void computeGENSetForWrite(NTuple<Descriptor> fldHeapPath,
1912       Hashtable<NTuple<Descriptor>, Set<WriteAge>> GENSet) {
1913
1914     // generate write age 0 for the field being written to
1915     Set<WriteAge> writeAgeSet = new HashSet<WriteAge>();
1916     writeAgeSet.add(new WriteAge(0));
1917     GENSet.put(fldHeapPath, writeAgeSet);
1918
1919   }
1920
1921   private void readValue(FlatNode fn, NTuple<Descriptor> hp,
1922       Hashtable<NTuple<Descriptor>, Hashtable<FlatNode, Boolean>> curr) {
1923     Hashtable<FlatNode, Boolean> gen = curr.get(hp);
1924     if (gen == null) {
1925       gen = new Hashtable<FlatNode, Boolean>();
1926       curr.put(hp, gen);
1927     }
1928     Boolean currentStatus = gen.get(fn);
1929     if (currentStatus == null) {
1930       gen.put(fn, Boolean.FALSE);
1931     } else {
1932       checkFlag(currentStatus.booleanValue(), fn, hp);
1933     }
1934
1935   }
1936
1937   private void computeKILLSetForWrite(Hashtable<NTuple<Descriptor>, Set<WriteAge>> curr,
1938       NTuple<Descriptor> hp, Hashtable<NTuple<Descriptor>, Set<WriteAge>> KILLSet) {
1939
1940     // removes all of heap path that starts with prefix 'hp'
1941     // since any reference overwrite along heap path gives overwriting side
1942     // effects on the value
1943
1944     Set<NTuple<Descriptor>> keySet = curr.keySet();
1945     for (Iterator<NTuple<Descriptor>> iter = keySet.iterator(); iter.hasNext();) {
1946       NTuple<Descriptor> key = iter.next();
1947       if (key.startsWith(hp)) {
1948         KILLSet.put(key, curr.get(key));
1949       }
1950     }
1951
1952   }
1953
1954   private void bindHeapPathCallerArgWithCalleeParam(FlatCall fc) {
1955     // compute all possible callee set
1956     // transform all READ/WRITE set from the any possible
1957     // callees to the caller
1958     calleeUnionBoundReadSet.clear();
1959     calleeIntersectBoundMustWriteSet.clear();
1960     calleeUnionBoundMayWriteSet.clear();
1961
1962     if (ssjava.isSSJavaUtil(fc.getMethod().getClassDesc())) {
1963       // ssjava util case!
1964       // have write effects on the first argument
1965       TempDescriptor arg = fc.getArg(0);
1966       NTuple<Descriptor> argHeapPath = computePath(arg);
1967       calleeIntersectBoundMustWriteSet.add(argHeapPath);
1968       calleeUnionBoundMayWriteSet.add(argHeapPath);
1969     } else {
1970       MethodDescriptor mdCallee = fc.getMethod();
1971       Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
1972       setPossibleCallees.addAll(callGraph.getMethods(mdCallee));
1973
1974       // create mapping from arg idx to its heap paths
1975       Hashtable<Integer, NTuple<Descriptor>> mapArgIdx2CallerArgHeapPath =
1976           new Hashtable<Integer, NTuple<Descriptor>>();
1977
1978       // arg idx is starting from 'this' arg
1979       if (fc.getThis() != null) {
1980         NTuple<Descriptor> thisHeapPath = mapHeapPath.get(fc.getThis());
1981         if (thisHeapPath == null) {
1982           // method is called without creating new flat node representing 'this'
1983           thisHeapPath = new NTuple<Descriptor>();
1984           thisHeapPath.add(fc.getThis());
1985         }
1986
1987         mapArgIdx2CallerArgHeapPath.put(Integer.valueOf(0), thisHeapPath);
1988       }
1989
1990       for (int i = 0; i < fc.numArgs(); i++) {
1991         TempDescriptor arg = fc.getArg(i);
1992         NTuple<Descriptor> argHeapPath = computePath(arg);
1993         mapArgIdx2CallerArgHeapPath.put(Integer.valueOf(i + 1), argHeapPath);
1994       }
1995
1996       for (Iterator iterator = setPossibleCallees.iterator(); iterator.hasNext();) {
1997         MethodDescriptor callee = (MethodDescriptor) iterator.next();
1998         FlatMethod calleeFlatMethod = state.getMethodFlat(callee);
1999
2000         // binding caller's args and callee's params
2001
2002         Set<NTuple<Descriptor>> calleeReadSet = mapFlatMethodToReadSet.get(calleeFlatMethod);
2003         if (calleeReadSet == null) {
2004           calleeReadSet = new HashSet<NTuple<Descriptor>>();
2005           mapFlatMethodToReadSet.put(calleeFlatMethod, calleeReadSet);
2006         }
2007
2008         Set<NTuple<Descriptor>> calleeMustWriteSet =
2009             mapFlatMethodToMustWriteSet.get(calleeFlatMethod);
2010
2011         if (calleeMustWriteSet == null) {
2012           calleeMustWriteSet = new HashSet<NTuple<Descriptor>>();
2013           mapFlatMethodToMustWriteSet.put(calleeFlatMethod, calleeMustWriteSet);
2014         }
2015
2016         Set<NTuple<Descriptor>> calleeMayWriteSet =
2017             mapFlatMethodToMayWriteSet.get(calleeFlatMethod);
2018
2019         if (calleeMayWriteSet == null) {
2020           calleeMayWriteSet = new HashSet<NTuple<Descriptor>>();
2021           mapFlatMethodToMayWriteSet.put(calleeFlatMethod, calleeMayWriteSet);
2022         }
2023
2024         Hashtable<Integer, TempDescriptor> mapParamIdx2ParamTempDesc =
2025             new Hashtable<Integer, TempDescriptor>();
2026         int offset = 0;
2027         if (calleeFlatMethod.getMethod().isStatic()) {
2028           // static method does not have implicit 'this' arg
2029           offset = 1;
2030         }
2031         for (int i = 0; i < calleeFlatMethod.numParameters(); i++) {
2032           TempDescriptor param = calleeFlatMethod.getParameter(i);
2033           mapParamIdx2ParamTempDesc.put(Integer.valueOf(i + offset), param);
2034         }
2035
2036         Set<NTuple<Descriptor>> calleeBoundReadSet =
2037             bindSet(calleeReadSet, mapParamIdx2ParamTempDesc, mapArgIdx2CallerArgHeapPath);
2038         // union of the current read set and the current callee's
2039         // read set
2040         calleeUnionBoundReadSet.addAll(calleeBoundReadSet);
2041
2042         Set<NTuple<Descriptor>> calleeBoundMustWriteSet =
2043             bindSet(calleeMustWriteSet, mapParamIdx2ParamTempDesc, mapArgIdx2CallerArgHeapPath);
2044         // intersection of the current overwrite set and the current
2045         // callee's
2046         // overwrite set
2047         merge(calleeIntersectBoundMustWriteSet, calleeBoundMustWriteSet);
2048
2049         Set<NTuple<Descriptor>> boundWriteSetFromCallee =
2050             bindSet(calleeMayWriteSet, mapParamIdx2ParamTempDesc, mapArgIdx2CallerArgHeapPath);
2051         calleeUnionBoundMayWriteSet.addAll(boundWriteSetFromCallee);
2052       }
2053
2054     }
2055
2056   }
2057
2058   private void bindHeapPathCallerArgWithCaleeParamForSharedLoc(MethodDescriptor mdCaller,
2059       FlatCall fc) {
2060
2061     calleeIntersectBoundSharedSet.clear();
2062     calleeUnionBoundDeleteSet.clear();
2063
2064     // if arg is not primitive type, we need to propagate maywritten set to
2065     // the caller's location path
2066
2067     MethodDescriptor mdCallee = fc.getMethod();
2068     Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
2069     setPossibleCallees.addAll(callGraph.getMethods(mdCallee));
2070
2071     // create mapping from arg idx to its heap paths
2072     Hashtable<Integer, NTuple<Descriptor>> mapArgIdx2CallerArgHeapPath =
2073         new Hashtable<Integer, NTuple<Descriptor>>();
2074
2075     // arg idx is starting from 'this' arg
2076     if (fc.getThis() != null) {
2077       NTuple<Descriptor> thisHeapPath = mapHeapPath.get(fc.getThis());
2078       if (thisHeapPath == null) {
2079         // method is called without creating new flat node representing 'this'
2080         thisHeapPath = new NTuple<Descriptor>();
2081         thisHeapPath.add(fc.getThis());
2082       }
2083
2084       mapArgIdx2CallerArgHeapPath.put(Integer.valueOf(0), thisHeapPath);
2085     }
2086
2087     for (int i = 0; i < fc.numArgs(); i++) {
2088       TempDescriptor arg = fc.getArg(i);
2089       NTuple<Descriptor> argHeapPath = computePath(arg);
2090       mapArgIdx2CallerArgHeapPath.put(Integer.valueOf(i + 1), argHeapPath);
2091     }
2092
2093     // create mapping from arg idx to its location paths
2094     Hashtable<Integer, NTuple<Location>> mapArgIdx2CallerAgLocationPath =
2095         new Hashtable<Integer, NTuple<Location>>();
2096
2097     // arg idx is starting from 'this' arg
2098     if (fc.getThis() != null) {
2099       NTuple<Location> thisLocationPath = deriveLocationTuple(mdCaller, fc.getThis());
2100       mapArgIdx2CallerAgLocationPath.put(Integer.valueOf(0), thisLocationPath);
2101     }
2102
2103     for (int i = 0; i < fc.numArgs(); i++) {
2104       TempDescriptor arg = fc.getArg(i);
2105       NTuple<Location> argLocationPath = deriveLocationTuple(mdCaller, arg);
2106       mapArgIdx2CallerAgLocationPath.put(Integer.valueOf(i + 1), argLocationPath);
2107     }
2108
2109     for (Iterator iterator = setPossibleCallees.iterator(); iterator.hasNext();) {
2110       MethodDescriptor callee = (MethodDescriptor) iterator.next();
2111       FlatMethod calleeFlatMethod = state.getMethodFlat(callee);
2112
2113       // binding caller's args and callee's params
2114
2115       Hashtable<Integer, TempDescriptor> mapParamIdx2ParamTempDesc =
2116           new Hashtable<Integer, TempDescriptor>();
2117       int offset = 0;
2118       if (calleeFlatMethod.getMethod().isStatic()) {
2119         // static method does not have implicit 'this' arg
2120         offset = 1;
2121       }
2122       for (int i = 0; i < calleeFlatMethod.numParameters(); i++) {
2123         TempDescriptor param = calleeFlatMethod.getParameter(i);
2124         mapParamIdx2ParamTempDesc.put(Integer.valueOf(i + offset), param);
2125       }
2126
2127       Set<Integer> keySet = mapArgIdx2CallerAgLocationPath.keySet();
2128       for (Iterator iterator2 = keySet.iterator(); iterator2.hasNext();) {
2129         Integer idx = (Integer) iterator2.next();
2130         NTuple<Location> callerArgLocationPath = mapArgIdx2CallerAgLocationPath.get(idx);
2131         NTuple<Descriptor> callerArgHeapPath = mapArgIdx2CallerArgHeapPath.get(idx);
2132
2133         TempDescriptor calleeParam = mapParamIdx2ParamTempDesc.get(idx);
2134         NTuple<Location> calleeLocationPath = deriveLocationTuple(mdCallee, calleeParam);
2135         SharedLocMap calleeDeleteSet = mapFlatMethodToDeleteSet.get(calleeFlatMethod);
2136         SharedLocMap calleeSharedLocMap = mapFlatMethodToSharedLocMap.get(calleeFlatMethod);
2137
2138         if (calleeDeleteSet != null) {
2139           createNewMappingOfDeleteSet(callerArgLocationPath, callerArgHeapPath, calleeLocationPath,
2140               calleeDeleteSet);
2141         }
2142
2143         if (calleeSharedLocMap != null) {
2144           createNewMappingOfSharedSet(callerArgLocationPath, callerArgHeapPath, calleeLocationPath,
2145               calleeSharedLocMap);
2146         }
2147
2148       }
2149
2150     }
2151
2152   }
2153
2154   private void createNewMappingOfDeleteSet(NTuple<Location> callerArgLocationPath,
2155       NTuple<Descriptor> callerArgHeapPath, NTuple<Location> calleeLocationPath,
2156       SharedLocMap calleeDeleteSet) {
2157
2158     SharedLocMap calleeParamDeleteSet = calleeDeleteSet.getHeapPathStartedWith(calleeLocationPath);
2159
2160     Set<NTuple<Location>> keySet = calleeParamDeleteSet.keySet();
2161     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
2162       NTuple<Location> calleeLocTupleKey = (NTuple<Location>) iterator.next();
2163       Set<NTuple<Descriptor>> heapPathSet = calleeParamDeleteSet.get(calleeLocTupleKey);
2164       for (Iterator iterator2 = heapPathSet.iterator(); iterator2.hasNext();) {
2165         NTuple<Descriptor> calleeHeapPath = (NTuple<Descriptor>) iterator2.next();
2166         calleeUnionBoundDeleteSet.addWrite(
2167             bindLocationPath(callerArgLocationPath, calleeLocTupleKey),
2168             bindHeapPath(callerArgHeapPath, calleeHeapPath));
2169       }
2170     }
2171
2172   }
2173
2174   private void createNewMappingOfSharedSet(NTuple<Location> callerArgLocationPath,
2175       NTuple<Descriptor> callerArgHeapPath, NTuple<Location> calleeLocationPath,
2176       SharedLocMap calleeSharedLocMap) {
2177
2178     SharedLocMap calleeParamSharedSet =
2179         calleeSharedLocMap.getHeapPathStartedWith(calleeLocationPath);
2180
2181     Set<NTuple<Location>> keySet = calleeParamSharedSet.keySet();
2182     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
2183       NTuple<Location> calleeLocTupleKey = (NTuple<Location>) iterator.next();
2184       Set<NTuple<Descriptor>> heapPathSet = calleeParamSharedSet.get(calleeLocTupleKey);
2185       Set<NTuple<Descriptor>> boundHeapPathSet = new HashSet<NTuple<Descriptor>>();
2186       for (Iterator iterator2 = heapPathSet.iterator(); iterator2.hasNext();) {
2187         NTuple<Descriptor> calleeHeapPath = (NTuple<Descriptor>) iterator2.next();
2188         boundHeapPathSet.add(bindHeapPath(callerArgHeapPath, calleeHeapPath));
2189       }
2190       calleeIntersectBoundSharedSet.intersect(
2191           bindLocationPath(callerArgLocationPath, calleeLocTupleKey), boundHeapPathSet);
2192     }
2193
2194   }
2195
2196   private NTuple<Location> bindLocationPath(NTuple<Location> start, NTuple<Location> end) {
2197     NTuple<Location> locPath = new NTuple<Location>();
2198     locPath.addAll(start);
2199     for (int i = 1; i < end.size(); i++) {
2200       locPath.add(end.get(i));
2201     }
2202     return locPath;
2203   }
2204
2205   private NTuple<Descriptor> bindHeapPath(NTuple<Descriptor> start, NTuple<Descriptor> end) {
2206     NTuple<Descriptor> heapPath = new NTuple<Descriptor>();
2207     heapPath.addAll(start);
2208     for (int i = 1; i < end.size(); i++) {
2209       heapPath.add(end.get(i));
2210     }
2211     return heapPath;
2212   }
2213
2214   private NTuple<Descriptor> bind(NTuple<Descriptor> calleeHeapPathKey,
2215       Hashtable<Integer, TempDescriptor> mapParamIdx2ParamTempDesc,
2216       Hashtable<Integer, NTuple<Descriptor>> mapCallerArgIdx2HeapPath) {
2217
2218     Set<Integer> keySet = mapCallerArgIdx2HeapPath.keySet();
2219     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
2220       Integer idx = (Integer) iterator.next();
2221       NTuple<Descriptor> callerArgHeapPath = mapCallerArgIdx2HeapPath.get(idx);
2222       TempDescriptor calleeParam = mapParamIdx2ParamTempDesc.get(idx);
2223       if (calleeHeapPathKey.startsWith(calleeParam)) {
2224         NTuple<Descriptor> boundElement = combine(callerArgHeapPath, calleeHeapPathKey);
2225         return boundElement;
2226       }
2227     }
2228     return null;
2229   }
2230
2231   private void checkFlag(boolean booleanValue, FlatNode fn, NTuple<Descriptor> hp) {
2232     if (booleanValue) {
2233       // the definitely written analysis only takes care about locations that
2234       // are written to inside of the SSJava loop
2235       for (Iterator iterator = calleeUnionBoundMayWriteSet.iterator(); iterator.hasNext();) {
2236         NTuple<Descriptor> write = (NTuple<Descriptor>) iterator.next();
2237         if (hp.startsWith(write)) {
2238           // it has write effect!
2239           // throw new Error(
2240           System.out
2241               .println("###"
2242                   + "There is a variable, which is reachable through references "
2243                   + hp
2244                   + ", who comes back to the same read statement without being overwritten at the out-most iteration at "
2245                   + methodContainingSSJavaLoop.getClassDesc().getSourceFileName() + "::"
2246                   + fn.getNumLine());
2247           debugcount++;
2248         }
2249       }
2250     }
2251   }
2252
2253   private void initialize() {
2254     // First, identify ssjava loop entrace
2255
2256     // no need to analyze method having ssjava loop
2257     methodContainingSSJavaLoop = ssjava.getMethodContainingSSJavaLoop();
2258
2259     FlatMethod fm = state.getMethodFlat(methodContainingSSJavaLoop);
2260     Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
2261     flatNodesToVisit.add(fm);
2262
2263     LoopFinder loopFinder = new LoopFinder(fm);
2264
2265     while (!flatNodesToVisit.isEmpty()) {
2266       FlatNode fn = flatNodesToVisit.iterator().next();
2267       flatNodesToVisit.remove(fn);
2268
2269       String label = (String) state.fn2labelMap.get(fn);
2270       if (label != null) {
2271
2272         if (label.equals(ssjava.SSJAVA)) {
2273           ssjavaLoopEntrance = fn;
2274           break;
2275         }
2276       }
2277
2278       for (int i = 0; i < fn.numNext(); i++) {
2279         FlatNode nn = fn.getNext(i);
2280         flatNodesToVisit.add(nn);
2281       }
2282     }
2283
2284     assert ssjavaLoopEntrance != null;
2285
2286     // assume that ssjava loop is top-level loop in method, not nested loop
2287     Set nestedLoop = loopFinder.nestedLoops();
2288     for (Iterator loopIter = nestedLoop.iterator(); loopIter.hasNext();) {
2289       LoopFinder lf = (LoopFinder) loopIter.next();
2290       if (lf.loopEntrances().iterator().next().equals(ssjavaLoopEntrance)) {
2291         ssjavaLoop = lf;
2292       }
2293     }
2294
2295     assert ssjavaLoop != null;
2296
2297     loopIncElements = (Set<FlatNode>) ssjavaLoop.loopIncElements();
2298
2299     // perform topological sort over the set of methods accessed by the main
2300     // event loop
2301     Set<MethodDescriptor> methodDescriptorsToAnalyze = new HashSet<MethodDescriptor>();
2302     methodDescriptorsToAnalyze.addAll(ssjava.getAnnotationRequireSet());
2303     sortedDescriptors = topologicalSort(methodDescriptorsToAnalyze);
2304   }
2305
2306   private void methodReadWriteSetAnalysis() {
2307     // perform method READ/OVERWRITE analysis
2308     LinkedList<MethodDescriptor> descriptorListToAnalyze =
2309         (LinkedList<MethodDescriptor>) sortedDescriptors.clone();
2310
2311     // current descriptors to visit in fixed-point interprocedural analysis,
2312     // prioritized by
2313     // dependency in the call graph
2314     methodDescriptorsToVisitStack.clear();
2315
2316     descriptorListToAnalyze.removeFirst();
2317
2318     Set<MethodDescriptor> methodDescriptorToVistSet = new HashSet<MethodDescriptor>();
2319     methodDescriptorToVistSet.addAll(descriptorListToAnalyze);
2320
2321     while (!descriptorListToAnalyze.isEmpty()) {
2322       MethodDescriptor md = descriptorListToAnalyze.removeFirst();
2323       methodDescriptorsToVisitStack.add(md);
2324     }
2325
2326     // analyze scheduled methods until there are no more to visit
2327     while (!methodDescriptorsToVisitStack.isEmpty()) {
2328       // start to analyze leaf node
2329       MethodDescriptor md = methodDescriptorsToVisitStack.pop();
2330       FlatMethod fm = state.getMethodFlat(md);
2331
2332       Set<NTuple<Descriptor>> readSet = new HashSet<NTuple<Descriptor>>();
2333       Set<NTuple<Descriptor>> mustWriteSet = new HashSet<NTuple<Descriptor>>();
2334       Set<NTuple<Descriptor>> mayWriteSet = new HashSet<NTuple<Descriptor>>();
2335
2336       methodReadWriteSet_analyzeMethod(fm, readSet, mustWriteSet, mayWriteSet);
2337
2338       Set<NTuple<Descriptor>> prevRead = mapFlatMethodToReadSet.get(fm);
2339       Set<NTuple<Descriptor>> prevMustWrite = mapFlatMethodToMustWriteSet.get(fm);
2340       Set<NTuple<Descriptor>> prevMayWrite = mapFlatMethodToMayWriteSet.get(fm);
2341
2342       if (!(readSet.equals(prevRead) && mustWriteSet.equals(prevMustWrite) && mayWriteSet
2343           .equals(prevMayWrite))) {
2344         mapFlatMethodToReadSet.put(fm, readSet);
2345         mapFlatMethodToMustWriteSet.put(fm, mustWriteSet);
2346         mapFlatMethodToMayWriteSet.put(fm, mayWriteSet);
2347
2348         // results for callee changed, so enqueue dependents caller for
2349         // further
2350         // analysis
2351         Iterator<MethodDescriptor> depsItr = getDependents(md).iterator();
2352         while (depsItr.hasNext()) {
2353           MethodDescriptor methodNext = depsItr.next();
2354           if (!methodDescriptorsToVisitStack.contains(methodNext)
2355               && methodDescriptorToVistSet.contains(methodNext)) {
2356             methodDescriptorsToVisitStack.add(methodNext);
2357           }
2358
2359         }
2360
2361       }
2362
2363     }
2364
2365     methodReadWriteSetAnalysisToEventLoopBody();
2366
2367   }
2368
2369   private void methodReadWriteSet_analyzeMethod(FlatMethod fm, Set<NTuple<Descriptor>> readSet,
2370       Set<NTuple<Descriptor>> mustWriteSet, Set<NTuple<Descriptor>> mayWriteSet) {
2371     if (state.SSJAVADEBUG) {
2372       System.out.println("SSJAVA: Definitely written Analyzing: " + fm);
2373     }
2374
2375     methodReadWriteSet_analyzeBody(fm, readSet, mustWriteSet, mayWriteSet, false);
2376
2377   }
2378
2379   private void methodReadWriteSetAnalysisToEventLoopBody() {
2380
2381     // perform method read/write analysis for Event Loop Body
2382
2383     FlatMethod flatMethodContainingSSJavaLoop = state.getMethodFlat(methodContainingSSJavaLoop);
2384
2385     if (state.SSJAVADEBUG) {
2386       System.out.println("SSJAVA: Definitely written Event Loop Analyzing: "
2387           + flatMethodContainingSSJavaLoop);
2388     }
2389
2390     Set<NTuple<Descriptor>> readSet = new HashSet<NTuple<Descriptor>>();
2391     Set<NTuple<Descriptor>> mustWriteSet = new HashSet<NTuple<Descriptor>>();
2392     Set<NTuple<Descriptor>> mayWriteSet = new HashSet<NTuple<Descriptor>>();
2393
2394     mapFlatMethodToReadSet.put(flatMethodContainingSSJavaLoop, readSet);
2395     mapFlatMethodToMustWriteSet.put(flatMethodContainingSSJavaLoop, mustWriteSet);
2396     mapFlatMethodToMayWriteSet.put(flatMethodContainingSSJavaLoop, mayWriteSet);
2397
2398     methodReadWriteSet_analyzeBody(ssjavaLoopEntrance, readSet, mustWriteSet, mayWriteSet, true);
2399
2400   }
2401
2402   private void methodReadWriteSet_analyzeBody(FlatNode startNode, Set<NTuple<Descriptor>> readSet,
2403       Set<NTuple<Descriptor>> mustWriteSet, Set<NTuple<Descriptor>> mayWriteSet,
2404       boolean isEventLoopBody) {
2405
2406     // intraprocedural analysis
2407     Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
2408     flatNodesToVisit.add(startNode);
2409
2410     while (!flatNodesToVisit.isEmpty()) {
2411       FlatNode fn = flatNodesToVisit.iterator().next();
2412       flatNodesToVisit.remove(fn);
2413
2414       Set<NTuple<Descriptor>> currMustWriteSet = new HashSet<NTuple<Descriptor>>();
2415
2416       for (int i = 0; i < fn.numPrev(); i++) {
2417         FlatNode prevFn = fn.getPrev(i);
2418         Set<NTuple<Descriptor>> in = mapFlatNodeToMustWriteSet.get(prevFn);
2419         if (in != null) {
2420           merge(currMustWriteSet, in);
2421         }
2422       }
2423
2424       methodReadWriteSet_nodeActions(fn, currMustWriteSet, readSet, mustWriteSet, mayWriteSet,
2425           isEventLoopBody);
2426
2427       Set<NTuple<Descriptor>> mustSetPrev = mapFlatNodeToMustWriteSet.get(fn);
2428
2429       if (!currMustWriteSet.equals(mustSetPrev)) {
2430         mapFlatNodeToMustWriteSet.put(fn, currMustWriteSet);
2431         for (int i = 0; i < fn.numNext(); i++) {
2432           FlatNode nn = fn.getNext(i);
2433           if ((!isEventLoopBody) || loopIncElements.contains(nn)) {
2434             flatNodesToVisit.add(nn);
2435           }
2436
2437         }
2438       }
2439
2440     }
2441
2442   }
2443
2444   private void methodReadWriteSet_nodeActions(FlatNode fn,
2445       Set<NTuple<Descriptor>> currMustWriteSet, Set<NTuple<Descriptor>> readSet,
2446       Set<NTuple<Descriptor>> mustWriteSet, Set<NTuple<Descriptor>> mayWriteSet,
2447       boolean isEventLoopBody) {
2448
2449     TempDescriptor lhs;
2450     TempDescriptor rhs;
2451     FieldDescriptor fld;
2452
2453     switch (fn.kind()) {
2454     case FKind.FlatMethod: {
2455
2456       // set up initial heap paths for method parameters
2457       FlatMethod fm = (FlatMethod) fn;
2458       for (int i = 0; i < fm.numParameters(); i++) {
2459         TempDescriptor param = fm.getParameter(i);
2460         NTuple<Descriptor> heapPath = new NTuple<Descriptor>();
2461         heapPath.add(param);
2462         mapHeapPath.put(param, heapPath);
2463       }
2464     }
2465       break;
2466
2467     case FKind.FlatOpNode: {
2468       FlatOpNode fon = (FlatOpNode) fn;
2469       // for a normal assign node, need to propagate lhs's heap path to
2470       // rhs
2471       if (fon.getOp().getOp() == Operation.ASSIGN) {
2472         rhs = fon.getLeft();
2473         lhs = fon.getDest();
2474
2475         NTuple<Descriptor> rhsHeapPath = mapHeapPath.get(rhs);
2476         if (rhsHeapPath != null) {
2477           mapHeapPath.put(lhs, mapHeapPath.get(rhs));
2478         } else {
2479           NTuple<Descriptor> heapPath = new NTuple<Descriptor>();
2480           heapPath.add(rhs);
2481           mapHeapPath.put(lhs, heapPath);
2482         }
2483
2484         // shared loc extension
2485         if (isEventLoopBody) {
2486           if (!lhs.getSymbol().startsWith("neverused") && rhs.getType().isImmutable()) {
2487
2488             if (rhs.getType().getExtension() instanceof Location
2489                 && lhs.getType().getExtension() instanceof CompositeLocation) {
2490               // rhs is field!
2491               Location rhsLoc = (Location) rhs.getType().getExtension();
2492
2493               CompositeLocation lhsCompLoc = (CompositeLocation) lhs.getType().getExtension();
2494               Location dstLoc = lhsCompLoc.get(lhsCompLoc.getSize() - 1);
2495
2496               NTuple<Descriptor> heapPath = new NTuple<Descriptor>();
2497               for (int i = 0; i < rhsHeapPath.size() - 1; i++) {
2498                 heapPath.add(rhsHeapPath.get(i));
2499               }
2500
2501               NTuple<Descriptor> writeHeapPath = new NTuple<Descriptor>();
2502               writeHeapPath.addAll(heapPath);
2503               writeHeapPath.add(lhs);
2504
2505               System.out.println("VAR WRITE:" + fn);
2506               System.out.println("LHS TYPE EXTENSION=" + lhs.getType().getExtension());
2507               System.out.println("RHS TYPE EXTENSION=" + rhs.getType().getExtension()
2508                   + " HEAPPATH=" + rhsHeapPath);
2509
2510               // TODO
2511               // computing gen/kill set
2512               // computeKILLSetForWrite(currSharedLocMapping, heapPath, dstLoc,
2513               // killSetSharedLoc);
2514               // if (!dstLoc.equals(rhsLoc)) {
2515               // computeGENSetForHigherWrite(currSharedLocMapping, heapPath,
2516               // dstLoc, lhs,
2517               // genSetSharedLoc);
2518               // deleteSet.remove(writeHeapPath);
2519               // } else {
2520               // computeGENSetForSharedWrite(currSharedLocMapping, heapPath,
2521               // dstLoc, lhs,
2522               // genSetSharedLoc);
2523               // deleteSet.add(writeHeapPath);
2524               // }
2525
2526             }
2527           }
2528         }
2529
2530       }
2531     }
2532       break;
2533
2534     case FKind.FlatElementNode:
2535     case FKind.FlatFieldNode: {
2536
2537       // x=y.f;
2538
2539       if (fn.kind() == FKind.FlatFieldNode) {
2540         FlatFieldNode ffn = (FlatFieldNode) fn;
2541         lhs = ffn.getDst();
2542         rhs = ffn.getSrc();
2543         fld = ffn.getField();
2544       } else {
2545         FlatElementNode fen = (FlatElementNode) fn;
2546         lhs = fen.getDst();
2547         rhs = fen.getSrc();
2548         TypeDescriptor td = rhs.getType().dereference();
2549         fld = getArrayField(td);
2550       }
2551
2552       if (fld.isFinal()) {
2553         // if field is final no need to check
2554         break;
2555       }
2556
2557       // set up heap path
2558       NTuple<Descriptor> srcHeapPath = mapHeapPath.get(rhs);
2559       if (srcHeapPath != null) {
2560         // if lhs srcHeapPath is null, it means that it is not reachable from
2561         // callee's parameters. so just ignore it
2562
2563         NTuple<Descriptor> readingHeapPath = new NTuple<Descriptor>(srcHeapPath.getList());
2564         readingHeapPath.add(fld);
2565         mapHeapPath.put(lhs, readingHeapPath);
2566
2567         // read (x.f)
2568         if (fld.getType().isImmutable()) {
2569           // if WT doesnot have hp(x.f), add hp(x.f) to READ
2570           if (!currMustWriteSet.contains(readingHeapPath)) {
2571             readSet.add(readingHeapPath);
2572           }
2573         }
2574
2575         // no need to kill hp(x.f) from WT
2576       }
2577
2578     }
2579       break;
2580
2581     case FKind.FlatSetFieldNode:
2582     case FKind.FlatSetElementNode: {
2583
2584       // x.f=y;
2585
2586       if (fn.kind() == FKind.FlatSetFieldNode) {
2587         FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
2588         lhs = fsfn.getDst();
2589         fld = fsfn.getField();
2590         rhs = fsfn.getSrc();
2591       } else {
2592         FlatSetElementNode fsen = (FlatSetElementNode) fn;
2593         lhs = fsen.getDst();
2594         rhs = fsen.getSrc();
2595         TypeDescriptor td = lhs.getType().dereference();
2596         fld = getArrayField(td);
2597       }
2598
2599       // set up heap path
2600       NTuple<Descriptor> lhsHeapPath = mapHeapPath.get(lhs);
2601
2602       if (lhsHeapPath != null) {
2603         // if lhs heap path is null, it means that it is not reachable from
2604         // callee's parameters. so just ignore it
2605         NTuple<Descriptor> fldHeapPath = new NTuple<Descriptor>(lhsHeapPath.getList());
2606         fldHeapPath.add(fld);
2607         mapHeapPath.put(fld, fldHeapPath);
2608
2609         // write(x.f)
2610         // need to add hp(y) to WT
2611         currMustWriteSet.add(fldHeapPath);
2612         mayWriteSet.add(fldHeapPath);
2613
2614       }
2615
2616     }
2617       break;
2618
2619     case FKind.FlatCall: {
2620
2621       FlatCall fc = (FlatCall) fn;
2622
2623       bindHeapPathCallerArgWithCalleeParam(fc);
2624
2625       mapFlatNodeToBoundReadSet.put(fn, calleeUnionBoundReadSet);
2626       mapFlatNodeToBoundMustWriteSet.put(fn, calleeIntersectBoundMustWriteSet);
2627       mapFlatNodeToBoundMayWriteSet.put(fn, calleeUnionBoundMayWriteSet);
2628
2629       // add heap path, which is an element of READ_bound set and is not
2630       // an
2631       // element of WT set, to the caller's READ set
2632       for (Iterator iterator = calleeUnionBoundReadSet.iterator(); iterator.hasNext();) {
2633         NTuple<Descriptor> read = (NTuple<Descriptor>) iterator.next();
2634         if (!currMustWriteSet.contains(read)) {
2635           readSet.add(read);
2636         }
2637       }
2638
2639       // add heap path, which is an element of OVERWRITE_bound set, to the
2640       // caller's WT set
2641       for (Iterator iterator = calleeIntersectBoundMustWriteSet.iterator(); iterator.hasNext();) {
2642         NTuple<Descriptor> write = (NTuple<Descriptor>) iterator.next();
2643         currMustWriteSet.add(write);
2644       }
2645
2646       // add heap path, which is an element of WRITE_BOUND set, to the
2647       // caller's writeSet
2648       for (Iterator iterator = calleeUnionBoundMayWriteSet.iterator(); iterator.hasNext();) {
2649         NTuple<Descriptor> write = (NTuple<Descriptor>) iterator.next();
2650         mayWriteSet.add(write);
2651       }
2652
2653     }
2654       break;
2655
2656     case FKind.FlatExit: {
2657       // merge the current written set with OVERWRITE set
2658       merge(mustWriteSet, currMustWriteSet);
2659     }
2660       break;
2661
2662     }
2663
2664   }
2665
2666   public NTuple<Descriptor> getPrefix(NTuple<Descriptor> in) {
2667     return in.subList(0, in.size() - 1);
2668   }
2669
2670   public NTuple<Descriptor> getSuffix(NTuple<Descriptor> in) {
2671     return in.subList(in.size() - 1, in.size());
2672   }
2673
2674   static public FieldDescriptor getArrayField(TypeDescriptor td) {
2675     FieldDescriptor fd = mapTypeToArrayField.get(td);
2676     if (fd == null) {
2677       fd =
2678           new FieldDescriptor(new Modifiers(Modifiers.PUBLIC), td, arrayElementFieldName, null,
2679               false);
2680       mapTypeToArrayField.put(td, fd);
2681     }
2682     return fd;
2683   }
2684
2685   private void mergeSharedLocationAnaylsis(ClearingSummary curr, Set<ClearingSummary> inSet) {
2686     if (inSet.size() == 0) {
2687       return;
2688     }
2689     Hashtable<Pair<NTuple<Descriptor>, Location>, Boolean> mapHeapPathLoc2Flag =
2690         new Hashtable<Pair<NTuple<Descriptor>, Location>, Boolean>();
2691
2692     for (Iterator inIterator = inSet.iterator(); inIterator.hasNext();) {
2693
2694       ClearingSummary inTable = (ClearingSummary) inIterator.next();
2695
2696       Set<NTuple<Descriptor>> keySet = inTable.keySet();
2697
2698       for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
2699         NTuple<Descriptor> hpKey = (NTuple<Descriptor>) iterator.next();
2700         SharedStatus inState = inTable.get(hpKey);
2701         SharedStatus currState = curr.get(hpKey);
2702         if (currState == null) {
2703           currState = new SharedStatus();
2704           curr.put(hpKey, currState);
2705         }
2706
2707         currState.merge(inState);
2708
2709         Set<Location> locSet = inState.getMap().keySet();
2710         for (Iterator iterator2 = locSet.iterator(); iterator2.hasNext();) {
2711           Location loc = (Location) iterator2.next();
2712           Pair<Set<Descriptor>, Boolean> pair = inState.getMap().get(loc);
2713           boolean inFlag = pair.getSecond().booleanValue();
2714
2715           Pair<NTuple<Descriptor>, Location> flagKey =
2716               new Pair<NTuple<Descriptor>, Location>(hpKey, loc);
2717           Boolean current = mapHeapPathLoc2Flag.get(flagKey);
2718           if (current == null) {
2719             current = new Boolean(true);
2720           }
2721           boolean newInFlag = current.booleanValue() & inFlag;
2722           mapHeapPathLoc2Flag.put(flagKey, Boolean.valueOf(newInFlag));
2723         }
2724
2725       }
2726
2727     }
2728
2729     // merge flag status
2730     Set<NTuple<Descriptor>> hpKeySet = curr.keySet();
2731     for (Iterator iterator = hpKeySet.iterator(); iterator.hasNext();) {
2732       NTuple<Descriptor> hpKey = (NTuple<Descriptor>) iterator.next();
2733       SharedStatus currState = curr.get(hpKey);
2734       Set<Location> locKeySet = currState.getMap().keySet();
2735       for (Iterator iterator2 = locKeySet.iterator(); iterator2.hasNext();) {
2736         Location locKey = (Location) iterator2.next();
2737         Pair<Set<Descriptor>, Boolean> pair = currState.getMap().get(locKey);
2738         boolean currentFlag = pair.getSecond().booleanValue();
2739         Boolean inFlag = mapHeapPathLoc2Flag.get(new Pair(hpKey, locKey));
2740         if (inFlag != null) {
2741           boolean newFlag = currentFlag | inFlag.booleanValue();
2742           if (currentFlag != newFlag) {
2743             currState.getMap().put(locKey, new Pair(pair.getFirst(), new Boolean(newFlag)));
2744           }
2745         }
2746       }
2747     }
2748
2749   }
2750
2751   private void merge(Set<NTuple<Descriptor>> curr, Set<NTuple<Descriptor>> in) {
2752     if (curr.isEmpty()) {
2753       // set has a special initial value which covers all possible
2754       // elements
2755       // For the first time of intersection, we can take all previous set
2756       curr.addAll(in);
2757     } else {
2758       // otherwise, current set is the intersection of the two sets
2759       curr.retainAll(in);
2760     }
2761
2762   }
2763
2764   // combine two heap path
2765   private NTuple<Descriptor> combine(NTuple<Descriptor> callerIn, NTuple<Descriptor> calleeIn) {
2766     NTuple<Descriptor> combined = new NTuple<Descriptor>();
2767
2768     for (int i = 0; i < callerIn.size(); i++) {
2769       combined.add(callerIn.get(i));
2770     }
2771
2772     // the first element of callee's heap path represents parameter
2773     // so we skip the first one since it is already added from caller's heap
2774     // path
2775     for (int i = 1; i < calleeIn.size(); i++) {
2776       combined.add(calleeIn.get(i));
2777     }
2778
2779     return combined;
2780   }
2781
2782   private Set<NTuple<Descriptor>> bindSet(Set<NTuple<Descriptor>> calleeSet,
2783       Hashtable<Integer, TempDescriptor> mapParamIdx2ParamTempDesc,
2784       Hashtable<Integer, NTuple<Descriptor>> mapCallerArgIdx2HeapPath) {
2785
2786     Set<NTuple<Descriptor>> boundedCalleeSet = new HashSet<NTuple<Descriptor>>();
2787
2788     Set<Integer> keySet = mapCallerArgIdx2HeapPath.keySet();
2789     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
2790       Integer idx = (Integer) iterator.next();
2791
2792       NTuple<Descriptor> callerArgHeapPath = mapCallerArgIdx2HeapPath.get(idx);
2793       TempDescriptor calleeParam = mapParamIdx2ParamTempDesc.get(idx);
2794       for (Iterator iterator2 = calleeSet.iterator(); iterator2.hasNext();) {
2795         NTuple<Descriptor> element = (NTuple<Descriptor>) iterator2.next();
2796         if (element.startsWith(calleeParam)) {
2797           NTuple<Descriptor> boundElement = combine(callerArgHeapPath, element);
2798           boundedCalleeSet.add(boundElement);
2799         }
2800
2801       }
2802
2803     }
2804     return boundedCalleeSet;
2805
2806   }
2807
2808   // Borrowed it from disjoint analysis
2809   private LinkedList<MethodDescriptor> topologicalSort(Set<MethodDescriptor> toSort) {
2810
2811     Set<MethodDescriptor> discovered = new HashSet<MethodDescriptor>();
2812
2813     LinkedList<MethodDescriptor> sorted = new LinkedList<MethodDescriptor>();
2814
2815     Iterator<MethodDescriptor> itr = toSort.iterator();
2816     while (itr.hasNext()) {
2817       MethodDescriptor d = itr.next();
2818
2819       if (!discovered.contains(d)) {
2820         dfsVisit(d, toSort, sorted, discovered);
2821       }
2822     }
2823
2824     return sorted;
2825   }
2826
2827   // While we're doing DFS on call graph, remember
2828   // dependencies for efficient queuing of methods
2829   // during interprocedural analysis:
2830   //
2831   // a dependent of a method decriptor d for this analysis is:
2832   // 1) a method or task that invokes d
2833   // 2) in the descriptorsToAnalyze set
2834   private void dfsVisit(MethodDescriptor md, Set<MethodDescriptor> toSort,
2835       LinkedList<MethodDescriptor> sorted, Set<MethodDescriptor> discovered) {
2836
2837     discovered.add(md);
2838
2839     Iterator itr = callGraph.getCallerSet(md).iterator();
2840     while (itr.hasNext()) {
2841       MethodDescriptor dCaller = (MethodDescriptor) itr.next();
2842       // only consider callers in the original set to analyze
2843       if (!toSort.contains(dCaller)) {
2844         continue;
2845       }
2846       if (!discovered.contains(dCaller)) {
2847         addDependent(md, // callee
2848             dCaller // caller
2849         );
2850
2851         dfsVisit(dCaller, toSort, sorted, discovered);
2852       }
2853     }
2854
2855     // for leaf-nodes last now!
2856     sorted.addLast(md);
2857   }
2858
2859   // a dependent of a method decriptor d for this analysis is:
2860   // 1) a method or task that invokes d
2861   // 2) in the descriptorsToAnalyze set
2862   private void addDependent(MethodDescriptor callee, MethodDescriptor caller) {
2863     Set<MethodDescriptor> deps = mapDescriptorToSetDependents.get(callee);
2864     if (deps == null) {
2865       deps = new HashSet<MethodDescriptor>();
2866     }
2867     deps.add(caller);
2868     mapDescriptorToSetDependents.put(callee, deps);
2869   }
2870
2871   private Set<MethodDescriptor> getDependents(MethodDescriptor callee) {
2872     Set<MethodDescriptor> deps = mapDescriptorToSetDependents.get(callee);
2873     if (deps == null) {
2874       deps = new HashSet<MethodDescriptor>();
2875       mapDescriptorToSetDependents.put(callee, deps);
2876     }
2877     return deps;
2878   }
2879
2880   private NTuple<Descriptor> computePath(Descriptor td) {
2881     // generate proper path fot input td
2882     // if td is local variable, it just generate one element tuple path
2883     if (mapHeapPath.containsKey(td)) {
2884       return mapHeapPath.get(td);
2885     } else {
2886       NTuple<Descriptor> path = new NTuple<Descriptor>();
2887       path.add(td);
2888       return path;
2889     }
2890   }
2891
2892   private NTuple<Location> deriveThisLocationTuple(MethodDescriptor md) {
2893     String thisLocIdentifier = ssjava.getMethodLattice(md).getThisLoc();
2894     Location thisLoc = new Location(md, thisLocIdentifier);
2895     NTuple<Location> locTuple = new NTuple<Location>();
2896     locTuple.add(thisLoc);
2897     return locTuple;
2898   }
2899
2900   private NTuple<Location> deriveLocationTuple(MethodDescriptor md, TempDescriptor td) {
2901
2902     assert td.getType() != null;
2903
2904     if (mapDescriptorToLocationPath.containsKey(td)) {
2905       return mapDescriptorToLocationPath.get(td);
2906     } else {
2907       if (td.getSymbol().startsWith("this")) {
2908         return deriveThisLocationTuple(md);
2909       } else {
2910         NTuple<Location> locTuple =
2911             ((SSJavaType) td.getType().getExtension()).getCompLoc().getTuple();
2912         return locTuple;
2913       }
2914     }
2915
2916   }
2917
2918 }