fix bug w/ recycling + RCR
[IRC.git] / Robust / src / IR / Flat / RuntimeConflictResolver.java
1 package IR.Flat;
2 import java.io.File;
3 import java.io.FileNotFoundException;
4 import java.io.PrintWriter;
5 import java.util.ArrayList;
6 import java.util.Collection;
7 import java.util.HashSet;
8 import java.util.Hashtable;
9 import java.util.Iterator;
10 import java.util.Set;
11 import java.util.Vector;
12 import Util.Tuple;
13 import Analysis.Disjoint.*;
14 import Analysis.MLP.CodePlan;
15 import IR.TypeDescriptor;
16 import Analysis.OoOJava.OoOJavaAnalysis;
17
18 /* An instance of this class manages all OoOJava coarse-grained runtime conflicts
19  * by generating C-code to either rule out the conflict at runtime or resolve one.
20  * 
21  * How to Use:
22  * 1) Instantiate singleton object (String input is to specify output dir)
23  * 2) Call setGlobalEffects setGlobalEffects(Hashtable<Taint, Set<Effect>> ) ONCE
24  * 3) Input SESE blocks, for each block:
25  *    3a) call addToTraverseToDoList(FlatSESEEnterNode , ReachGraph , Hashtable<Taint, Set<Effect>>) for the seseBlock
26  *    3b) call String getTraverserInvocation(TempDescriptor, String, FlatSESEEnterNode) to get the name of the traverse method in C
27  * 4) Call void close() 
28  * Note: All computation is done upon closing the object. Steps 1-3 only input data
29  */
30 public class RuntimeConflictResolver {
31   public static final boolean javaDebug = true;
32   public static final boolean cSideDebug = true;
33   
34   private PrintWriter cFile;
35   private PrintWriter headerFile;
36   private static final String hashAndQueueCFileDir = "oooJava/";
37   //This keeps track of taints we've traversed to prevent printing duplicate traverse functions
38   //The Integer keeps track of the weakly connected group it's in (used in enumerateHeapRoots)
39   private Hashtable<Taint, Integer> doneTaints;
40   private Hashtable<Tuple, Integer> idMap=new Hashtable<Tuple,Integer>();
41   private Hashtable<Taint, Set<Effect>> globalEffects;
42   private Hashtable<Taint, Set<Effect>> globalConflicts;
43   private ArrayList<TraversalInfo> toTraverse;
44
45   public int currentID=1;
46
47   // initializing variables can be found in printHeader()
48   private static final String getAllocSiteInC = "->allocsite";
49   private static final String queryVistedHashtable = "hashRCRInsert";
50   private static final String addToQueueInC = "enqueueRCRQueue(";
51   private static final String dequeueFromQueueInC = "dequeueRCRQueue()";
52   private static final String clearQueue = "resetRCRQueue()";
53   // Make hashtable; hashRCRCreate(unsigned int size, double loadfactor)
54   private static final String mallocVisitedHashtable = "hashRCRCreate(128, 0.75)";
55   private static final String deallocVisitedHashTable = "hashRCRDelete()";
56   private static final String resetVisitedHashTable = "hashRCRreset()";
57   
58   // Hashtable provides fast access to heaproot # lookups
59   private Hashtable<Taint, WeaklyConectedHRGroup> connectedHRHash;
60   private ArrayList<WeaklyConectedHRGroup> num2WeaklyConnectedHRGroup;
61   private int traverserIDCounter;
62   private int weaklyConnectedHRCounter;
63   private ArrayList<TaintAndInternalHeapStructure> pendingPrintout;
64   private EffectsTable effectsLookupTable;
65   private OoOJavaAnalysis oooa;
66
67   public RuntimeConflictResolver(String buildir, OoOJavaAnalysis oooa) throws FileNotFoundException {
68     String outputFile = buildir + "RuntimeConflictResolver";
69     this.oooa=oooa;
70
71     cFile = new PrintWriter(new File(outputFile + ".c"));
72     headerFile = new PrintWriter(new File(outputFile + ".h"));
73     
74     cFile.println("#include \"" + hashAndQueueCFileDir + "hashRCR.h\"\n#include \""
75         + hashAndQueueCFileDir + "Queue_RCR.h\"\n#include <stdlib.h>");
76     cFile.println("#include \"classdefs.h\"");
77     cFile.println("#include \"structdefs.h\"");
78     cFile.println("#include \"mlp_runtime.h\"");
79     cFile.println("#include \"RuntimeConflictResolver.h\"");
80     cFile.println("#include \"hashStructure.h\"");
81     
82     headerFile.println("#ifndef __3_RCR_H_");
83     headerFile.println("#define __3_RCR_H_");
84     
85     doneTaints = new Hashtable<Taint, Integer>();
86     connectedHRHash = new Hashtable<Taint, WeaklyConectedHRGroup>();
87     
88     traverserIDCounter = 1;
89     weaklyConnectedHRCounter = 0;
90     pendingPrintout = new ArrayList<TaintAndInternalHeapStructure>();
91     toTraverse = new ArrayList<TraversalInfo>();
92     globalConflicts = new Hashtable<Taint, Set<Effect>>(); 
93     //Note: globalEffects is not instantiated since it'll be passed in whole while conflicts comes in chunks
94   }
95
96   public void setGlobalEffects(Hashtable<Taint, Set<Effect>> effects) {
97     globalEffects = effects;
98     
99     if(javaDebug) {
100       System.out.println("============EFFECTS LIST AS PASSED IN============");
101       for(Taint t: globalEffects.keySet()) {
102         System.out.println("For Taint " + t);
103         for(Effect e: globalEffects.get(t)) {
104           System.out.println("\t" + e);
105         }
106       }
107       System.out.println("====================END  LIST====================");
108     }
109   }
110
111   public void init() {
112     // Go through the SESE's
113     for (Iterator<FlatSESEEnterNode> seseit = oooa.getAllSESEs().iterator(); seseit.hasNext();) {
114       FlatSESEEnterNode fsen = seseit.next();
115       Analysis.OoOJava.ConflictGraph conflictGraph;
116       Hashtable<Taint, Set<Effect>> conflicts;
117       System.out.println("-------");
118       System.out.println(fsen);
119       System.out.println(fsen.getIsCallerSESEplaceholder());
120       System.out.println(fsen.getParent());
121
122       if (fsen.getParent() != null) {
123         conflictGraph = oooa.getConflictGraph(fsen.getParent());
124         System.out.println("CG=" + conflictGraph);
125         if (conflictGraph != null)
126           System.out.println("Conflicts=" + conflictGraph.getConflictEffectSet(fsen));
127       }
128
129       if (!fsen.getIsCallerSESEplaceholder() && fsen.getParent() != null
130           && (conflictGraph = oooa.getConflictGraph(fsen.getParent())) != null
131           && (conflicts = conflictGraph.getConflictEffectSet(fsen)) != null) {
132         FlatMethod fm = fsen.getfmEnclosing();
133         ReachGraph rg = oooa.getDisjointAnalysis().getReachGraph(fm.getMethod());
134         if (cSideDebug)
135           rg.writeGraph("RCR_RG_SESE_DEBUG");
136
137         addToTraverseToDoList(fsen, rg, conflicts);
138       }
139     }
140     // Go through the stall sites
141     for (Iterator<FlatNode> codeit = oooa.getNodesWithPlans().iterator(); codeit.hasNext();) {
142       FlatNode fn = codeit.next();
143       CodePlan cp = oooa.getCodePlan(fn);
144       FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
145       Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(currentSESE);
146
147       if (graph != null) {
148         Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
149         Set<Analysis.OoOJava.WaitingElement> waitingElementSet =
150             graph.getStallSiteWaitingElementSet(fn, seseLockSet);
151
152         if (waitingElementSet.size() > 0) {
153           for (Iterator<Analysis.OoOJava.WaitingElement> iterator = waitingElementSet.iterator(); iterator.hasNext();) {
154             Analysis.OoOJava.WaitingElement waitingElement =
155                 (Analysis.OoOJava.WaitingElement) iterator.next();
156
157             Analysis.OoOJava.ConflictGraph conflictGraph = graph;
158             Hashtable<Taint, Set<Effect>> conflicts;
159             ReachGraph rg = oooa.getDisjointAnalysis().getReachGraph(currentSESE.getmdEnclosing());
160             if (cSideDebug) {
161               rg.writeGraph("RCR_RG_STALLSITE_DEBUG");
162             }
163             if ((conflictGraph != null) && (conflicts = graph.getConflictEffectSet(fn)) != null
164                 && (rg != null)) {
165               addToTraverseToDoList(fn, waitingElement.getTempDesc(), rg, conflicts);
166             }
167           }
168         }
169       }
170     }
171
172     buildEffectsLookupStructure();
173     runAllTraversals();
174   }
175   
176   /*
177    * Basic Strategy:
178    * 1) Get global effects and conflicts 
179    * 2) Create a hash structure (EffectsTable) to manage effects (hashed by affected Allocsite, then taint, then field)
180    *     2a) Use Effects to verify we can access something (reads)
181    *     2b) Use conflicts to mark conflicts (read/write/strongupdate)
182    *     2c) At second level of hash, store Heaproots that can cause conflicts at the field
183    * 3) Walk hash structure to identify and enumerate weakly connected groups and generate waiting queue slots. 
184    * 4) Build internal representation of the rgs (pruned)
185    * 5) Print c methods by walking internal representation
186    */
187   
188   public void addToTraverseToDoList(FlatSESEEnterNode rblock, ReachGraph rg, Hashtable<Taint, Set<Effect>> conflicts) {
189     //Add to todo list
190     toTraverse.add(new TraversalInfo(rblock, rg));
191
192     //Add to Global conflicts
193     for(Taint t: conflicts.keySet()) {
194       if(globalConflicts.containsKey(t)) {
195         globalConflicts.get(t).addAll(conflicts.get(t));
196       } else {
197         globalConflicts.put(t, conflicts.get(t));
198       }
199     }
200   }
201   
202
203   public void addToTraverseToDoList(FlatNode fn, TempDescriptor tempDesc, 
204       ReachGraph rg, Hashtable<Taint, Set<Effect>> conflicts) {
205     toTraverse.add(new TraversalInfo(fn, rg, tempDesc));
206     
207     for(Taint t: conflicts.keySet()) {
208       if(globalConflicts.containsKey(t)) {
209         globalConflicts.get(t).addAll(conflicts.get(t));
210       } else {
211         globalConflicts.put(t, conflicts.get(t));
212       }
213     }
214   }
215
216   private void traverseSESEBlock(FlatSESEEnterNode rblock, ReachGraph rg) {
217     Collection<TempDescriptor> inVars = rblock.getInVarSet();
218     
219     if (inVars.size() == 0)
220       return;
221     System.out.println("RBLOCK:"+rblock);
222     System.out.println("["+inVars+"]");
223     
224     // For every non-primitive variable, generate unique method
225     for (TempDescriptor invar : inVars) {
226       TypeDescriptor type = invar.getType();
227       if(type.isPrimitive()) {
228         continue;
229       }
230       System.out.println(invar);
231       //created stores nodes with specific alloc sites that have been traversed while building
232       //internal data structure. It is later traversed sequentially to find inset variables and
233       //build output code.
234       //NOTE: Integer stores Allocation Site ID in hashtable
235       Hashtable<Integer, ConcreteRuntimeObjNode> created = new Hashtable<Integer, ConcreteRuntimeObjNode>();
236       VariableNode varNode = rg.getVariableNodeNoMutation(invar);
237       Taint taint = getProperTaintForFlatSESEEnterNode(rblock, varNode, globalEffects);
238       if (taint == null) {
239         printDebug(javaDebug, "Null FOR " +varNode.getTempDescriptor().getSafeSymbol() + rblock.toPrettyString());
240         continue;
241       }
242       
243       //This is to prevent duplicate traversals from being generated 
244       if(doneTaints.containsKey(taint))
245         return;
246       
247       doneTaints.put(taint, traverserIDCounter++);
248       createConcreteGraph(effectsLookupTable, created, varNode, taint);
249       
250       
251       //This will add the taint to the printout, there will be NO duplicates (checked above)
252       if(!created.isEmpty()) {
253         for(Iterator<ConcreteRuntimeObjNode> it=created.values().iterator();it.hasNext();) {
254           ConcreteRuntimeObjNode obj=it.next();
255           if (obj.hasPrimitiveConflicts()||obj.decendantsConflict()) {
256             rblock.addInVarForDynamicCoarseConflictResolution(invar);
257             break;
258           }
259         }
260         
261         pendingPrintout.add(new TaintAndInternalHeapStructure(taint, created));
262       }
263     }
264   }
265   
266   private void traverseStallSite(FlatNode enterNode, TempDescriptor invar, ReachGraph rg) {
267     TypeDescriptor type = invar.getType();
268     if(type == null || type.isPrimitive()) {
269       return;
270     }
271     
272     Hashtable<Integer, ConcreteRuntimeObjNode> created = new Hashtable<Integer, ConcreteRuntimeObjNode>();
273     VariableNode varNode = rg.getVariableNodeNoMutation(invar);
274     Taint taint = getProperTaintForEnterNode(enterNode, varNode, globalEffects);
275     
276     if (taint == null) {
277       printDebug(javaDebug, "Null FOR " +varNode.getTempDescriptor().getSafeSymbol() + enterNode.toString());
278       return;
279     }        
280     
281     if(doneTaints.containsKey(taint))
282       return;
283     
284     doneTaints.put(taint, traverserIDCounter++);
285     createConcreteGraph(effectsLookupTable, created, varNode, taint);
286     
287     if (!created.isEmpty()) {
288       pendingPrintout.add(new TaintAndInternalHeapStructure(taint, created));
289     }
290   }
291   
292   public String getTraverserInvocation(TempDescriptor invar, String varString, FlatNode fn) {
293     String flatname;
294     if(fn instanceof FlatSESEEnterNode) {
295       flatname = ((FlatSESEEnterNode) fn).getPrettyIdentifier();
296     } else {
297       flatname = fn.toString();
298     }
299     
300     return "traverse___" + invar.getSafeSymbol() + 
301     removeInvalidChars(flatname) + "___("+varString+");";
302   }
303
304   public int getTraverserID(TempDescriptor invar, FlatNode fn) {
305     Tuple t=new Tuple(invar, fn);
306     if (idMap.containsKey(t))
307       return idMap.get(t).intValue();
308     int value=currentID++;
309     idMap.put(t, new Integer(value));
310     return value;
311   }
312   
313   public String removeInvalidChars(String in) {
314     StringBuilder s = new StringBuilder(in);
315     for(int i = 0; i < s.length(); i++) {
316       if(s.charAt(i) == ' ' || s.charAt(i) == '.' || s.charAt(i) == '='||s.charAt(i)=='['||s.charAt(i)==']') {
317         s.deleteCharAt(i);
318         i--;
319       }
320     }
321     return s.toString();
322   }
323
324   public void close() {
325     //prints out all generated code
326     for(TaintAndInternalHeapStructure ths: pendingPrintout) {
327       printCMethod(ths.nodesInHeap, ths.t);
328     }
329     
330     //Prints out the master traverser Invocation that'll call all other traversers
331     //based on traverserID
332     printMasterTraverserInvocation();
333     printResumeTraverserInvocation();
334     
335     //TODO this is only temporary, remove when thread local vars implemented. 
336     createMasterHashTableArray();
337     
338     // Adds Extra supporting methods
339     cFile.println("void initializeStructsRCR() {\n  " + mallocVisitedHashtable + ";\n  " + clearQueue + ";\n}");
340     cFile.println("void destroyRCR() {\n  " + deallocVisitedHashTable + ";\n}");
341     
342     headerFile.println("void initializeStructsRCR();\nvoid destroyRCR();");
343     headerFile.println("#endif\n");
344
345     cFile.close();
346     headerFile.close();
347   }
348
349   //Builds Effects Table and runs the analysis on them to get weakly connected HRs
350   //SPECIAL NOTE: Only runs after we've taken all the conflicts and effects
351   private void buildEffectsLookupStructure(){
352     effectsLookupTable = new EffectsTable(globalEffects, globalConflicts);
353     effectsLookupTable.runAnalysis();
354     enumerateHeaproots();
355   }
356
357   private void runAllTraversals() {
358     for(TraversalInfo t: toTraverse) {
359       printDebug(javaDebug, "Running Traversal a traversal on " + t.f);
360       
361       if(t.f instanceof FlatSESEEnterNode) {
362         traverseSESEBlock((FlatSESEEnterNode)t.f, t.rg);
363       } else {
364         if(t.invar == null) {
365           System.out.println("RCR ERROR: Attempted to run a stall site traversal with NO INVAR");
366         } else {
367           traverseStallSite(t.f, t.invar, t.rg);
368         }
369       }
370         
371     }
372   }
373
374   //TODO: This is only temporary, remove when thread local variables are functional. 
375   private void createMasterHashTableArray() {
376     headerFile.println("void createAndFillMasterHashStructureArray();");
377     cFile.println("void createAndFillMasterHashStructureArray() {\n" +
378                 "  rcr_createMasterHashTableArray("+weaklyConnectedHRCounter + ");");
379     
380     for(int i = 0; i < weaklyConnectedHRCounter; i++) {
381       cFile.println("  allHashStructures["+i+"] = (HashStructure *) rcr_createHashtable("+num2WeaklyConnectedHRGroup.get(i).connectedHRs.size()+");");
382     }
383     cFile.println("}");
384   }
385
386   private void printMasterTraverserInvocation() {
387     headerFile.println("\nint tasktraverse(SESEcommon * record);");
388     cFile.println("\nint tasktraverse(SESEcommon * record) {");
389     cFile.println("  if(!CAS(&record->rcrstatus,1,2)) return;");
390     cFile.println("  switch(record->classID) {");
391     
392     for(Iterator<FlatSESEEnterNode> seseit=oooa.getAllSESEs().iterator();seseit.hasNext();) {
393       FlatSESEEnterNode fsen=seseit.next();
394       cFile.println(    "    /* "+fsen.getPrettyIdentifier()+" */");
395       cFile.println(    "    case "+fsen.getIdentifier()+": {");
396       cFile.println(    "      "+fsen.getSESErecordName()+" * rec=("+fsen.getSESErecordName()+" *) record;");
397       Vector<TempDescriptor> invars=fsen.getInVarsForDynamicCoarseConflictResolution();
398       for(int i=0;i<invars.size();i++) {
399         TempDescriptor tmp=invars.get(i);
400         cFile.println("      " + this.getTraverserInvocation(tmp, "rec->"+tmp+", rec", fsen));
401       }
402       cFile.println(    "    }");
403       cFile.println(    "    break;");
404     }
405     
406     for(Taint t: doneTaints.keySet()) {
407       if (t.isStallSiteTaint()){
408         cFile.println(    "    case -" + getTraverserID(t.getVar(), t.getStallSite())+ ": {");
409         cFile.println(    "      SESEstall * rec=(SESEstall*) record;");
410         cFile.println(    "      " + this.getTraverserInvocation(t.getVar(), "rec->___obj___, rec", t.getStallSite())+";");
411         cFile.println(    "    }");
412         cFile.println("    break;");
413       }
414     }
415
416     cFile.println("    default:\n    printf(\"Invalid SESE ID was passed in: %d.\\n\",record->classID);\n    break;");
417     
418     cFile.println("  }");
419     cFile.println("}");
420   }
421
422
423   //This will print the traverser invocation that takes in a traverserID and starting ptr
424   private void printResumeTraverserInvocation() {
425     headerFile.println("\nint traverse(void * startingPtr, SESEcommon * record, int traverserID);");
426     cFile.println("\nint traverse(void * startingPtr, SESEcommon *record, int traverserID) {");
427     cFile.println("  switch(traverserID) {");
428     
429     for(Taint t: doneTaints.keySet()) {
430       cFile.println("  case " + doneTaints.get(t)+ ":");
431       if(t.isRBlockTaint()) {
432         cFile.println("    " + this.getTraverserInvocation(t.getVar(), "startingPtr, ("+t.getSESE().getSESErecordName()+" *)record", t.getSESE()));
433       } else if (t.isStallSiteTaint()){
434         cFile.println("/*    " + this.getTraverserInvocation(t.getVar(), "startingPtr, record", t.getStallSite())+"*/");
435       } else {
436         System.out.println("RuntimeConflictResolver encountered a taint that is neither SESE nor stallsite: " + t);
437       }
438       cFile.println("    break;");
439     }
440     
441     if(RuntimeConflictResolver.cSideDebug) {
442       cFile.println("  default:\n    printf(\"Invalid traverser ID %u was passed in.\\n\", traverserID);\n    break;");
443     } else {
444       cFile.println("  default:\n    break;");
445     }
446     
447     cFile.println(" }");
448     cFile.println("}");
449   }
450
451   private void createConcreteGraph(
452       EffectsTable table,
453       Hashtable<Integer, ConcreteRuntimeObjNode> created, 
454       VariableNode varNode, 
455       Taint t) {
456     
457     // if table is null that means there's no conflicts, therefore we need not
458     // create a traversal
459     if (table == null)
460       return;
461
462     Iterator<RefEdge> possibleEdges = varNode.iteratorToReferencees();
463     while (possibleEdges.hasNext()) {
464       RefEdge edge = possibleEdges.next();
465       assert edge != null;
466
467       ConcreteRuntimeObjNode singleRoot = new ConcreteRuntimeObjNode(edge.getDst(), true, false);
468       int rootKey = singleRoot.allocSite.getUniqueAllocSiteID();
469
470       if (!created.containsKey(rootKey)) {
471         created.put(rootKey, singleRoot);
472         createHelper(singleRoot, edge.getDst().iteratorToReferencees(), created, table, t);
473       }
474     }
475   }
476
477   // Plan is to add stuff to the tree depth-first sort of way. That way, we can
478   // propagate up conflicts
479   private void createHelper(ConcreteRuntimeObjNode curr, 
480                             Iterator<RefEdge> edges, 
481                             Hashtable<Integer, ConcreteRuntimeObjNode> created,
482                             EffectsTable table, 
483                             Taint taint) {
484     assert table != null;
485     AllocSite parentKey = curr.allocSite;
486     EffectsGroup currEffects = table.getEffects(parentKey, taint); 
487     
488     if (currEffects == null || currEffects.isEmpty()) 
489       return;
490     
491     //Handle Objects (and primitives if child is new)
492     if(currEffects.hasObjectEffects()) {
493       while(edges.hasNext()) {
494         RefEdge edge = edges.next();
495         String field = edge.getField();
496         CombinedObjEffects effectsForGivenField = currEffects.getObjEffect(field);
497         //If there are no effects, then there's no point in traversing this edge
498         if(effectsForGivenField != null) {
499           HeapRegionNode childHRN = edge.getDst();
500           int childKey = childHRN.getAllocSite().getUniqueAllocSiteID();
501           boolean isNewChild = !created.containsKey(childKey);
502           ConcreteRuntimeObjNode child; 
503           
504           if(isNewChild) {
505             child = new ConcreteRuntimeObjNode(childHRN, false, curr.isObjectArray());
506             created.put(childKey, child);
507           } else {
508             child = created.get(childKey);
509           }
510     
511           curr.addObjChild(field, child, effectsForGivenField);
512           
513           if (effectsForGivenField.hasConflict()) {
514             child.hasPotentialToBeIncorrectDueToConflict |= effectsForGivenField.hasReadConflict;
515             propagateObjConflict(curr, child);
516           }
517           
518           if(effectsForGivenField.hasReadEffect) {
519             child.addReachableParent(curr);
520             
521             //If isNewChild, flag propagation will be handled at recursive call
522             if(isNewChild) {
523               createHelper(child, childHRN.iteratorToReferencees(), created, table, taint);
524             } else {
525             //This makes sure that all conflicts below the child is propagated up the referencers.
526               if(child.decendantsPrimConflict || child.hasPrimitiveConflicts()) {
527                 propagatePrimConflict(child, child.enqueueToWaitingQueueUponConflict);
528               }
529               
530               if(child.decendantsObjConflict) {
531                 propagateObjConflict(child, child.enqueueToWaitingQueueUponConflict);
532               }
533             }
534           }
535         }
536       }
537     }
538     
539     //Handles primitives
540     curr.primitiveConflictingFields = currEffects.primitiveConflictingFields; 
541     if(currEffects.hasPrimitiveConflicts()) {
542       //Reminder: primitive conflicts are abstracted to object. 
543       propagatePrimConflict(curr, curr);
544     }
545   }
546
547   // This will propagate the conflict up the data structure.
548   private void propagateObjConflict(ConcreteRuntimeObjNode curr, HashSet<ConcreteRuntimeObjNode> pointsOfAccess) {
549     for(ConcreteRuntimeObjNode referencer: curr.parentsWithReadToNode) {
550       if(curr.parentsThatWillLeadToConflicts.add(referencer) || //case where referencee has never seen referncer
551           (pointsOfAccess != null && referencer.addPossibleWaitingQueueEnqueue(pointsOfAccess))) // case where referencer has never seen possible unresolved referencee below 
552       {
553         referencer.decendantsObjConflict = true;
554         propagateObjConflict(referencer, pointsOfAccess);
555       }
556     }
557   }
558   
559   private void propagateObjConflict(ConcreteRuntimeObjNode curr, ConcreteRuntimeObjNode pointOfAccess) {
560     for(ConcreteRuntimeObjNode referencer: curr.parentsWithReadToNode) {
561       if(curr.parentsThatWillLeadToConflicts.add(referencer) || //case where referencee has never seen referncer
562           (pointOfAccess != null && referencer.addPossibleWaitingQueueEnqueue(pointOfAccess))) // case where referencer has never seen possible unresolved referencee below 
563       {
564         referencer.decendantsObjConflict = true;
565         propagateObjConflict(referencer, pointOfAccess);
566       }
567     }
568   }
569   
570   private void propagatePrimConflict(ConcreteRuntimeObjNode curr, HashSet<ConcreteRuntimeObjNode> pointsOfAccess) {
571     for(ConcreteRuntimeObjNode referencer: curr.parentsWithReadToNode) {
572       if(curr.parentsThatWillLeadToConflicts.add(referencer) || //same cases as above
573           (pointsOfAccess != null && referencer.addPossibleWaitingQueueEnqueue(pointsOfAccess))) 
574       {
575         referencer.decendantsPrimConflict = true;
576         propagatePrimConflict(referencer, pointsOfAccess);
577       }
578     }
579   }
580   
581   private void propagatePrimConflict(ConcreteRuntimeObjNode curr, ConcreteRuntimeObjNode pointOfAccess) {
582     for(ConcreteRuntimeObjNode referencer: curr.parentsWithReadToNode) {
583       if(curr.parentsThatWillLeadToConflicts.add(referencer) || //same cases as above
584           (pointOfAccess != null && referencer.addPossibleWaitingQueueEnqueue(pointOfAccess))) 
585       {
586         referencer.decendantsPrimConflict = true;
587         propagatePrimConflict(referencer, pointOfAccess);
588       }
589     }
590   }
591   
592   /*
593    * This method generates a C method for every inset variable and rblock. 
594    * 
595    * The C method works by generating a large switch statement that will run the appropriate 
596    * checking code for each object based on its allocation site. The switch statement is 
597    * surrounded by a while statement which dequeues objects to be checked from a queue. An
598    * object is added to a queue only if it contains a conflict (in itself or in its referencees)
599    *  and we came across it while checking through it's referencer. Because of this property, 
600    *  conflicts will be signaled by the referencer; the only exception is the inset variable which can 
601    *  signal a conflict within itself. 
602    */
603   
604   private void printCMethod(Hashtable<Integer, ConcreteRuntimeObjNode> created, Taint taint) {
605     String inVar = taint.getVar().getSafeSymbol();
606     String rBlock;
607     
608     if(taint.isStallSiteTaint()) {
609       rBlock = taint.getStallSite().toString();
610     } else if(taint.isRBlockTaint()) {
611       rBlock = taint.getSESE().getPrettyIdentifier();
612     } else {
613       System.out.println("RCR CRITICAL ERROR: TAINT IS NEITHER A STALLSITE NOR SESE! " + taint.toString());
614       return;
615     }
616     
617     //This hash table keeps track of all the case statements generated.
618     Hashtable<AllocSite, StringBuilder> cases = new Hashtable<AllocSite, StringBuilder>();
619     
620     //Generate C cases 
621     for (ConcreteRuntimeObjNode node : created.values()) {
622       printDebug(javaDebug, "Considering " + node.allocSite + " for traversal");
623       if (!cases.containsKey(node.allocSite) && qualifiesForCaseStatement(node)) {
624         printDebug(javaDebug, "+\t" + node.allocSite + " qualified for case statement");
625         addChecker(taint, node, cases, null, "ptr", 0);
626       }
627     }
628     
629     String methodName;
630     int index=-1;
631
632     if (taint.isStallSiteTaint()) {
633       methodName= "void traverse___" + inVar + removeInvalidChars(rBlock) + "___(void * InVar, SESEstall *record)";
634     } else {
635       methodName= "void traverse___" + inVar + removeInvalidChars(rBlock) + "___(void * InVar, "+taint.getSESE().getSESErecordName() +" *record)";
636       FlatSESEEnterNode fsese=taint.getSESE();
637       TempDescriptor tmp=taint.getVar();
638       index=fsese.getInVarsForDynamicCoarseConflictResolution().indexOf(tmp);
639     }
640
641     cFile.println(methodName + " {");
642     headerFile.println(methodName + ";");
643     
644     if(cases.size() == 0) {
645       cFile.println(" return;");
646     } else {
647       cFile.println("    int totalcount=RUNBIAS;\n");
648       
649       if (taint.isStallSiteTaint()) {
650         cFile.println("    record->rcrRecords[0].count=RUNBIAS;\n");
651       } else {
652         cFile.println("    record->rcrRecords["+index+"].count=RUNBIAS;\n");
653         cFile.println("    record->rcrRecords["+index+"].index=0;\n");
654       }
655       
656       //clears queue and hashtable that keeps track of where we've been. 
657       cFile.println(clearQueue + ";\n" + resetVisitedHashTable + ";"); 
658       //generic cast to ___Object___ to access ptr->allocsite field. 
659       cFile.println("struct ___Object___ * ptr = (struct ___Object___ *) InVar;\nif (InVar != NULL) {\n " + queryVistedHashtable + "(ptr);\n do {");
660       if (taint.isRBlockTaint()) {
661         cFile.println("  if(unlikely(record->common.doneExecuting)) {");
662         cFile.println("    record->common.rcrstatus=0;");
663         cFile.println("    return;");
664         cFile.println("  }");
665       }
666       cFile.println("  switch(ptr->allocsite) {");
667       
668       for(AllocSite singleCase: cases.keySet()) {
669         cFile.append(cases.get(singleCase));
670       }
671       
672       cFile.println("  default:\n    break; ");
673       cFile.println("  }\n } while((ptr = " + dequeueFromQueueInC + ") != NULL);\n}");
674       
675       if (taint.isStallSiteTaint()) {
676         //need to add this
677         cFile.println("     if(atomic_sub_and_test(RUNBIAS-totalcount,&(record->rcrRecords[0].count))) {");
678         cFile.println("         psem_give_tag(record->common.parentsStallSem, record->tag);");
679         cFile.println("         BARRIER();");
680         cFile.println("         record->common.rcrstatus=0;");
681         cFile.println("}");
682       } else {
683         cFile.println("     if(atomic_sub_and_test(RUNBIAS-totalcount,&(record->rcrRecords["+index+"].count))) {");
684         cFile.println("        int flag=LOCKXCHG32(&(record->rcrRecords["+index+"].flag),0);");
685         cFile.println("        if(flag) {");
686         //we have resolved a heap root...see if this was the last dependence
687         cFile.println("            if(atomic_sub_and_test(1, &(record->common.unresolvedDependencies))) workScheduleSubmit((void *)record);");
688         cFile.println("        }");
689         cFile.println("     }");
690         cFile.println("     record->common.rcrstatus=0;");
691       }
692     }
693     cFile.println("}");
694     cFile.flush();
695   }
696   
697   /*
698    * addChecker creates a case statement for every object that is an inset variable, has more
699    * than 1 parent && has conflicts, or where resumes are possible (from waiting queue). 
700    * See .qualifiesForCaseStatement
701    */
702   private void addChecker(Taint taint, 
703                           ConcreteRuntimeObjNode node, 
704                           Hashtable<AllocSite,StringBuilder> cases, 
705                           StringBuilder possibleContinuingCase, 
706                           String prefix, 
707                           int depth) {
708     StringBuilder currCase = possibleContinuingCase;
709     if(qualifiesForCaseStatement(node)) {
710       assert prefix.equals("ptr") && !cases.containsKey(node.allocSite);
711       currCase = new StringBuilder();
712       cases.put(node.allocSite, currCase);
713       currCase.append("  case " + node.getAllocationSite() + ": {\n");
714     }
715     //either currCase is continuing off a parent case or is its own. 
716     assert currCase !=null;
717     
718     boolean primConfRead=false;
719     boolean primConfWrite=false;
720     boolean objConfRead=false;
721     boolean objConfWrite=false;
722
723     //Primitives Test
724     for(String field: node.primitiveConflictingFields.keySet()) {
725       CombinedObjEffects effect=node.primitiveConflictingFields.get(field);
726       primConfRead|=effect.hasReadConflict;
727       primConfWrite|=effect.hasWriteConflict;
728     }
729
730     //Object Reference Test
731     for(String field: node.objectRefs.keySet()) {
732       for(ObjRef ref: node.objectRefs.get(field)) {
733         CombinedObjEffects effect=ref.myEffects;
734         objConfRead|=effect.hasReadConflict;
735         objConfWrite|=effect.hasWriteConflict;
736       }
737     }
738
739     int index=-1;
740     if (taint.isRBlockTaint()) {
741       FlatSESEEnterNode fsese=taint.getSESE();
742       TempDescriptor tmp=taint.getVar();
743       index=fsese.getInVarsForDynamicCoarseConflictResolution().indexOf(tmp);
744     }
745
746     String strrcr=taint.isRBlockTaint()?"&record->rcrRecords["+index+"], ":"NULL, ";
747     
748     //Do call if we need it.
749     if(primConfWrite||objConfWrite) {
750       int heaprootNum = connectedHRHash.get(taint).id;
751       assert heaprootNum != -1;
752       int allocSiteID = connectedHRHash.get(taint).getWaitingQueueBucketNum(node);
753       int traverserID = doneTaints.get(taint);
754         currCase.append("    int tmpkey"+depth+"=rcr_generateKey("+prefix+");\n");
755       if (objConfRead)
756         currCase.append("    int tmpvar"+depth+"=rcr_WTWRITEBINCASE(allHashStructures["+heaprootNum+"], tmpkey"+depth+", (SESEcommon *) record, "+strrcr+index+");\n");
757       else
758         currCase.append("    int tmpvar"+depth+"=rcr_WRITEBINCASE(allHashStructures["+heaprootNum+"], tmpkey"+depth+", (SESEcommon *) record, "+strrcr+index+");\n");
759     } else if (primConfRead||objConfRead) {
760       int heaprootNum = connectedHRHash.get(taint).id;
761       assert heaprootNum != -1;
762       int allocSiteID = connectedHRHash.get(taint).getWaitingQueueBucketNum(node);
763       int traverserID = doneTaints.get(taint);
764       currCase.append("    int tmpkey"+depth+"=rcr_generateKey("+prefix+");\n");
765       if (objConfRead) 
766         currCase.append("    int tmpvar"+depth+"=rcr_WTREADBINCASE(allHashStructures["+heaprootNum+"], tmpkey"+depth+", (SESEcommon *) record, "+strrcr+index+");\n");
767       else
768         currCase.append("    int tmpvar"+depth+"=rcr_READBINCASE(allHashStructures["+heaprootNum+"], tmpkey"+depth+", (SESEcommon *) record, "+strrcr+index+");\n");
769     }
770
771     if(primConfWrite||objConfWrite||primConfRead||objConfRead) {
772       currCase.append("if (!(tmpvar"+depth+"&READYMASK)) totalcount--;\n");
773     }
774     
775     int pdepth=depth+1;
776     currCase.append("{\n");
777     //Array Case
778     if(node.isObjectArray() && node.decendantsConflict()) {
779       //since each array element will get its own case statement, we just need to enqueue each item into the queue
780       //note that the ref would be the actual object and node would be of struct ArrayObject
781       
782       ArrayList<Integer> allocSitesWithProblems = node.getReferencedAllocSites();
783       if(!allocSitesWithProblems.isEmpty()) {
784         String childPtr = "((struct ___Object___ **)(((char *) &(((struct ArrayObject *)"+ prefix+")->___length___))+sizeof(int)))[i]";
785         String currPtr = "arrayElement" + pdepth;
786         
787         //This is done with the assumption that an array of object stores pointers. 
788         currCase.append("{\n  int i;\n");
789         currCase.append("  for(i = 0; i<((struct ArrayObject *) " + prefix + " )->___length___; i++ ) {\n");
790         currCase.append("    struct ___Object___ *"+currPtr+" = "+childPtr+";\n");
791         currCase.append("    if( arrayElement"+pdepth+" != NULL) {\n");
792         
793         //There should be only one field, hence we only take the first field in the keyset.
794         assert node.objectRefs.keySet().size() <= 1;
795         ArrayList<ObjRef> refsAtParticularField = node.objectRefs.get(node.objectRefs.keySet().iterator().next());
796         printObjRefSwitchStatement(taint,cases,pdepth,currCase,refsAtParticularField,childPtr,currPtr);
797         currCase.append("      }}}\n");
798       }
799     } else {
800     //All other cases
801       for(String field: node.objectRefs.keySet()) {
802         ArrayList<ObjRef> refsAtParticularField = node.objectRefs.get(field);
803         String childPtr = "((struct "+node.original.getType().getSafeSymbol()+" *)"+prefix +")->___" + field + "___";
804         String currPtr = "myPtr" + pdepth;
805         currCase.append("    struct ___Object___ * "+currPtr+"= (struct ___Object___ * ) " + childPtr + ";\n");
806         currCase.append("    if (" + currPtr + " != NULL) { ");
807         
808         printObjRefSwitchStatement(taint, cases, depth, currCase, refsAtParticularField, childPtr, currPtr);
809         currCase.append("}");
810       }      
811     }
812     
813     currCase.append("}\n"); //For particular top level case statement. 
814
815     if(qualifiesForCaseStatement(node)) {
816       currCase.append("  }\n  break;\n");
817     }
818   }
819
820   private void printObjRefSwitchStatement(Taint taint, Hashtable<AllocSite, StringBuilder> cases,
821       int pDepth, StringBuilder currCase, ArrayList<ObjRef> refsAtParticularField, String childPtr,
822       String currPtr) {
823     currCase.append("    switch(" + currPtr + getAllocSiteInC + ") {\n");
824     
825     for(ObjRef ref: refsAtParticularField) {
826       if(ref.child.decendantsConflict() || ref.child.hasPrimitiveConflicts()) {
827         currCase.append("      case "+ref.allocSite+":\n      {\n");
828         //The hash insert is here because we don't want to enqueue things unless we know it conflicts. 
829         currCase.append("        if (" + queryVistedHashtable +"("+ currPtr + ")) {\n");
830         
831         if (ref.child.getNumOfReachableParents() == 1 && !ref.child.isInsetVar) {
832           addChecker(taint, ref.child, cases, currCase, currPtr, pDepth + 1);
833         }
834         else {
835           currCase.append("        " + addToQueueInC + childPtr + ");\n ");
836         }
837         currCase.append("    }\n");  //close for queryVistedHashtable
838         
839         currCase.append("}\n"); //close for internal case statement
840       }
841     }
842     
843     currCase.append("    default:\n" +
844                             "       break;\n"+
845                             "    }\n"); //internal switch. 
846   }
847   
848   private boolean qualifiesForCaseStatement(ConcreteRuntimeObjNode node) {
849     return (          
850         //insetVariable case
851         (node.isInsetVar && (node.decendantsConflict() || node.hasPrimitiveConflicts())) ||
852         //non-inline-able code cases
853         (node.getNumOfReachableParents() != 1 && node.decendantsConflict()) ||
854         //Cases where resumes are possible
855         (node.hasPotentialToBeIncorrectDueToConflict) && node.decendantsObjConflict);
856   }
857   
858   private Taint getProperTaintForFlatSESEEnterNode(FlatSESEEnterNode rblock, VariableNode var,
859       Hashtable<Taint, Set<Effect>> effects) {
860     Set<Taint> taints = effects.keySet();
861     for (Taint t : taints) {
862       FlatSESEEnterNode sese = t.getSESE();
863       if(sese != null && sese.equals(rblock) && t.getVar().equals(var.getTempDescriptor())) {
864         return t;
865       }
866     }
867     return null;
868   }
869   
870   
871   private Taint getProperTaintForEnterNode(FlatNode stallSite, VariableNode var,
872       Hashtable<Taint, Set<Effect>> effects) {
873     Set<Taint> taints = effects.keySet();
874     for (Taint t : taints) {
875       FlatNode flatnode = t.getStallSite();
876       if(flatnode != null && flatnode.equals(stallSite) && t.getVar().equals(var.getTempDescriptor())) {
877         return t;
878       }
879     }
880     return null;
881   }
882
883   private void printDebug(boolean guard, String debugStatements) {
884     if(guard)
885       System.out.println(debugStatements);
886   }
887   
888   private void enumerateHeaproots() {
889     weaklyConnectedHRCounter = 0;
890     num2WeaklyConnectedHRGroup = new ArrayList<WeaklyConectedHRGroup>();
891     
892     for(Taint t: connectedHRHash.keySet()) {
893       if(connectedHRHash.get(t).id == -1) {
894         WeaklyConectedHRGroup hg = connectedHRHash.get(t);
895         hg.id = weaklyConnectedHRCounter;
896         num2WeaklyConnectedHRGroup.add(weaklyConnectedHRCounter, hg);
897         weaklyConnectedHRCounter++;
898       }
899     }
900   }
901   
902   private void printoutTable(EffectsTable table) {
903     
904     System.out.println("==============EFFECTS TABLE PRINTOUT==============");
905     for(AllocSite as: table.table.keySet()) {
906       System.out.println("\tFor AllocSite " + as.getUniqueAllocSiteID());
907       
908       BucketOfEffects boe = table.table.get(as);
909       
910       if(boe.potentiallyConflictingRoots != null && !boe.potentiallyConflictingRoots.isEmpty()) {
911         System.out.println("\t\tPotentially conflicting roots: ");
912         for(String key: boe.potentiallyConflictingRoots.keySet()) {
913           System.out.println("\t\t-Field: " + key);
914           System.out.println("\t\t\t" + boe.potentiallyConflictingRoots.get(key));
915         }
916       }
917       for(Taint t: boe.taint2EffectsGroup.keySet()) {
918         System.out.println("\t\t For Taint " + t);
919         EffectsGroup eg = boe.taint2EffectsGroup.get(t);
920           
921         if(eg.hasPrimitiveConflicts()) {
922           System.out.print("\t\t\tPrimitive Conflicts at alloc " + as.getUniqueAllocSiteID() +" : ");
923           for(String field: eg.primitiveConflictingFields.keySet()) {
924             System.out.print(field + " ");
925           }
926           System.out.println();
927         }
928         for(String fieldKey: eg.myEffects.keySet()) {
929           CombinedObjEffects ce = eg.myEffects.get(fieldKey);
930           System.out.println("\n\t\t\tFor allocSite " + as.getUniqueAllocSiteID() + " && field " + fieldKey);
931           System.out.println("\t\t\t\tread " + ce.hasReadEffect + "/"+ce.hasReadConflict + 
932               " write " + ce.hasWriteEffect + "/" + ce.hasWriteConflict + 
933               " SU " + ce.hasStrongUpdateEffect + "/" + ce.hasStrongUpdateConflict);
934           for(Effect ef: ce.originalEffects) {
935             System.out.println("\t" + ef);
936           }
937         }
938       }
939         
940     }
941     
942   }
943   
944   private class EffectsGroup {
945     Hashtable<String, CombinedObjEffects> myEffects;
946     Hashtable<String, CombinedObjEffects> primitiveConflictingFields;
947     
948     public EffectsGroup() {
949       myEffects = new Hashtable<String, CombinedObjEffects>();
950       primitiveConflictingFields = new Hashtable<String, CombinedObjEffects>();
951     }
952
953     public void addPrimitive(Effect e, boolean conflict) {
954       CombinedObjEffects effects;
955       if((effects = primitiveConflictingFields.get(e.getField().getSymbol())) == null) {
956         effects = new CombinedObjEffects();
957         primitiveConflictingFields.put(e.getField().getSymbol(), effects);
958       }
959       effects.add(e, conflict);
960     }
961     
962     public void addObjEffect(Effect e, boolean conflict) {
963       CombinedObjEffects effects;
964       if((effects = myEffects.get(e.getField().getSymbol())) == null) {
965         effects = new CombinedObjEffects();
966         myEffects.put(e.getField().getSymbol(), effects);
967       }
968       effects.add(e, conflict);
969     }
970     
971     public boolean isEmpty() {
972       return myEffects.isEmpty() && primitiveConflictingFields.isEmpty();
973     }
974     
975     public boolean hasPrimitiveConflicts(){
976       return !primitiveConflictingFields.isEmpty();
977     }
978     
979     public CombinedObjEffects getPrimEffect(String field) {
980       return primitiveConflictingFields.get(field);
981     }
982
983     public boolean hasObjectEffects() {
984       return !myEffects.isEmpty();
985     }
986     
987     public CombinedObjEffects getObjEffect(String field) {
988       return myEffects.get(field);
989     }
990   }
991   
992   //Is the combined effects for all effects with the same affectedAllocSite and field
993   private class CombinedObjEffects {
994     ArrayList<Effect> originalEffects;
995     
996     public boolean hasReadEffect;
997     public boolean hasWriteEffect;
998     public boolean hasStrongUpdateEffect;
999     
1000     public boolean hasReadConflict;
1001     public boolean hasWriteConflict;
1002     public boolean hasStrongUpdateConflict;
1003     
1004     
1005     public CombinedObjEffects() {
1006       originalEffects = new ArrayList<Effect>();
1007       
1008       hasReadEffect = false;
1009       hasWriteEffect = false;
1010       hasStrongUpdateEffect = false;
1011       
1012       hasReadConflict = false;
1013       hasWriteConflict = false;
1014       hasStrongUpdateConflict = false;
1015     }
1016     
1017     public boolean add(Effect e, boolean conflict) {
1018       if(!originalEffects.add(e))
1019         return false;
1020       
1021       switch(e.getType()) {
1022       case Effect.read:
1023         hasReadEffect = true;
1024         hasReadConflict = conflict;
1025         break;
1026       case Effect.write:
1027         hasWriteEffect = true;
1028         hasWriteConflict = conflict;
1029         break;
1030       case Effect.strongupdate:
1031         hasStrongUpdateEffect = true;
1032         hasStrongUpdateConflict = conflict;
1033         break;
1034       default:
1035         System.out.println("RCR ERROR: An Effect Type never seen before has been encountered");
1036         assert false;
1037         break;
1038       }
1039       return true;
1040     }
1041     
1042     public boolean hasConflict() {
1043       return hasReadConflict || hasWriteConflict || hasStrongUpdateConflict;
1044     }
1045
1046     public void mergeWith(CombinedObjEffects other) {
1047       for(Effect e: other.originalEffects) {
1048         if(!originalEffects.contains(e)){
1049           originalEffects.add(e);
1050         }
1051       }
1052       
1053       hasReadEffect |= other.hasReadEffect;
1054       hasWriteEffect |= other.hasWriteEffect;
1055       hasStrongUpdateEffect |= other.hasStrongUpdateEffect;
1056       
1057       hasReadConflict |= other.hasReadConflict;
1058       hasWriteConflict |= other.hasWriteConflict;
1059       hasStrongUpdateConflict |= other.hasStrongUpdateConflict;
1060     }
1061   }
1062
1063   //This will keep track of a reference
1064   private class ObjRef {
1065     String field;
1066     int allocSite;
1067     CombinedObjEffects myEffects;
1068     
1069     //This keeps track of the parent that we need to pass by inorder to get
1070     //to the conflicting child (if there is one). 
1071     ConcreteRuntimeObjNode child;
1072
1073     public ObjRef(String fieldname, 
1074                   ConcreteRuntimeObjNode ref, 
1075                   CombinedObjEffects myEffects) {
1076       field = fieldname;
1077       allocSite = ref.getAllocationSite();
1078       child = ref;
1079       
1080       this.myEffects = myEffects;
1081     }
1082     
1083     public boolean hasConflictsDownThisPath() {
1084       return child.decendantsObjConflict || child.decendantsPrimConflict || child.hasPrimitiveConflicts() || myEffects.hasConflict(); 
1085     }
1086     
1087     public boolean hasDirectObjConflict() {
1088       return myEffects.hasConflict();
1089     }
1090     
1091     public boolean equals(Object other) {
1092       if(other == null || !(other instanceof ObjRef)) 
1093         return false;
1094       
1095       ObjRef o = (ObjRef) other;
1096       
1097       if(o.field == this.field && o.allocSite == this.allocSite && this.child.equals(o.child))
1098         return true;
1099       
1100       return false;
1101     }
1102     
1103     public int hashCode() {
1104       return child.allocSite.hashCode() ^ field.hashCode();
1105     }
1106
1107     public void mergeWith(ObjRef ref) {
1108       myEffects.mergeWith(ref.myEffects);
1109     }
1110   }
1111
1112   private class ConcreteRuntimeObjNode {
1113     Hashtable<String, ArrayList<ObjRef>> objectRefs;
1114     Hashtable<String, CombinedObjEffects> primitiveConflictingFields;
1115     HashSet<ConcreteRuntimeObjNode> parentsWithReadToNode;
1116     HashSet<ConcreteRuntimeObjNode> parentsThatWillLeadToConflicts;
1117     //this set keeps track of references down the line that need to be enqueued if traverser is "paused"
1118     HashSet<ConcreteRuntimeObjNode> enqueueToWaitingQueueUponConflict;
1119     boolean decendantsPrimConflict;
1120     boolean decendantsObjConflict;
1121     boolean hasPotentialToBeIncorrectDueToConflict;
1122     boolean isInsetVar;
1123     boolean isArrayElement;
1124     AllocSite allocSite;
1125     HeapRegionNode original;
1126
1127     public ConcreteRuntimeObjNode(HeapRegionNode me, boolean isInVar, boolean isArrayElement) {
1128       objectRefs = new Hashtable<String, ArrayList<ObjRef>>(5);
1129       primitiveConflictingFields = null;
1130       parentsThatWillLeadToConflicts = new HashSet<ConcreteRuntimeObjNode>();
1131       parentsWithReadToNode = new HashSet<ConcreteRuntimeObjNode>();
1132       enqueueToWaitingQueueUponConflict = new HashSet<ConcreteRuntimeObjNode>();
1133       allocSite = me.getAllocSite();
1134       original = me;
1135       isInsetVar = isInVar;
1136       decendantsPrimConflict = false;
1137       decendantsObjConflict = false;
1138       hasPotentialToBeIncorrectDueToConflict = false;
1139       this.isArrayElement = isArrayElement;
1140     }
1141
1142     public void addReachableParent(ConcreteRuntimeObjNode curr) {
1143       parentsWithReadToNode.add(curr);
1144     }
1145
1146     @Override
1147     public boolean equals(Object other) {
1148       if(other == null || !(other instanceof ConcreteRuntimeObjNode)) 
1149         return false;
1150       
1151       return original.equals(((ConcreteRuntimeObjNode)other).original);
1152     }
1153
1154     public int getAllocationSite() {
1155       return allocSite.getUniqueAllocSiteID();
1156     }
1157
1158     public int getNumOfReachableParents() {
1159       return parentsThatWillLeadToConflicts.size();
1160     }
1161     
1162     public boolean hasPrimitiveConflicts() {
1163       return primitiveConflictingFields != null && !primitiveConflictingFields.isEmpty();
1164     }
1165     
1166     public boolean decendantsConflict() {
1167       return decendantsPrimConflict || decendantsObjConflict;
1168     }
1169     
1170     
1171     //returns true if at least one of the objects in points of access has been added
1172     public boolean addPossibleWaitingQueueEnqueue(HashSet<ConcreteRuntimeObjNode> pointsOfAccess) {
1173       boolean addedNew = false;
1174       for(ConcreteRuntimeObjNode dec: pointsOfAccess) {
1175         if(dec != null && dec != this){
1176           addedNew = addedNew || enqueueToWaitingQueueUponConflict.add(dec);
1177         }
1178       }
1179       
1180       return addedNew;
1181     }
1182     
1183     public boolean addPossibleWaitingQueueEnqueue(ConcreteRuntimeObjNode pointOfAccess) {
1184       if(pointOfAccess != null && pointOfAccess != this){
1185         return enqueueToWaitingQueueUponConflict.add(pointOfAccess);
1186       }
1187       
1188       return false;
1189     }
1190
1191     public void addObjChild(String field, ConcreteRuntimeObjNode child, CombinedObjEffects ce) {
1192       printDebug(javaDebug,this.allocSite.getUniqueAllocSiteID() + " added child at " + child.getAllocationSite());
1193       ObjRef ref = new ObjRef(field, child, ce);
1194       
1195       if(objectRefs.containsKey(field)){
1196         ArrayList<ObjRef> array = objectRefs.get(field);
1197         
1198         if(array.contains(ref)) {
1199           ObjRef other = array.get(array.indexOf(ref));
1200           other.mergeWith(ref);
1201           printDebug(javaDebug,"    Merged with old");
1202           printDebug(javaDebug,"    Old="+ other.child.original + "\n    new="+ref.child.original);
1203         }
1204         else {
1205           array.add(ref);
1206           printDebug(javaDebug,"    Just added new;\n      Field: " + field);
1207           printDebug(javaDebug,"      AllocSite: " + child.getAllocationSite());
1208           printDebug(javaDebug,"      Child: "+child.original);
1209         }
1210       }
1211       else {
1212         ArrayList<ObjRef> array = new ArrayList<ObjRef>(3);
1213         
1214         array.add(ref);
1215         objectRefs.put(field, array);
1216       }
1217     }
1218     
1219     public boolean isObjectArray() {
1220       return original.getType().isArray() && !original.getType().isPrimitive() && !original.getType().isImmutable();
1221     }
1222     
1223     public boolean canBeArrayElement() {
1224       return isArrayElement;
1225     }
1226     
1227     public ArrayList<Integer> getReferencedAllocSites() {
1228       ArrayList<Integer> list = new ArrayList<Integer>();
1229       
1230       for(String key: objectRefs.keySet()) {
1231         for(ObjRef r: objectRefs.get(key)) {
1232           if(r.hasDirectObjConflict() || (r.child.parentsWithReadToNode.contains(this) && r.hasConflictsDownThisPath())) {
1233             list.add(r.allocSite);
1234           }
1235         }
1236       }
1237       
1238       return list;
1239     }
1240     
1241     public String toString() {
1242       return "AllocSite=" + getAllocationSite() + " myConflict=" + !parentsThatWillLeadToConflicts.isEmpty() + 
1243               " decCon="+decendantsObjConflict+ 
1244               " NumOfConParents=" + getNumOfReachableParents() + " ObjectChildren=" + objectRefs.size();
1245     }
1246   }
1247   
1248   private class EffectsTable {
1249     private Hashtable<AllocSite, BucketOfEffects> table;
1250
1251     public EffectsTable(Hashtable<Taint, Set<Effect>> effects,
1252         Hashtable<Taint, Set<Effect>> conflicts) {
1253       table = new Hashtable<AllocSite, BucketOfEffects>();
1254
1255       // rehash all effects (as a 5-tuple) by their affected allocation site
1256       for (Taint t : effects.keySet()) {
1257         Set<Effect> localConflicts = conflicts.get(t);
1258         for (Effect e : effects.get(t)) {
1259           BucketOfEffects bucket;
1260           if ((bucket = table.get(e.getAffectedAllocSite())) == null) {
1261             bucket = new BucketOfEffects();
1262             table.put(e.getAffectedAllocSite(), bucket);
1263           }
1264           printDebug(javaDebug, "Added Taint" + t + " Effect " + e + "Conflict Status = " + (localConflicts!=null?localConflicts.contains(e):false)+" localConflicts = "+localConflicts);
1265           bucket.add(t, e, localConflicts!=null?localConflicts.contains(e):false);
1266         }
1267       }
1268     }
1269
1270     public EffectsGroup getEffects(AllocSite parentKey, Taint taint) {
1271       //This would get the proper bucket of effects and then get all the effects
1272       //for a parent for a specific taint
1273       try {
1274         return table.get(parentKey).taint2EffectsGroup.get(taint);
1275       }
1276       catch (NullPointerException e) {
1277         return null;
1278       }
1279     }
1280
1281     // Run Analysis will walk the data structure and figure out the weakly
1282     // connected heap roots. 
1283     public void runAnalysis() {
1284       if(javaDebug) {
1285         printoutTable(this); 
1286       }
1287       
1288       for(AllocSite key: table.keySet()) {
1289         BucketOfEffects effects = table.get(key);
1290         //make sure there are actually conflicts in the bucket
1291         if(effects.potentiallyConflictingRoots != null && !effects.potentiallyConflictingRoots.isEmpty()){
1292           for(String field: effects.potentiallyConflictingRoots.keySet()){
1293             ArrayList<Taint> taints = effects.potentiallyConflictingRoots.get(field);
1294             //For simplicity, we just create a new group and add everything to it instead of
1295             //searching through all of them for the largest group and adding everyone in. 
1296             WeaklyConectedHRGroup group = new WeaklyConectedHRGroup();
1297             group.add(taints); //This will automatically add the taint to the connectedHRhash
1298           }
1299         }
1300       }
1301     }
1302   }
1303   
1304   private class WeaklyConectedHRGroup {
1305     HashSet<Taint> connectedHRs;
1306     //This is to keep track of unique waitingQueue positions for each allocsite. 
1307     Hashtable<AllocSite, Integer> allocSiteToWaitingQueueMap;
1308     int waitingQueueCounter;
1309     int id;
1310     
1311     public WeaklyConectedHRGroup() {
1312       connectedHRs = new HashSet<Taint>();
1313       id = -1; //this will be later modified
1314       waitingQueueCounter = 0;
1315       allocSiteToWaitingQueueMap = new Hashtable<AllocSite, Integer>();
1316     }
1317     
1318     public void add(ArrayList<Taint> list) {
1319       for(Taint t: list) {
1320         this.add(t);
1321       }
1322     }
1323     
1324     public int getWaitingQueueBucketNum(ConcreteRuntimeObjNode node) {
1325       if(allocSiteToWaitingQueueMap.containsKey(node.allocSite)) {
1326         return allocSiteToWaitingQueueMap.get(node.allocSite);
1327       } else {
1328         allocSiteToWaitingQueueMap.put(node.allocSite, waitingQueueCounter);
1329         return waitingQueueCounter++;
1330       }
1331     }
1332     
1333     public void add(Taint t) {
1334       connectedHRs.add(t);
1335       WeaklyConectedHRGroup oldGroup = connectedHRHash.get(t);
1336       connectedHRHash.put(t, this); //put new group into hash
1337       //If the taint was already in another group, move all its buddies over. 
1338       if(oldGroup != this && oldGroup != null) {
1339         Iterator<Taint> it = oldGroup.connectedHRs.iterator();
1340         Taint relatedTaint;
1341         
1342         while((relatedTaint = it.next()) != null && !connectedHRs.contains(relatedTaint)) {
1343           this.add(relatedTaint);
1344         }
1345       }
1346     }
1347   }
1348   
1349   //This is a class that stores all the effects for an affected allocation site
1350   //across ALL taints. The structure is a hashtable of EffectGroups (see above) hashed
1351   //by a Taint. This way, I can keep EffectsGroups so I can reuse most to all of my old code
1352   //and allows for easier tracking of effects. In addition, a hashtable (keyed by the string
1353   //of the field access) keeps track of an ArrayList of taints of SESEblocks that conflict on that
1354   //field.
1355   private class BucketOfEffects {
1356     // This table is used for lookup while creating the traversal.
1357     Hashtable<Taint, EffectsGroup> taint2EffectsGroup;
1358     
1359     //This table is used to help identify weakly connected groups: Contains ONLY 
1360     //conflicting effects AND is only initialized when needed
1361     //String stores the field
1362     Hashtable<String, ArrayList<Taint>> potentiallyConflictingRoots;
1363
1364     public BucketOfEffects() {
1365       taint2EffectsGroup = new Hashtable<Taint, EffectsGroup>();
1366     }
1367
1368     public void add(Taint t, Effect e, boolean conflict) {
1369       EffectsGroup effectsForGivenTaint;
1370
1371       if ((effectsForGivenTaint = taint2EffectsGroup.get(t)) == null) {
1372         effectsForGivenTaint = new EffectsGroup();
1373         taint2EffectsGroup.put(t, effectsForGivenTaint);
1374       }
1375
1376       if (e.getField().getType().isPrimitive()) {
1377         if (conflict) {
1378           effectsForGivenTaint.addPrimitive(e, true);
1379         }
1380       } else {
1381         effectsForGivenTaint.addObjEffect(e, conflict);
1382       }
1383       
1384       if(conflict) {
1385         if(potentiallyConflictingRoots == null) {
1386           potentiallyConflictingRoots = new Hashtable<String, ArrayList<Taint>>();
1387         }
1388         
1389         ArrayList<Taint> taintsForField = potentiallyConflictingRoots.get(e.getField().getSafeSymbol());
1390         if(taintsForField == null) {
1391           taintsForField = new ArrayList<Taint>();
1392           potentiallyConflictingRoots.put(e.getField().getSafeSymbol(), taintsForField);
1393         }
1394         
1395         if(!taintsForField.contains(t)) {
1396           taintsForField.add(t);
1397         }
1398       }
1399     }
1400   }
1401   
1402   private class TaintAndInternalHeapStructure {
1403     public Taint t;
1404     public Hashtable<Integer, ConcreteRuntimeObjNode> nodesInHeap;
1405     
1406     public TaintAndInternalHeapStructure(Taint taint, Hashtable<Integer, ConcreteRuntimeObjNode> nodesInHeap) {
1407       t = taint;
1408       this.nodesInHeap = nodesInHeap;
1409     }
1410   }
1411   
1412   private class TraversalInfo {
1413     public FlatNode f;
1414     public ReachGraph rg;
1415     public TempDescriptor invar;
1416     
1417     public TraversalInfo(FlatNode fn, ReachGraph g) {
1418       f = fn;
1419       rg =g;
1420       invar = null;
1421     }
1422
1423     public TraversalInfo(FlatNode fn, ReachGraph rg2, TempDescriptor tempDesc) {
1424       f = fn;
1425       rg =rg2;
1426       invar = tempDesc;
1427     }
1428   }
1429 }