fix: make OID only available for MLP.
[IRC.git] / Robust / src / IR / Flat / BuildCode.java
1 package IR.Flat;
2 import IR.Tree.Modifiers;
3 import IR.Tree.FlagExpressionNode;
4 import IR.Tree.DNFFlag;
5 import IR.Tree.DNFFlagAtom;
6 import IR.Tree.TagExpressionList;
7 import IR.Tree.OffsetNode;
8 import IR.*;
9 import java.util.*;
10 import java.io.*;
11
12 import Util.Relation;
13 import Analysis.TaskStateAnalysis.FlagState;
14 import Analysis.TaskStateAnalysis.FlagComparator;
15 import Analysis.TaskStateAnalysis.OptionalTaskDescriptor;
16 import Analysis.TaskStateAnalysis.Predicate;
17 import Analysis.TaskStateAnalysis.SafetyAnalysis;
18 import Analysis.TaskStateAnalysis.TaskIndex;
19 import Analysis.Locality.LocalityAnalysis;
20 import Analysis.Locality.LocalityBinding;
21 import Analysis.Locality.DiscoverConflicts;
22 import Analysis.Locality.DCWrapper;
23 import Analysis.Locality.DelayComputation;
24 import Analysis.Locality.BranchAnalysis;
25 import Analysis.CallGraph.CallGraph;
26 import Analysis.Prefetch.*;
27 import Analysis.Loops.WriteBarrier;
28 import Analysis.Loops.GlobalFieldType;
29 import Analysis.Locality.TypeAnalysis;
30 import Analysis.MLP.ConflictGraph;
31 import Analysis.MLP.ConflictNode;
32 import Analysis.MLP.MLPAnalysis;
33 import Analysis.MLP.ParentChildConflictsMap;
34 import Analysis.MLP.SESELock;
35 import Analysis.MLP.SESEWaitingQueue;
36 import Analysis.MLP.VariableSourceToken;
37 import Analysis.MLP.VSTWrapper;
38 import Analysis.MLP.CodePlan;
39 import Analysis.MLP.SESEandAgePair;
40 import Analysis.MLP.WaitingElement;
41
42 public class BuildCode {
43   State state;
44   Hashtable temptovar;
45   Hashtable paramstable;
46   Hashtable tempstable;
47   Hashtable fieldorder;
48   Hashtable flagorder;
49   int tag=0;
50   String localsprefix="___locals___";
51   String localsprefixaddr="&"+localsprefix;
52   String localsprefixderef=localsprefix+".";
53   String fcrevert="___fcrevert___";
54   String paramsprefix="___params___";
55   String oidstr="___nextobject___";
56   String nextobjstr="___nextobject___";
57   String localcopystr="___localcopy___";
58   public static boolean GENERATEPRECISEGC=false;
59   public static String PREFIX="";
60   public static String arraytype="ArrayObject";
61   public static int flagcount = 0;
62   Virtual virtualcalls;
63   TypeUtil typeutil;
64   protected int maxtaskparams=0;
65   private int maxcount=0;
66   ClassDescriptor[] cdarray;
67   TypeDescriptor[] arraytable;
68   LocalityAnalysis locality;
69   Hashtable<LocalityBinding, TempDescriptor> reverttable;
70   Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>> backuptable;
71   SafetyAnalysis sa;
72   PrefetchAnalysis pa;
73   MLPAnalysis mlpa;
74   String mlperrstr = "if(status != 0) { "+
75     "sprintf(errmsg, \"MLP error at %s:%d\", __FILE__, __LINE__); "+
76     "perror(errmsg); exit(-1); }";
77   boolean nonSESEpass=true;
78   WriteBarrier wb;
79   DiscoverConflicts dc;
80   DiscoverConflicts recorddc;
81   DCWrapper delaycomp;
82   CallGraph callgraph;
83
84
85   public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa) {
86     this(st, temptovar, typeutil, null, sa, pa, null);
87   }
88
89   public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa) {
90     this(st, temptovar, typeutil, null, sa, pa, mlpa);
91   }
92
93   public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, PrefetchAnalysis pa, MLPAnalysis mlpa) {
94     this(st, temptovar, typeutil, locality, null, pa, mlpa);
95   }
96
97   public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa) {
98     this.sa=sa;
99     this.pa=pa;
100     this.mlpa=mlpa;
101     state=st;
102     callgraph=new CallGraph(state);
103     if (state.SINGLETM)
104       oidstr="___objlocation___";
105     this.temptovar=temptovar;
106     paramstable=new Hashtable();
107     tempstable=new Hashtable();
108     fieldorder=new Hashtable();
109     flagorder=new Hashtable();
110     this.typeutil=typeutil;
111     virtualcalls=new Virtual(state,locality);
112     if (locality!=null) {
113       this.locality=locality;
114       this.reverttable=new Hashtable<LocalityBinding, TempDescriptor>();
115       this.backuptable=new Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>>();
116       this.wb=new WriteBarrier(locality, st);
117     }
118     if (state.SINGLETM&&state.DCOPTS) {
119       TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
120       GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
121       this.dc=new DiscoverConflicts(locality, st, typeanalysis, gft);
122       dc.doAnalysis();
123     }
124     if (state.DELAYCOMP) {
125       //TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
126       TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
127       GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
128       delaycomp=new DCWrapper(locality, st, typeanalysis, gft);
129       dc=delaycomp.getConflicts();
130       recorddc=new DiscoverConflicts(locality, st, typeanalysis, delaycomp.getCannotDelayMap(), true, true, null);
131       recorddc.doAnalysis();
132     }
133   }
134
135   /** The buildCode method outputs C code for all the methods.  The Flat
136    * versions of the methods must already be generated and stored in
137    * the State object. */
138   PrintWriter outsandbox=null;
139
140   public void buildCode() {
141     /* Create output streams to write to */
142     PrintWriter outclassdefs=null;
143     PrintWriter outstructs=null;
144     PrintWriter outrepairstructs=null;
145     PrintWriter outmethodheader=null;
146     PrintWriter outmethod=null;
147     PrintWriter outvirtual=null;
148     PrintWriter outtask=null;
149     PrintWriter outtaskdefs=null;
150     PrintWriter outoptionalarrays=null;
151     PrintWriter optionalheaders=null;
152
153     try {
154       if (state.SANDBOX) {
155         outsandbox=new PrintWriter(new FileOutputStream(PREFIX+"sandboxdefs.c"), true);
156       }
157       outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
158       outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
159       outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
160       outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
161       outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
162       if (state.TASK) {
163         outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
164         outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
165         if (state.OPTIONAL) {
166           outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
167           optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
168         }
169       }
170       if (state.structfile!=null) {
171         outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
172       }
173     } catch (Exception e) {
174       e.printStackTrace();
175       System.exit(-1);
176     }
177
178     /* Build the virtual dispatch tables */
179     buildVirtualTables(outvirtual);
180
181     /* Output includes */
182     outmethodheader.println("#ifndef METHODHEADERS_H");
183     outmethodheader.println("#define METHODHEADERS_H");
184     outmethodheader.println("#include \"structdefs.h\"");
185     if (state.DSM)
186       outmethodheader.println("#include \"dstm.h\"");
187     if (state.SANDBOX) {
188       outmethodheader.println("#include \"sandbox.h\"");
189     }
190     if (state.EVENTMONITOR) {
191       outmethodheader.println("#include \"monitor.h\"");
192     }
193     if (state.SINGLETM) {
194       outmethodheader.println("#include \"tm.h\"");
195       outmethodheader.println("#include \"delaycomp.h\"");
196       outmethodheader.println("#include \"inlinestm.h\"");
197     }
198     if (state.ABORTREADERS) {
199       outmethodheader.println("#include \"abortreaders.h\"");
200       outmethodheader.println("#include <setjmp.h>");
201     }
202     if (state.MLP) {
203       outmethodheader.println("#include <stdlib.h>");
204       outmethodheader.println("#include <stdio.h>");
205       outmethodheader.println("#include <string.h>");
206       outmethodheader.println("#include \"mlp_runtime.h\"");
207       outmethodheader.println("#include \"psemaphore.h\"");
208     }
209
210     /* Output Structures */
211     outputStructs(outstructs);
212
213     // Output the C class declarations
214     // These could mutually reference each other
215     outputClassDeclarations(outclassdefs);
216
217     // Output function prototypes and structures for parameters
218     Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
219     while(it.hasNext()) {
220       ClassDescriptor cn=(ClassDescriptor)it.next();
221       generateCallStructs(cn, outclassdefs, outstructs, outmethodheader);
222     }
223     outclassdefs.close();
224
225     if (state.TASK) {
226       /* Map flags to integers */
227       /* The runtime keeps track of flags using these integers */
228       it=state.getClassSymbolTable().getDescriptorsIterator();
229       while(it.hasNext()) {
230         ClassDescriptor cn=(ClassDescriptor)it.next();
231         mapFlags(cn);
232       }
233       /* Generate Tasks */
234       generateTaskStructs(outstructs, outmethodheader);
235
236       /* Outputs generic task structures if this is a task
237          program */
238       outputTaskTypes(outtask);
239     }
240
241     if( state.MLP ) {
242       // have to initialize some SESE compiler data before
243       // analyzing normal methods, which must happen before
244       // generating SESE internal code
245       for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
246         FlatSESEEnterNode fsen = seseit.next();
247         initializeSESE( fsen );
248       }
249     }
250
251     /* Build the actual methods */
252     outputMethods(outmethod);
253
254     // Output function prototypes and structures for SESE's and code
255     if( state.MLP ) {
256
257       // used to differentiate, during code generation, whether we are
258       // passing over SESE body code, or non-SESE code
259       nonSESEpass = false;
260
261       // first generate code for each sese's internals
262       for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
263         FlatSESEEnterNode fsen = seseit.next();
264         generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
265       }
266
267       // then write the invokeSESE switch to decouple scheduler
268       // from having to do unique details of sese invocation
269       generateSESEinvocationMethod(outmethodheader, outmethod);
270     }
271
272     if (state.TASK) {
273       /* Output code for tasks */
274       outputTaskCode(outtaskdefs, outmethod);
275       outtaskdefs.close();
276       /* Record maximum number of task parameters */
277       outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
278     } else if (state.main!=null) {
279       /* Generate main method */
280       outputMainMethod(outmethod);
281     }
282
283     /* Generate information for task with optional parameters */
284     if (state.TASK&&state.OPTIONAL) {
285       generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
286       outoptionalarrays.close();
287     }
288     
289     /* Output structure definitions for repair tool */
290     if (state.structfile!=null) {
291       buildRepairStructs(outrepairstructs);
292       outrepairstructs.close();
293     }
294     
295     /* Close files */
296     outmethodheader.println("#endif");
297     outmethodheader.close();
298     outmethod.close();
299     outstructs.println("#endif");
300     outstructs.close();
301   }
302   
303
304   /* This code just generates the main C method for java programs.
305    * The main C method packs up the arguments into a string array
306    * and passes it to the java main method. */
307
308   private void outputMainMethod(PrintWriter outmethod) {
309     outmethod.println("int main(int argc, const char *argv[]) {");
310     outmethod.println("  int i;");
311
312     if (state.MLP) {
313       //outmethod.println("  pthread_once( &mlpOnceObj, mlpInitOncePerThread );");
314       outmethod.println("  workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
315     }
316
317     if (state.DSM) {
318       if (state.DSMRECOVERYSTATS) {
319         outmethod.println("#ifdef RECOVERYSTATS \n");
320         outmethod.println("handle();\n");
321         outmethod.println("#endif\n");
322       } else {
323         outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
324         outmethod.println("handle();\n");
325         outmethod.println("#endif\n");
326       }
327     }
328     
329     if (state.THREAD||state.DSM||state.SINGLETM) {
330       outmethod.println("initializethreads();");
331     }
332     if (state.DSM) {
333       outmethod.println("if (dstmStartup(argv[1])) {");
334       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
335         outmethod.println("  struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
336       } else {
337         outmethod.println("  struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
338       }
339     } else {
340       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
341         outmethod.println("  struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
342       } else {
343         outmethod.println("  struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
344       }
345     }
346     if (state.DSM) {
347       outmethod.println("  for(i=2;i<argc;i++) {");
348     } else
349       outmethod.println("  for(i=1;i<argc;i++) {");
350     outmethod.println("    int length=strlen(argv[i]);");
351     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
352       outmethod.println("    struct ___String___ *newstring=NewString(NULL, argv[i], length);");
353     } else {
354       outmethod.println("    struct ___String___ *newstring=NewString(argv[i], length);");
355     }
356     if (state.DSM)
357       outmethod.println("    ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
358     else
359       outmethod.println("    ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
360     outmethod.println("  }");
361
362     MethodDescriptor md=typeutil.getMain();
363     ClassDescriptor cd=typeutil.getMainClass();
364
365     outmethod.println("   {");
366     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
367       if (state.DSM||state.SINGLETM) {
368         outmethod.print("       struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
369       } else
370         outmethod.print("       struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
371     outmethod.println("1, NULL,"+"stringarray};");
372       if (state.DSM||state.SINGLETM)
373         outmethod.println("     "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
374       else
375         outmethod.println("     "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
376     } else {
377       if (state.DSM||state.SINGLETM)
378         outmethod.println("     "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
379       else
380         outmethod.println("     "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
381     }
382     outmethod.println("   }");
383
384     if (state.DSM) {
385       outmethod.println("}");
386     }
387
388     if (state.THREAD||state.DSM||state.SINGLETM) {
389       outmethod.println("pthread_mutex_lock(&gclistlock);");
390       outmethod.println("threadcount--;");
391       outmethod.println("pthread_cond_signal(&gccond);");
392       outmethod.println("pthread_mutex_unlock(&gclistlock);");
393     }
394
395     if (state.DSM||state.SINGLETM) {
396       //outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
397       outmethod.println("#if defined(TRANSSTATS) \n");
398       outmethod.println("printf(\"******  Transaction Stats   ******\\n\");");
399       outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
400       outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
401       outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
402       if (state.DSM) {
403         outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
404         outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
405         outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
406         outmethod.println("printf(\"ndirtyCacheObj= %d\\n\", ndirtyCacheObj);");
407         outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
408         outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
409         outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
410         outmethod.println("printf(\"totalObjSize= %d\\n\", totalObjSize);");
411         outmethod.println("printf(\"sendRemoteReq= %d\\n\", sendRemoteReq);");
412         outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
413       } else if (state.SINGLETM) {
414         outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
415         outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
416         outmethod.println("#ifdef STMSTATS\n");
417         outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
418         outmethod.println("  printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
419         outmethod.println("}\n");
420         outmethod.println("#endif\n");
421         outmethod.println("fflush(stdout);");
422       }
423       outmethod.println("#endif\n");
424     }
425
426     if (state.EVENTMONITOR) {
427       outmethod.println("dumpdata();");
428     }
429
430     if (state.THREAD||state.SINGLETM)
431       outmethod.println("pthread_exit(NULL);");
432
433     if (state.MLP) {
434       outmethod.println("  workScheduleBegin();");
435     }
436
437     outmethod.println("}");
438   }
439
440   /* This method outputs code for each task. */
441
442   private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
443     /* Compile task based program */
444     outtaskdefs.println("#include \"task.h\"");
445     outtaskdefs.println("#include \"methodheaders.h\"");
446     Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
447     while(taskit.hasNext()) {
448       TaskDescriptor td=(TaskDescriptor)taskit.next();
449       FlatMethod fm=state.getMethodFlat(td);
450       generateFlatMethod(fm, null, outmethod);
451       generateTaskDescriptor(outtaskdefs, fm, td);
452     }
453
454     //Output task descriptors
455     taskit=state.getTaskSymbolTable().getDescriptorsIterator();
456     outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
457     boolean first=true;
458     while(taskit.hasNext()) {
459       TaskDescriptor td=(TaskDescriptor)taskit.next();
460       if (first)
461         first=false;
462       else
463         outtaskdefs.println(",");
464       outtaskdefs.print("&task_"+td.getSafeSymbol());
465     }
466     outtaskdefs.println("};");
467
468     outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
469   }
470
471   /* This method outputs most of the methods.c file.  This includes
472    * some standard includes and then an array with the sizes of
473    * objets and array that stores supertype and then the code for
474    * the Java methods.. */
475
476   protected void outputMethods(PrintWriter outmethod) {
477     outmethod.println("#include \"methodheaders.h\"");
478     outmethod.println("#include \"virtualtable.h\"");
479     outmethod.println("#include \"runtime.h\"");
480     if (state.SANDBOX) {
481       outmethod.println("#include \"sandboxdefs.c\"");
482     }
483     if (state.DSM) {
484       outmethod.println("#include \"addPrefetchEnhance.h\"");
485       outmethod.println("#include \"localobjects.h\"");
486     }
487     if (state.FASTCHECK) {
488       outmethod.println("#include \"localobjects.h\"");
489     }
490     if(state.MULTICORE) {
491       outmethod.println("#include \"task.h\"");
492           outmethod.println("#include \"multicoreruntime.h\"");
493           outmethod.println("#include \"runtime_arch.h\"");
494     }
495     if (state.THREAD||state.DSM||state.SINGLETM)
496       outmethod.println("#include <thread.h>");
497     if (state.main!=null) {
498       outmethod.println("#include <string.h>");
499     }
500     if (state.CONSCHECK) {
501       outmethod.println("#include \"checkers.h\"");
502     }
503     if (state.MLP) {
504       outmethod.println("#include <stdlib.h>");
505       outmethod.println("#include <stdio.h>");
506       outmethod.println("#include \"mlp_runtime.h\"");
507       outmethod.println("#include \"psemaphore.h\"");
508     }
509
510
511     //Store the sizes of classes & array elements
512     generateSizeArray(outmethod);
513
514     //Store table of supertypes
515     generateSuperTypeTable(outmethod);
516
517     //Store the layout of classes
518     generateLayoutStructs(outmethod);
519
520     /* Generate code for methods */
521     if (state.DSM||state.SINGLETM) {
522       for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
523         LocalityBinding lb=lbit.next();
524         MethodDescriptor md=lb.getMethod();
525         FlatMethod fm=state.getMethodFlat(md);
526         wb.analyze(lb);
527         if (!md.getModifiers().isNative()) {
528           generateFlatMethod(fm, lb, outmethod);
529       //System.out.println("fm= " + fm + " md= " + md);
530         }
531       }
532     } else {
533       Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
534       while(classit.hasNext()) {
535         ClassDescriptor cn=(ClassDescriptor)classit.next();
536         Iterator methodit=cn.getMethods();
537         while(methodit.hasNext()) {
538           /* Classify parameters */
539           MethodDescriptor md=(MethodDescriptor)methodit.next();
540           FlatMethod fm=state.getMethodFlat(md);
541           if (!md.getModifiers().isNative()) {
542             generateFlatMethod(fm, null, outmethod);
543           }
544         }
545       }
546     }
547   }
548
549   protected void outputStructs(PrintWriter outstructs) {
550     outstructs.println("#ifndef STRUCTDEFS_H");
551     outstructs.println("#define STRUCTDEFS_H");
552     outstructs.println("#include \"classdefs.h\"");
553     outstructs.println("#ifndef INTPTR");
554     outstructs.println("#ifdef BIT64");
555     outstructs.println("#define INTPTR long");
556     outstructs.println("#else");
557     outstructs.println("#define INTPTR int");
558     outstructs.println("#endif");
559     outstructs.println("#endif");
560     if( state.MLP ) {
561       outstructs.println("#include \"mlp_runtime.h\"");
562       outstructs.println("#include \"psemaphore.h\"");
563     }
564
565     /* Output #defines that the runtime uses to determine type
566      * numbers for various objects it needs */
567     outstructs.println("#define MAXCOUNT "+maxcount);
568     if (state.DSM||state.SINGLETM) {
569       LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
570       if (state.DSM) {
571         lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
572       }
573       else if (state.SINGLETM) {
574         lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
575       }
576       outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
577     }
578
579     if (state.DSMTASK) {
580       LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
581       if(state.DSM)
582         lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
583       else if( state.SINGLETM)
584         lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
585       outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
586     }
587
588     outstructs.println("#define STRINGARRAYTYPE "+
589                        (state.getArrayNumber(
590                           (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
591
592     outstructs.println("#define OBJECTARRAYTYPE "+
593                        (state.getArrayNumber(
594                           (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
595
596
597     outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
598     outstructs.println("#define CHARARRAYTYPE "+
599                        (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
600
601     outstructs.println("#define BYTEARRAYTYPE "+
602                        (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
603
604     outstructs.println("#define BYTEARRAYARRAYTYPE "+
605                        (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
606
607     outstructs.println("#define NUMCLASSES "+state.numClasses());
608     int totalClassSize = state.numClasses() + state.numArrays();
609     outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
610     if (state.TASK) {
611       outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
612       outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
613       outstructs.println("#define TAGARRAYTYPE "+
614                          (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
615     }
616   }
617
618   protected void outputClassDeclarations(PrintWriter outclassdefs) {
619     if (state.THREAD||state.DSM||state.SINGLETM)
620       outclassdefs.println("#include <pthread.h>");
621     outclassdefs.println("#ifndef INTPTR");
622     outclassdefs.println("#ifdef BIT64");
623     outclassdefs.println("#define INTPTR long");
624     outclassdefs.println("#else");
625     outclassdefs.println("#define INTPTR int");
626     outclassdefs.println("#endif");
627     outclassdefs.println("#endif");
628     if(state.OPTIONAL)
629       outclassdefs.println("#include \"optionalstruct.h\"");
630     outclassdefs.println("struct "+arraytype+";");
631     /* Start by declaring all structs */
632     Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
633     while(it.hasNext()) {
634       ClassDescriptor cn=(ClassDescriptor)it.next();
635       outclassdefs.println("struct "+cn.getSafeSymbol()+";");
636     }
637     outclassdefs.println("");
638     //Print out definition for array type
639     outclassdefs.println("struct "+arraytype+" {");
640     outclassdefs.println("  int type;");
641     if(state.MLP){
642       outclassdefs.println("  int oid;");
643     }
644     if (state.EVENTMONITOR) {
645       outclassdefs.println("  int objuid;");
646     }
647     if (state.THREAD) {
648       outclassdefs.println("  pthread_t tid;");
649       outclassdefs.println("  void * lockentry;");
650       outclassdefs.println("  int lockcount;");
651     }
652     if (state.TASK) {
653       outclassdefs.println("  int flag;");
654       if(!state.MULTICORE) {
655         outclassdefs.println("  void * flagptr;");
656       } else {
657         outclassdefs.println("  int version;");
658         outclassdefs.println("  int * lock;");  // lock entry for this obj
659         outclassdefs.println("  int mutex;");  
660         outclassdefs.println("  int lockcount;");
661         if(state.MULTICOREGC) {
662           outclassdefs.println("  int marked;");
663         }
664       }
665       if(state.OPTIONAL) {
666         outclassdefs.println("  int numfses;");
667         outclassdefs.println("  int * fses;");
668       }
669     }
670     printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
671
672     if (state.STMARRAY) {
673       outclassdefs.println("  int lowindex;");
674       outclassdefs.println("  int highindex;");
675     }
676     if (state.ARRAYPAD)
677       outclassdefs.println("  int paddingforarray;");
678     if (state.DUALVIEW) {
679       outclassdefs.println("  int arrayversion;");
680     }
681
682     outclassdefs.println("  int ___length___;");
683     outclassdefs.println("};\n");
684     outclassdefs.println("extern int classsize[];");
685     outclassdefs.println("extern int hasflags[];");
686     outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
687     outclassdefs.println("extern int supertypes[];");
688   }
689
690   /** Prints out definitions for generic task structures */
691
692   private void outputTaskTypes(PrintWriter outtask) {
693     outtask.println("#ifndef _TASK_H");
694     outtask.println("#define _TASK_H");
695     outtask.println("struct parameterdescriptor {");
696     outtask.println("int type;");
697     outtask.println("int numberterms;");
698     outtask.println("int *intarray;");
699     outtask.println("void * queue;");
700     outtask.println("int numbertags;");
701     outtask.println("int *tagarray;");
702     outtask.println("};");
703
704     outtask.println("struct taskdescriptor {");
705     outtask.println("void * taskptr;");
706     outtask.println("int numParameters;");
707     outtask.println("  int numTotal;");
708     outtask.println("struct parameterdescriptor **descriptorarray;");
709     outtask.println("char * name;");
710     outtask.println("};");
711     outtask.println("extern struct taskdescriptor * taskarray[];");
712     outtask.println("extern numtasks;");
713     outtask.println("#endif");
714   }
715
716
717   private void buildRepairStructs(PrintWriter outrepairstructs) {
718     Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
719     while(classit.hasNext()) {
720       ClassDescriptor cn=(ClassDescriptor)classit.next();
721       outrepairstructs.println("structure "+cn.getSymbol()+" {");
722       outrepairstructs.println("  int __type__;");
723       if (state.TASK) {
724         outrepairstructs.println("  int __flag__;");
725         if(!state.MULTICORE) {
726           outrepairstructs.println("  int __flagptr__;");
727         }
728       }
729       printRepairStruct(cn, outrepairstructs);
730       outrepairstructs.println("}\n");
731     }
732
733     for(int i=0; i<state.numArrays(); i++) {
734       TypeDescriptor tdarray=arraytable[i];
735       TypeDescriptor tdelement=tdarray.dereference();
736       outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
737       outrepairstructs.println("  int __type__;");
738       printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
739       outrepairstructs.println("  int length;");
740       /*
741          // Need to add support to repair tool for this
742          if (tdelement.isClass()||tdelement.isArray())
743           outrepairstructs.println("  "+tdelement.getRepairSymbol()+" * elem[this.length];");
744          else
745           outrepairstructs.println("  "+tdelement.getRepairSymbol()+" elem[this.length];");
746        */
747       outrepairstructs.println("}\n");
748     }
749   }
750
751   private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
752     ClassDescriptor sp=cn.getSuperDesc();
753     if (sp!=null)
754       printRepairStruct(sp, output);
755
756     Vector fields=(Vector)fieldorder.get(cn);
757
758     for(int i=0; i<fields.size(); i++) {
759       FieldDescriptor fd=(FieldDescriptor)fields.get(i);
760       if (fd.getType().isArray()) {
761         output.println("  "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
762       } else if (fd.getType().isClass())
763         output.println("  "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
764       else if (fd.getType().isFloat())
765         output.println("  int "+fd.getSymbol()+"; /* really float */");
766       else
767         output.println("  "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
768     }
769   }
770
771   /** This method outputs TaskDescriptor information */
772   private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
773     for (int i=0; i<task.numParameters(); i++) {
774       VarDescriptor param_var=task.getParameter(i);
775       TypeDescriptor param_type=task.getParamType(i);
776       FlagExpressionNode param_flag=task.getFlag(param_var);
777       TagExpressionList param_tag=task.getTag(param_var);
778
779       int dnfterms;
780       if (param_flag==null) {
781         output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
782         output.println("0x0, 0x0 };");
783         dnfterms=1;
784       } else {
785         DNFFlag dflag=param_flag.getDNF();
786         dnfterms=dflag.size();
787
788         Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
789         output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
790         for(int j=0; j<dflag.size(); j++) {
791           if (j!=0)
792             output.println(",");
793           Vector term=dflag.get(j);
794           int andmask=0;
795           int checkmask=0;
796           for(int k=0; k<term.size(); k++) {
797             DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
798             FlagDescriptor fd=dfa.getFlag();
799             boolean negated=dfa.getNegated();
800             int flagid=1<<((Integer)flags.get(fd)).intValue();
801             andmask|=flagid;
802             if (!negated)
803               checkmask|=flagid;
804           }
805           output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
806         }
807         output.println("};");
808       }
809
810       output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
811       //BUG...added next line to fix, test with any task program
812       if (param_tag!=null)
813         for(int j=0; j<param_tag.numTags(); j++) {
814           if (j!=0)
815             output.println(",");
816           /* for each tag we need */
817           /* which slot it is */
818           /* what type it is */
819           TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
820           TempDescriptor tmp=param_tag.getTemp(j);
821           int slot=fm.getTagInt(tmp);
822           output.println(slot+", "+state.getTagId(tvd.getTag()));
823         }
824       output.println("};");
825
826       output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
827       output.println("/* type */"+param_type.getClassDesc().getId()+",");
828       output.println("/* number of DNF terms */"+dnfterms+",");
829       output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
830       output.println("0,");
831       //BUG, added next line to fix and else statement...test
832       //with any task program
833       if (param_tag!=null)
834         output.println("/* number of tags */"+param_tag.numTags()+",");
835       else
836         output.println("/* number of tags */ 0,");
837       output.println("parametertag_"+i+"_"+task.getSafeSymbol());
838       output.println("};");
839     }
840
841
842     output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
843     for (int i=0; i<task.numParameters(); i++) {
844       if (i!=0)
845         output.println(",");
846       output.print("&parameter_"+i+"_"+task.getSafeSymbol());
847     }
848     output.println("};");
849
850     output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
851     output.println("&"+task.getSafeSymbol()+",");
852     output.println("/* number of parameters */" +task.numParameters() + ",");
853     int numtotal=task.numParameters()+fm.numTags();
854     output.println("/* number total parameters */" +numtotal + ",");
855     output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
856     output.println("\""+task.getSymbol()+"\"");
857     output.println("};");
858   }
859
860
861   /** The buildVirtualTables method outputs the virtual dispatch
862    * tables for methods. */
863
864   protected void buildVirtualTables(PrintWriter outvirtual) {
865     Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
866     while(classit.hasNext()) {
867       ClassDescriptor cd=(ClassDescriptor)classit.next();
868       if (virtualcalls.getMethodCount(cd)>maxcount)
869         maxcount=virtualcalls.getMethodCount(cd);
870     }
871     MethodDescriptor[][] virtualtable=null;
872     LocalityBinding[][] lbvirtualtable=null;
873     if (state.DSM||state.SINGLETM)
874       lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
875     else
876       virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
877
878     /* Fill in virtual table */
879     classit=state.getClassSymbolTable().getDescriptorsIterator();
880     while(classit.hasNext()) {
881       ClassDescriptor cd=(ClassDescriptor)classit.next();
882       if (state.DSM||state.SINGLETM)
883         fillinRow(cd, lbvirtualtable, cd.getId());
884       else
885         fillinRow(cd, virtualtable, cd.getId());
886     }
887
888     ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
889     Iterator arrayit=state.getArrayIterator();
890     while(arrayit.hasNext()) {
891       TypeDescriptor td=(TypeDescriptor)arrayit.next();
892       int id=state.getArrayNumber(td);
893       if (state.DSM||state.SINGLETM)
894         fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
895       else
896         fillinRow(objectcd, virtualtable, id+state.numClasses());
897     }
898
899     outvirtual.print("void * virtualtable[]={");
900     boolean needcomma=false;
901     for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
902       for(int j=0; j<maxcount; j++) {
903         if (needcomma)
904           outvirtual.print(", ");
905         if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
906           LocalityBinding lb=lbvirtualtable[i][j];
907           MethodDescriptor md=lb.getMethod();
908           outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
909         } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
910           MethodDescriptor md=virtualtable[i][j];
911           outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
912         } else {
913           outvirtual.print("0");
914         }
915         needcomma=true;
916       }
917       outvirtual.println("");
918     }
919     outvirtual.println("};");
920     outvirtual.close();
921   }
922
923   private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
924     /* Get inherited methods */
925     if (cd.getSuperDesc()!=null)
926       fillinRow(cd.getSuperDesc(), virtualtable, rownum);
927     /* Override them with our methods */
928     for(Iterator it=cd.getMethods(); it.hasNext();) {
929       MethodDescriptor md=(MethodDescriptor)it.next();
930       if (md.isStatic()||md.getReturnType()==null)
931         continue;
932       int methodnum=virtualcalls.getMethodNumber(md);
933       virtualtable[rownum][methodnum]=md;
934     }
935   }
936
937   private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
938     /* Get inherited methods */
939     if (cd.getSuperDesc()!=null)
940       fillinRow(cd.getSuperDesc(), virtualtable, rownum);
941     /* Override them with our methods */
942     if (locality.getClassBindings(cd)!=null)
943       for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
944         LocalityBinding lb=lbit.next();
945         MethodDescriptor md=lb.getMethod();
946         //Is the method static or a constructor
947         if (md.isStatic()||md.getReturnType()==null)
948           continue;
949         int methodnum=virtualcalls.getLocalityNumber(lb);
950         virtualtable[rownum][methodnum]=lb;
951       }
952   }
953
954   /** Generate array that contains the sizes of class objects.  The
955    * object allocation functions in the runtime use this
956    * information. */
957
958   private void generateSizeArray(PrintWriter outclassdefs) {
959     outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
960     outclassdefs.print("#ifdef TRANSSTATS \n");
961     outclassdefs.print("extern int numTransAbort;\n");
962     outclassdefs.print("extern int numTransCommit;\n");
963     outclassdefs.print("extern int nSoftAbort;\n");
964     if (state.DSM) {
965       outclassdefs.print("extern int nchashSearch;\n");
966       outclassdefs.print("extern int nmhashSearch;\n");
967       outclassdefs.print("extern int nprehashSearch;\n");
968       outclassdefs.print("extern int ndirtyCacheObj;\n");
969       outclassdefs.print("extern int nRemoteSend;\n");
970       outclassdefs.print("extern int sendRemoteReq;\n");
971       outclassdefs.print("extern int getResponse;\n");
972       outclassdefs.print("extern int bytesSent;\n");
973       outclassdefs.print("extern int bytesRecv;\n");
974       outclassdefs.print("extern int totalObjSize;\n");
975       outclassdefs.print("extern void handle();\n");
976     } else if (state.SINGLETM) {
977       outclassdefs.println("extern int nSoftAbortAbort;");
978       outclassdefs.println("extern int nSoftAbortCommit;");
979       outclassdefs.println("#ifdef STMSTATS\n");
980       outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
981       outclassdefs.println("#endif\n");
982     }
983     outclassdefs.print("#endif\n");
984
985     outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
986     if(this.state.MLP){
987         outclassdefs.print("extern __thread int oid;\n");
988         outclassdefs.print("extern int numWorkers;\n");
989     }
990
991     Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
992     cdarray=new ClassDescriptor[state.numClasses()];
993     cdarray[0] = null;
994     while(it.hasNext()) {
995       ClassDescriptor cd=(ClassDescriptor)it.next();
996       cdarray[cd.getId()]=cd;
997     }
998
999     arraytable=new TypeDescriptor[state.numArrays()];
1000
1001     Iterator arrayit=state.getArrayIterator();
1002     while(arrayit.hasNext()) {
1003       TypeDescriptor td=(TypeDescriptor)arrayit.next();
1004       int id=state.getArrayNumber(td);
1005       arraytable[id]=td;
1006     }
1007
1008
1009
1010     /* Print out types */
1011     outclassdefs.println("/* ");
1012     for(int i=0; i<state.numClasses(); i++) {
1013       ClassDescriptor cd=cdarray[i];
1014       if(cd == null) {
1015         outclassdefs.println("NULL " + i);
1016       } else {
1017         outclassdefs.println(cd +"  "+i);
1018       }
1019     }
1020
1021     for(int i=0; i<state.numArrays(); i++) {
1022       TypeDescriptor arraytd=arraytable[i];
1023       outclassdefs.println(arraytd.toPrettyString() +"  "+(i+state.numClasses()));
1024     }
1025
1026     outclassdefs.println("*/");
1027
1028
1029     outclassdefs.print("int classsize[]={");
1030
1031     boolean needcomma=false;
1032     for(int i=0; i<state.numClasses(); i++) {
1033       if (needcomma)
1034         outclassdefs.print(", ");
1035       if(i>0) {
1036         outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1037       } else {
1038         outclassdefs.print("0");
1039       }
1040       needcomma=true;
1041     }
1042
1043
1044     for(int i=0; i<state.numArrays(); i++) {
1045       if (needcomma)
1046         outclassdefs.print(", ");
1047       TypeDescriptor tdelement=arraytable[i].dereference();
1048       if (tdelement.isArray()||tdelement.isClass())
1049         outclassdefs.print("sizeof(void *)");
1050       else
1051         outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1052       needcomma=true;
1053     }
1054
1055     outclassdefs.println("};");
1056
1057     ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1058     needcomma=false;
1059     outclassdefs.print("int typearray[]={");
1060     for(int i=0; i<state.numClasses(); i++) {
1061       ClassDescriptor cd=cdarray[i];
1062       ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1063       if (needcomma)
1064         outclassdefs.print(", ");
1065       if (supercd==null)
1066         outclassdefs.print("-1");
1067       else
1068         outclassdefs.print(supercd.getId());
1069       needcomma=true;
1070     }
1071
1072     for(int i=0; i<state.numArrays(); i++) {
1073       TypeDescriptor arraytd=arraytable[i];
1074       ClassDescriptor arraycd=arraytd.getClassDesc();
1075       if (arraycd==null) {
1076         if (needcomma)
1077           outclassdefs.print(", ");
1078         outclassdefs.print(objectclass.getId());
1079         needcomma=true;
1080         continue;
1081       }
1082       ClassDescriptor cd=arraycd.getSuperDesc();
1083       int type=-1;
1084       while(cd!=null) {
1085         TypeDescriptor supertd=new TypeDescriptor(cd);
1086         supertd.setArrayCount(arraytd.getArrayCount());
1087         type=state.getArrayNumber(supertd);
1088         if (type!=-1) {
1089           type+=state.numClasses();
1090           break;
1091         }
1092         cd=cd.getSuperDesc();
1093       }
1094       if (needcomma)
1095         outclassdefs.print(", ");
1096       outclassdefs.print(type);
1097       needcomma=true;
1098     }
1099
1100     outclassdefs.println("};");
1101
1102     needcomma=false;
1103
1104
1105     outclassdefs.print("int typearray2[]={");
1106     for(int i=0; i<state.numArrays(); i++) {
1107       TypeDescriptor arraytd=arraytable[i];
1108       ClassDescriptor arraycd=arraytd.getClassDesc();
1109       if (arraycd==null) {
1110         if (needcomma)
1111           outclassdefs.print(", ");
1112         outclassdefs.print("-1");
1113         needcomma=true;
1114         continue;
1115       }
1116       ClassDescriptor cd=arraycd.getSuperDesc();
1117       int level=arraytd.getArrayCount()-1;
1118       int type=-1;
1119       for(; level>0; level--) {
1120         TypeDescriptor supertd=new TypeDescriptor(objectclass);
1121         supertd.setArrayCount(level);
1122         type=state.getArrayNumber(supertd);
1123         if (type!=-1) {
1124           type+=state.numClasses();
1125           break;
1126         }
1127       }
1128       if (needcomma)
1129         outclassdefs.print(", ");
1130       outclassdefs.print(type);
1131       needcomma=true;
1132     }
1133
1134     outclassdefs.println("};");
1135   }
1136
1137   /** Constructs params and temp objects for each method or task.
1138    * These objects tell the compiler which temps need to be
1139    * allocated.  */
1140
1141   protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1142     MethodDescriptor md=fm.getMethod();
1143     TaskDescriptor task=fm.getTask();
1144     Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1145     ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1146     if (lb!=null) {
1147       paramstable.put(lb, objectparams);
1148       backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1149     } else if (md!=null)
1150       paramstable.put(md, objectparams);
1151     else
1152       paramstable.put(task, objectparams);
1153
1154     for(int i=0; i<fm.numParameters(); i++) {
1155       TempDescriptor temp=fm.getParameter(i);
1156       TypeDescriptor type=temp.getType();
1157       if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1158         objectparams.addPtr(temp);
1159       else
1160         objectparams.addPrim(temp);
1161       if(lb!=null&&saveset.contains(temp)) {
1162         backuptable.get(lb).put(temp, temp.createNew());
1163       }
1164     }
1165
1166     for(int i=0; i<fm.numTags(); i++) {
1167       TempDescriptor temp=fm.getTag(i);
1168       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1169         objectparams.addPtr(temp);
1170       else
1171         objectparams.addPrim(temp);
1172     }
1173
1174     TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1175     if (lb!=null)
1176       tempstable.put(lb, objecttemps);
1177     else if (md!=null)
1178       tempstable.put(md, objecttemps);
1179     else
1180       tempstable.put(task, objecttemps);
1181
1182     for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1183       FlatNode fn=(FlatNode)nodeit.next();
1184       TempDescriptor[] writes=fn.writesTemps();
1185       for(int i=0; i<writes.length; i++) {
1186         TempDescriptor temp=writes[i];
1187         TypeDescriptor type=temp.getType();
1188         if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1189           objecttemps.addPtr(temp);
1190         else
1191           objecttemps.addPrim(temp);
1192         if(lb!=null&&saveset.contains(temp)&&
1193            !backuptable.get(lb).containsKey(temp))
1194           backuptable.get(lb).put(temp, temp.createNew());
1195       }
1196     }
1197
1198     /* Create backup temps */
1199     if (lb!=null) {
1200       for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1201         TempDescriptor tmp=tmpit.next();
1202         TypeDescriptor type=tmp.getType();
1203         if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1204           objecttemps.addPtr(tmp);
1205         else
1206           objecttemps.addPrim(tmp);
1207       }
1208       /* Create temp to hold revert table */
1209       if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1210         TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1211         if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1212           objecttemps.addPtr(reverttmp);
1213         else
1214           objecttemps.addPrim(reverttmp);
1215         reverttable.put(lb, reverttmp);
1216       }
1217     }
1218   }
1219
1220   /** This method outputs the following information about classes
1221    * and arrays:
1222    * (1) For classes, what are the locations of pointers.
1223    * (2) For arrays, does the array contain pointers or primitives.
1224    * (3) For classes, does the class contain flags.
1225    */
1226
1227   private void generateLayoutStructs(PrintWriter output) {
1228     Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1229     while(it.hasNext()) {
1230       ClassDescriptor cn=(ClassDescriptor)it.next();
1231       output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1232       Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1233       int count=0;
1234       while(allit.hasNext()) {
1235         FieldDescriptor fd=(FieldDescriptor)allit.next();
1236         TypeDescriptor type=fd.getType();
1237         if (state.DSM&&fd.isGlobal())         //Don't GC the global objects for now
1238           continue;
1239         if (type.isPtr())
1240           count++;
1241       }
1242       output.print(count);
1243       allit=cn.getFieldTable().getAllDescriptorsIterator();
1244       while(allit.hasNext()) {
1245         FieldDescriptor fd=(FieldDescriptor)allit.next();
1246         TypeDescriptor type=fd.getType();
1247         if (state.DSM&&fd.isGlobal())         //Don't GC the global objects for now
1248           continue;
1249         if (type.isPtr()) {
1250           output.println(",");
1251           output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1252         }
1253       }
1254       output.println("};");
1255     }
1256     output.println("unsigned INTPTR * pointerarray[]={");
1257     boolean needcomma=false;
1258     for(int i=0; i<state.numClasses(); i++) {
1259       ClassDescriptor cn=cdarray[i];
1260       if (needcomma)
1261         output.println(",");
1262       needcomma=true;
1263       if(cn != null) {
1264         output.print(cn.getSafeSymbol()+"_pointers");
1265       } else {
1266         output.print("NULL");
1267       }
1268     }
1269
1270     for(int i=0; i<state.numArrays(); i++) {
1271       if (needcomma)
1272         output.println(", ");
1273       TypeDescriptor tdelement=arraytable[i].dereference();
1274       if (tdelement.isArray()||tdelement.isClass())
1275         output.print("((unsigned INTPTR *)1)");
1276       else
1277         output.print("0");
1278       needcomma=true;
1279     }
1280
1281     output.println("};");
1282     needcomma=false;
1283     output.println("int hasflags[]={");
1284     for(int i=0; i<state.numClasses(); i++) {
1285       ClassDescriptor cn=cdarray[i];
1286       if (needcomma)
1287         output.println(", ");
1288       needcomma=true;
1289       if ((cn != null) && (cn.hasFlags()))
1290         output.print("1");
1291       else
1292         output.print("0");
1293     }
1294     output.println("};");
1295   }
1296
1297   /** Print out table to give us supertypes */
1298   private void generateSuperTypeTable(PrintWriter output) {
1299     output.println("int supertypes[]={");
1300     boolean needcomma=false;
1301     for(int i=0; i<state.numClasses(); i++) {
1302       ClassDescriptor cn=cdarray[i];
1303       if (needcomma)
1304         output.println(",");
1305       needcomma=true;
1306       if ((cn != null) && (cn.getSuperDesc()!=null)) {
1307         ClassDescriptor cdsuper=cn.getSuperDesc();
1308         output.print(cdsuper.getId());
1309       } else
1310         output.print("-1");
1311     }
1312     output.println("};");
1313   }
1314
1315   /** Force consistent field ordering between inherited classes. */
1316
1317   private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1318
1319     ClassDescriptor sp=cn.getSuperDesc();
1320     if (sp!=null)
1321       printClassStruct(sp, classdefout);
1322
1323     if (!fieldorder.containsKey(cn)) {
1324       Vector fields=new Vector();
1325       fieldorder.put(cn,fields);
1326       Vector fieldvec=cn.getFieldVec();
1327       for(int i=0;i<fieldvec.size();i++) {
1328         FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1329         if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1330           fields.add(fd);
1331       }
1332     }
1333     Vector fields=(Vector)fieldorder.get(cn);
1334
1335     for(int i=0; i<fields.size(); i++) {
1336       FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1337       if (fd.getType().isClass()||fd.getType().isArray())
1338         classdefout.println("  struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1339       else
1340         classdefout.println("  "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1341     }
1342   }
1343
1344
1345   /* Map flags to integers consistently between inherited
1346    * classes. */
1347
1348   protected void mapFlags(ClassDescriptor cn) {
1349     ClassDescriptor sp=cn.getSuperDesc();
1350     if (sp!=null)
1351       mapFlags(sp);
1352     int max=0;
1353     if (!flagorder.containsKey(cn)) {
1354       Hashtable flags=new Hashtable();
1355       flagorder.put(cn,flags);
1356       if (sp!=null) {
1357         Hashtable superflags=(Hashtable)flagorder.get(sp);
1358         Iterator superflagit=superflags.keySet().iterator();
1359         while(superflagit.hasNext()) {
1360           FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1361           Integer number=(Integer)superflags.get(fd);
1362           flags.put(fd, number);
1363           if ((number.intValue()+1)>max)
1364             max=number.intValue()+1;
1365         }
1366       }
1367
1368       Iterator flagit=cn.getFlags();
1369       while(flagit.hasNext()) {
1370         FlagDescriptor fd=(FlagDescriptor)flagit.next();
1371         if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1372           flags.put(fd, new Integer(max++));
1373       }
1374     }
1375   }
1376
1377
1378   /** This function outputs (1) structures that parameters are
1379    * passed in (when PRECISE GC is enabled) and (2) function
1380    * prototypes for the methods */
1381
1382   protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1383     /* Output class structure */
1384     classdefout.println("struct "+cn.getSafeSymbol()+" {");
1385     classdefout.println("  int type;");
1386     if(state.MLP){
1387       classdefout.println("  int oid;");
1388     }
1389     if (state.EVENTMONITOR) {
1390       classdefout.println("  int objuid;");
1391     }
1392     if (state.THREAD) {
1393       classdefout.println("  pthread_t tid;");
1394       classdefout.println("  void * lockentry;");
1395       classdefout.println("  int lockcount;");
1396     }
1397
1398     if (state.TASK) {
1399       classdefout.println("  int flag;");
1400       if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1401         classdefout.println("  void * flagptr;");
1402       } else if (state.MULTICORE) {
1403         classdefout.println("  int version;");
1404     classdefout.println("  int * lock;");  // lock entry for this obj
1405     classdefout.println("  int mutex;");  
1406     classdefout.println("  int lockcount;");
1407     if(state.MULTICOREGC) {
1408       classdefout.println("  int marked;");
1409     }
1410       }
1411       if (state.OPTIONAL) {
1412         classdefout.println("  int numfses;");
1413         classdefout.println("  int * fses;");
1414       }
1415     }
1416     printClassStruct(cn, classdefout);
1417     classdefout.println("};\n");
1418
1419     if (state.DSM||state.SINGLETM) {
1420       /* Cycle through LocalityBindings */
1421       HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1422       Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1423       if (lbset!=null) {
1424         for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1425           LocalityBinding lb=lbit.next();
1426           MethodDescriptor md=lb.getMethod();
1427           if (md.getModifiers().isNative()) {
1428             //make sure we only print a native method once
1429             if (nativemethods.contains(md)) {
1430               FlatMethod fm=state.getMethodFlat(md);
1431               generateTempStructs(fm, lb);
1432               continue;
1433             } else
1434               nativemethods.add(md);
1435           }
1436           generateMethod(cn, md, lb, headersout, output);
1437         }
1438       }
1439       for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1440         MethodDescriptor md=(MethodDescriptor)methodit.next();
1441         if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1442           //Need to build param structure for library code
1443           FlatMethod fm=state.getMethodFlat(md);
1444           generateTempStructs(fm, null);
1445           generateMethodParam(cn, md, null, output);
1446         }
1447       }
1448
1449     } else
1450       for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1451         MethodDescriptor md=(MethodDescriptor)methodit.next();
1452         generateMethod(cn, md, null, headersout, output);
1453       }
1454   }
1455
1456   private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1457     /* Output parameter structure */
1458     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1459       ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1460       if ((state.DSM||state.SINGLETM)&&lb!=null)
1461         output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1462       else
1463         output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1464       output.println("  int size;");
1465       output.println("  void * next;");      
1466       for(int i=0; i<objectparams.numPointers(); i++) {
1467         TempDescriptor temp=objectparams.getPointer(i);
1468         output.println("  struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1469       }
1470       output.println("};\n");
1471     }
1472   }
1473
1474   private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1475     FlatMethod fm=state.getMethodFlat(md);
1476     generateTempStructs(fm, lb);
1477
1478     ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1479     TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1480
1481     generateMethodParam(cn, md, lb, output);
1482
1483     /* Output temp structure */
1484     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1485       if (state.DSM||state.SINGLETM)
1486         output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1487       else
1488         output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1489       output.println("  int size;");
1490       output.println("  void * next;");
1491       for(int i=0; i<objecttemps.numPointers(); i++) {
1492         TempDescriptor temp=objecttemps.getPointer(i);
1493         if (temp.getType().isNull())
1494           output.println("  void * "+temp.getSafeSymbol()+";");
1495         else
1496           output.println("  struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1497       }
1498       output.println("};\n");
1499     }
1500
1501     /********* Output method declaration ***********/
1502     if (state.DSM||state.SINGLETM) {
1503       headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1504     } else {
1505       headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1506     }
1507     /* First the return type */
1508     if (md.getReturnType()!=null) {
1509       if (md.getReturnType().isClass()||md.getReturnType().isArray())
1510         headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1511       else
1512         headersout.print(md.getReturnType().getSafeSymbol()+" ");
1513     } else
1514       //catch the constructor case
1515       headersout.print("void ");
1516
1517     /* Next the method name */
1518     if (state.DSM||state.SINGLETM) {
1519       headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1520     } else {
1521       headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1522     }
1523     boolean printcomma=false;
1524     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1525       if (state.DSM||state.SINGLETM) {
1526         headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1527       } else
1528         headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1529       printcomma=true;
1530     }
1531
1532     /*  Output parameter list*/
1533     for(int i=0; i<objectparams.numPrimitives(); i++) {
1534       TempDescriptor temp=objectparams.getPrimitive(i);
1535       if (printcomma)
1536         headersout.print(", ");
1537       printcomma=true;
1538       if (temp.getType().isClass()||temp.getType().isArray())
1539         headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1540       else
1541         headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1542     }
1543     headersout.println(");\n");
1544   }
1545
1546
1547   /** This function outputs (1) structures that parameters are
1548    * passed in (when PRECISE GC is enabled) and (2) function
1549    * prototypes for the tasks */
1550
1551   private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1552     /* Cycle through tasks */
1553     Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1554
1555     while(taskit.hasNext()) {
1556       /* Classify parameters */
1557       TaskDescriptor task=(TaskDescriptor)taskit.next();
1558       FlatMethod fm=state.getMethodFlat(task);
1559       generateTempStructs(fm, null);
1560
1561       ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1562       TempObject objecttemps=(TempObject) tempstable.get(task);
1563
1564       /* Output parameter structure */
1565       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1566         output.println("struct "+task.getSafeSymbol()+"_params {");
1567         output.println("  int size;");
1568         output.println("  void * next;");
1569         for(int i=0; i<objectparams.numPointers(); i++) {
1570           TempDescriptor temp=objectparams.getPointer(i);
1571           output.println("  struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1572         }
1573
1574         output.println("};\n");
1575         if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1576           maxtaskparams=objectparams.numPointers()+fm.numTags();
1577         }
1578       }
1579
1580       /* Output temp structure */
1581       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1582         output.println("struct "+task.getSafeSymbol()+"_locals {");
1583         output.println("  int size;");
1584         output.println("  void * next;");
1585         for(int i=0; i<objecttemps.numPointers(); i++) {
1586           TempDescriptor temp=objecttemps.getPointer(i);
1587           if (temp.getType().isNull())
1588             output.println("  void * "+temp.getSafeSymbol()+";");
1589           else if(temp.getType().isTag())
1590             output.println("  struct "+
1591                            (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1592           else
1593             output.println("  struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1594         }
1595         output.println("};\n");
1596       }
1597
1598       /* Output task declaration */
1599       headersout.print("void " + task.getSafeSymbol()+"(");
1600
1601       boolean printcomma=false;
1602       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1603         headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1604       } else
1605         headersout.print("void * parameterarray[]");
1606       headersout.println(");\n");
1607     }
1608   }
1609
1610   /***** Generate code for FlatMethod fm. *****/
1611
1612   Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1613   static int atomicmethodcount=0;
1614
1615
1616   BranchAnalysis branchanalysis;
1617   private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1618     if (State.PRINTFLAT)
1619       System.out.println(fm.printMethod());
1620     MethodDescriptor md=fm.getMethod();
1621     TaskDescriptor task=fm.getTask();
1622     ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1623     ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1624
1625     HashSet<AtomicRecord> arset=null;
1626     branchanalysis=null;
1627
1628     if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1629       //create map
1630       if (atomicmethodmap==null)
1631         atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1632
1633       //fix these so we get right strings for local variables
1634       localsprefixaddr=localsprefix;
1635       localsprefixderef=localsprefix+"->";
1636       arset=new HashSet<AtomicRecord>();
1637
1638       //build branchanalysis
1639       branchanalysis=new BranchAnalysis(locality, lb, delaycomp.getNotReady(lb), delaycomp.livecode(lb), state);
1640       
1641       //Generate commit methods here
1642       for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1643         FlatNode fn=fnit.next();
1644         if (fn.kind()==FKind.FlatAtomicEnterNode&&
1645             locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
1646             delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
1647           //We have an atomic enter
1648           FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1649           Set<FlatNode> exitset=faen.getExits();
1650           //generate header
1651           String methodname=md.getSymbol()+(atomicmethodcount++);
1652           AtomicRecord ar=new AtomicRecord();
1653           ar.name=methodname;
1654           arset.add(ar);
1655
1656           atomicmethodmap.put(faen, ar);
1657
1658           //build data structure declaration
1659           output.println("struct atomicprimitives_"+methodname+" {");
1660
1661           Set<FlatNode> recordset=delaycomp.livecode(lb);
1662           Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1663           Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1664           Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1665           ar.livein=liveinto;
1666           ar.reallivein=new HashSet(liveinto);
1667           ar.liveout=liveout;
1668           ar.liveoutvirtualread=liveoutvirtualread;
1669
1670
1671           for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1672             TempDescriptor tmp=it.next();
1673             //remove the pointers
1674             if (tmp.getType().isPtr()) {
1675               it.remove();
1676             } else {
1677               //let's print it here
1678               output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1679             }
1680           }
1681           for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1682             TempDescriptor tmp=it.next();
1683             //remove the pointers
1684             if (tmp.getType().isPtr()) {
1685               it.remove();
1686             } else if (!liveinto.contains(tmp)) {
1687               //let's print it here
1688               output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1689             }
1690           }
1691           output.println("};");
1692
1693           //print out method name
1694           output.println("void "+methodname+"(struct "+ cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix+", struct "+ cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals *"+localsprefix+", struct atomicprimitives_"+methodname+" * primitives) {");
1695           //build code for commit method
1696           
1697           //first define local primitives
1698           Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1699           for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1700             TempDescriptor tmp=tmpit.next();
1701             if (!tmp.getType().isPtr()) {
1702               if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1703                 //read from live into set
1704                 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1705               } else {
1706                 //just define
1707                 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1708               }
1709             }
1710           }
1711           //turn off write barrier generation
1712           wb.turnoff();
1713           state.SINGLETM=false;
1714           generateCode(faen, fm, lb, exitset, output, false);
1715           state.SINGLETM=true;
1716           //turn on write barrier generation
1717           wb.turnon();
1718           output.println("}\n\n");
1719         }
1720       }
1721     }
1722     //redefine these back to normal
1723
1724     localsprefixaddr="&"+localsprefix;
1725     localsprefixderef=localsprefix+".";
1726
1727     generateHeader(fm, lb, md!=null ? md : task,output);
1728     TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1729
1730     if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1731       for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1732         AtomicRecord ar=arit.next();
1733         output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1734       }
1735     }
1736
1737     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1738       if (md!=null&&(state.DSM||state.SINGLETM))
1739         output.print("   struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1740       else if (md!=null&&!(state.DSM||state.SINGLETM))
1741         output.print("   struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1742       else
1743         output.print("   struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1744       output.print(objecttemp.numPointers()+",");
1745       output.print(paramsprefix);
1746       for(int j=0; j<objecttemp.numPointers(); j++)
1747         output.print(", NULL");
1748       output.println("};");
1749     }
1750
1751     for(int i=0; i<objecttemp.numPrimitives(); i++) {
1752       TempDescriptor td=objecttemp.getPrimitive(i);
1753       TypeDescriptor type=td.getType();
1754       if (type.isNull())
1755         output.println("   void * "+td.getSafeSymbol()+";");
1756       else if (type.isClass()||type.isArray())
1757         output.println("   struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1758       else
1759         output.println("   "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1760     }
1761
1762
1763     if( state.MLP ) {      
1764       if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1765         FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1766         if( callerSESEplaceholder != mlpa.getMainSESE() ) {
1767           // declare variables for naming static SESE's
1768           output.println("   /* static SESE names */");
1769           Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1770           while( pItr.hasNext() ) {
1771             SESEandAgePair pair = pItr.next();
1772             output.println("   void* "+pair+";");
1773           }
1774
1775           // declare variables for tracking dynamic sources
1776           output.println("   /* dynamic variable sources */");
1777           Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1778           while( dynSrcItr.hasNext() ) {
1779             TempDescriptor dynSrcVar = dynSrcItr.next();
1780             output.println("   void* "+dynSrcVar+"_srcSESE;");
1781             output.println("   int   "+dynSrcVar+"_srcOffset;");
1782           }    
1783         }
1784       }
1785       
1786       // set up related allocation sites's waiting queues
1787       // eom
1788                 ConflictGraph graph = null;
1789                 graph = mlpa.getConflictGraphResults().get(fm);
1790                 if (graph != null && graph.hasConflictEdge()) {
1791                         output.println("   /* set up waiting queues */");
1792                         output.println("   int numMemoryQueue=0;");
1793                         output.println("   int memoryQueueItemID=0;");
1794                         HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
1795                                         graph);
1796                         System.out.println("#lockSet="+lockSet.hashCode());
1797                         System.out.println("lockset="+lockSet);
1798                         for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1799                                 SESELock seseLock = (SESELock) iterator.next();
1800                                 System.out.println("id="+seseLock.getID());
1801                                 System.out.println("#="+seseLock);
1802                         }
1803                         System.out.println("size="+lockSet.size());
1804                         if (lockSet.size() > 0) {
1805                                 output.println("   numMemoryQueue=" + lockSet.size() + ";");
1806                                 output
1807                                                 .println("   seseCaller->numMemoryQueue=numMemoryQueue;");
1808                                 output
1809                                                 .println("   seseCaller->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1810                                 output.println();
1811                         }
1812                 }
1813     }
1814
1815
1816     /* Check to see if we need to do a GC if this is a
1817      * multi-threaded program...*/
1818
1819     if (((state.MLP||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC) 
1820         || this.state.MULTICOREGC) {
1821       //Don't bother if we aren't in recursive methods...The loops case will catch it
1822       if (callgraph.getAllMethods(md).contains(md)) {
1823         if (state.DSM&&lb.isAtomic())
1824           output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1825         else if (this.state.MULTICOREGC) {
1826           output.println("if(gcflag) gc("+localsprefixaddr+");");
1827         } else {
1828           output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1829         }
1830       }
1831     }
1832
1833     generateCode(fm.getNext(0), fm, lb, null, output, true);
1834
1835     output.println("}\n\n");
1836   }
1837
1838
1839   protected void initializeSESE( FlatSESEEnterNode fsen ) {
1840
1841     FlatMethod       fm = fsen.getfmEnclosing();
1842     MethodDescriptor md = fm.getMethod();
1843     ClassDescriptor  cn = md.getClassDesc();
1844     
1845         
1846     // Creates bogus method descriptor to index into tables
1847     Modifiers modBogus = new Modifiers();
1848     MethodDescriptor mdBogus = 
1849       new MethodDescriptor( modBogus, 
1850                             new TypeDescriptor( TypeDescriptor.VOID ), 
1851                             "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1852                             );
1853     
1854     mdBogus.setClassDesc( fsen.getcdEnclosing() );
1855     FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1856     fsen.setfmBogus( fmBogus );
1857     fsen.setmdBogus( mdBogus );
1858
1859     Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1860     inSetAndOutSet.addAll( fsen.getInVarSet() );
1861     inSetAndOutSet.addAll( fsen.getOutVarSet() );
1862
1863     // Build paramsobj for bogus method descriptor
1864     ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
1865     paramstable.put( mdBogus, objectparams );
1866     
1867     Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1868     while( itr.hasNext() ) {
1869       TempDescriptor temp = itr.next();
1870       TypeDescriptor type = temp.getType();
1871       if( type.isPtr() ) {
1872         objectparams.addPtr( temp );
1873       } else {
1874         objectparams.addPrim( temp );
1875       }
1876     }
1877         
1878     // Build normal temp object for bogus method descriptor
1879     TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
1880     tempstable.put( mdBogus, objecttemps );
1881
1882     for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
1883       FlatNode         fn     = (FlatNode)nodeit.next();
1884       TempDescriptor[] writes = fn.writesTemps();
1885
1886       for( int i = 0; i < writes.length; i++ ) {
1887         TempDescriptor temp = writes[i];
1888         TypeDescriptor type = temp.getType();
1889
1890         if( type.isPtr() ) {
1891           objecttemps.addPtr( temp );
1892         } else {
1893           objecttemps.addPrim( temp );
1894         }
1895       }
1896     }
1897   }
1898
1899   protected void generateMethodSESE(FlatSESEEnterNode fsen,
1900                                     LocalityBinding lb,
1901                                     PrintWriter outputStructs,
1902                                     PrintWriter outputMethHead,
1903                                     PrintWriter outputMethods
1904                                     ) {
1905
1906     ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );                
1907     TempObject   objecttemps  = (TempObject)   tempstable .get( fsen.getmdBogus() );
1908     
1909     // generate locals structure
1910     outputStructs.println("struct "+
1911                           fsen.getcdEnclosing().getSafeSymbol()+
1912                           fsen.getmdBogus().getSafeSymbol()+"_"+
1913                           fsen.getmdBogus().getSafeMethodDescriptor()+
1914                           "_locals {");
1915     outputStructs.println("  int size;");
1916     outputStructs.println("  void * next;");
1917     for(int i=0; i<objecttemps.numPointers(); i++) {
1918       TempDescriptor temp=objecttemps.getPointer(i);
1919
1920       if (temp.getType().isNull())
1921         outputStructs.println("  void * "+temp.getSafeSymbol()+";");
1922       else
1923         outputStructs.println("  struct "+
1924                               temp.getType().getSafeSymbol()+" * "+
1925                               temp.getSafeSymbol()+";");
1926     }
1927     outputStructs.println("};\n");
1928
1929     
1930     // generate the SESE record structure
1931     outputStructs.println(fsen.getSESErecordName()+" {");
1932     
1933     // data common to any SESE, and it must be placed first so
1934     // a module that doesn't know what kind of SESE record this
1935     // is can cast the pointer to a common struct
1936     outputStructs.println("  SESEcommon common;");
1937
1938     // then garbage list stuff
1939     outputStructs.println("  int size;");
1940     outputStructs.println("  void * next;");
1941
1942     // DYNAMIC stuff was here
1943     
1944     // invar source taking was here
1945
1946     // space for all in and out set primitives
1947     Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1948     inSetAndOutSet.addAll( fsen.getInVarSet() );
1949     inSetAndOutSet.addAll( fsen.getOutVarSet() );
1950
1951     Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
1952
1953     Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1954     while( itr.hasNext() ) {
1955       TempDescriptor temp = itr.next();
1956       TypeDescriptor type = temp.getType();
1957       if( !type.isPtr() ) {
1958         inSetAndOutSetPrims.add( temp );
1959       }
1960     }
1961
1962     Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
1963     while( itrPrims.hasNext() ) {
1964       TempDescriptor temp = itrPrims.next();
1965       TypeDescriptor type = temp.getType();
1966       if(!type.isPrimitive()){
1967           outputStructs.println("  "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
1968       }      
1969     }
1970
1971     for(int i=0; i<objectparams.numPointers(); i++) {
1972       TempDescriptor temp=objectparams.getPointer(i);
1973       if (temp.getType().isNull())
1974         outputStructs.println("  void * "+temp.getSafeSymbol()+";");
1975       else
1976         outputStructs.println("  struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1977     }
1978     
1979     // DYNAMIC stuff needs a source SESE ptr and offset
1980     Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
1981     while( itrDynInVars.hasNext() ) {
1982       TempDescriptor dynInVar = itrDynInVars.next();
1983 //      outputStructs.println("  void* "+dynInVar+"_srcSESE;");
1984       outputStructs.println("  int   "+dynInVar+"_srcOffset;");
1985     }  
1986     
1987     itrPrims = inSetAndOutSetPrims.iterator();
1988     while( itrPrims.hasNext() ) {
1989       TempDescriptor temp = itrPrims.next();
1990       TypeDescriptor type = temp.getType();
1991       if(type.isPrimitive()){
1992           outputStructs.println("  "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
1993       }      
1994     }
1995     
1996     outputStructs.println("  int prevSESECount;");
1997     
1998     // DYNAMIC stuff needs a source SESE ptr and offset
1999     itrDynInVars = fsen.getDynamicInVarSet().iterator();
2000     while( itrDynInVars.hasNext() ) {
2001       TempDescriptor dynInVar = itrDynInVars.next();
2002       outputStructs.println("  void* "+dynInVar+"_srcSESE;");
2003 //      outputStructs.println("  int   "+dynInVar+"_srcOffset;");
2004     }  
2005     
2006     // in-set source tracking
2007     // in-vars that are READY come from parent, don't need anything
2008     // stuff STATIC needs a custom SESE pointer for each age pair
2009     Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
2010     while( itrStaticInVarSrcs.hasNext() ) {
2011       SESEandAgePair srcPair = itrStaticInVarSrcs.next();
2012       outputStructs.println("  "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
2013     }    
2014     
2015     outputStructs.println("};\n");
2016
2017     
2018     // write method declaration to header file
2019     outputMethHead.print("void ");
2020     outputMethHead.print(fsen.getSESEmethodName()+"(");
2021     outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
2022     outputMethHead.println(");\n");
2023
2024
2025     generateFlatMethodSESE( fsen.getfmBogus(), 
2026                             fsen.getcdEnclosing(), 
2027                             fsen, 
2028                             fsen.getFlatExit(), 
2029                             outputMethods );
2030   }
2031
2032   private void generateFlatMethodSESE(FlatMethod fm, 
2033                                       ClassDescriptor cn, 
2034                                       FlatSESEEnterNode fsen, 
2035                                       FlatSESEExitNode  seseExit, 
2036                                       PrintWriter output
2037                                       ) {
2038
2039     MethodDescriptor md=fm.getMethod();
2040
2041     output.print("void ");
2042     output.print(fsen.getSESEmethodName()+"(");
2043     output.print(fsen.getSESErecordName()+"* "+paramsprefix);
2044     output.println("){\n");
2045
2046     TempObject objecttemp=(TempObject) tempstable.get(md);
2047
2048     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2049       output.print("   struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2050       output.print(objecttemp.numPointers()+",");
2051       output.print("&(((SESEcommon*)(___params___))[1])");
2052       for(int j=0; j<objecttemp.numPointers(); j++)
2053         output.print(", NULL");
2054       output.println("};");
2055     }
2056
2057     output.println("   /* regular local primitives */");
2058     for(int i=0; i<objecttemp.numPrimitives(); i++) {
2059       TempDescriptor td=objecttemp.getPrimitive(i);
2060       TypeDescriptor type=td.getType();
2061       if (type.isNull())
2062         output.println("   void * "+td.getSafeSymbol()+";");
2063       else if (type.isClass()||type.isArray())
2064         output.println("   struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2065       else
2066         output.println("   "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2067     }
2068
2069
2070     // declare variables for naming static SESE's
2071     output.println("   /* static SESE names */");
2072     Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
2073     while( pItr.hasNext() ) {
2074       SESEandAgePair pair = pItr.next();
2075       output.println("   void* "+pair+";");
2076     }
2077
2078     // declare variables for tracking dynamic sources
2079     output.println("   /* dynamic variable sources */");
2080     Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
2081     while( dynSrcItr.hasNext() ) {
2082       TempDescriptor dynSrcVar = dynSrcItr.next();
2083       output.println("   void* "+dynSrcVar+"_srcSESE;");
2084       output.println("   int   "+dynSrcVar+"_srcOffset;");
2085     }    
2086
2087     // declare local temps for in-set primitives, and if it is
2088     // a ready-source variable, get the value from the record
2089     output.println("   /* local temps for in-set primitives */");
2090     Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2091     while( itrInSet.hasNext() ) {
2092       TempDescriptor temp = itrInSet.next();
2093       TypeDescriptor type = temp.getType();
2094       if( !type.isPtr() ) {
2095         if( fsen.getReadyInVarSet().contains( temp ) ) {
2096           output.println("   "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2097         } else {
2098           output.println("   "+type+" "+temp+";");
2099         }
2100       }
2101     }    
2102
2103     // declare local temps for out-set primitives if its not already
2104     // in the in-set, and it's value will get written so no problem
2105     output.println("   /* local temp for out-set prim, not already in the in-set */");
2106     Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2107     while( itrOutSet.hasNext() ) {
2108       TempDescriptor temp = itrOutSet.next();
2109       TypeDescriptor type = temp.getType();
2110       if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2111         output.println("   "+type+" "+temp+";");       
2112       }
2113     }    
2114     
2115     // setup memory queue
2116     // eom
2117     output.println("   // set up memory queues ");
2118         output.println("   int numMemoryQueue=0;");
2119         output.println("   int memoryQueueItemID=0;");
2120         ConflictGraph graph = null;
2121         graph = mlpa.getConflictGraphResults().get(fsen);
2122         if (graph != null && graph.hasConflictEdge()) {
2123                 output.println("   {");
2124                 output
2125                                 .println("   SESEcommon* parentCommon = &(___params___->common);");
2126                 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
2127                                 graph);
2128                 System.out.println("#lockSet="+lockSet);
2129
2130                 if (lockSet.size() > 0) {
2131                         output.println("   numMemoryQueue=" + lockSet.size() + ";");
2132                         output
2133                                         .println("   parentCommon->numMemoryQueue=numMemoryQueue;");
2134                         output
2135                                         .println("   parentCommon->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2136                         output.println();
2137                 }
2138                 output.println("   }");
2139         }
2140
2141
2142     // copy in-set into place, ready vars were already 
2143     // copied when the SESE was issued
2144     Iterator<TempDescriptor> tempItr;
2145
2146     // static vars are from a known SESE
2147     tempItr = fsen.getStaticInVarSet().iterator();
2148     while( tempItr.hasNext() ) {
2149       TempDescriptor temp = tempItr.next();
2150       VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2151       SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2152       
2153       // can't grab something from this source until it is done
2154       output.println("   {");
2155       /*
2156         If we are running, everything is done.  This check is redundant.
2157
2158         output.println("     SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+srcPair+";" );
2159         output.println("     pthread_mutex_lock( &(com->lock) );");
2160         output.println("     while( com->doneExecuting == FALSE ) {");
2161         output.println("       pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2162         output.println("     }");
2163         output.println("     pthread_mutex_unlock( &(com->lock) );");
2164       */
2165       output.println("     "+generateTemp( fsen.getfmBogus(), temp, null )+
2166                      " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2167
2168       output.println("   }");
2169     }
2170
2171     // dynamic vars come from an SESE and src
2172     tempItr = fsen.getDynamicInVarSet().iterator();
2173     while( tempItr.hasNext() ) {
2174       TempDescriptor temp = tempItr.next();
2175       TypeDescriptor type = temp.getType();
2176       
2177       // go grab it from the SESE source
2178       output.println("   if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2179
2180       // gotta wait until the source is done
2181       output.println("     SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+temp+"_srcSESE;" );
2182       /*
2183         If we are running, everything is done!
2184         output.println("     pthread_mutex_lock( &(com->lock) );");
2185         output.println("     while( com->doneExecuting == FALSE ) {");
2186         output.println("       pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2187         output.println("     }");
2188         output.println("     pthread_mutex_unlock( &(com->lock) );");
2189       */
2190
2191       String typeStr;
2192       if( type.isNull() ) {
2193         typeStr = "void*";
2194       } else if( type.isClass() || type.isArray() ) {
2195         typeStr = "struct "+type.getSafeSymbol()+"*";
2196       } else {
2197         typeStr = type.getSafeSymbol();
2198       }
2199       
2200       output.println("     "+generateTemp( fsen.getfmBogus(), temp, null )+
2201                      " = *(("+typeStr+"*) ("+
2202                      paramsprefix+"->"+temp+"_srcSESE + "+
2203                      paramsprefix+"->"+temp+"_srcOffset));");
2204
2205       // or if the source was our parent, its in the record to grab
2206       output.println("   } else {");
2207       output.println("     "+generateTemp( fsen.getfmBogus(), temp, null )+
2208                            " = "+paramsprefix+"->"+temp+";");
2209       output.println("   }");
2210     }
2211
2212     // Check to see if we need to do a GC if this is a
2213     // multi-threaded program...    
2214     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2215         output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2216       //Don't bother if we aren't in recursive methods...The loops case will catch it
2217 //      if (callgraph.getAllMethods(md).contains(md)) {
2218 //        if(this.state.MULTICOREGC) {
2219 //          output.println("if(gcflag) gc("+localsprefixaddr+");");
2220 //        } else {
2221 //        output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2222 //      }
2223 //      }
2224     }    
2225
2226     // initialize thread-local var to a non-zero, invalid address
2227     output.println("   seseCaller = (SESEcommon*) 0x2;");
2228     HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2229     exitset.add(seseExit);    
2230     generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2231     output.println("}\n\n");
2232     
2233   }
2234
2235
2236   // when a new mlp thread is created for an issued SESE, it is started
2237   // by running this method which blocks on a cond variable until
2238   // it is allowed to transition to execute.  Then a case statement
2239   // allows it to invoke the method with the proper SESE body, and after
2240   // exiting the SESE method, executes proper SESE exit code before the
2241   // thread can be destroyed
2242   private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2243                                             PrintWriter outmethod
2244                                             ) {
2245
2246     outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2247     outmethod.println(      "void* invokeSESEmethod( void* seseRecord ) {");
2248     outmethod.println(      "  int status;");
2249     outmethod.println(      "  char errmsg[128];");
2250
2251     // generate a case for each SESE class that can be invoked
2252     outmethod.println(      "  switch( *((int*)seseRecord) ) {");
2253     outmethod.println(      "    ");
2254     for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
2255       FlatSESEEnterNode fsen = seseit.next();
2256
2257       outmethod.println(    "    /* "+fsen.getPrettyIdentifier()+" */");
2258       outmethod.println(    "    case "+fsen.getIdentifier()+":");
2259       outmethod.println(    "      "+fsen.getSESEmethodName()+"( seseRecord );");  
2260       
2261       if( fsen.equals( mlpa.getMainSESE() ) ) {
2262         outmethod.println(  "      /* work scheduler works forever, explicitly exit */");
2263         outmethod.println(  "      exit( 0 );");
2264       }
2265
2266       outmethod.println(    "      break;");
2267       outmethod.println(    "");
2268     }
2269
2270     // default case should never be taken, error out
2271     outmethod.println(      "    default:");
2272     outmethod.println(      "      printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2273     outmethod.println(      "      exit(-30);");
2274     outmethod.println(      "      break;");
2275     outmethod.println(      "  }");
2276     outmethod.println(      "  return NULL;");
2277     outmethod.println(      "}\n\n");
2278   }
2279
2280
2281   protected void generateCode(FlatNode first,
2282                               FlatMethod fm,
2283                               LocalityBinding lb,
2284                               Set<FlatNode> stopset,
2285                               PrintWriter output, boolean firstpass) {
2286
2287     /* Assign labels to FlatNode's if necessary.*/
2288
2289     Hashtable<FlatNode, Integer> nodetolabel;
2290
2291     if (state.DELAYCOMP&&!firstpass)
2292       nodetolabel=dcassignLabels(first, stopset);      
2293     else
2294       nodetolabel=assignLabels(first, stopset);      
2295     
2296     Set<FlatNode> storeset=null;
2297     HashSet<FlatNode> genset=null;
2298     HashSet<FlatNode> refset=null;
2299     Set<FlatNode> unionset=null;
2300
2301     if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2302       storeset=delaycomp.livecode(lb);
2303       genset=new HashSet<FlatNode>();
2304       if (state.STMARRAY&&!state.DUALVIEW) {
2305         refset=new HashSet<FlatNode>();
2306         refset.addAll(delaycomp.getDeref(lb));
2307         refset.removeAll(delaycomp.getCannotDelay(lb));
2308         refset.removeAll(delaycomp.getOther(lb));
2309       }
2310       if (firstpass) {
2311         genset.addAll(delaycomp.getCannotDelay(lb));
2312         genset.addAll(delaycomp.getOther(lb));
2313       } else {
2314         genset.addAll(delaycomp.getNotReady(lb));
2315         if (state.STMARRAY&&!state.DUALVIEW) {
2316           genset.removeAll(refset);
2317         }
2318       }
2319       unionset=new HashSet<FlatNode>();
2320       unionset.addAll(storeset);
2321       unionset.addAll(genset);
2322       if (state.STMARRAY&&!state.DUALVIEW)
2323         unionset.addAll(refset);
2324     }
2325     
2326     /* Do the actual code generation */
2327     FlatNode current_node=null;
2328     HashSet tovisit=new HashSet();
2329     HashSet visited=new HashSet();
2330     if (!firstpass)
2331       tovisit.add(first.getNext(0));
2332     else
2333       tovisit.add(first);
2334     while(current_node!=null||!tovisit.isEmpty()) {
2335       if (current_node==null) {
2336         current_node=(FlatNode)tovisit.iterator().next();
2337         tovisit.remove(current_node);
2338       } else if (tovisit.contains(current_node)) {
2339         tovisit.remove(current_node);
2340       }
2341       visited.add(current_node);
2342       if (nodetolabel.containsKey(current_node)) {
2343         output.println("L"+nodetolabel.get(current_node)+":");
2344       }
2345       if (state.INSTRUCTIONFAILURE) {
2346         if (state.THREAD||state.DSM||state.SINGLETM) {
2347           output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2348         } else
2349           output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2350       }
2351       if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2352         output.print("   ");
2353         if (!state.DELAYCOMP||firstpass) {
2354           generateFlatNode(fm, lb, current_node, output);
2355         } else {
2356           //store primitive variables in out set
2357           AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2358           Set<TempDescriptor> liveout=ar.liveout;
2359           for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2360             TempDescriptor tmp=tmpit.next();
2361             output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2362           }
2363         }
2364         if (state.MLP && stopset!=null) {
2365           assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2366           assert current_node       instanceof FlatSESEExitNode;
2367           FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2368           FlatSESEExitNode  fsxn = (FlatSESEExitNode)  current_node;
2369           assert fsen.getFlatExit().equals( fsxn );
2370           assert fsxn.getFlatEnter().equals( fsen );
2371         }
2372         if (current_node.kind()!=FKind.FlatReturnNode) {
2373           output.println("   return;");
2374         }
2375         current_node=null;
2376       } else if(current_node.numNext()==1) {
2377         FlatNode nextnode;
2378         if (state.MLP && 
2379             current_node.kind()==FKind.FlatSESEEnterNode && 
2380             !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2381            ) {
2382           FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2383           generateFlatNode(fm, lb, current_node, output);
2384           nextnode=fsen.getFlatExit().getNext(0);
2385         } else if (state.DELAYCOMP) {
2386           boolean specialprimitive=false;
2387           //skip literals...no need to add extra overhead
2388           if (storeset!=null&&storeset.contains(current_node)&&current_node.kind()==FKind.FlatLiteralNode) {
2389             TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2390             if (!typedesc.isClass()&&!typedesc.isArray()) {
2391               specialprimitive=true;
2392             }
2393           }
2394
2395           if (genset==null||genset.contains(current_node)||specialprimitive)
2396             generateFlatNode(fm, lb, current_node, output);
2397           if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2398             //need to acquire lock
2399             handleArrayDeref(fm, lb, current_node, output, firstpass);
2400           }
2401           if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2402             TempDescriptor wrtmp=current_node.writesTemps()[0];
2403             if (firstpass) {
2404               //need to store value written by previous node
2405               if (wrtmp.getType().isPtr()) {
2406                 //only lock the objects that may actually need locking
2407                 if (recorddc.getNeedTrans(lb, current_node)&&
2408                     (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2409                      wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2410                   output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2411                 } else {
2412                   output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2413                 }
2414               } else {
2415                 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2416               }
2417             } else {
2418               //need to read value read by previous node
2419               if (wrtmp.getType().isPtr()) {
2420                 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2421               } else {
2422                 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");               
2423               }
2424             }
2425           }
2426           nextnode=current_node.getNext(0);
2427         } else {
2428           output.print("   ");
2429           generateFlatNode(fm, lb, current_node, output);
2430           nextnode=current_node.getNext(0);
2431         }
2432         if (visited.contains(nextnode)) {
2433           output.println("goto L"+nodetolabel.get(nextnode)+";");
2434           current_node=null;
2435         } else 
2436           current_node=nextnode;
2437       } else if (current_node.numNext()==2) {
2438         /* Branch */
2439         if (state.DELAYCOMP) {
2440           boolean computeside=false;
2441           if (firstpass) {
2442             //need to record which way it should go
2443             if (genset==null||genset.contains(current_node)) {
2444               if (storeset!=null&&storeset.contains(current_node)) {
2445                 //need to store which way branch goes
2446                 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2447               } else
2448                 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2449             } else {
2450               //which side to execute
2451               computeside=true;
2452             }
2453           } else {
2454             if (genset.contains(current_node)) {
2455               generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);             
2456             } else if (storeset.contains(current_node)) {
2457               //need to do branch
2458               branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2459             } else {
2460               //which side to execute
2461               computeside=true;
2462             }
2463           }
2464           if (computeside) {
2465             Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2466             int branch=0;
2467             if (leftset.size()==0)
2468               branch=1;
2469             if (visited.contains(current_node.getNext(branch))) {
2470               //already visited -- build jump
2471               output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2472               current_node=null;
2473             } else {
2474               current_node=current_node.getNext(branch);
2475             }
2476           } else {
2477             if (!visited.contains(current_node.getNext(1)))
2478               tovisit.add(current_node.getNext(1));
2479             if (visited.contains(current_node.getNext(0))) {
2480               output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2481               current_node=null;
2482             } else 
2483               current_node=current_node.getNext(0);
2484           }
2485         } else {
2486           output.print("   ");  
2487           generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2488           if (!visited.contains(current_node.getNext(1)))
2489             tovisit.add(current_node.getNext(1));
2490           if (visited.contains(current_node.getNext(0))) {
2491             output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2492             current_node=null;
2493           } else 
2494             current_node=current_node.getNext(0);
2495         }
2496       } else throw new Error();
2497     }
2498   }
2499
2500   protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2501     if (fn.kind()==FKind.FlatSetElementNode) {
2502       FlatSetElementNode fsen=(FlatSetElementNode) fn;
2503       String dst=generateTemp(fm, fsen.getDst(), lb);
2504       String src=generateTemp(fm, fsen.getSrc(), lb);
2505       String index=generateTemp(fm, fsen.getIndex(), lb);      
2506       TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2507       String type="";
2508       if (elementtype.isArray()||elementtype.isClass())
2509         type="void *";
2510       else
2511         type=elementtype.getSafeSymbol()+" ";
2512       if (firstpass) {
2513         output.println("STOREARRAY("+dst+","+index+","+type+")");
2514       } else {
2515         output.println("{");
2516         output.println("  struct ArrayObject *array;");
2517         output.println("  int index;");
2518         output.println("  RESTOREARRAY(array,index);");
2519         output.println("  (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2520         output.println("}");
2521       }
2522     } else if (fn.kind()==FKind.FlatElementNode) {
2523       FlatElementNode fen=(FlatElementNode) fn;
2524       String src=generateTemp(fm, fen.getSrc(), lb);
2525       String index=generateTemp(fm, fen.getIndex(), lb);
2526       TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2527       String dst=generateTemp(fm, fen.getDst(), lb);
2528       String type="";
2529       if (elementtype.isArray()||elementtype.isClass())
2530         type="void *";
2531       else
2532         type=elementtype.getSafeSymbol()+" ";
2533       if (firstpass) {
2534         output.println("STOREARRAY("+src+","+index+","+type+")");
2535       } else {
2536         output.println("{");
2537         output.println("  struct ArrayObject *array;");
2538         output.println("  int index;");
2539         output.println("  RESTOREARRAY(array,index);");
2540         output.println("  "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2541         output.println("}");
2542       }
2543     }
2544   }
2545   /** Special label assignment for delaycomputation */
2546   protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2547     HashSet tovisit=new HashSet();
2548     HashSet visited=new HashSet();
2549     int labelindex=0;
2550     Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2551
2552     //Label targets of branches
2553     Set<FlatNode> targets=branchanalysis.getTargets();
2554     for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2555       nodetolabel.put(it.next(), new Integer(labelindex++));
2556     }
2557
2558
2559     tovisit.add(first);
2560     /*Assign labels first.  A node needs a label if the previous
2561      * node has two exits or this node is a join point. */
2562
2563     while(!tovisit.isEmpty()) {
2564       FlatNode fn=(FlatNode)tovisit.iterator().next();
2565       tovisit.remove(fn);
2566       visited.add(fn);
2567
2568
2569       if(lastset!=null&&lastset.contains(fn)) {
2570         // if last is not null and matches, don't go 
2571         // any further for assigning labels
2572         continue;
2573       }
2574
2575       for(int i=0; i<fn.numNext(); i++) {
2576         FlatNode nn=fn.getNext(i);
2577
2578         if(i>0) {
2579           //1) Edge >1 of node
2580           nodetolabel.put(nn,new Integer(labelindex++));
2581         }
2582         if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2583           tovisit.add(nn);
2584         } else {
2585           //2) Join point
2586           nodetolabel.put(nn,new Integer(labelindex++));
2587         }
2588       }
2589     }
2590     return nodetolabel;
2591
2592   }
2593
2594   protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2595     return assignLabels(first, null);
2596   }
2597
2598   protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2599     HashSet tovisit=new HashSet();
2600     HashSet visited=new HashSet();
2601     int labelindex=0;
2602     Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2603     tovisit.add(first);
2604
2605     /*Assign labels first.  A node needs a label if the previous
2606      * node has two exits or this node is a join point. */
2607
2608     while(!tovisit.isEmpty()) {
2609       FlatNode fn=(FlatNode)tovisit.iterator().next();
2610       tovisit.remove(fn);
2611       visited.add(fn);
2612
2613
2614       if(lastset!=null&&lastset.contains(fn)) {
2615         // if last is not null and matches, don't go 
2616         // any further for assigning labels
2617         continue;
2618       }
2619
2620       for(int i=0; i<fn.numNext(); i++) {
2621         FlatNode nn=fn.getNext(i);
2622
2623         if(i>0) {
2624           //1) Edge >1 of node
2625           nodetolabel.put(nn,new Integer(labelindex++));
2626         }
2627         if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2628           tovisit.add(nn);
2629         } else {
2630           //2) Join point
2631           nodetolabel.put(nn,new Integer(labelindex++));
2632         }
2633       }
2634     }
2635     return nodetolabel;
2636   }
2637
2638
2639   /** Generate text string that corresponds to the TempDescriptor td. */
2640   protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2641     MethodDescriptor md=fm.getMethod();
2642     TaskDescriptor task=fm.getTask();
2643     TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2644
2645     if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2646       return td.getSafeSymbol();
2647     }
2648
2649     if (objecttemps.isLocalPtr(td)) {
2650       return localsprefixderef+td.getSafeSymbol();
2651     }
2652
2653     if (objecttemps.isParamPtr(td)) {
2654       return paramsprefix+"->"+td.getSafeSymbol();
2655     }
2656
2657     throw new Error();
2658   }
2659
2660   protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2661
2662     // insert pre-node actions from the code plan
2663     if( state.MLP ) {
2664       
2665       CodePlan cp = mlpa.getCodePlan( fn );
2666       if( cp != null ) {                
2667         
2668         FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2669         
2670         // for each sese and age pair that this parent statement
2671         // must stall on, take that child's stall semaphore, the
2672         // copying of values comes after the statement
2673         Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2674         while( vstItr.hasNext() ) {
2675           VariableSourceToken vst = vstItr.next();
2676
2677           SESEandAgePair pair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2678
2679           output.println("   {");
2680           output.println("     SESEcommon* common = (SESEcommon*) "+pair+";");
2681
2682           output.println("     pthread_mutex_lock( &(common->lock) );");
2683           output.println("     while( common->doneExecuting == FALSE ) {");
2684           output.println("       pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2685           output.println("     }");
2686           output.println("     pthread_mutex_unlock( &(common->lock) );");
2687
2688           // copy things we might have stalled for        
2689           output.println("     "+pair.getSESE().getSESErecordName()+"* child = ("+
2690                                  pair.getSESE().getSESErecordName()+"*) "+pair+";");
2691           
2692           Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2693           while( tdItr.hasNext() ) {
2694             TempDescriptor td = tdItr.next();
2695             FlatMethod fmContext;
2696             if( currentSESE.getIsCallerSESEplaceholder() ) {
2697               fmContext = currentSESE.getfmEnclosing();
2698             } else {
2699               fmContext = currentSESE.getfmBogus();
2700             }
2701             output.println("       "+generateTemp( fmContext, td, null )+
2702                            " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2703           }
2704
2705           output.println("   }");
2706         }
2707         
2708         // for each variable with a dynamic source, stall just for that variable
2709         Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2710         while( dynItr.hasNext() ) {
2711           TempDescriptor dynVar = dynItr.next();
2712
2713           // only stall if the dynamic source is not yourself, denoted by src==NULL
2714           // otherwise the dynamic write nodes will have the local var up-to-date
2715           output.println("   {");
2716           output.println("     if( "+dynVar+"_srcSESE != NULL ) {");
2717           output.println("       SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2718           output.println("       psem_take( &(common->stallSem) );");
2719
2720           FlatMethod fmContext;
2721           if( currentSESE.getIsCallerSESEplaceholder() ) {
2722             fmContext = currentSESE.getfmEnclosing();
2723           } else {
2724             fmContext = currentSESE.getfmBogus();
2725           }
2726           
2727           TypeDescriptor type=dynVar.getType();
2728       String typeStr;
2729       if( type.isNull() ) {
2730              typeStr = "void*";
2731       } else if( type.isClass() || type.isArray() ) {
2732              typeStr = "struct "+type.getSafeSymbol()+"*";
2733       } else {
2734              typeStr = type.getSafeSymbol();
2735       }
2736       
2737           output.println("       "+generateTemp( fmContext, dynVar, null )+
2738                  " = *(("+typeStr+"*) ("+
2739                  dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2740           
2741           output.println("     }");
2742           output.println("   }");
2743         }
2744
2745         // for each assignment of a variable to rhs that has a dynamic source,
2746         // copy the dynamic sources
2747         Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2748         while( dynAssignItr.hasNext() ) {
2749           Map.Entry      me  = (Map.Entry)      dynAssignItr.next();
2750           TempDescriptor lhs = (TempDescriptor) me.getKey();
2751           TempDescriptor rhs = (TempDescriptor) me.getValue();
2752           output.println("   "+lhs+"_srcSESE   = "+rhs+"_srcSESE;");
2753           output.println("   "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2754         }
2755
2756         // for each lhs that is dynamic from a non-dynamic source, set the
2757         // dynamic source vars to the current SESE
2758         dynItr = cp.getDynAssignCurr().iterator();
2759         while( dynItr.hasNext() ) {
2760           TempDescriptor dynVar = dynItr.next();          
2761           assert currentSESE.getDynamicVarSet().contains( dynVar );
2762           output.println("   "+dynVar+"_srcSESE = NULL;");
2763         }
2764         
2765         // eom
2766     // handling stall site
2767         ParentChildConflictsMap conflictsMap = mlpa.getConflictsResults().get(fn);
2768         if (conflictsMap != null) {
2769                 Set<Long> allocSet = conflictsMap.getAllocationSiteIDSetofStallSite();
2770                 if (allocSet.size() > 0) {
2771                         FlatNode enclosingFlatNode=null;
2772                         if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
2773                                 enclosingFlatNode=currentSESE.getfmEnclosing();
2774                         }else{
2775                                 enclosingFlatNode=currentSESE;
2776                         }                                               
2777                         ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
2778                         HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
2779                         Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
2780                         
2781                         if(waitingElementSet.size()>0){
2782                                 output.println("// stall on parent's stall sites ");
2783                                 output.println("   {");
2784                                 output.println("     REntry* rentry;");
2785                                 
2786                                 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
2787                                         WaitingElement waitingElement = (WaitingElement) iterator.next();
2788                                         
2789                                         if( waitingElement.getStatus() >= ConflictNode.COARSE ){
2790                                                 output.println("     rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", seseCaller);");
2791                                         }else{
2792                                                 output.println("     rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller,  (void*)&___locals___."+ waitingElement.getDynID() + ");");
2793 //                                              output.println("     rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller,  ___locals___."+ waitingElement.getDynID() + "->oid);");  
2794                                         }                                       
2795                                         output.println("     psem_init( &(rentry->parentStallSem) );");
2796                                         output.println("     rentry->queue=seseCaller->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
2797                                         output
2798                                                         .println("     if(ADDRENTRY(seseCaller->memoryQueueArray["+ waitingElement.getQueueID()
2799                                                                         + "],rentry)==NOTREADY){");
2800                                         output.println("        psem_take( &(rentry->parentStallSem) );");
2801                                         output.println("     }  ");
2802                                 }
2803                                 output.println("   }");
2804                         }
2805                 }
2806         }       
2807
2808       }     
2809     }
2810
2811     switch(fn.kind()) {
2812     case FKind.FlatAtomicEnterNode:
2813       generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
2814       break;
2815
2816     case FKind.FlatAtomicExitNode:
2817       generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
2818       break;
2819
2820     case FKind.FlatInstanceOfNode:
2821       generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
2822       break;
2823
2824     case FKind.FlatSESEEnterNode:
2825       generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
2826       break;
2827
2828     case FKind.FlatSESEExitNode:
2829       generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
2830       break;
2831       
2832     case FKind.FlatWriteDynamicVarNode:
2833       generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
2834       break;
2835
2836     case FKind.FlatGlobalConvNode:
2837       generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
2838       break;
2839
2840     case FKind.FlatTagDeclaration:
2841       generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
2842       break;
2843
2844     case FKind.FlatCall:
2845       generateFlatCall(fm, lb, (FlatCall) fn,output);
2846       break;
2847
2848     case FKind.FlatFieldNode:
2849       generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
2850       break;
2851
2852     case FKind.FlatElementNode:
2853       generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
2854       break;
2855
2856     case FKind.FlatSetElementNode:
2857       generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
2858       break;
2859
2860     case FKind.FlatSetFieldNode:
2861       generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
2862       break;
2863
2864     case FKind.FlatNew:
2865       generateFlatNew(fm, lb, (FlatNew) fn,output);
2866       break;
2867
2868     case FKind.FlatOpNode:
2869       generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
2870       break;
2871
2872     case FKind.FlatCastNode:
2873       generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
2874       break;
2875
2876     case FKind.FlatLiteralNode:
2877       generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
2878       break;
2879
2880     case FKind.FlatReturnNode:
2881       generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
2882       break;
2883
2884     case FKind.FlatNop:
2885       output.println("/* nop */");
2886       break;
2887
2888     case FKind.FlatExit:
2889       output.println("/* exit */");
2890       break;
2891
2892     case FKind.FlatBackEdge:
2893       if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
2894         output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
2895       }
2896       if(state.DSM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
2897         output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
2898       }
2899       if (((state.MLP||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
2900           || (this.state.MULTICOREGC)) {
2901         if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
2902           output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
2903         } else if(this.state.MULTICOREGC) {
2904           output.println("if (gcflag) gc("+localsprefixaddr+");");
2905         } else {
2906           output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2907         }
2908       } else
2909         output.println("/* nop */");
2910       break;
2911
2912     case FKind.FlatCheckNode:
2913       generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
2914       break;
2915
2916     case FKind.FlatFlagActionNode:
2917       generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
2918       break;
2919
2920     case FKind.FlatPrefetchNode:
2921       generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
2922       break;
2923
2924     case FKind.FlatOffsetNode:
2925       generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
2926       break;
2927
2928     default:
2929       throw new Error();
2930     }
2931
2932     // insert post-node actions from the code-plan    
2933     if( state.MLP ) {
2934       CodePlan cp = mlpa.getCodePlan( fn );
2935
2936       if( cp != null ) {     
2937       }
2938     }    
2939   }
2940
2941   public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
2942     output.println("/* FlatOffsetNode */");
2943     FieldDescriptor fd=fofn.getField();
2944     output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
2945     output.println("/* offset */");
2946   }
2947
2948   public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
2949     if (state.PREFETCH) {
2950       Vector oids = new Vector();
2951       Vector fieldoffset = new Vector();
2952       Vector endoffset = new Vector();
2953       int tuplecount = 0;        //Keeps track of number of prefetch tuples that need to be generated
2954       for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
2955         PrefetchPair pp = (PrefetchPair) it.next();
2956         Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
2957         /* Find prefetches that can generate oid */
2958         if(statusbase == LocalityAnalysis.GLOBAL) {
2959           generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
2960           tuplecount++;
2961         } else if (statusbase == LocalityAnalysis.LOCAL) {
2962           generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
2963         } else {
2964           continue;
2965         }
2966       }
2967       if (tuplecount==0)
2968         return;
2969       System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
2970       output.println("{");
2971       output.println("/* prefetch */");
2972       output.println("/* prefetchid_" + fpn.siteid + " */");
2973       output.println("void * prefptr;");
2974       output.println("int tmpindex;");
2975
2976       output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
2977       /*Create C code for oid array */
2978       output.print("   unsigned int oidarray_[] = {");
2979       boolean needcomma=false;
2980       for (Iterator it = oids.iterator(); it.hasNext();) {
2981         if (needcomma)
2982           output.print(", ");
2983         output.print(it.next());
2984         needcomma=true;
2985       }
2986       output.println("};");
2987
2988       /*Create C code for endoffset values */
2989       output.print("   unsigned short endoffsetarry_[] = {");
2990       needcomma=false;
2991       for (Iterator it = endoffset.iterator(); it.hasNext();) {
2992         if (needcomma)
2993           output.print(", ");
2994         output.print(it.next());
2995         needcomma=true;
2996       }
2997       output.println("};");
2998
2999       /*Create C code for Field Offset Values */
3000       output.print("   short fieldarry_[] = {");
3001       needcomma=false;
3002       for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
3003         if (needcomma)
3004           output.print(", ");
3005         output.print(it.next());
3006         needcomma=true;
3007       }
3008       output.println("};");
3009       /* make the prefetch call to Runtime */
3010       output.println("   if(!evalPrefetch["+fpn.siteid+"].operMode) {");
3011       output.println("     evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
3012       output.println("   }");
3013       output.println("   prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
3014       output.println(" } else {");
3015       output.println("   evalPrefetch["+fpn.siteid+"].retrycount--;");
3016       output.println(" }");
3017       output.println("}");
3018     }
3019   }
3020
3021   public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
3022     short offsetcount = 0;
3023     int breakindex=0;
3024     if (inside) {
3025       breakindex=1;
3026     } else if (localbase) {
3027       for(; breakindex<pp.desc.size(); breakindex++) {
3028         Descriptor desc=pp.getDescAt(breakindex);
3029         if (desc instanceof FieldDescriptor) {
3030           FieldDescriptor fd=(FieldDescriptor)desc;
3031           if (fd.isGlobal()) {
3032             break;
3033           }
3034         }
3035       }
3036       breakindex++;
3037     }
3038
3039     if (breakindex>pp.desc.size())     //all local
3040       return;
3041
3042     TypeDescriptor lasttype=pp.base.getType();
3043     String basestr=generateTemp(fm, pp.base, lb);
3044     String teststr="";
3045     boolean maybenull=fm.getMethod().isStatic()||
3046                        !pp.base.equals(fm.getParameter(0));
3047
3048     for(int i=0; i<breakindex; i++) {
3049       String indexcheck="";
3050
3051       Descriptor desc=pp.getDescAt(i);
3052       if (desc instanceof FieldDescriptor) {
3053         FieldDescriptor fd=(FieldDescriptor)desc;
3054         if (maybenull) {
3055           if (!teststr.equals(""))
3056             teststr+="&&";
3057           teststr+="((prefptr="+basestr+")!=NULL)";
3058           basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3059         } else {
3060           basestr=basestr+"->"+fd.getSafeSymbol();
3061           maybenull=true;
3062         }
3063         lasttype=fd.getType();
3064       } else {
3065         IndexDescriptor id=(IndexDescriptor)desc;
3066         indexcheck="((tmpindex=";
3067         for(int j=0; j<id.tddesc.size(); j++) {
3068           indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3069         }
3070         indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3071
3072         if (!teststr.equals(""))
3073           teststr+="&&";
3074         teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3075         basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3076         maybenull=true;
3077         lasttype=lasttype.dereference();
3078       }
3079     }
3080
3081     String oid;
3082     if (teststr.equals("")) {
3083       oid="((unsigned int)"+basestr+")";
3084     } else {
3085       oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3086     }
3087     oids.add(oid);
3088
3089     for(int i = breakindex; i < pp.desc.size(); i++) {
3090       String newfieldoffset;
3091       Object desc = pp.getDescAt(i);
3092       if(desc instanceof FieldDescriptor) {
3093         FieldDescriptor fd=(FieldDescriptor)desc;
3094         newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3095         lasttype=fd.getType();
3096       } else {
3097         newfieldoffset = "";
3098         IndexDescriptor id=(IndexDescriptor)desc;
3099         for(int j = 0; j < id.tddesc.size(); j++) {
3100           newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3101         }
3102         newfieldoffset += id.offset.toString();
3103         lasttype=lasttype.dereference();
3104       }
3105       fieldoffset.add(newfieldoffset);
3106     }
3107
3108     int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3109     base+=pp.desc.size()-breakindex;
3110     endoffset.add(new Short((short)base));
3111   }
3112
3113
3114
3115   public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3116     if (lb!=fgcn.getLocality())
3117       return;
3118     /* Have to generate flat globalconv */
3119     if (fgcn.getMakePtr()) {
3120       if (state.DSM) {
3121         //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3122            output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3123       } else {
3124         if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3125           //need to do translation
3126           output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3127         } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3128           if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3129             output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3130           } else
3131             output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3132         }
3133       }
3134     } else {
3135       /* Need to convert to OID */
3136       if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3137         if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3138           output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3139         } else {
3140           output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3141         }
3142       }
3143     }
3144   }
3145
3146   public void generateFlatInstanceOfNode(FlatMethod fm,  LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3147     int type;
3148     if (fion.getType().isArray()) {
3149       type=state.getArrayNumber(fion.getType())+state.numClasses();
3150     } else {
3151       type=fion.getType().getClassDesc().getId();
3152     }
3153
3154     if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3155       output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3156     else
3157       output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3158   }
3159
3160   int sandboxcounter=0;
3161   public void generateFlatAtomicEnterNode(FlatMethod fm,  LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3162     /* Check to see if we need to generate code for this atomic */
3163     if (locality==null) {
3164       if (GENERATEPRECISEGC) {
3165         output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3166         output.println("stopforgc((struct garbagelist *) &___locals___);");
3167         output.println("pthread_mutex_lock(&atomiclock);");
3168         output.println("restartaftergc();");
3169         output.println("}");
3170       } else {
3171         output.println("pthread_mutex_lock(&atomiclock);");
3172       }
3173       return;
3174     }
3175
3176     if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3177       return;
3178
3179
3180     if (state.SANDBOX) {
3181       outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3182       output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3183     }
3184
3185     if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3186       AtomicRecord ar=atomicmethodmap.get(faen);
3187       //copy in
3188       for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3189         TempDescriptor tmp=tmpit.next();
3190         output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3191       }
3192
3193       //copy outs that depend on path
3194       for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3195         TempDescriptor tmp=tmpit.next();
3196         if (!ar.livein.contains(tmp))
3197           output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3198       }
3199     }
3200
3201     /* Backup the temps. */
3202     for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3203       TempDescriptor tmp=tmpit.next();
3204       output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3205     }
3206
3207     output.println("goto transstart"+faen.getIdentifier()+";");
3208
3209     /******* Print code to retry aborted transaction *******/
3210     output.println("transretry"+faen.getIdentifier()+":");
3211
3212     /* Restore temps */
3213     for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3214       TempDescriptor tmp=tmpit.next();
3215       output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3216     }
3217
3218     if (state.DSM) {
3219       /********* Need to revert local object store ********/
3220       String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3221
3222       output.println("while ("+revertptr+") {");
3223       output.println("struct ___Object___ * tmpptr;");
3224       output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3225       output.println("REVERT_OBJ("+revertptr+");");
3226       output.println(revertptr+"=tmpptr;");
3227       output.println("}");
3228     }
3229     /******* Tell the runtime to start the transaction *******/
3230
3231     output.println("transstart"+faen.getIdentifier()+":");
3232     if (state.SANDBOX) {
3233       output.println("transaction_check_counter=*counter_reset_pointer;");
3234       sandboxcounter++;
3235     }
3236     output.println("transStart();");
3237
3238     if (state.ABORTREADERS||state.SANDBOX) {
3239       if (state.SANDBOX)
3240         output.println("abortenabled=1;");
3241       output.println("if (_setjmp(aborttrans)) {");
3242       output.println("  goto transretry"+faen.getIdentifier()+"; }");
3243     }
3244   }
3245
3246   public void generateFlatAtomicExitNode(FlatMethod fm,  LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3247     /* Check to see if we need to generate code for this atomic */
3248     if (locality==null) {
3249       output.println("pthread_mutex_unlock(&atomiclock);");
3250       return;
3251     }
3252     if (locality.getAtomic(lb).get(faen).intValue()>0)
3253       return;
3254     //store the revert list before we lose the transaction object
3255     
3256     if (state.DSM) {
3257       String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3258       output.println(revertptr+"=revertlist;");
3259       output.println("if (transCommit()) {");
3260       output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3261       output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3262       output.println("} else {");
3263       /* Need to commit local object store */
3264       output.println("while ("+revertptr+") {");
3265       output.println("struct ___Object___ * tmpptr;");
3266       output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3267       output.println("COMMIT_OBJ("+revertptr+");");
3268       output.println(revertptr+"=tmpptr;");
3269       output.println("}");
3270       output.println("}");
3271       return;
3272     }
3273
3274     if (!state.DELAYCOMP) {
3275       //Normal STM stuff
3276       output.println("if (transCommit()) {");
3277       /* Transaction aborts if it returns true */
3278       output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3279       output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3280       output.println("}");
3281     } else {
3282       if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW))  {
3283         AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3284         output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3285         //copy out
3286         for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3287           TempDescriptor tmp=tmpit.next();
3288           output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3289         }
3290       } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3291         AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3292         //do call
3293         output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3294         output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3295         output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3296         output.println("}");
3297         //copy out
3298         output.println("else {");
3299         for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3300           TempDescriptor tmp=tmpit.next();
3301           output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3302         }
3303         output.println("}");
3304       } else {
3305         output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3306         output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3307         output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3308         output.println("}");
3309       }
3310     }
3311   }
3312
3313   public void generateFlatSESEEnterNode( FlatMethod fm,  
3314                                          LocalityBinding lb, 
3315                                          FlatSESEEnterNode fsen, 
3316                                          PrintWriter output 
3317                                        ) {
3318
3319     // if MLP flag is off, okay that SESE nodes are in IR graph, 
3320     // just skip over them and code generates exactly the same
3321     if( !state.MLP ) {
3322       return;
3323     }    
3324
3325     // there may be an SESE in an unreachable method, skip over
3326     if( !mlpa.getAllSESEs().contains( fsen ) ) {
3327       return;
3328     }
3329
3330     // also, if we have encountered a placeholder, just skip it
3331     if( fsen.getIsCallerSESEplaceholder() ) {
3332       return;
3333     }
3334
3335     output.println("   {");
3336
3337     // set up the parent
3338     if( fsen == mlpa.getMainSESE() ) {
3339       output.println("     SESEcommon* parentCommon = NULL;");
3340     } else {
3341       if( fsen.getParent() == null ) {
3342         System.out.println( "in "+fm+", "+fsen+" has null parent" );
3343       }
3344       assert fsen.getParent() != null;
3345       if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3346         output.println("     SESEcommon* parentCommon = &("+paramsprefix+"->common);");
3347       } else {
3348         //output.println("     SESEcommon* parentCommon = (SESEcommon*) peekItem( seseCallStack );");
3349         output.println("     SESEcommon* parentCommon = seseCaller;");
3350       }
3351     }
3352     
3353     // before doing anything, lock your own record and increment the running children
3354     if( fsen != mlpa.getMainSESE() ) {      
3355       output.println("     atomic_inc(&parentCommon->numRunningChildren);");
3356     }
3357
3358     // just allocate the space for this record
3359     output.println("     "+fsen.getSESErecordName()+"* seseToIssue = ("+
3360                            fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3361                            fsen.getSESErecordName()+" ) );");
3362     //eomgc need to set next, size
3363 //    output.println("       struct garbagelist * gl= (struct garbagelist *)&(((SESEcommon*)(seseToIssue))[1]);");
3364     output.println("     struct garbagelist * gl= (struct garbagelist *)&(((SESEcommon*)(seseToIssue))[1]);");
3365     // sizeof(int)*2 + sizeof(void*)*calculateSizeOfSESEParamList(fsen)
3366     //output.println("       // sizeof(int)*2+sizeof(void*)*"+calculateSizeOfSESEParamList(fsen));
3367     //output.println("       // blah="+calculateSizeOfSESEParamSize(fsen));
3368     output.println("     (seseToIssue->common).offsetsize=sizeof(int)+sizeof(void*)+sizeof(void*)*"+calculateSizeOfSESEParamList(fsen)+calculateSizeOfSESEParamSize(fsen)+";");
3369     output.println("     gl->size="+calculateSizeOfSESEParamList(fsen)+";");
3370 //    output.println("       gl->next = (struct garbagelist *)&___locals___;");
3371     output.println("     seseToIssue->prevSESECount="+calculatePrevSESECount(fsen)+";");
3372 //    output.println("     seseToIssue->prevSESECount=50;");
3373     output.println("     gl->next = NULL;");
3374 //    output.println("     seseToIssue->size = "+calculateSizeOfSESEParamList(fsen)+";");
3375 //    output.println("     seseToIssue->next = &___locals___;");
3376     
3377
3378     // and keep the thread-local sese stack up to date
3379     //output.println("     addNewItem( seseCallStack, (void*) seseToIssue);");
3380
3381     // fill in common data
3382     output.println("     int localCount=0;");
3383     output.println("     seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3384     output.println("     psem_init( &(seseToIssue->common.stallSem) );");
3385
3386     output.println("     seseToIssue->common.forwardList = createQueue();");
3387     output.println("     seseToIssue->common.unresolvedDependencies = 10000;");
3388     output.println("     pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3389     output.println("     seseToIssue->common.doneExecuting = FALSE;");    
3390     output.println("     pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3391     output.println("     seseToIssue->common.numRunningChildren = 0;");
3392     output.println("     seseToIssue->common.parent = parentCommon;");
3393
3394     // all READY in-vars should be copied now and be done with it
3395     Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3396     while( tempItr.hasNext() ) {
3397       TempDescriptor temp = tempItr.next();
3398
3399       // when we are issuing the main SESE or an SESE with placeholder
3400       // caller SESE as parent, generate temp child child's eclosing method,
3401       // otherwise use the parent's enclosing method as the context
3402       boolean useParentContext = false;
3403
3404       if( fsen != mlpa.getMainSESE() ) {
3405         assert fsen.getParent() != null;
3406         if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3407           useParentContext = true;
3408         }
3409       }
3410
3411       if( useParentContext ) {
3412         output.println("     seseToIssue->"+temp+" = "+
3413                        generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");   
3414       } else {
3415         output.println("     seseToIssue->"+temp+" = "+
3416                        generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3417       }
3418     }
3419     
3420     // before potentially adding this SESE to other forwarding lists,
3421     //  create it's lock and take it immediately
3422     output.println("     pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3423 //    output.println("     pthread_mutex_lock( &(seseToIssue->common.lock) );");
3424   
3425     if( fsen != mlpa.getMainSESE() ) {
3426       // count up outstanding dependencies, static first, then dynamic
3427       Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3428       while( staticSrcsItr.hasNext() ) {
3429         SESEandAgePair srcPair = staticSrcsItr.next();
3430         output.println("     {");
3431         output.println("       SESEcommon* src = (SESEcommon*)"+srcPair+";");
3432         //eomgc
3433         if(GENERATEPRECISEGC){
3434                 output.println("       stopforgc((struct garbagelist *)&___locals___);");
3435         }
3436         output.println("       pthread_mutex_lock( &(src->lock) );");
3437         if(GENERATEPRECISEGC){
3438                 output.println("       restartaftergc();");
3439         }
3440         output.println("       if( !isEmpty( src->forwardList ) &&");
3441         output.println("           seseToIssue == peekItem( src->forwardList ) ) {");
3442         output.println("         printf( \"This shouldnt already be here\\n\");");
3443         output.println("         exit( -1 );");
3444         output.println("       }");
3445         output.println("       if( !src->doneExecuting ) {");
3446         output.println("         addNewItem( src->forwardList, seseToIssue );");
3447 //      output.println("         ++(seseToIssue->common.unresolvedDependencies);");
3448         output.println("         ++(localCount);");
3449         output.println("       }");
3450         output.println("       pthread_mutex_unlock( &(src->lock) );");
3451         output.println("     }");
3452
3453         // whether or not it is an outstanding dependency, make sure
3454         // to pass the static name to the child's record
3455         output.println("     seseToIssue->"+srcPair+" = "+srcPair+";");
3456       }
3457       
3458       // dynamic sources might already be accounted for in the static list,
3459       // so only add them to forwarding lists if they're not already there
3460       Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3461       while( dynVarsItr.hasNext() ) {
3462         TempDescriptor dynInVar = dynVarsItr.next();
3463         output.println("     {");
3464         output.println("       SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3465
3466         // the dynamic source is NULL if it comes from your own space--you can't pass
3467         // the address off to the new child, because you're not done executing and
3468         // might change the variable, so copy it right now
3469         output.println("       if( src != NULL ) {");
3470         //eomgc
3471         if(GENERATEPRECISEGC){
3472                 output.println("         stopforgc((struct garbagelist *)&___locals___);");
3473         }
3474         output.println("         pthread_mutex_lock( &(src->lock) );");
3475         if(GENERATEPRECISEGC){
3476                 output.println("         restartaftergc();");
3477         }
3478         output.println("         if( isEmpty( src->forwardList ) ||");
3479         output.println("             seseToIssue != peekItem( src->forwardList ) ) {");
3480         output.println("           if( !src->doneExecuting ) {");
3481         output.println("             addNewItem( src->forwardList, seseToIssue );");
3482 //      output.println("             ++(seseToIssue->common.unresolvedDependencies);");
3483         output.println("             ++(localCount);");
3484         output.println("           }");
3485         output.println("         }");
3486         output.println("         pthread_mutex_unlock( &(src->lock) );");       
3487         output.println("         seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3488         output.println("       } else {");
3489
3490         boolean useParentContext = false;
3491         if( fsen != mlpa.getMainSESE() ) {
3492           assert fsen.getParent() != null;
3493           if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3494             useParentContext = true;
3495           }
3496         }       
3497         if( useParentContext ) {
3498           output.println("         seseToIssue->"+dynInVar+" = "+
3499                          generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3500         } else {
3501           output.println("         seseToIssue->"+dynInVar+" = "+
3502                          generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3503         }
3504         
3505         output.println("       }");
3506         output.println("     }");
3507         
3508         // even if the value is already copied, make sure your NULL source
3509         // gets passed so child knows it already has the dynamic value
3510         output.println("     seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3511       }
3512       
3513       // maintain pointers for finding dynamic SESE 
3514       // instances from static names      
3515       SESEandAgePair pair = new SESEandAgePair( fsen, 0 );
3516       if(  fsen.getParent() != null && 
3517            //!fsen.getParent().getIsCallerSESEplaceholder() &&
3518            fsen.getParent().getNeededStaticNames().contains( pair ) 
3519         ) {       
3520
3521         for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3522           SESEandAgePair pair1 = new SESEandAgePair( fsen, i   );
3523           SESEandAgePair pair2 = new SESEandAgePair( fsen, i-1 );
3524           output.println("     "+pair1+" = "+pair2+";");
3525         }      
3526         output.println("     "+pair+" = seseToIssue;");
3527       }
3528       
3529       ////////////////
3530       // count up memory conflict dependencies,
3531       // eom
3532         ConflictGraph graph = null;
3533         FlatSESEEnterNode parent = fsen.getParent();
3534         if (parent != null) {
3535                 if (parent.isCallerSESEplaceholder) {
3536                         graph = mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
3537                 } else {
3538                         graph = mlpa.getConflictGraphResults().get(parent);
3539                 }
3540         }
3541                         if (graph != null && graph.hasConflictEdge()) {
3542                                 HashSet<SESELock> seseLockSet = mlpa.getConflictGraphLockMap()
3543                                                 .get(graph);
3544                                 output.println();
3545                                 output.println("     //add memory queue element");
3546                                 SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(fsen.getIdentifier(),
3547                                                 seseLockSet);
3548                                 if(seseWaitingQueue.getWaitingElementSize()>0){
3549                                         output.println("     {");
3550                                         output.println("     REntry* rentry=NULL;");
3551                                         output.println("     INTPTR* pointer=NULL;");
3552                                         output.println("     seseToIssue->common.rentryIdx=0;");
3553                                         
3554                                         Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
3555                                         for (Iterator iterator = queueIDSet.iterator(); iterator
3556                                                         .hasNext();) {
3557                                                 Integer key = (Integer) iterator.next();
3558                                                 int queueID=key.intValue();
3559                                                 Set<WaitingElement> waitingQueueSet =  seseWaitingQueue.getWaitingElementSet(queueID);
3560                                                 int enqueueType=seseWaitingQueue.getType(queueID);
3561                                                 if(enqueueType==SESEWaitingQueue.EXCEPTION){
3562                                                         output.println("     INITIALIZEBUF(parentCommon->memoryQueueArray["
3563                                                                                 + queueID+ "]);");
3564                                                 }
3565                                                 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2
3566                                                                 .hasNext();) {
3567                                                         WaitingElement waitingElement = (WaitingElement) iterator2
3568                                                                         .next();
3569                                                         if (waitingElement.getStatus() >= ConflictNode.COARSE) {
3570                                                                 output.println("     rentry=mlpCreateREntry("
3571                                                                                 + waitingElement.getStatus()
3572                                                                                 + ", seseToIssue);");
3573                                                         } else {
3574                                                                 TempDescriptor td = waitingElement
3575                                                                                 .getTempDesc();
3576                                                                 // decide whether waiting element is dynamic or
3577                                                                 // static
3578                                                                 if (fsen.getDynamicInVarSet().contains(td)) {
3579                                                                         // dynamic in-var case
3580                                                                         output.println("     pointer=seseToIssue->"
3581                                                                                         + waitingElement.getDynID()
3582                                                                                         + "_srcSESE+seseToIssue->"
3583                                                                                         + waitingElement.getDynID()
3584                                                                                         + "_srcOffset;");
3585                                                                         output
3586                                                                                         .println("     rentry=mlpCreateFineREntry("
3587                                                                                                         + waitingElement
3588                                                                                                                         .getStatus()
3589                                                                                                         + ", seseToIssue,  pointer );");
3590                                                                 } else if (fsen.getStaticInVarSet()
3591                                                                                 .contains(td)) {
3592                                                                         // static in-var case
3593                                                                         VariableSourceToken vst = fsen
3594                                                                                         .getStaticInVarSrc(td);
3595                                                                         if (vst != null) {
3596
3597                                                                                 String srcId = "SESE_"
3598                                                                                                 + vst.getSESE()
3599                                                                                                                 .getPrettyIdentifier()
3600                                                                                                 + vst.getSESE().getIdentifier()
3601                                                                                                 + "_" + vst.getAge();
3602                                                                                 output
3603                                                                                                 .println("     pointer=(void*)&seseToIssue->"
3604                                                                                                                 + srcId
3605                                                                                                                 + "->"
3606                                                                                                                 + waitingElement
3607                                                                                                                                 .getDynID()
3608                                                                                                                 + ";");
3609                                                                                 output
3610                                                                                                 .println("     rentry=mlpCreateFineREntry("
3611                                                                                                                 + waitingElement
3612                                                                                                                                 .getStatus()
3613                                                                                                                 + ", seseToIssue,  pointer );");
3614
3615                                                                         }
3616                                                                 } else {
3617                                                                         output
3618                                                                                         .println("     rentry=mlpCreateFineREntry("
3619                                                                                                         + waitingElement
3620                                                                                                                         .getStatus()
3621                                                                                                         + ", seseToIssue,  (void*)&seseToIssue->"
3622                                                                                                         + waitingElement.getDynID()
3623                                                                                                         + ");");
3624                                                                 }
3625                                                         }
3626                                                         output
3627                                                                         .println("     rentry->queue=parentCommon->memoryQueueArray["
3628                                                                                         + waitingElement.getQueueID()
3629                                                                                         + "];");
3630                                                         
3631                                                         if(enqueueType==SESEWaitingQueue.NORMAL){
3632                                                                 output
3633                                                                 .println("     seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
3634                                                                 output
3635                                                                                 .println("     if(ADDRENTRY(parentCommon->memoryQueueArray["
3636                                                                                                 + waitingElement.getQueueID()
3637                                                                                                 + "],rentry)==NOTREADY){");
3638                                                                 output.println("        ++(localCount);");
3639                                                                 output.println("     } ");
3640                                                         }else{
3641                                                                 output
3642                                                                 .println("     ADDRENTRYTOBUF(parentCommon->memoryQueueArray["
3643                                                                                 + waitingElement.getQueueID()
3644                                                                                 + "],rentry);");
3645                                                         }
3646                                                 }
3647                                                 if(enqueueType!=SESEWaitingQueue.NORMAL){
3648                                                         output.println("     localCount+=RESOLVEBUF(parentCommon->memoryQueueArray["
3649                                                                                 + queueID+ "],&seseToIssue->common);");
3650                                                 }                               
3651                                         }
3652                                         output.println("     }");
3653                                 }
3654                                 output.println();
3655                         }
3656       ////////////////
3657     }
3658     
3659     // release this SESE for siblings to update its dependencies or,
3660     // eventually, for it to mark itself finished
3661     //    output.println("     pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3662     
3663     // if there were no outstanding dependencies, issue here
3664     output.println("     if(  atomic_sub_and_test(10000-localCount,&(seseToIssue->common.unresolvedDependencies) ) ) {");
3665     output.println("       workScheduleSubmit( (void*)seseToIssue );");
3666     output.println("     }");
3667     /*
3668     output.println("     if( seseToIssue->common.unresolvedDependencies == 0 ) {");
3669     output.println("       workScheduleSubmit( (void*)seseToIssue );");
3670     output.println("     }");
3671     */
3672     // release this SESE for siblings to update its dependencies or,
3673     // eventually, for it to mark itself finished
3674 //    output.println("     pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3675     output.println("   }");
3676     
3677   }
3678
3679   public void generateFlatSESEExitNode( FlatMethod fm,  
3680                                         LocalityBinding lb, 
3681                                         FlatSESEExitNode fsexn, 
3682                                         PrintWriter output
3683                                       ) {
3684
3685     // if MLP flag is off, okay that SESE nodes are in IR graph, 
3686     // just skip over them and code generates exactly the same 
3687     if( !state.MLP ) {
3688       return;
3689     }
3690
3691     // get the enter node for this exit that has meta data embedded
3692     FlatSESEEnterNode fsen = fsexn.getFlatEnter();
3693
3694     // there may be an SESE in an unreachable method, skip over
3695     if( !mlpa.getAllSESEs().contains( fsen ) ) {
3696       return;
3697     }
3698
3699     // also, if we have encountered a placeholder, just jump it
3700     if( fsen.getIsCallerSESEplaceholder() ) {
3701       return;
3702     }
3703
3704     output.println("   /* SESE exiting */");
3705     
3706     String com = paramsprefix+"->common";
3707
3708     // this SESE cannot be done until all of its children are done
3709     // so grab your own lock with the condition variable for watching
3710     // that the number of your running children is greater than zero    
3711     if (GENERATEPRECISEGC){
3712         output.println("   stopforgc((struct garbagelist *)&___locals___);");
3713     }
3714     output.println("   pthread_mutex_lock( &("+com+".lock) );");
3715     if (GENERATEPRECISEGC){
3716         output.println("   restartaftergc();");
3717     }
3718     output.println("   while( "+com+".numRunningChildren > 0 ) {");
3719     if (GENERATEPRECISEGC){
3720 //      output.println("   stopforgc((struct garbagelist *)&(((SESEcommon*)(___params___))[1]));");
3721         output.println("   stopforgc((struct garbagelist *)&___locals___);");
3722     }
3723     output.println("     pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
3724     if (GENERATEPRECISEGC){
3725         output.println("   restartaftergc();");
3726     }
3727     output.println("   }");
3728
3729
3730     // copy out-set from local temps into the sese record
3731     Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
3732     while( itr.hasNext() ) {
3733       TempDescriptor temp = itr.next();
3734
3735       // only have to do this for primitives non-arrays
3736       if( !(
3737             temp.getType().isPrimitive() && !temp.getType().isArray()
3738            )
3739         ) {
3740         continue;
3741       }
3742
3743       // have to determine the context enclosing this sese
3744       boolean useParentContext = false;
3745
3746       if( fsen != mlpa.getMainSESE() ) {
3747         assert fsen.getParent() != null;
3748         if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3749           useParentContext = true;
3750         }
3751       }
3752
3753       String from;
3754       if( useParentContext ) {
3755         from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
3756       } else {
3757         from = generateTemp( fsen.getfmEnclosing(),         temp, null );
3758       }
3759
3760       output.println("   "+paramsprefix+
3761                      "->"+temp.getSafeSymbol()+
3762                      " = "+from+";");
3763     }    
3764     
3765     // mark yourself done, your SESE data is now read-only
3766     output.println("   "+com+".doneExecuting = TRUE;");
3767     output.println("   pthread_cond_signal( &("+com+".doneCond) );");
3768     output.println("   pthread_mutex_unlock( &("+com+".lock) );");
3769
3770     // decrement dependency count for all SESE's on your forwarding list
3771     output.println("   while( !isEmpty( "+com+".forwardList ) ) {");
3772     output.println("     SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
3773     
3774    
3775     output.println("     if(consumer->rentryIdx>0){");
3776     output.println("        // resolved null pointer");
3777     output.println("        int idx;");
3778     output.println("        for(idx=0;idx<consumer->rentryIdx;idx++){");
3779     output.println("           resolvePointer(consumer->rentryArray[idx]);");
3780     output.println("        }");
3781     output.println("     }");
3782     
3783     
3784 //    output.println("     pthread_mutex_lock( &(consumer->lock) );");
3785 //  output.println("     --(consumer->unresolvedDependencies);");
3786 //    output.println("     if( consumer->unresolvedDependencies == 0 ) {");
3787     output.println("     if( atomic_sub_and_test(1, &(consumer->unresolvedDependencies)) ){");
3788     output.println("       workScheduleSubmit( (void*)consumer );");
3789     output.println("     }");
3790 //    output.println("     pthread_mutex_unlock( &(consumer->lock) );");
3791     output.println("   }");
3792     
3793     
3794     // eom
3795     // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
3796     if( fsen != mlpa.getMainSESE() ) {
3797         
3798                 output.println();
3799                 output.println("   /* check memory dependency*/");
3800                 output.println("  {");                  
3801                 output.println("      int idx;");
3802                 output.println("      for(idx=0;idx<___params___->common.rentryIdx;idx++){");
3803                 output.println("           REntry* re=___params___->common.rentryArray[idx];");
3804                 output.println("           RETIRERENTRY(re->queue,re);");
3805                 output.println("      }");
3806                 output.println("   }");
3807                 
3808     }
3809     
3810     // if parent is stalling on you, let them know you're done
3811     if( fsexn.getFlatEnter() != mlpa.getMainSESE() ) {
3812       output.println("   psem_give( &("+paramsprefix+"->common.stallSem) );");
3813     }
3814
3815     // last of all, decrement your parent's number of running children    
3816     output.println("   if( "+paramsprefix+"->common.parent != NULL ) {");
3817     output.println("     if (atomic_sub_and_test(1, &"+paramsprefix+"->common.parent->numRunningChildren)) {");
3818     if (GENERATEPRECISEGC){
3819         output.println("   stopforgc((struct garbagelist *)&___locals___);");
3820     }
3821     output.println("       pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
3822     if (GENERATEPRECISEGC){
3823         output.println("   restartaftergc();");
3824     }
3825     output.println("       pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
3826     output.println("       pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
3827     output.println("     }");
3828     output.println("   }");
3829
3830     // this is a thread-only variable that can be handled when critical sese-to-sese
3831     // data has been taken care of--set sese pointer to remember self over method
3832     // calls to a non-zero, invalid address
3833     output.println("   seseCaller = (SESEcommon*) 0x1;");    
3834     
3835   }
3836  
3837   public void generateFlatWriteDynamicVarNode( FlatMethod fm,  
3838                                                LocalityBinding lb, 
3839                                                FlatWriteDynamicVarNode fwdvn,
3840                                                PrintWriter output
3841                                              ) {
3842     if( !state.MLP ) {
3843       // should node should not be in an IR graph if the
3844       // MLP flag is not set
3845       throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
3846     }
3847         
3848     Hashtable<TempDescriptor, VSTWrapper> writeDynamic = fwdvn.getVar2src();
3849
3850     assert writeDynamic != null;
3851
3852     Iterator wdItr = writeDynamic.entrySet().iterator();
3853     while( wdItr.hasNext() ) {
3854       Map.Entry           me     = (Map.Entry)      wdItr.next();
3855       TempDescriptor      refVar = (TempDescriptor) me.getKey();
3856       VSTWrapper          vstW   = (VSTWrapper)     me.getValue();
3857       VariableSourceToken vst    =                  vstW.vst;
3858
3859       /*
3860       // only do this if the variable in question should be tracked,
3861       // meaning that it was explicitly added to the dynamic var set
3862       if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
3863         continue;
3864       }
3865       */
3866
3867       if( vst == null ) {
3868         // if there is no given source, this variable is ready so
3869         // mark src pointer NULL to signify that the var is up-to-date
3870         output.println("     "+refVar+"_srcSESE = NULL;");
3871         continue;
3872       }
3873
3874       // otherwise we track where it will come from
3875       SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
3876       output.println("     "+refVar+"_srcSESE = "+instance+";");    
3877       output.println("     "+refVar+"_srcOffset = (int) &((("+
3878                      vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
3879     }   
3880   }
3881
3882   
3883   private void generateFlatCheckNode(FlatMethod fm,  LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
3884     if (state.CONSCHECK) {
3885       String specname=fcn.getSpec();
3886       String varname="repairstate___";
3887       output.println("{");
3888       output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
3889
3890       TempDescriptor[] temps=fcn.getTemps();
3891       String[] vars=fcn.getVars();
3892       for(int i=0; i<temps.length; i++) {
3893         output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
3894       }
3895
3896       output.println("if (doanalysis"+specname+"("+varname+")) {");
3897       output.println("free"+specname+"_state("+varname+");");
3898       output.println("} else {");
3899       output.println("/* Bad invariant */");
3900       output.println("free"+specname+"_state("+varname+");");
3901       output.println("abort_task();");
3902       output.println("}");
3903       output.println("}");
3904     }
3905   }
3906
3907   private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
3908
3909     if( state.MLP && !nonSESEpass ) {
3910       output.println("     seseCaller = (SESEcommon*)"+paramsprefix+";");
3911     }
3912
3913     MethodDescriptor md=fc.getMethod();
3914     ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
3915     ClassDescriptor cn=md.getClassDesc();
3916     output.println("{");
3917     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3918       if (lb!=null) {
3919         LocalityBinding fclb=locality.getBinding(lb, fc);
3920         output.print("       struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3921       } else
3922         output.print("       struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3923       output.print(objectparams.numPointers());
3924       output.print(", "+localsprefixaddr);
3925       if (md.getThis()!=null) {
3926         output.print(", ");
3927         output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
3928       }
3929       if (fc.getThis()!=null&&md.getThis()==null) {
3930         System.out.println("WARNING!!!!!!!!!!!!");
3931         System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
3932       }
3933
3934
3935       for(int i=0; i<fc.numArgs(); i++) {
3936         Descriptor var=md.getParameter(i);
3937         TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3938         if (objectparams.isParamPtr(paramtemp)) {
3939           TempDescriptor targ=fc.getArg(i);
3940           output.print(", ");
3941           TypeDescriptor td=md.getParamType(i);
3942           if (td.isTag())
3943             output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()  +" *)"+generateTemp(fm, targ,lb));
3944           else
3945             output.print("(struct "+md.getParamType(i).getSafeSymbol()  +" *)"+generateTemp(fm, targ,lb));
3946         }
3947       }
3948       output.println("};");
3949     }
3950     output.print("       ");
3951
3952
3953     if (fc.getReturnTemp()!=null)
3954       output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
3955
3956     /* Do we need to do virtual dispatch? */
3957     if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
3958       //no
3959       if (lb!=null) {
3960         LocalityBinding fclb=locality.getBinding(lb, fc);
3961         output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3962       } else {
3963         output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3964       }
3965     } else {
3966       //yes
3967       output.print("((");
3968       if (md.getReturnType().isClass()||md.getReturnType().isArray())
3969         output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3970       else
3971         output.print(md.getReturnType().getSafeSymbol()+" ");
3972       output.print("(*)(");
3973
3974       boolean printcomma=false;
3975       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3976         if (lb!=null) {
3977           LocalityBinding fclb=locality.getBinding(lb, fc);
3978           output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3979         } else
3980           output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3981         printcomma=true;
3982       }
3983
3984       for(int i=0; i<objectparams.numPrimitives(); i++) {
3985         TempDescriptor temp=objectparams.getPrimitive(i);
3986         if (printcomma)
3987           output.print(", ");
3988         printcomma=true;
3989         if (temp.getType().isClass()||temp.getType().isArray())
3990           output.print("struct " + temp.getType().getSafeSymbol()+" * ");
3991         else
3992           output.print(temp.getType().getSafeSymbol());
3993       }
3994
3995
3996       if (lb!=null) {
3997         LocalityBinding fclb=locality.getBinding(lb, fc);
3998         output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
3999       } else
4000         output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
4001     }
4002
4003     output.print("(");
4004     boolean needcomma=false;
4005     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4006       output.print("&__parameterlist__");
4007       needcomma=true;
4008     }
4009
4010     if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4011       if (fc.getThis()!=null) {
4012         TypeDescriptor ptd=md.getThis().getType();
4013         if (needcomma)
4014           output.print(",");
4015         if (ptd.isClass()&&!ptd.isArray())
4016           output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4017         output.print(generateTemp(fm,fc.getThis(),lb));
4018         needcomma=true;
4019       }
4020     }
4021
4022     for(int i=0; i<fc.numArgs(); i++) {
4023       Descriptor var=md.getParameter(i);
4024       TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4025       if (objectparams.isParamPrim(paramtemp)) {
4026         TempDescriptor targ=fc.getArg(i);
4027         if (needcomma)
4028           output.print(", ");
4029
4030         TypeDescriptor ptd=md.getParamType(i);
4031         if (ptd.isClass()&&!ptd.isArray())
4032           output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4033         output.print(generateTemp(fm, targ,lb));
4034         needcomma=true;
4035       }
4036     }
4037     output.println(");");
4038     output.println("   }");
4039   }
4040
4041   private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
4042     Set subclasses=typeutil.getSubClasses(thiscd);
4043     if (subclasses==null)
4044       return true;
4045     for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
4046       ClassDescriptor cd=(ClassDescriptor)classit.next();
4047       Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
4048       for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
4049         MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
4050         if (md.matches(matchmd))
4051           return false;
4052       }
4053     }
4054     return true;
4055   }
4056
4057   private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
4058     if (state.SINGLETM) {
4059       //single machine transactional memory case
4060       String field=ffn.getField().getSafeSymbol();
4061       String src=generateTemp(fm, ffn.getSrc(),lb);
4062       String dst=generateTemp(fm, ffn.getDst(),lb);
4063
4064       output.println(dst+"="+ src +"->"+field+ ";");
4065       if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
4066           locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
4067         if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
4068             (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
4069           output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
4070         } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
4071           if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
4072             output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4073           } else
4074             output.println("TRANSREADRD("+dst+", "+dst+");");
4075         }
4076       }
4077     } else if (state.DSM) {
4078       Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
4079       if (status==LocalityAnalysis.GLOBAL) {
4080         String field=ffn.getField().getSafeSymbol();
4081         String src=generateTemp(fm, ffn.getSrc(),lb);
4082         String dst=generateTemp(fm, ffn.getDst(),lb);
4083
4084         if (ffn.getField().getType().isPtr()) {
4085
4086           //TODO: Uncomment this when we have runtime support
4087           //if (ffn.getSrc()==ffn.getDst()) {
4088           //output.println("{");
4089           //output.println("void * temp="+src+";");
4090           //output.println("if (temp&0x1) {");
4091           //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
4092           //output.println(src+"->"+field+"="+temp+";");
4093           //output.println("}");
4094           //output.println(dst+"=temp;");
4095           //output.println("}");
4096           //} else {
4097           output.println(dst+"="+ src +"->"+field+ ";");
4098           //output.println("if ("+dst+"&0x1) {");
4099           //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4100       output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4101           //output.println(src+"->"+field+"="+src+"->"+field+";");
4102           //output.println("}");
4103           //}
4104         } else {
4105           output.println(dst+"="+ src+"->"+field+";");
4106         }
4107       } else if (status==LocalityAnalysis.LOCAL) {
4108         if (ffn.getField().getType().isPtr()&&
4109             ffn.getField().isGlobal()) {
4110           String field=ffn.getField().getSafeSymbol();
4111           String src=generateTemp(fm, ffn.getSrc(),lb);
4112           String dst=generateTemp(fm, ffn.getDst(),lb);
4113           output.println(dst+"="+ src +"->"+field+ ";");
4114           if (locality.getAtomic(lb).get(ffn).intValue()>0)
4115             //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4116             output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4117         } else
4118           output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4119       } else if (status==LocalityAnalysis.EITHER) {
4120         //Code is reading from a null pointer
4121         output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
4122         output.println("#ifndef RAW");
4123         output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4124         output.println("#endif");
4125         //This should throw a suitable null pointer error
4126         output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4127       } else
4128         throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4129     } else{
4130 // DEBUG        if(!ffn.getDst().getType().isPrimitive()){
4131 // DEBUG                output.println("within((void*)"+generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+");");
4132 // DEBUG        }      
4133       output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4134     }
4135   }
4136
4137
4138   private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
4139     if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
4140       throw new Error("Can't set array length");
4141     if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4142       //Single Machine Transaction Case
4143       boolean srcptr=fsfn.getSrc().getType().isPtr();
4144       String src=generateTemp(fm,fsfn.getSrc(),lb);
4145       String dst=generateTemp(fm,fsfn.getDst(),lb);
4146       output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
4147       if (srcptr&&!fsfn.getSrc().getType().isNull()) {
4148         output.println("{");
4149         if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
4150             locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
4151           output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4152         } else {
4153           output.println("INTPTR srcoid=(INTPTR)"+src+";");
4154         }
4155       }
4156       if (wb.needBarrier(fsfn)&&
4157           locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
4158         if (state.EVENTMONITOR) {
4159           output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
4160         }
4161         output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
4162       }
4163       if (srcptr&!fsfn.getSrc().getType().isNull()) {
4164         output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4165         output.println("}");
4166       } else {
4167         output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4168       }
4169     } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4170       Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
4171       Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
4172       boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4173
4174       String src=generateTemp(fm,fsfn.getSrc(),lb);
4175       String dst=generateTemp(fm,fsfn.getDst(),lb);
4176       if (srcglobal) {
4177         output.println("{");
4178         output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4179       }
4180       if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
4181         String glbdst=dst;
4182         //mark it dirty
4183         if (wb.needBarrier(fsfn))
4184           output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
4185         if (srcglobal) {
4186           output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4187         } else
4188           output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4189       } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
4190         /** Check if we need to copy */
4191         output.println("if(!"+dst+"->"+localcopystr+") {");
4192         /* Link object into list */
4193         String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4194         output.println(revertptr+"=revertlist;");
4195         if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4196           output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4197         else
4198           output.println("COPY_OBJ("+dst+");");
4199         output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4200         output.println("revertlist=(struct ___Object___ *)"+dst+";");
4201         output.println("}");
4202         if (srcglobal)
4203           output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4204         else
4205           output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4206       } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
4207         //writing to a null...bad
4208         output.println("if ("+dst+") {");
4209         output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
4210         if (srcglobal)
4211           output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4212         else
4213           output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4214       }
4215       if (srcglobal) {
4216         output.println("}");
4217       }
4218     } else {
4219       if (state.FASTCHECK) {
4220         String dst=generateTemp(fm, fsfn.getDst(),lb);
4221         output.println("if(!"+dst+"->"+localcopystr+") {");
4222         /* Link object into list */
4223         if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4224           output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4225         else
4226           output.println("COPY_OBJ("+dst+");");
4227         output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4228         output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4229         output.println("}");
4230       }
4231       
4232 // DEBUG        if(!fsfn.getField().getType().isPrimitive()){
4233 // DEBUG                output.println("within((void*)"+generateTemp(fm,fsfn.getSrc(),lb)+");");
4234 // DEBUG   }   
4235       output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4236     }
4237   }
4238
4239   private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
4240     TypeDescriptor elementtype=fen.getSrc().getType().dereference();
4241     String type="";
4242
4243     if (elementtype.isArray()||elementtype.isClass())
4244       type="void *";
4245     else
4246       type=elementtype.getSafeSymbol()+" ";
4247
4248     if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
4249       output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
4250       output.println("failedboundschk();");
4251     }
4252     if (state.SINGLETM) {
4253       //Single machine transaction case
4254       String dst=generateTemp(fm, fen.getDst(),lb);
4255       if ((!state.STMARRAY)||(!wb.needBarrier(fen))||locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())==LocalityAnalysis.SCRATCH||locality.getAtomic(lb).get(fen).intValue()==0||(state.READSET&&!dc.getNeedGet(lb, fen))) {
4256         output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4257       } else {
4258         output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
4259       }
4260
4261       if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
4262           locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
4263         if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
4264           output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
4265         } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
4266           if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
4267             output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4268           } else
4269             output.println("TRANSREADRD("+dst+", "+dst+");");
4270         }
4271       }
4272     } else if (state.DSM) {
4273       Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
4274       if (status==LocalityAnalysis.GLOBAL) {
4275         String dst=generateTemp(fm, fen.getDst(),lb);
4276         if (elementtype.isPtr()) {
4277           output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4278           //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
4279           output.println("TRANSREAD("+dst+", "+dst+");");
4280         } else {
4281           output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4282         }
4283       } else if (status==LocalityAnalysis.LOCAL) {
4284         output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4285       } else if (status==LocalityAnalysis.EITHER) {
4286         //Code is reading from a null pointer
4287         output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
4288         output.println("#ifndef RAW");
4289         output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4290         output.println("#endif");
4291         //This should throw a suitable null pointer error
4292         output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4293       } else
4294         throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4295     } else {
4296 // DEBUG output.println("within((void*)"+generateTemp(fm,fen.getSrc(),lb)+");");
4297         output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4298     }
4299   }
4300
4301   private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
4302     //TODO: need dynamic check to make sure this assignment is actually legal
4303     //Because Object[] could actually be something more specific...ie. Integer[]
4304
4305     TypeDescriptor elementtype=fsen.getDst().getType().dereference();
4306     String type="";
4307
4308     if (elementtype.isArray()||elementtype.isClass())
4309       type="void *";
4310     else
4311       type=elementtype.getSafeSymbol()+" ";
4312
4313     if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
4314       output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
4315       output.println("failedboundschk();");
4316     }
4317
4318     if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4319       //Transaction set element case
4320       if (wb.needBarrier(fsen)&&
4321           locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
4322         output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
4323       }
4324       if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
4325         output.println("{");
4326         String src=generateTemp(fm, fsen.getSrc(), lb);
4327         if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
4328             locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
4329           output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4330         } else {
4331           output.println("INTPTR srcoid=(INTPTR)"+src+";");
4332         }
4333         if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4334           output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
4335         } else {
4336           output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4337         }
4338         output.println("}");
4339       } else {
4340         if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4341           output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
4342         } else {
4343           output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4344         }
4345       }
4346     } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4347       Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
4348       Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
4349       boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4350       boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
4351       boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
4352       
4353       if (dstglobal) {
4354         if (wb.needBarrier(fsen))
4355           output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
4356       } else if (dstlocal) {
4357         /** Check if we need to copy */
4358         String dst=generateTemp(fm, fsen.getDst(),lb);
4359         output.println("if(!"+dst+"->"+localcopystr+") {");
4360         /* Link object into list */
4361         String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4362         output.println(revertptr+"=revertlist;");
4363         if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
4364         output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4365         else
4366           output.println("COPY_OBJ("+dst+");");
4367         output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4368         output.println("revertlist=(struct ___Object___ *)"+dst+";");
4369         output.println("}");
4370       } else {
4371         System.out.println("Node: "+fsen);
4372         System.out.println(lb);
4373         System.out.println("statusdst="+statusdst);
4374         System.out.println(fm.printMethod());
4375         throw new Error("Unknown array type");
4376       }
4377       if (srcglobal) {
4378         output.println("{");
4379         String src=generateTemp(fm, fsen.getSrc(), lb);
4380         output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4381         output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4382         output.println("}");
4383       } else {
4384         output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4385       }
4386     } else {
4387       if (state.FASTCHECK) {
4388         String dst=generateTemp(fm, fsen.getDst(),lb);
4389         output.println("if(!"+dst+"->"+localcopystr+") {");
4390         /* Link object into list */
4391         if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4392           output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4393         else
4394           output.println("COPY_OBJ("+dst+");");
4395         output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4396         output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4397         output.println("}");
4398       }
4399 // DEBUG      output.println("within((void*)"+generateTemp(fm,fsen.getDst(),lb)+");");
4400       output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4401     }
4402   }
4403
4404   protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
4405     if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4406       //Stash pointer in case of GC
4407       String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4408       output.println(revertptr+"=revertlist;");
4409     }
4410     if (state.SINGLETM) {
4411       if (fn.getType().isArray()) {
4412         int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4413         if (locality.getAtomic(lb).get(fn).intValue()>0) {
4414           //inside transaction
4415           output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4416         } else {
4417           //outside transaction
4418           output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4419         }
4420       } else {
4421         if (locality.getAtomic(lb).get(fn).intValue()>0) {
4422           //inside transaction
4423           output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4424         } else {
4425           //outside transaction
4426           output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4427         }
4428       }
4429     } else if (fn.getType().isArray()) {
4430       int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4431       if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4432         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4433       } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4434           if(this.state.MLP){
4435         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray_oid("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+", oid);");
4436         output.println("    oid += numWorkers;");
4437           }else{
4438     output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");                      
4439           }
4440       } else {
4441         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4442       }
4443     } else {
4444       if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4445         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
4446       } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4447           if (this.state.MLP){
4448         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new_oid("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+", oid);");
4449         output.println("    oid += numWorkers;");
4450           } else {
4451     output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");                      
4452           }
4453       } else {
4454         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
4455       }
4456     }
4457     if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4458       String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4459       String dst=generateTemp(fm,fn.getDst(),lb);
4460       output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4461       output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4462       output.println("revertlist=(struct ___Object___ *)"+dst+";");
4463     }
4464     if (state.FASTCHECK) {
4465       String dst=generateTemp(fm,fn.getDst(),lb);
4466       output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4467       output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4468       output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4469     }
4470   }
4471
4472   private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
4473     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4474       output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
4475     } else {
4476       output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
4477     }
4478   }
4479
4480   private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
4481     if (fon.getRight()!=null) {
4482       if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
4483         if (fon.getLeft().getType().isLong())
4484           output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4485         else
4486           output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4487
4488       } else if (dc!=null) {
4489         output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
4490         if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4491             output.print("(void *)");
4492         if (dc.getNeedLeftSrcTrans(lb, fon))
4493           output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
4494         else
4495           output.print(generateTemp(fm, fon.getLeft(),lb));
4496         output.print(")"+fon.getOp().toString()+"(");
4497         if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4498             output.print("(void *)");
4499         if (dc.getNeedRightSrcTrans(lb, fon))
4500           output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
4501         else
4502           output.println(generateTemp(fm,fon.getRight(),lb)+");");
4503       } else
4504         output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
4505     } else if (fon.getOp().getOp()==Operation.ASSIGN)
4506       output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4507     else if (fon.getOp().getOp()==Operation.UNARYPLUS)
4508       output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4509     else if (fon.getOp().getOp()==Operation.UNARYMINUS)
4510       output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
4511     else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
4512       output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
4513     else if (fon.getOp().getOp()==Operation.COMP)
4514       output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
4515     else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
4516       output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
4517     } else
4518       output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
4519   }
4520
4521   private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
4522     /* TODO: Do type check here */
4523     if (fcn.getType().isArray()) {
4524       output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4525     } else if (fcn.getType().isClass())
4526       output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4527     else
4528       output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
4529   }
4530
4531   private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
4532     if (fln.getValue()==null)
4533       output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4534     else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
4535       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4536         if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4537           //Stash pointer in case of GC
4538           String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4539           output.println(revertptr+"=revertlist;");
4540         }
4541         output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4542         if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4543           //Stash pointer in case of GC
4544           String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4545           output.println("revertlist="+revertptr+";");
4546         }
4547       } else {
4548         output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4549       }
4550     } else if (fln.getType().isBoolean()) {
4551       if (((Boolean)fln.getValue()).booleanValue())
4552         output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
4553       else
4554         output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4555     } else if (fln.getType().isChar()) {
4556       String st=FlatLiteralNode.escapeString(fln.getValue().toString());
4557       output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
4558     } else if (fln.getType().isLong()) {
4559       output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
4560     } else
4561       output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
4562   }
4563
4564   protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
4565     if (frn.getReturnTemp()!=null) {
4566       if (frn.getReturnTemp().getType().isPtr())
4567         output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4568       else
4569         output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4570     } else {
4571       output.println("return;");
4572     }
4573   }
4574
4575   protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4576     int left=-1;
4577     int right=-1;
4578     //only record if this group has more than one exit
4579     if (branchanalysis.numJumps(fcb)>1) {
4580       left=branchanalysis.jumpValue(fcb, 0);
4581       right=branchanalysis.jumpValue(fcb, 1);
4582     }
4583     output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
4584     if (right!=-1)
4585       output.println("STOREBRANCH("+right+");");
4586     output.println("goto "+label+";");
4587     output.println("}");
4588     if (left!=-1)
4589       output.println("STOREBRANCH("+left+");");
4590   }
4591
4592   protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4593     output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
4594   }
4595
4596   /** This method generates header information for the method or
4597    * task referenced by the Descriptor des. */
4598   private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
4599     generateHeader(fm, lb, des, output, false);
4600   }
4601
4602   private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
4603     /* Print header */
4604     ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
4605     MethodDescriptor md=null;
4606     TaskDescriptor task=null;
4607     if (des instanceof MethodDescriptor)
4608       md=(MethodDescriptor) des;
4609     else
4610       task=(TaskDescriptor) des;
4611
4612     ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
4613
4614     if (md!=null&&md.getReturnType()!=null) {
4615       if (md.getReturnType().isClass()||md.getReturnType().isArray())
4616         output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4617       else
4618         output.print(md.getReturnType().getSafeSymbol()+" ");
4619     } else
4620       //catch the constructor case
4621       output.print("void ");
4622     if (md!=null) {
4623       if (state.DSM||state.SINGLETM) {
4624         output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4625       } else
4626         output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4627     } else
4628       output.print(task.getSafeSymbol()+"(");
4629     
4630     boolean printcomma=false;
4631     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4632       if (md!=null) {
4633         if (state.DSM||state.SINGLETM) {
4634           output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4635         } else
4636           output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4637       } else
4638         output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
4639       printcomma=true;
4640     }
4641
4642     if (md!=null) {
4643       /* Method */
4644       for(int i=0; i<objectparams.numPrimitives(); i++) {
4645         TempDescriptor temp=objectparams.getPrimitive(i);
4646         if (printcomma)
4647           output.print(", ");
4648         printcomma=true;
4649         if (temp.getType().isClass()||temp.getType().isArray())
4650           output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
4651         else
4652           output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
4653       }
4654       output.println(") {");
4655     } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4656       /* Imprecise Task */
4657       output.println("void * parameterarray[]) {");
4658       /* Unpack variables */
4659       for(int i=0; i<objectparams.numPrimitives(); i++) {
4660         TempDescriptor temp=objectparams.getPrimitive(i);
4661         output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
4662       }
4663       for(int i=0; i<fm.numTags(); i++) {
4664         TempDescriptor temp=fm.getTag(i);
4665         int offset=i+objectparams.numPrimitives();
4666         output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
4667       }
4668
4669       if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
4670         maxtaskparams=objectparams.numPrimitives()+fm.numTags();
4671     } else output.println(") {");
4672   }
4673
4674   public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
4675     output.println("/* FlatFlagActionNode */");
4676
4677
4678     /* Process tag changes */
4679     Relation tagsettable=new Relation();
4680     Relation tagcleartable=new Relation();
4681
4682     Iterator tagsit=ffan.getTempTagPairs();
4683     while (tagsit.hasNext()) {
4684       TempTagPair ttp=(TempTagPair) tagsit.next();
4685       TempDescriptor objtmp=ttp.getTemp();
4686       TagDescriptor tag=ttp.getTag();
4687       TempDescriptor tagtmp=ttp.getTagTemp();
4688       boolean tagstatus=ffan.getTagChange(ttp);
4689       if (tagstatus) {
4690         tagsettable.put(objtmp, tagtmp);
4691       } else {
4692         tagcleartable.put(objtmp, tagtmp);
4693       }
4694     }
4695
4696
4697     Hashtable flagandtable=new Hashtable();
4698     Hashtable flagortable=new Hashtable();
4699
4700     /* Process flag changes */
4701     Iterator flagsit=ffan.getTempFlagPairs();
4702     while(flagsit.hasNext()) {
4703       TempFlagPair tfp=(TempFlagPair)flagsit.next();
4704       TempDescriptor temp=tfp.getTemp();
4705       Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
4706       FlagDescriptor flag=tfp.getFlag();
4707       if (flag==null) {
4708         //Newly allocate objects that don't set any flags case
4709         if (flagortable.containsKey(temp)) {
4710           throw new Error();
4711         }
4712         int mask=0;
4713         flagortable.put(temp,new Integer(mask));
4714       } else {
4715         int flagid=1<<((Integer)flagtable.get(flag)).intValue();
4716         boolean flagstatus=ffan.getFlagChange(tfp);
4717         if (flagstatus) {
4718           int mask=0;
4719           if (flagortable.containsKey(temp)) {
4720             mask=((Integer)flagortable.get(temp)).intValue();
4721           }
4722           mask|=flagid;
4723           flagortable.put(temp,new Integer(mask));
4724         } else {
4725           int mask=0xFFFFFFFF;
4726           if (flagandtable.containsKey(temp)) {
4727             mask=((Integer)flagandtable.get(temp)).intValue();
4728           }
4729           mask&=(0xFFFFFFFF^flagid);
4730           flagandtable.put(temp,new Integer(mask));
4731         }
4732       }
4733     }
4734
4735
4736     HashSet flagtagset=new HashSet();
4737     flagtagset.addAll(flagortable.keySet());
4738     flagtagset.addAll(flagandtable.keySet());
4739     flagtagset.addAll(tagsettable.keySet());
4740     flagtagset.addAll(tagcleartable.keySet());
4741
4742     Iterator ftit=flagtagset.iterator();
4743     while(ftit.hasNext()) {
4744       TempDescriptor temp=(TempDescriptor)ftit.next();
4745
4746
4747       Set tagtmps=tagcleartable.get(temp);
4748       if (tagtmps!=null) {
4749         Iterator tagit=tagtmps.iterator();
4750         while(tagit.hasNext()) {
4751           TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4752           if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4753             output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4754           else
4755             output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4756         }
4757       }
4758
4759       tagtmps=tagsettable.get(temp);
4760       if (tagtmps!=null) {
4761         Iterator tagit=tagtmps.iterator();
4762         while(tagit.hasNext()) {
4763           TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4764           if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4765             output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4766           else
4767             output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
4768         }
4769       }
4770
4771       int ormask=0;
4772       int andmask=0xFFFFFFF;
4773
4774       if (flagortable.containsKey(temp))
4775         ormask=((Integer)flagortable.get(temp)).intValue();
4776       if (flagandtable.containsKey(temp))
4777         andmask=((Integer)flagandtable.get(temp)).intValue();
4778       generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
4779       generateObjectDistribute(ffan, fm, lb, temp, output);
4780     }
4781   }
4782
4783   protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
4784                                    PrintWriter output, int ormask, int andmask) {
4785     if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
4786       output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4787     } else {
4788       output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4789     }
4790   }
4791
4792   protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
4793     output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
4794   }
4795
4796   void generateOptionalHeader(PrintWriter headers) {
4797
4798     //GENERATE HEADERS
4799     headers.println("#include \"task.h\"\n\n");
4800     headers.println("#ifndef _OPTIONAL_STRUCT_");
4801     headers.println("#define _OPTIONAL_STRUCT_");
4802
4803     //STRUCT PREDICATEMEMBER
4804     headers.println("struct predicatemember{");
4805     headers.println("int type;");
4806     headers.println("int numdnfterms;");
4807     headers.println("int * flags;");
4808     headers.println("int numtags;");
4809     headers.println("int * tags;\n};\n\n");
4810
4811     //STRUCT OPTIONALTASKDESCRIPTOR
4812     headers.println("struct optionaltaskdescriptor{");
4813     headers.println("struct taskdescriptor * task;");
4814     headers.println("int index;");
4815     headers.println("int numenterflags;");
4816     headers.println("int * enterflags;");
4817     headers.println("int numpredicatemembers;");
4818     headers.println("struct predicatemember ** predicatememberarray;");
4819     headers.println("};\n\n");
4820
4821     //STRUCT TASKFAILURE
4822     headers.println("struct taskfailure {");
4823     headers.println("struct taskdescriptor * task;");
4824     headers.println("int index;");
4825     headers.println("int numoptionaltaskdescriptors;");
4826     headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4827
4828     //STRUCT FSANALYSISWRAPPER
4829     headers.println("struct fsanalysiswrapper{");
4830     headers.println("int  flags;");
4831     headers.println("int numtags;");
4832     headers.println("int * tags;");
4833     headers.println("int numtaskfailures;");
4834     headers.println("struct taskfailure ** taskfailurearray;");
4835     headers.println("int numoptionaltaskdescriptors;");
4836     headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4837
4838     //STRUCT CLASSANALYSISWRAPPER
4839     headers.println("struct classanalysiswrapper{");
4840     headers.println("int type;");
4841     headers.println("int numotd;");
4842     headers.println("struct optionaltaskdescriptor ** otdarray;");
4843     headers.println("int numfsanalysiswrappers;");
4844     headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
4845
4846     headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
4847
4848     Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
4849     while(taskit.hasNext()) {
4850       TaskDescriptor td=(TaskDescriptor)taskit.next();
4851       headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
4852     }
4853
4854   }
4855
4856   //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
4857   int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
4858     int predicateindex = 0;
4859     //iterate through the classes concerned by the predicate
4860     Set c_vard = predicate.vardescriptors;
4861     Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
4862     int current_slot=0;
4863
4864     for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
4865       VarDescriptor vard = (VarDescriptor)vard_it.next();
4866       TypeDescriptor typed = vard.getType();
4867
4868       //generate for flags
4869       HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
4870       output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4871       int numberterms=0;
4872       if (fen_hashset!=null) {
4873         for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
4874           FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
4875           if (fen!=null) {
4876             DNFFlag dflag=fen.getDNF();
4877             numberterms+=dflag.size();
4878
4879             Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
4880
4881             for(int j=0; j<dflag.size(); j++) {
4882               if (j!=0)
4883                 output.println(",");
4884               Vector term=dflag.get(j);
4885               int andmask=0;
4886               int checkmask=0;
4887               for(int k=0; k<term.size(); k++) {
4888                 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
4889                 FlagDescriptor fd=dfa.getFlag();
4890                 boolean negated=dfa.getNegated();
4891                 int flagid=1<<((Integer)flags.get(fd)).intValue();
4892                 andmask|=flagid;
4893                 if (!negated)
4894                   checkmask|=flagid;
4895               }
4896               output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
4897             }
4898           }
4899         }
4900       }
4901       output.println("};\n");
4902
4903       //generate for tags
4904       TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
4905       output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4906       int numtags = 0;
4907       if (tagel!=null) {
4908         for(int j=0; j<tagel.numTags(); j++) {
4909           if (j!=0)
4910             output.println(",");
4911           TempDescriptor tmp=tagel.getTemp(j);
4912           if (!slotnumber.containsKey(tmp)) {
4913             Integer slotint=new Integer(current_slot++);
4914             slotnumber.put(tmp,slotint);
4915           }
4916           int slot=slotnumber.get(tmp).intValue();
4917           output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
4918         }
4919         numtags = tagel.numTags();
4920       }
4921       output.println("};");
4922
4923       //store the result into a predicatemember struct
4924       output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4925       output.println("/*type*/"+typed.getClassDesc().getId()+",");
4926       output.println("/* number of dnf terms */"+numberterms+",");
4927       output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4928       output.println("/* number of tag */"+numtags+",");
4929       output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4930       output.println("};\n");
4931       predicateindex++;
4932     }
4933
4934
4935     //generate an array that stores the entire predicate
4936     output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4937     for( int j = 0; j<predicateindex; j++) {
4938       if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4939       else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4940     }
4941     output.println("};\n");
4942     return predicateindex;
4943   }
4944
4945
4946   void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
4947     generateOptionalHeader(headers);
4948     //GENERATE STRUCTS
4949     output.println("#include \"optionalstruct.h\"\n\n");
4950     output.println("#include \"stdlib.h\"\n");
4951
4952     HashSet processedcd = new HashSet();
4953     int maxotd=0;
4954     Enumeration e = safeexecution.keys();
4955     while (e.hasMoreElements()) {
4956       int numotd=0;
4957       //get the class
4958       ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
4959       Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp);       //will be used several times
4960
4961       //Generate the struct of optionals
4962       Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4963       numotd = c_otd.size();
4964       if(maxotd<numotd) maxotd = numotd;
4965       if( !c_otd.isEmpty() ) {
4966         for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4967           OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4968
4969           //generate the int arrays for the predicate
4970           Predicate predicate = otd.predicate;
4971           int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
4972           TreeSet<Integer> fsset=new TreeSet<Integer>();
4973           //iterate through possible FSes corresponding to
4974           //the state when entering
4975
4976           for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
4977             FlagState fs = (FlagState)fses.next();
4978             int flagid=0;
4979             for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4980               FlagDescriptor flagd = (FlagDescriptor)flags.next();
4981               int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4982               flagid|=id;
4983             }
4984             fsset.add(new Integer(flagid));
4985             //tag information not needed because tag
4986             //changes are not tolerated.
4987           }
4988
4989           output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4990           boolean needcomma=false;
4991           for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
4992             if(needcomma)
4993               output.print(", ");
4994             output.println(it.next());
4995           }
4996
4997           output.println("};\n");
4998
4999
5000           //generate optionaltaskdescriptor that actually
5001           //includes exit fses, predicate and the task
5002           //concerned
5003           output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5004           output.println("&task_"+otd.td.getSafeSymbol()+",");
5005           output.println("/*index*/"+otd.getIndex()+",");
5006           output.println("/*number of enter flags*/"+fsset.size()+",");
5007           output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5008           output.println("/*number of members */"+predicateindex+",");
5009           output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5010           output.println("};\n");
5011         }
5012       } else
5013         continue;
5014       // if there are no optionals, there is no need to build the rest of the struct
5015
5016       output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
5017       c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5018       if( !c_otd.isEmpty() ) {
5019         boolean needcomma=false;
5020         for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5021           OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5022           if(needcomma)
5023             output.println(",");
5024           needcomma=true;
5025           output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5026         }
5027       }
5028       output.println("};\n");
5029
5030       //get all the possible flagstates reachable by an object
5031       Hashtable hashtbtemp = safeexecution.get(cdtemp);
5032       int fscounter = 0;
5033       TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
5034       fsts.addAll(hashtbtemp.keySet());
5035       for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
5036         FlagState fs = (FlagState)fsit.next();
5037         fscounter++;
5038
5039         //get the set of OptionalTaskDescriptors corresponding
5040         HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
5041         //iterate through the OptionalTaskDescriptors and
5042         //store the pointers to the optionals struct (see on
5043         //top) into an array
5044
5045         output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
5046         for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
5047           OptionalTaskDescriptor mm = mos.next();
5048           if(!mos.hasNext())
5049             output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
5050           else
5051             output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5052         }
5053
5054         output.println("};\n");
5055
5056         //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
5057
5058         int flagid=0;
5059         for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5060           FlagDescriptor flagd = (FlagDescriptor)flags.next();
5061           int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5062           flagid|=id;
5063         }
5064
5065         //process tag information
5066
5067         int tagcounter = 0;
5068         boolean first = true;
5069         Enumeration tag_enum = fs.getTags();
5070         output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5071         while(tag_enum.hasMoreElements()) {
5072           tagcounter++;
5073           TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
5074           if(first==true)
5075             first = false;
5076           else
5077             output.println(", ");
5078           output.println("/*tagid*/"+state.getTagId(tagd));
5079         }
5080         output.println("};");
5081
5082         Set<TaskIndex> tiset=sa.getTaskIndex(fs);
5083         for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5084           TaskIndex ti=itti.next();
5085           if (ti.isRuntime())
5086             continue;
5087
5088           Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
5089
5090           output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
5091           boolean needcomma=false;
5092           for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
5093             OptionalTaskDescriptor otd=otdit.next();
5094             if(needcomma)
5095               output.print(", ");
5096             needcomma=true;
5097             output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5098           }
5099           output.println("};");
5100
5101           output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
5102           output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
5103           output.print(ti.getIndex()+", ");
5104           output.print(otdset.size()+", ");
5105           output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
5106           output.println("};");
5107         }
5108
5109         tiset=sa.getTaskIndex(fs);
5110         boolean needcomma=false;
5111         int runtimeti=0;
5112         output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5113         for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5114           TaskIndex ti=itti.next();
5115           if (ti.isRuntime()) {
5116             runtimeti++;
5117             continue;
5118           }
5119           if (needcomma)
5120             output.print(", ");
5121           needcomma=true;
5122           output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
5123         }
5124         output.println("};\n");
5125
5126         //Store the result in fsanalysiswrapper
5127
5128         output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
5129         output.println("/*flag*/"+flagid+",");
5130         output.println("/* number of tags*/"+tagcounter+",");
5131         output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5132         output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
5133         output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5134         output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
5135         output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
5136         output.println("};\n");
5137
5138       }
5139
5140       //Build the array of fsanalysiswrappers
5141       output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
5142       boolean needcomma=false;
5143       for(int i = 0; i<fscounter; i++) {
5144         if (needcomma) output.print(",");
5145         output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
5146         needcomma=true;
5147       }
5148       output.println("};");
5149
5150       //Build the classanalysiswrapper referring to the previous array
5151       output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
5152       output.println("/*type*/"+cdtemp.getId()+",");
5153       output.println("/*numotd*/"+numotd+",");
5154       output.println("otdarray"+cdtemp.getSafeSymbol()+",");
5155       output.println("/* number of fsanalysiswrappers */"+fscounter+",");
5156       output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
5157       processedcd.add(cdtemp);
5158     }
5159
5160     //build an array containing every classes for which code has been build
5161     output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
5162     for(int i=0; i<state.numClasses(); i++) {
5163       ClassDescriptor cn=cdarray[i];
5164       if (i>0)
5165         output.print(", ");
5166       if ((cn != null) && (processedcd.contains(cn)))
5167         output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
5168       else
5169         output.print("NULL");
5170     }
5171     output.println("};");
5172
5173     output.println("#define MAXOTD "+maxotd);
5174     headers.println("#endif");
5175   }
5176
5177   public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
5178     Relation r=new Relation();
5179     for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
5180       OptionalTaskDescriptor otd=otdit.next();
5181       TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
5182       r.put(ti, otd);
5183     }
5184
5185     LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
5186     for(Iterator it=r.keySet().iterator(); it.hasNext();) {
5187       Set s=r.get(it.next());
5188       for(Iterator it2=s.iterator(); it2.hasNext();) {
5189         OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
5190         l.add(otd);
5191       }
5192     }
5193
5194     return l;
5195   }
5196
5197   protected void outputTransCode(PrintWriter output) {
5198   }
5199   
5200   private int calculateSizeOfSESEParamList(FlatSESEEnterNode fsen){
5201           
5202           Set<TempDescriptor> tdSet=new HashSet<TempDescriptor>();
5203           
5204           for (Iterator iterator = fsen.getInVarSet().iterator(); iterator.hasNext();) {
5205                 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5206                 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5207                         tdSet.add(tempDescriptor);
5208                 }       
5209           }
5210           
5211           for (Iterator iterator = fsen.getOutVarSet().iterator(); iterator.hasNext();) {
5212                         TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5213                         if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5214                                 tdSet.add(tempDescriptor);
5215                         }       
5216           }       
5217                   
5218           return tdSet.size();
5219   }
5220   
5221 private String calculateSizeOfSESEParamSize(FlatSESEEnterNode fsen){
5222           HashMap <String,Integer> map=new HashMap();
5223           HashSet <TempDescriptor> processed=new HashSet<TempDescriptor>();
5224           String rtr="";
5225           
5226           // space for all in and out set primitives
5227             Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
5228             inSetAndOutSet.addAll( fsen.getInVarSet() );
5229             inSetAndOutSet.addAll( fsen.getOutVarSet() );
5230             
5231             Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
5232
5233             Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
5234             while( itr.hasNext() ) {
5235               TempDescriptor temp = itr.next();
5236               TypeDescriptor type = temp.getType();
5237               if( !type.isPtr() ) {
5238                 inSetAndOutSetPrims.add( temp );
5239               }
5240             }
5241             
5242             Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
5243             while( itrPrims.hasNext() ) {
5244               TempDescriptor temp = itrPrims.next();
5245               TypeDescriptor type = temp.getType();
5246               if(type.isPrimitive()){
5247                                 Integer count=map.get(type.getSymbol());
5248                                 if(count==null){
5249                                         count=new Integer(1);
5250                                         map.put(type.getSymbol(), count);
5251                                 }else{
5252                                         map.put(type.getSymbol(), new Integer(count.intValue()+1));
5253                                 }
5254               }      
5255             }
5256           
5257           Set<String> keySet=map.keySet();
5258           for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
5259                 String key = (String) iterator.next();
5260                 rtr+="+sizeof("+key+")*"+map.get(key);
5261           }
5262           return  rtr;
5263 }
5264
5265 private int calculatePrevSESECount(FlatSESEEnterNode fsen){
5266         int count=0;
5267         
5268     // dynamic stuff
5269     Iterator<TempDescriptor>itrDynInVars = fsen.getDynamicInVarSet().iterator();
5270     while( itrDynInVars.hasNext() ) {
5271       TempDescriptor dynInVar = itrDynInVars.next();
5272       count++;
5273     }  
5274     
5275     // in-set source tracking
5276     Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
5277     while( itrStaticInVarSrcs.hasNext() ) {
5278       SESEandAgePair srcPair = itrStaticInVarSrcs.next();
5279       count++;
5280     }   
5281     
5282         return count;
5283 }
5284
5285
5286 }
5287
5288
5289
5290
5291
5292