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