more changes
[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) {
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);
1788                         for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1789                                 SESELock seseLock = (SESELock) iterator.next();
1790                                 System.out.println("id="+seseLock.getID());
1791                                 System.out.println("#="+seseLock);
1792                         }
1793                         System.out.println("size="+lockSet.size());
1794                         if (lockSet.size() > 0) {
1795                                 output.println("   numMemoryQueue=" + lockSet.size() + ";");
1796                                 output
1797                                                 .println("   seseCaller->numMemoryQueue=numMemoryQueue;");
1798                                 output
1799                                                 .println("   seseCaller->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1800                                 output.println();
1801                         }
1802                 }
1803     }
1804
1805
1806     /* Check to see if we need to do a GC if this is a
1807      * multi-threaded program...*/
1808
1809     if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC) 
1810         || this.state.MULTICOREGC) {
1811       //Don't bother if we aren't in recursive methods...The loops case will catch it
1812       if (callgraph.getAllMethods(md).contains(md)) {
1813         if (state.DSM&&lb.isAtomic())
1814           output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1815         else if (this.state.MULTICOREGC) {
1816           output.println("if(gcflag) gc("+localsprefixaddr+");");
1817         } else {
1818           output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1819         }
1820       }
1821     }
1822
1823     generateCode(fm.getNext(0), fm, lb, null, output, true);
1824
1825     output.println("}\n\n");
1826   }
1827
1828
1829   protected void initializeSESE( FlatSESEEnterNode fsen ) {
1830
1831     FlatMethod       fm = fsen.getfmEnclosing();
1832     MethodDescriptor md = fm.getMethod();
1833     ClassDescriptor  cn = md.getClassDesc();
1834     
1835         
1836     // Creates bogus method descriptor to index into tables
1837     Modifiers modBogus = new Modifiers();
1838     MethodDescriptor mdBogus = 
1839       new MethodDescriptor( modBogus, 
1840                             new TypeDescriptor( TypeDescriptor.VOID ), 
1841                             "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1842                             );
1843     
1844     mdBogus.setClassDesc( fsen.getcdEnclosing() );
1845     FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1846     fsen.setfmBogus( fmBogus );
1847     fsen.setmdBogus( mdBogus );
1848
1849     Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1850     inSetAndOutSet.addAll( fsen.getInVarSet() );
1851     inSetAndOutSet.addAll( fsen.getOutVarSet() );
1852
1853     // Build paramsobj for bogus method descriptor
1854     ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
1855     paramstable.put( mdBogus, objectparams );
1856     
1857     Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1858     while( itr.hasNext() ) {
1859       TempDescriptor temp = itr.next();
1860       TypeDescriptor type = temp.getType();
1861       if( type.isPtr() ) {
1862         objectparams.addPtr( temp );
1863       } else {
1864         objectparams.addPrim( temp );
1865       }
1866     }
1867         
1868     // Build normal temp object for bogus method descriptor
1869     TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
1870     tempstable.put( mdBogus, objecttemps );
1871
1872     for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
1873       FlatNode         fn     = (FlatNode)nodeit.next();
1874       TempDescriptor[] writes = fn.writesTemps();
1875
1876       for( int i = 0; i < writes.length; i++ ) {
1877         TempDescriptor temp = writes[i];
1878         TypeDescriptor type = temp.getType();
1879
1880         if( type.isPtr() ) {
1881           objecttemps.addPtr( temp );
1882         } else {
1883           objecttemps.addPrim( temp );
1884         }
1885       }
1886     }
1887   }
1888
1889   protected void generateMethodSESE(FlatSESEEnterNode fsen,
1890                                     LocalityBinding lb,
1891                                     PrintWriter outputStructs,
1892                                     PrintWriter outputMethHead,
1893                                     PrintWriter outputMethods
1894                                     ) {
1895
1896     ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );                
1897     TempObject   objecttemps  = (TempObject)   tempstable .get( fsen.getmdBogus() );
1898     
1899     // generate locals structure
1900     outputStructs.println("struct "+
1901                           fsen.getcdEnclosing().getSafeSymbol()+
1902                           fsen.getmdBogus().getSafeSymbol()+"_"+
1903                           fsen.getmdBogus().getSafeMethodDescriptor()+
1904                           "_locals {");
1905     outputStructs.println("  INTPTR size;");
1906     outputStructs.println("  void * next;");
1907     for(int i=0; i<objecttemps.numPointers(); i++) {
1908       TempDescriptor temp=objecttemps.getPointer(i);
1909
1910       if (temp.getType().isNull())
1911         outputStructs.println("  void * "+temp.getSafeSymbol()+";");
1912       else
1913         outputStructs.println("  struct "+
1914                               temp.getType().getSafeSymbol()+" * "+
1915                               temp.getSafeSymbol()+";");
1916     }
1917     outputStructs.println("};\n");
1918
1919     
1920     // generate the SESE record structure
1921     outputStructs.println(fsen.getSESErecordName()+" {");
1922     
1923     // data common to any SESE, and it must be placed first so
1924     // a module that doesn't know what kind of SESE record this
1925     // is can cast the pointer to a common struct
1926     outputStructs.println("  SESEcommon common;");
1927
1928     // then garbage list stuff
1929     outputStructs.println("  INTPTR size;");
1930     outputStructs.println("  void * next;");
1931
1932     // in-set source tracking
1933     // in-vars that are READY come from parent, don't need anything
1934     // stuff STATIC needs a custom SESE pointer for each age pair
1935     Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
1936     while( itrStaticInVarSrcs.hasNext() ) {
1937       SESEandAgePair srcPair = itrStaticInVarSrcs.next();
1938       outputStructs.println("  "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
1939     }    
1940
1941     // DYNAMIC stuff needs a source SESE ptr and offset
1942     Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
1943     while( itrDynInVars.hasNext() ) {
1944       TempDescriptor dynInVar = itrDynInVars.next();
1945       outputStructs.println("  void* "+dynInVar+"_srcSESE;");
1946       outputStructs.println("  int   "+dynInVar+"_srcOffset;");
1947     }    
1948
1949     // space for all in and out set primitives
1950     Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1951     inSetAndOutSet.addAll( fsen.getInVarSet() );
1952     inSetAndOutSet.addAll( fsen.getOutVarSet() );
1953
1954     Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
1955
1956     Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1957     while( itr.hasNext() ) {
1958       TempDescriptor temp = itr.next();
1959       TypeDescriptor type = temp.getType();
1960       if( !type.isPtr() ) {
1961         inSetAndOutSetPrims.add( temp );
1962       }
1963     }
1964
1965     Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
1966     while( itrPrims.hasNext() ) {
1967       TempDescriptor temp = itrPrims.next();
1968       TypeDescriptor type = temp.getType();
1969       outputStructs.println("  "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
1970     }
1971
1972     for(int i=0; i<objectparams.numPointers(); i++) {
1973       TempDescriptor temp=objectparams.getPointer(i);
1974       if (temp.getType().isNull())
1975         outputStructs.println("  void * "+temp.getSafeSymbol()+";");
1976       else
1977         outputStructs.println("  struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1978     }
1979     
1980     outputStructs.println("};\n");
1981
1982     
1983     // write method declaration to header file
1984     outputMethHead.print("void ");
1985     outputMethHead.print(fsen.getSESEmethodName()+"(");
1986     outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
1987     outputMethHead.println(");\n");
1988
1989
1990     generateFlatMethodSESE( fsen.getfmBogus(), 
1991                             fsen.getcdEnclosing(), 
1992                             fsen, 
1993                             fsen.getFlatExit(), 
1994                             outputMethods );
1995   }
1996
1997   private void generateFlatMethodSESE(FlatMethod fm, 
1998                                       ClassDescriptor cn, 
1999                                       FlatSESEEnterNode fsen, 
2000                                       FlatSESEExitNode  seseExit, 
2001                                       PrintWriter output
2002                                       ) {
2003
2004     MethodDescriptor md=fm.getMethod();
2005
2006     output.print("void ");
2007     output.print(fsen.getSESEmethodName()+"(");
2008     output.print(fsen.getSESErecordName()+"* "+paramsprefix);
2009     output.println("){\n");
2010
2011     TempObject objecttemp=(TempObject) tempstable.get(md);
2012
2013     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2014       output.print("   struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2015       output.print(objecttemp.numPointers()+",");
2016       output.print("(void*) &("+paramsprefix+"->size)");
2017       for(int j=0; j<objecttemp.numPointers(); j++)
2018         output.print(", NULL");
2019       output.println("};");
2020     }
2021
2022     output.println("   /* regular local primitives */");
2023     for(int i=0; i<objecttemp.numPrimitives(); i++) {
2024       TempDescriptor td=objecttemp.getPrimitive(i);
2025       TypeDescriptor type=td.getType();
2026       if (type.isNull())
2027         output.println("   void * "+td.getSafeSymbol()+";");
2028       else if (type.isClass()||type.isArray())
2029         output.println("   struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2030       else
2031         output.println("   "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2032     }
2033
2034
2035     // declare variables for naming static SESE's
2036     output.println("   /* static SESE names */");
2037     Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
2038     while( pItr.hasNext() ) {
2039       SESEandAgePair pair = pItr.next();
2040       output.println("   void* "+pair+";");
2041     }
2042
2043     // declare variables for tracking dynamic sources
2044     output.println("   /* dynamic variable sources */");
2045     Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
2046     while( dynSrcItr.hasNext() ) {
2047       TempDescriptor dynSrcVar = dynSrcItr.next();
2048       output.println("   void* "+dynSrcVar+"_srcSESE;");
2049       output.println("   int   "+dynSrcVar+"_srcOffset;");
2050     }    
2051
2052     // declare local temps for in-set primitives, and if it is
2053     // a ready-source variable, get the value from the record
2054     output.println("   /* local temps for in-set primitives */");
2055     Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2056     while( itrInSet.hasNext() ) {
2057       TempDescriptor temp = itrInSet.next();
2058       TypeDescriptor type = temp.getType();
2059       if( !type.isPtr() ) {
2060         if( fsen.getReadyInVarSet().contains( temp ) ) {
2061           output.println("   "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2062         } else {
2063           output.println("   "+type+" "+temp+";");
2064         }
2065       }
2066     }    
2067
2068     // declare local temps for out-set primitives if its not already
2069     // in the in-set, and it's value will get written so no problem
2070     output.println("   /* local temp for out-set prim, not already in the in-set */");
2071     Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2072     while( itrOutSet.hasNext() ) {
2073       TempDescriptor temp = itrOutSet.next();
2074       TypeDescriptor type = temp.getType();
2075       if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2076         output.println("   "+type+" "+temp+";");       
2077       }
2078     }    
2079     
2080     // setup memory queue
2081     // eom
2082     output.println("   // set up memory queues ");
2083         output.println("   int numMemoryQueue=0;");
2084         output.println("   int memoryQueueItemID=0;");
2085         ConflictGraph graph = null;
2086         graph = mlpa.getConflictGraphResults().get(fsen);
2087         if (graph != null) {
2088                 output.println("   {");
2089                 output
2090                                 .println("   SESEcommon* parentCommon = &(___params___->common);");
2091                 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
2092                                 graph);
2093
2094                 if (lockSet.size() > 0) {
2095                         output.println("   numMemoryQueue=" + lockSet.size() + ";");
2096                         output
2097                                         .println("   parentCommon->numMemoryQueue=numMemoryQueue;");
2098                         output
2099                                         .println("   parentCommon->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2100                         output.println();
2101                 }
2102                 output.println("   }");
2103         }
2104
2105
2106     // copy in-set into place, ready vars were already 
2107     // copied when the SESE was issued
2108     Iterator<TempDescriptor> tempItr;
2109
2110     // static vars are from a known SESE
2111     tempItr = fsen.getStaticInVarSet().iterator();
2112     while( tempItr.hasNext() ) {
2113       TempDescriptor temp = tempItr.next();
2114       VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2115       SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2116       
2117       // can't grab something from this source until it is done
2118       output.println("   {");
2119       /*
2120         If we are running, everything is done.  This check is redundant.
2121
2122         output.println("     SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+srcPair+";" );
2123         output.println("     pthread_mutex_lock( &(com->lock) );");
2124         output.println("     while( com->doneExecuting == FALSE ) {");
2125         output.println("       pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2126         output.println("     }");
2127         output.println("     pthread_mutex_unlock( &(com->lock) );");
2128       */
2129       output.println("     "+generateTemp( fsen.getfmBogus(), temp, null )+
2130                      " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2131
2132       output.println("   }");
2133     }
2134
2135     // dynamic vars come from an SESE and src
2136     tempItr = fsen.getDynamicInVarSet().iterator();
2137     while( tempItr.hasNext() ) {
2138       TempDescriptor temp = tempItr.next();
2139       TypeDescriptor type = temp.getType();
2140       
2141       // go grab it from the SESE source
2142       output.println("   if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2143
2144       // gotta wait until the source is done
2145       output.println("     SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+temp+"_srcSESE;" );
2146       /*
2147         If we are running, everything is done!
2148         output.println("     pthread_mutex_lock( &(com->lock) );");
2149         output.println("     while( com->doneExecuting == FALSE ) {");
2150         output.println("       pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2151         output.println("     }");
2152         output.println("     pthread_mutex_unlock( &(com->lock) );");
2153       */
2154
2155       String typeStr;
2156       if( type.isNull() ) {
2157         typeStr = "void*";
2158       } else if( type.isClass() || type.isArray() ) {
2159         typeStr = "struct "+type.getSafeSymbol()+"*";
2160       } else {
2161         typeStr = type.getSafeSymbol();
2162       }
2163       
2164       output.println("     "+generateTemp( fsen.getfmBogus(), temp, null )+
2165                      " = *(("+typeStr+"*) ("+
2166                      paramsprefix+"->"+temp+"_srcSESE + "+
2167                      paramsprefix+"->"+temp+"_srcOffset));");
2168
2169       // or if the source was our parent, its in the record to grab
2170       output.println("   } else {");
2171       output.println("     "+generateTemp( fsen.getfmBogus(), temp, null )+
2172                            " = "+paramsprefix+"->"+temp+";");
2173       output.println("   }");
2174     }
2175
2176     // Check to see if we need to do a GC if this is a
2177     // multi-threaded program...    
2178     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2179       //Don't bother if we aren't in recursive methods...The loops case will catch it
2180       if (callgraph.getAllMethods(md).contains(md)) {
2181         if(this.state.MULTICOREGC) {
2182           output.println("if(gcflag) gc("+localsprefixaddr+");");
2183         } else {
2184           output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2185         }
2186       }
2187     }    
2188
2189     // initialize thread-local var to a non-zero, invalid address
2190     output.println("   seseCaller = (SESEcommon*) 0x2;");
2191     HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2192     exitset.add(seseExit);    
2193     generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2194     output.println("}\n\n");
2195     
2196   }
2197
2198
2199   // when a new mlp thread is created for an issued SESE, it is started
2200   // by running this method which blocks on a cond variable until
2201   // it is allowed to transition to execute.  Then a case statement
2202   // allows it to invoke the method with the proper SESE body, and after
2203   // exiting the SESE method, executes proper SESE exit code before the
2204   // thread can be destroyed
2205   private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2206                                             PrintWriter outmethod
2207                                             ) {
2208
2209     outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2210     outmethod.println(      "void* invokeSESEmethod( void* seseRecord ) {");
2211     outmethod.println(      "  int status;");
2212     outmethod.println(      "  char errmsg[128];");
2213
2214     // generate a case for each SESE class that can be invoked
2215     outmethod.println(      "  switch( *((int*)seseRecord) ) {");
2216     outmethod.println(      "    ");
2217     for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
2218       FlatSESEEnterNode fsen = seseit.next();
2219
2220       outmethod.println(    "    /* "+fsen.getPrettyIdentifier()+" */");
2221       outmethod.println(    "    case "+fsen.getIdentifier()+":");
2222       outmethod.println(    "      "+fsen.getSESEmethodName()+"( seseRecord );");  
2223       
2224       if( fsen.equals( mlpa.getMainSESE() ) ) {
2225         outmethod.println(  "      /* work scheduler works forever, explicitly exit */");
2226         outmethod.println(  "      exit( 0 );");
2227       }
2228
2229       outmethod.println(    "      break;");
2230       outmethod.println(    "");
2231     }
2232
2233     // default case should never be taken, error out
2234     outmethod.println(      "    default:");
2235     outmethod.println(      "      printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2236     outmethod.println(      "      exit(-30);");
2237     outmethod.println(      "      break;");
2238     outmethod.println(      "  }");
2239     outmethod.println(      "  return NULL;");
2240     outmethod.println(      "}\n\n");
2241   }
2242
2243
2244   protected void generateCode(FlatNode first,
2245                               FlatMethod fm,
2246                               LocalityBinding lb,
2247                               Set<FlatNode> stopset,
2248                               PrintWriter output, boolean firstpass) {
2249
2250     /* Assign labels to FlatNode's if necessary.*/
2251
2252     Hashtable<FlatNode, Integer> nodetolabel;
2253
2254     if (state.DELAYCOMP&&!firstpass)
2255       nodetolabel=dcassignLabels(first, stopset);      
2256     else
2257       nodetolabel=assignLabels(first, stopset);      
2258     
2259     Set<FlatNode> storeset=null;
2260     HashSet<FlatNode> genset=null;
2261     HashSet<FlatNode> refset=null;
2262     Set<FlatNode> unionset=null;
2263
2264     if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2265       storeset=delaycomp.livecode(lb);
2266       genset=new HashSet<FlatNode>();
2267       if (state.STMARRAY&&!state.DUALVIEW) {
2268         refset=new HashSet<FlatNode>();
2269         refset.addAll(delaycomp.getDeref(lb));
2270         refset.removeAll(delaycomp.getCannotDelay(lb));
2271         refset.removeAll(delaycomp.getOther(lb));
2272       }
2273       if (firstpass) {
2274         genset.addAll(delaycomp.getCannotDelay(lb));
2275         genset.addAll(delaycomp.getOther(lb));
2276       } else {
2277         genset.addAll(delaycomp.getNotReady(lb));
2278         if (state.STMARRAY&&!state.DUALVIEW) {
2279           genset.removeAll(refset);
2280         }
2281       }
2282       unionset=new HashSet<FlatNode>();
2283       unionset.addAll(storeset);
2284       unionset.addAll(genset);
2285       if (state.STMARRAY&&!state.DUALVIEW)
2286         unionset.addAll(refset);
2287     }
2288     
2289     /* Do the actual code generation */
2290     FlatNode current_node=null;
2291     HashSet tovisit=new HashSet();
2292     HashSet visited=new HashSet();
2293     if (!firstpass)
2294       tovisit.add(first.getNext(0));
2295     else
2296       tovisit.add(first);
2297     while(current_node!=null||!tovisit.isEmpty()) {
2298       if (current_node==null) {
2299         current_node=(FlatNode)tovisit.iterator().next();
2300         tovisit.remove(current_node);
2301       } else if (tovisit.contains(current_node)) {
2302         tovisit.remove(current_node);
2303       }
2304       visited.add(current_node);
2305       if (nodetolabel.containsKey(current_node)) {
2306         output.println("L"+nodetolabel.get(current_node)+":");
2307       }
2308       if (state.INSTRUCTIONFAILURE) {
2309         if (state.THREAD||state.DSM||state.SINGLETM) {
2310           output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2311         } else
2312           output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2313       }
2314       if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2315         output.print("   ");
2316         if (!state.DELAYCOMP||firstpass) {
2317           generateFlatNode(fm, lb, current_node, output);
2318         } else {
2319           //store primitive variables in out set
2320           AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2321           Set<TempDescriptor> liveout=ar.liveout;
2322           for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2323             TempDescriptor tmp=tmpit.next();
2324             output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2325           }
2326         }
2327         if (state.MLP && stopset!=null) {
2328           assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2329           assert current_node       instanceof FlatSESEExitNode;
2330           FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2331           FlatSESEExitNode  fsxn = (FlatSESEExitNode)  current_node;
2332           assert fsen.getFlatExit().equals( fsxn );
2333           assert fsxn.getFlatEnter().equals( fsen );
2334         }
2335         if (current_node.kind()!=FKind.FlatReturnNode) {
2336           output.println("   return;");
2337         }
2338         current_node=null;
2339       } else if(current_node.numNext()==1) {
2340         FlatNode nextnode;
2341         if (state.MLP && 
2342             current_node.kind()==FKind.FlatSESEEnterNode && 
2343             !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2344            ) {
2345           FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2346           generateFlatNode(fm, lb, current_node, output);
2347           nextnode=fsen.getFlatExit().getNext(0);
2348         } else if (state.DELAYCOMP) {
2349           boolean specialprimitive=false;
2350           //skip literals...no need to add extra overhead
2351           if (storeset!=null&&storeset.contains(current_node)&&current_node.kind()==FKind.FlatLiteralNode) {
2352             TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2353             if (!typedesc.isClass()&&!typedesc.isArray()) {
2354               specialprimitive=true;
2355             }
2356           }
2357
2358           if (genset==null||genset.contains(current_node)||specialprimitive)
2359             generateFlatNode(fm, lb, current_node, output);
2360           if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2361             //need to acquire lock
2362             handleArrayDeref(fm, lb, current_node, output, firstpass);
2363           }
2364           if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2365             TempDescriptor wrtmp=current_node.writesTemps()[0];
2366             if (firstpass) {
2367               //need to store value written by previous node
2368               if (wrtmp.getType().isPtr()) {
2369                 //only lock the objects that may actually need locking
2370                 if (recorddc.getNeedTrans(lb, current_node)&&
2371                     (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2372                      wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2373                   output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2374                 } else {
2375                   output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2376                 }
2377               } else {
2378                 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2379               }
2380             } else {
2381               //need to read value read by previous node
2382               if (wrtmp.getType().isPtr()) {
2383                 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2384               } else {
2385                 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");               
2386               }
2387             }
2388           }
2389           nextnode=current_node.getNext(0);
2390         } else {
2391           output.print("   ");
2392           generateFlatNode(fm, lb, current_node, output);
2393           nextnode=current_node.getNext(0);
2394         }
2395         if (visited.contains(nextnode)) {
2396           output.println("goto L"+nodetolabel.get(nextnode)+";");
2397           current_node=null;
2398         } else 
2399           current_node=nextnode;
2400       } else if (current_node.numNext()==2) {
2401         /* Branch */
2402         if (state.DELAYCOMP) {
2403           boolean computeside=false;
2404           if (firstpass) {
2405             //need to record which way it should go
2406             if (genset==null||genset.contains(current_node)) {
2407               if (storeset!=null&&storeset.contains(current_node)) {
2408                 //need to store which way branch goes
2409                 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2410               } else
2411                 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2412             } else {
2413               //which side to execute
2414               computeside=true;
2415             }
2416           } else {
2417             if (genset.contains(current_node)) {
2418               generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);             
2419             } else if (storeset.contains(current_node)) {
2420               //need to do branch
2421               branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2422             } else {
2423               //which side to execute
2424               computeside=true;
2425             }
2426           }
2427           if (computeside) {
2428             Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2429             int branch=0;
2430             if (leftset.size()==0)
2431               branch=1;
2432             if (visited.contains(current_node.getNext(branch))) {
2433               //already visited -- build jump
2434               output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2435               current_node=null;
2436             } else {
2437               current_node=current_node.getNext(branch);
2438             }
2439           } else {
2440             if (!visited.contains(current_node.getNext(1)))
2441               tovisit.add(current_node.getNext(1));
2442             if (visited.contains(current_node.getNext(0))) {
2443               output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2444               current_node=null;
2445             } else 
2446               current_node=current_node.getNext(0);
2447           }
2448         } else {
2449           output.print("   ");  
2450           generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2451           if (!visited.contains(current_node.getNext(1)))
2452             tovisit.add(current_node.getNext(1));
2453           if (visited.contains(current_node.getNext(0))) {
2454             output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2455             current_node=null;
2456           } else 
2457             current_node=current_node.getNext(0);
2458         }
2459       } else throw new Error();
2460     }
2461   }
2462
2463   protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2464     if (fn.kind()==FKind.FlatSetElementNode) {
2465       FlatSetElementNode fsen=(FlatSetElementNode) fn;
2466       String dst=generateTemp(fm, fsen.getDst(), lb);
2467       String src=generateTemp(fm, fsen.getSrc(), lb);
2468       String index=generateTemp(fm, fsen.getIndex(), lb);      
2469       TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2470       String type="";
2471       if (elementtype.isArray()||elementtype.isClass())
2472         type="void *";
2473       else
2474         type=elementtype.getSafeSymbol()+" ";
2475       if (firstpass) {
2476         output.println("STOREARRAY("+dst+","+index+","+type+")");
2477       } else {
2478         output.println("{");
2479         output.println("  struct ArrayObject *array;");
2480         output.println("  int index;");
2481         output.println("  RESTOREARRAY(array,index);");
2482         output.println("  (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2483         output.println("}");
2484       }
2485     } else if (fn.kind()==FKind.FlatElementNode) {
2486       FlatElementNode fen=(FlatElementNode) fn;
2487       String src=generateTemp(fm, fen.getSrc(), lb);
2488       String index=generateTemp(fm, fen.getIndex(), lb);
2489       TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2490       String dst=generateTemp(fm, fen.getDst(), lb);
2491       String type="";
2492       if (elementtype.isArray()||elementtype.isClass())
2493         type="void *";
2494       else
2495         type=elementtype.getSafeSymbol()+" ";
2496       if (firstpass) {
2497         output.println("STOREARRAY("+src+","+index+","+type+")");
2498       } else {
2499         output.println("{");
2500         output.println("  struct ArrayObject *array;");
2501         output.println("  int index;");
2502         output.println("  RESTOREARRAY(array,index);");
2503         output.println("  "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2504         output.println("}");
2505       }
2506     }
2507   }
2508   /** Special label assignment for delaycomputation */
2509   protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2510     HashSet tovisit=new HashSet();
2511     HashSet visited=new HashSet();
2512     int labelindex=0;
2513     Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2514
2515     //Label targets of branches
2516     Set<FlatNode> targets=branchanalysis.getTargets();
2517     for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2518       nodetolabel.put(it.next(), new Integer(labelindex++));
2519     }
2520
2521
2522     tovisit.add(first);
2523     /*Assign labels first.  A node needs a label if the previous
2524      * node has two exits or this node is a join point. */
2525
2526     while(!tovisit.isEmpty()) {
2527       FlatNode fn=(FlatNode)tovisit.iterator().next();
2528       tovisit.remove(fn);
2529       visited.add(fn);
2530
2531
2532       if(lastset!=null&&lastset.contains(fn)) {
2533         // if last is not null and matches, don't go 
2534         // any further for assigning labels
2535         continue;
2536       }
2537
2538       for(int i=0; i<fn.numNext(); i++) {
2539         FlatNode nn=fn.getNext(i);
2540
2541         if(i>0) {
2542           //1) Edge >1 of node
2543           nodetolabel.put(nn,new Integer(labelindex++));
2544         }
2545         if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2546           tovisit.add(nn);
2547         } else {
2548           //2) Join point
2549           nodetolabel.put(nn,new Integer(labelindex++));
2550         }
2551       }
2552     }
2553     return nodetolabel;
2554
2555   }
2556
2557   protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2558     return assignLabels(first, null);
2559   }
2560
2561   protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2562     HashSet tovisit=new HashSet();
2563     HashSet visited=new HashSet();
2564     int labelindex=0;
2565     Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2566     tovisit.add(first);
2567
2568     /*Assign labels first.  A node needs a label if the previous
2569      * node has two exits or this node is a join point. */
2570
2571     while(!tovisit.isEmpty()) {
2572       FlatNode fn=(FlatNode)tovisit.iterator().next();
2573       tovisit.remove(fn);
2574       visited.add(fn);
2575
2576
2577       if(lastset!=null&&lastset.contains(fn)) {
2578         // if last is not null and matches, don't go 
2579         // any further for assigning labels
2580         continue;
2581       }
2582
2583       for(int i=0; i<fn.numNext(); i++) {
2584         FlatNode nn=fn.getNext(i);
2585
2586         if(i>0) {
2587           //1) Edge >1 of node
2588           nodetolabel.put(nn,new Integer(labelindex++));
2589         }
2590         if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2591           tovisit.add(nn);
2592         } else {
2593           //2) Join point
2594           nodetolabel.put(nn,new Integer(labelindex++));
2595         }
2596       }
2597     }
2598     return nodetolabel;
2599   }
2600
2601
2602   /** Generate text string that corresponds to the TempDescriptor td. */
2603   protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2604     MethodDescriptor md=fm.getMethod();
2605     TaskDescriptor task=fm.getTask();
2606     TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2607
2608     if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2609       return td.getSafeSymbol();
2610     }
2611
2612     if (objecttemps.isLocalPtr(td)) {
2613       return localsprefixderef+td.getSafeSymbol();
2614     }
2615
2616     if (objecttemps.isParamPtr(td)) {
2617       return paramsprefix+"->"+td.getSafeSymbol();
2618     }
2619
2620     throw new Error();
2621   }
2622
2623   protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2624
2625     // insert pre-node actions from the code plan
2626     if( state.MLP ) {
2627       
2628       CodePlan cp = mlpa.getCodePlan( fn );
2629       if( cp != null ) {                
2630         
2631         FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2632         
2633         // for each sese and age pair that this parent statement
2634         // must stall on, take that child's stall semaphore, the
2635         // copying of values comes after the statement
2636         Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2637         while( vstItr.hasNext() ) {
2638           VariableSourceToken vst = vstItr.next();
2639
2640           SESEandAgePair pair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2641
2642           output.println("   {");
2643           output.println("     SESEcommon* common = (SESEcommon*) "+pair+";");
2644
2645           output.println("     pthread_mutex_lock( &(common->lock) );");
2646           output.println("     while( common->doneExecuting == FALSE ) {");
2647           output.println("       pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2648           output.println("     }");
2649           output.println("     pthread_mutex_unlock( &(common->lock) );");
2650
2651           // copy things we might have stalled for        
2652           output.println("     "+pair.getSESE().getSESErecordName()+"* child = ("+
2653                                  pair.getSESE().getSESErecordName()+"*) "+pair+";");
2654           
2655           Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2656           while( tdItr.hasNext() ) {
2657             TempDescriptor td = tdItr.next();
2658             FlatMethod fmContext;
2659             if( currentSESE.getIsCallerSESEplaceholder() ) {
2660               fmContext = currentSESE.getfmEnclosing();
2661             } else {
2662               fmContext = currentSESE.getfmBogus();
2663             }
2664             output.println("       "+generateTemp( fmContext, td, null )+
2665                            " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2666           }
2667
2668           output.println("   }");
2669         }
2670         
2671         // for each variable with a dynamic source, stall just for that variable
2672         Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2673         while( dynItr.hasNext() ) {
2674           TempDescriptor dynVar = dynItr.next();
2675
2676           // only stall if the dynamic source is not yourself, denoted by src==NULL
2677           // otherwise the dynamic write nodes will have the local var up-to-date
2678           output.println("   {");
2679           output.println("     if( "+dynVar+"_srcSESE != NULL ) {");
2680           output.println("       SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2681           output.println("       psem_take( &(common->stallSem) );");
2682
2683           FlatMethod fmContext;
2684           if( currentSESE.getIsCallerSESEplaceholder() ) {
2685             fmContext = currentSESE.getfmEnclosing();
2686           } else {
2687             fmContext = currentSESE.getfmBogus();
2688           }
2689           output.println("       "+generateTemp( fmContext, dynVar, null )+
2690                          " = *(("+dynVar.getType()+"*) ("+
2691                          dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2692           
2693           output.println("     }");
2694           output.println("   }");
2695         }
2696
2697         // for each assignment of a variable to rhs that has a dynamic source,
2698         // copy the dynamic sources
2699         Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2700         while( dynAssignItr.hasNext() ) {
2701           Map.Entry      me  = (Map.Entry)      dynAssignItr.next();
2702           TempDescriptor lhs = (TempDescriptor) me.getKey();
2703           TempDescriptor rhs = (TempDescriptor) me.getValue();
2704           output.println("   "+lhs+"_srcSESE   = "+rhs+"_srcSESE;");
2705           output.println("   "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2706         }
2707
2708         // for each lhs that is dynamic from a non-dynamic source, set the
2709         // dynamic source vars to the current SESE
2710         dynItr = cp.getDynAssignCurr().iterator();
2711         while( dynItr.hasNext() ) {
2712           TempDescriptor dynVar = dynItr.next();          
2713           assert currentSESE.getDynamicVarSet().contains( dynVar );
2714           output.println("   "+dynVar+"_srcSESE = NULL;");
2715         }
2716         
2717         // eom
2718     // handling stall site
2719         ParentChildConflictsMap conflictsMap = mlpa.getConflictsResults().get(fn);
2720         if (conflictsMap != null) {
2721                 Set<Long> allocSet = conflictsMap.getAllocationSiteIDSetofStallSite();
2722                 if (allocSet.size() > 0) {
2723                         FlatNode enclosingFlatNode=null;
2724                         if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
2725                                 enclosingFlatNode=currentSESE.getfmEnclosing();
2726                         }else{
2727                                 enclosingFlatNode=currentSESE;
2728                         }                                               
2729                         ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
2730                         HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
2731                         Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
2732                         
2733                         if(waitingElementSet.size()>0){
2734                                 output.println("// stall on parent's stall sites ");
2735                                 output.println("   {");
2736                                 output.println("     REntry* rentry;");
2737                                 
2738                                 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
2739                                         WaitingElement waitingElement = (WaitingElement) iterator.next();
2740                                         
2741                                         if( waitingElement.getStatus() >= ConflictNode.COARSE ){
2742                                                 output.println("     rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", seseCaller);");
2743                                         }else{
2744                                                 output.println("     rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller,  ___locals___."+ waitingElement.getDynID() + ");");       
2745                                         }                                       
2746                                         output.println("     psem_init( &(rentry->parentStallSem) );");
2747                                         output.println("     rentry->queue=seseCaller->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
2748                                         output
2749                                                         .println("     if(ADDRENTRY(seseCaller->memoryQueueArray["+ waitingElement.getQueueID()
2750                                                                         + "],rentry)==NOTREADY){");
2751                                         output.println("        psem_take( &(rentry->parentStallSem) );");
2752                                         output.println("     }  ");
2753                                 }
2754                                 output.println("   }");
2755                         }
2756                 }
2757         }       
2758
2759       }     
2760     }
2761
2762     switch(fn.kind()) {
2763     case FKind.FlatAtomicEnterNode:
2764       generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
2765       break;
2766
2767     case FKind.FlatAtomicExitNode:
2768       generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
2769       break;
2770
2771     case FKind.FlatInstanceOfNode:
2772       generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
2773       break;
2774
2775     case FKind.FlatSESEEnterNode:
2776       generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
2777       break;
2778
2779     case FKind.FlatSESEExitNode:
2780       generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
2781       break;
2782       
2783     case FKind.FlatWriteDynamicVarNode:
2784       generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
2785       break;
2786
2787     case FKind.FlatGlobalConvNode:
2788       generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
2789       break;
2790
2791     case FKind.FlatTagDeclaration:
2792       generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
2793       break;
2794
2795     case FKind.FlatCall:
2796       generateFlatCall(fm, lb, (FlatCall) fn,output);
2797       break;
2798
2799     case FKind.FlatFieldNode:
2800       generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
2801       break;
2802
2803     case FKind.FlatElementNode:
2804       generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
2805       break;
2806
2807     case FKind.FlatSetElementNode:
2808       generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
2809       break;
2810
2811     case FKind.FlatSetFieldNode:
2812       generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
2813       break;
2814
2815     case FKind.FlatNew:
2816       generateFlatNew(fm, lb, (FlatNew) fn,output);
2817       break;
2818
2819     case FKind.FlatOpNode:
2820       generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
2821       break;
2822
2823     case FKind.FlatCastNode:
2824       generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
2825       break;
2826
2827     case FKind.FlatLiteralNode:
2828       generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
2829       break;
2830
2831     case FKind.FlatReturnNode:
2832       generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
2833       break;
2834
2835     case FKind.FlatNop:
2836       output.println("/* nop */");
2837       break;
2838
2839     case FKind.FlatExit:
2840       output.println("/* exit */");
2841       break;
2842
2843     case FKind.FlatBackEdge:
2844       if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
2845         output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
2846       }
2847       if(state.DSM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
2848         output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
2849       }
2850       if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
2851           || (this.state.MULTICOREGC)) {
2852         if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
2853           output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
2854         } else if(this.state.MULTICOREGC) {
2855           output.println("if (gcflag) gc("+localsprefixaddr+");");
2856         } else {
2857           output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2858         }
2859       } else
2860         output.println("/* nop */");
2861       break;
2862
2863     case FKind.FlatCheckNode:
2864       generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
2865       break;
2866
2867     case FKind.FlatFlagActionNode:
2868       generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
2869       break;
2870
2871     case FKind.FlatPrefetchNode:
2872       generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
2873       break;
2874
2875     case FKind.FlatOffsetNode:
2876       generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
2877       break;
2878
2879     default:
2880       throw new Error();
2881     }
2882
2883     // insert post-node actions from the code-plan    
2884     if( state.MLP ) {
2885       CodePlan cp = mlpa.getCodePlan( fn );
2886
2887       if( cp != null ) {     
2888       }
2889     }    
2890   }
2891
2892   public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
2893     output.println("/* FlatOffsetNode */");
2894     FieldDescriptor fd=fofn.getField();
2895     output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
2896     output.println("/* offset */");
2897   }
2898
2899   public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
2900     if (state.PREFETCH) {
2901       Vector oids = new Vector();
2902       Vector fieldoffset = new Vector();
2903       Vector endoffset = new Vector();
2904       int tuplecount = 0;        //Keeps track of number of prefetch tuples that need to be generated
2905       for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
2906         PrefetchPair pp = (PrefetchPair) it.next();
2907         Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
2908         /* Find prefetches that can generate oid */
2909         if(statusbase == LocalityAnalysis.GLOBAL) {
2910           generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
2911           tuplecount++;
2912         } else if (statusbase == LocalityAnalysis.LOCAL) {
2913           generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
2914         } else {
2915           continue;
2916         }
2917       }
2918       if (tuplecount==0)
2919         return;
2920       System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
2921       output.println("{");
2922       output.println("/* prefetch */");
2923       output.println("/* prefetchid_" + fpn.siteid + " */");
2924       output.println("void * prefptr;");
2925       output.println("int tmpindex;");
2926
2927       output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
2928       /*Create C code for oid array */
2929       output.print("   unsigned int oidarray_[] = {");
2930       boolean needcomma=false;
2931       for (Iterator it = oids.iterator(); it.hasNext();) {
2932         if (needcomma)
2933           output.print(", ");
2934         output.print(it.next());
2935         needcomma=true;
2936       }
2937       output.println("};");
2938
2939       /*Create C code for endoffset values */
2940       output.print("   unsigned short endoffsetarry_[] = {");
2941       needcomma=false;
2942       for (Iterator it = endoffset.iterator(); it.hasNext();) {
2943         if (needcomma)
2944           output.print(", ");
2945         output.print(it.next());
2946         needcomma=true;
2947       }
2948       output.println("};");
2949
2950       /*Create C code for Field Offset Values */
2951       output.print("   short fieldarry_[] = {");
2952       needcomma=false;
2953       for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
2954         if (needcomma)
2955           output.print(", ");
2956         output.print(it.next());
2957         needcomma=true;
2958       }
2959       output.println("};");
2960       /* make the prefetch call to Runtime */
2961       output.println("   if(!evalPrefetch["+fpn.siteid+"].operMode) {");
2962       output.println("     evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
2963       output.println("   }");
2964       output.println("   prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
2965       output.println(" } else {");
2966       output.println("   evalPrefetch["+fpn.siteid+"].retrycount--;");
2967       output.println(" }");
2968       output.println("}");
2969     }
2970   }
2971
2972   public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
2973     short offsetcount = 0;
2974     int breakindex=0;
2975     if (inside) {
2976       breakindex=1;
2977     } else if (localbase) {
2978       for(; breakindex<pp.desc.size(); breakindex++) {
2979         Descriptor desc=pp.getDescAt(breakindex);
2980         if (desc instanceof FieldDescriptor) {
2981           FieldDescriptor fd=(FieldDescriptor)desc;
2982           if (fd.isGlobal()) {
2983             break;
2984           }
2985         }
2986       }
2987       breakindex++;
2988     }
2989
2990     if (breakindex>pp.desc.size())     //all local
2991       return;
2992
2993     TypeDescriptor lasttype=pp.base.getType();
2994     String basestr=generateTemp(fm, pp.base, lb);
2995     String teststr="";
2996     boolean maybenull=fm.getMethod().isStatic()||
2997                        !pp.base.equals(fm.getParameter(0));
2998
2999     for(int i=0; i<breakindex; i++) {
3000       String indexcheck="";
3001
3002       Descriptor desc=pp.getDescAt(i);
3003       if (desc instanceof FieldDescriptor) {
3004         FieldDescriptor fd=(FieldDescriptor)desc;
3005         if (maybenull) {
3006           if (!teststr.equals(""))
3007             teststr+="&&";
3008           teststr+="((prefptr="+basestr+")!=NULL)";
3009           basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3010         } else {
3011           basestr=basestr+"->"+fd.getSafeSymbol();
3012           maybenull=true;
3013         }
3014         lasttype=fd.getType();
3015       } else {
3016         IndexDescriptor id=(IndexDescriptor)desc;
3017         indexcheck="((tmpindex=";
3018         for(int j=0; j<id.tddesc.size(); j++) {
3019           indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3020         }
3021         indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3022
3023         if (!teststr.equals(""))
3024           teststr+="&&";
3025         teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3026         basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3027         maybenull=true;
3028         lasttype=lasttype.dereference();
3029       }
3030     }
3031
3032     String oid;
3033     if (teststr.equals("")) {
3034       oid="((unsigned int)"+basestr+")";
3035     } else {
3036       oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3037     }
3038     oids.add(oid);
3039
3040     for(int i = breakindex; i < pp.desc.size(); i++) {
3041       String newfieldoffset;
3042       Object desc = pp.getDescAt(i);
3043       if(desc instanceof FieldDescriptor) {
3044         FieldDescriptor fd=(FieldDescriptor)desc;
3045         newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3046         lasttype=fd.getType();
3047       } else {
3048         newfieldoffset = "";
3049         IndexDescriptor id=(IndexDescriptor)desc;
3050         for(int j = 0; j < id.tddesc.size(); j++) {
3051           newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3052         }
3053         newfieldoffset += id.offset.toString();
3054         lasttype=lasttype.dereference();
3055       }
3056       fieldoffset.add(newfieldoffset);
3057     }
3058
3059     int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3060     base+=pp.desc.size()-breakindex;
3061     endoffset.add(new Short((short)base));
3062   }
3063
3064
3065
3066   public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3067     if (lb!=fgcn.getLocality())
3068       return;
3069     /* Have to generate flat globalconv */
3070     if (fgcn.getMakePtr()) {
3071       if (state.DSM) {
3072         //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3073            output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3074       } else {
3075         if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3076           //need to do translation
3077           output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3078         } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3079           if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3080             output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3081           } else
3082             output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3083         }
3084       }
3085     } else {
3086       /* Need to convert to OID */
3087       if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3088         if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3089           output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3090         } else {
3091           output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3092         }
3093       }
3094     }
3095   }
3096
3097   public void generateFlatInstanceOfNode(FlatMethod fm,  LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3098     int type;
3099     if (fion.getType().isArray()) {
3100       type=state.getArrayNumber(fion.getType())+state.numClasses();
3101     } else {
3102       type=fion.getType().getClassDesc().getId();
3103     }
3104
3105     if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3106       output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3107     else
3108       output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3109   }
3110
3111   int sandboxcounter=0;
3112   public void generateFlatAtomicEnterNode(FlatMethod fm,  LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3113     /* Check to see if we need to generate code for this atomic */
3114     if (locality==null) {
3115       if (GENERATEPRECISEGC) {
3116         output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3117         output.println("stopforgc((struct garbagelist *) &___locals___);");
3118         output.println("pthread_mutex_lock(&atomiclock);");
3119         output.println("restartaftergc();");
3120         output.println("}");
3121       } else {
3122         output.println("pthread_mutex_lock(&atomiclock);");
3123       }
3124       return;
3125     }
3126
3127     if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3128       return;
3129
3130
3131     if (state.SANDBOX) {
3132       outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3133       output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3134     }
3135
3136     if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3137       AtomicRecord ar=atomicmethodmap.get(faen);
3138       //copy in
3139       for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3140         TempDescriptor tmp=tmpit.next();
3141         output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3142       }
3143
3144       //copy outs that depend on path
3145       for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3146         TempDescriptor tmp=tmpit.next();
3147         if (!ar.livein.contains(tmp))
3148           output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3149       }
3150     }
3151
3152     /* Backup the temps. */
3153     for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3154       TempDescriptor tmp=tmpit.next();
3155       output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3156     }
3157
3158     output.println("goto transstart"+faen.getIdentifier()+";");
3159
3160     /******* Print code to retry aborted transaction *******/
3161     output.println("transretry"+faen.getIdentifier()+":");
3162
3163     /* Restore temps */
3164     for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3165       TempDescriptor tmp=tmpit.next();
3166       output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3167     }
3168
3169     if (state.DSM) {
3170       /********* Need to revert local object store ********/
3171       String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3172
3173       output.println("while ("+revertptr+") {");
3174       output.println("struct ___Object___ * tmpptr;");
3175       output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3176       output.println("REVERT_OBJ("+revertptr+");");
3177       output.println(revertptr+"=tmpptr;");
3178       output.println("}");
3179     }
3180     /******* Tell the runtime to start the transaction *******/
3181
3182     output.println("transstart"+faen.getIdentifier()+":");
3183     if (state.SANDBOX) {
3184       output.println("transaction_check_counter=*counter_reset_pointer;");
3185       sandboxcounter++;
3186     }
3187     output.println("transStart();");
3188
3189     if (state.ABORTREADERS||state.SANDBOX) {
3190       if (state.SANDBOX)
3191         output.println("abortenabled=1;");
3192       output.println("if (_setjmp(aborttrans)) {");
3193       output.println("  goto transretry"+faen.getIdentifier()+"; }");
3194     }
3195   }
3196
3197   public void generateFlatAtomicExitNode(FlatMethod fm,  LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3198     /* Check to see if we need to generate code for this atomic */
3199     if (locality==null) {
3200       output.println("pthread_mutex_unlock(&atomiclock);");
3201       return;
3202     }
3203     if (locality.getAtomic(lb).get(faen).intValue()>0)
3204       return;
3205     //store the revert list before we lose the transaction object
3206     
3207     if (state.DSM) {
3208       String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3209       output.println(revertptr+"=revertlist;");
3210       output.println("if (transCommit()) {");
3211       output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3212       output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3213       output.println("} else {");
3214       /* Need to commit local object store */
3215       output.println("while ("+revertptr+") {");
3216       output.println("struct ___Object___ * tmpptr;");
3217       output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3218       output.println("COMMIT_OBJ("+revertptr+");");
3219       output.println(revertptr+"=tmpptr;");
3220       output.println("}");
3221       output.println("}");
3222       return;
3223     }
3224
3225     if (!state.DELAYCOMP) {
3226       //Normal STM stuff
3227       output.println("if (transCommit()) {");
3228       /* Transaction aborts if it returns true */
3229       output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3230       output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3231       output.println("}");
3232     } else {
3233       if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW))  {
3234         AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3235         output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3236         //copy out
3237         for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3238           TempDescriptor tmp=tmpit.next();
3239           output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3240         }
3241       } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3242         AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3243         //do call
3244         output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3245         output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3246         output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3247         output.println("}");
3248         //copy out
3249         output.println("else {");
3250         for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3251           TempDescriptor tmp=tmpit.next();
3252           output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3253         }
3254         output.println("}");
3255       } else {
3256         output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3257         output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3258         output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3259         output.println("}");
3260       }
3261     }
3262   }
3263
3264   public void generateFlatSESEEnterNode( FlatMethod fm,  
3265                                          LocalityBinding lb, 
3266                                          FlatSESEEnterNode fsen, 
3267                                          PrintWriter output 
3268                                        ) {
3269
3270     // if MLP flag is off, okay that SESE nodes are in IR graph, 
3271     // just skip over them and code generates exactly the same
3272     if( !state.MLP ) {
3273       return;
3274     }    
3275
3276     // there may be an SESE in an unreachable method, skip over
3277     if( !mlpa.getAllSESEs().contains( fsen ) ) {
3278       return;
3279     }
3280
3281     // also, if we have encountered a placeholder, just skip it
3282     if( fsen.getIsCallerSESEplaceholder() ) {
3283       return;
3284     }
3285
3286     output.println("   {");
3287
3288     // set up the parent
3289     if( fsen == mlpa.getMainSESE() ) {
3290       output.println("     SESEcommon* parentCommon = NULL;");
3291     } else {
3292       if( fsen.getParent() == null ) {
3293         System.out.println( "in "+fm+", "+fsen+" has null parent" );
3294       }
3295       assert fsen.getParent() != null;
3296       if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3297         output.println("     SESEcommon* parentCommon = &("+paramsprefix+"->common);");
3298       } else {
3299         //output.println("     SESEcommon* parentCommon = (SESEcommon*) peekItem( seseCallStack );");
3300         output.println("     SESEcommon* parentCommon = seseCaller;");
3301       }
3302     }
3303     
3304     // before doing anything, lock your own record and increment the running children
3305     if( fsen != mlpa.getMainSESE() ) {      
3306       output.println("     atomic_inc(&parentCommon->numRunningChildren);");
3307     }
3308
3309     // just allocate the space for this record
3310     output.println("     "+fsen.getSESErecordName()+"* seseToIssue = ("+
3311                            fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3312                            fsen.getSESErecordName()+" ) );");
3313
3314     // and keep the thread-local sese stack up to date
3315     //output.println("     addNewItem( seseCallStack, (void*) seseToIssue);");
3316
3317     // fill in common data
3318     output.println("     int localCount=0;");
3319     output.println("     seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3320     output.println("     psem_init( &(seseToIssue->common.stallSem) );");
3321
3322     output.println("     seseToIssue->common.forwardList = createQueue();");
3323     output.println("     seseToIssue->common.unresolvedDependencies = 10000;");
3324     output.println("     pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3325     output.println("     seseToIssue->common.doneExecuting = FALSE;");    
3326     output.println("     pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3327     output.println("     seseToIssue->common.numRunningChildren = 0;");
3328     output.println("     seseToIssue->common.parent = parentCommon;");
3329
3330     // all READY in-vars should be copied now and be done with it
3331     Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3332     while( tempItr.hasNext() ) {
3333       TempDescriptor temp = tempItr.next();
3334
3335       // when we are issuing the main SESE or an SESE with placeholder
3336       // caller SESE as parent, generate temp child child's eclosing method,
3337       // otherwise use the parent's enclosing method as the context
3338       boolean useParentContext = false;
3339
3340       if( fsen != mlpa.getMainSESE() ) {
3341         assert fsen.getParent() != null;
3342         if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3343           useParentContext = true;
3344         }
3345       }
3346
3347       if( useParentContext ) {
3348         output.println("     seseToIssue->"+temp+" = "+
3349                        generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");   
3350       } else {
3351         output.println("     seseToIssue->"+temp+" = "+
3352                        generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3353       }
3354     }
3355     
3356     // before potentially adding this SESE to other forwarding lists,
3357     //  create it's lock and take it immediately
3358     output.println("     pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3359 //    output.println("     pthread_mutex_lock( &(seseToIssue->common.lock) );");
3360     
3361     // count up memory conflict dependencies,
3362     // eom
3363         ConflictGraph graph = null;
3364         FlatSESEEnterNode parent = fsen.getParent();
3365         if (parent != null) {
3366                 if (parent.isCallerSESEplaceholder) {
3367                         graph = mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
3368                 } else {
3369                         graph = mlpa.getConflictGraphResults().get(parent);
3370                 }
3371         }
3372         if (graph != null) {
3373                 HashSet<SESELock> seseLockSet = mlpa.getConflictGraphLockMap().get(
3374                                 graph);
3375                 output.println();
3376                 output.println("     //add memory queue element");
3377                 Set<WaitingElement> waitingQueueSet = graph
3378                                 .getWaitingElementSetBySESEID(fsen.getIdentifier(),
3379                                                 seseLockSet);
3380                 if (waitingQueueSet.size() > 0) {
3381                         output.println("     {");
3382                         output.println("     REntry* rentry=NULL;");
3383                         output.println("     seseToIssue->common.rentryIdx=0;");
3384                         for (Iterator iterator = waitingQueueSet.iterator(); iterator
3385                                         .hasNext();) {
3386                                 WaitingElement waitingElement = (WaitingElement) iterator
3387                                                 .next();
3388                                 
3389                                 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3390                                         output.println("     rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", seseToIssue);");
3391                                 }else{
3392                                         output.println("     rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseToIssue,  seseToIssue->"+ waitingElement.getDynID() + ");");      
3393                                 }               
3394                                 output.println("     rentry->queue=parentCommon->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3395                                 output.println("     seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
3396                                 output
3397                                                 .println("     if(ADDRENTRY(parentCommon->memoryQueueArray["
3398                                                                 + waitingElement.getQueueID()
3399                                                                 + "],rentry)==NOTREADY){");
3400                                 output.println("        ++(localCount);");
3401                                 output.println("     } ");
3402                                 output.println();
3403                         }
3404                         output.println("     }");
3405                 }
3406                 output.println();
3407         }    
3408     
3409     if( fsen != mlpa.getMainSESE() ) {
3410       // count up outstanding dependencies, static first, then dynamic
3411       Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3412       while( staticSrcsItr.hasNext() ) {
3413         SESEandAgePair srcPair = staticSrcsItr.next();
3414         output.println("     {");
3415         output.println("       SESEcommon* src = (SESEcommon*)"+srcPair+";");
3416         output.println("       pthread_mutex_lock( &(src->lock) );");
3417         output.println("       if( !isEmpty( src->forwardList ) &&");
3418         output.println("           seseToIssue == peekItem( src->forwardList ) ) {");
3419         output.println("         printf( \"This shouldnt already be here\\n\");");
3420         output.println("         exit( -1 );");
3421         output.println("       }");
3422         output.println("       if( !src->doneExecuting ) {");
3423         output.println("         addNewItem( src->forwardList, seseToIssue );");
3424 //      output.println("         ++(seseToIssue->common.unresolvedDependencies);");
3425         output.println("         ++(localCount);");
3426         output.println("       }");
3427         output.println("       pthread_mutex_unlock( &(src->lock) );");
3428         output.println("     }");
3429
3430         // whether or not it is an outstanding dependency, make sure
3431         // to pass the static name to the child's record
3432         output.println("     seseToIssue->"+srcPair+" = "+srcPair+";");
3433       }
3434
3435       // dynamic sources might already be accounted for in the static list,
3436       // so only add them to forwarding lists if they're not already there
3437       Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3438       while( dynVarsItr.hasNext() ) {
3439         TempDescriptor dynInVar = dynVarsItr.next();
3440         output.println("     {");
3441         output.println("       SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3442
3443         // the dynamic source is NULL if it comes from your own space--you can't pass
3444         // the address off to the new child, because you're not done executing and
3445         // might change the variable, so copy it right now
3446         output.println("       if( src != NULL ) {");
3447         output.println("         pthread_mutex_lock( &(src->lock) );");
3448         output.println("         if( isEmpty( src->forwardList ) ||");
3449         output.println("             seseToIssue != peekItem( src->forwardList ) ) {");
3450         output.println("           if( !src->doneExecuting ) {");
3451         output.println("             addNewItem( src->forwardList, seseToIssue );");
3452 //      output.println("             ++(seseToIssue->common.unresolvedDependencies);");
3453         output.println("             ++(localCount);");
3454         output.println("           }");
3455         output.println("         }");
3456         output.println("         pthread_mutex_unlock( &(src->lock) );");       
3457         output.println("         seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3458         output.println("       } else {");
3459
3460         boolean useParentContext = false;
3461         if( fsen != mlpa.getMainSESE() ) {
3462           assert fsen.getParent() != null;
3463           if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3464             useParentContext = true;
3465           }
3466         }       
3467         if( useParentContext ) {
3468           output.println("         seseToIssue->"+dynInVar+" = "+
3469                          generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3470         } else {
3471           output.println("         seseToIssue->"+dynInVar+" = "+
3472                          generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3473         }
3474         
3475         output.println("       }");
3476         output.println("     }");
3477         
3478         // even if the value is already copied, make sure your NULL source
3479         // gets passed so child knows it already has the dynamic value
3480         output.println("     seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3481       }
3482       
3483       // maintain pointers for finding dynamic SESE 
3484       // instances from static names      
3485       SESEandAgePair pair = new SESEandAgePair( fsen, 0 );
3486       if(  fsen.getParent() != null && 
3487            //!fsen.getParent().getIsCallerSESEplaceholder() &&
3488            fsen.getParent().getNeededStaticNames().contains( pair ) 
3489         ) {       
3490
3491         for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3492           SESEandAgePair pair1 = new SESEandAgePair( fsen, i   );
3493           SESEandAgePair pair2 = new SESEandAgePair( fsen, i-1 );
3494           output.println("     "+pair1+" = "+pair2+";");
3495         }      
3496         output.println("     "+pair+" = seseToIssue;");
3497       }
3498  
3499     }
3500     
3501     // release this SESE for siblings to update its dependencies or,
3502     // eventually, for it to mark itself finished
3503     //    output.println("     pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3504     
3505     // if there were no outstanding dependencies, issue here
3506     output.println("     if(  atomic_sub_and_test(10000-localCount,&(seseToIssue->common.unresolvedDependencies) ) ) {");
3507     output.println("       workScheduleSubmit( (void*)seseToIssue );");
3508     output.println("     }");
3509     /*
3510     output.println("     if( seseToIssue->common.unresolvedDependencies == 0 ) {");
3511     output.println("       workScheduleSubmit( (void*)seseToIssue );");
3512     output.println("     }");
3513     */
3514     // release this SESE for siblings to update its dependencies or,
3515     // eventually, for it to mark itself finished
3516 //    output.println("     pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3517     output.println("   }");
3518     
3519   }
3520
3521   public void generateFlatSESEExitNode( FlatMethod fm,  
3522                                         LocalityBinding lb, 
3523                                         FlatSESEExitNode fsexn, 
3524                                         PrintWriter output
3525                                       ) {
3526
3527     // if MLP flag is off, okay that SESE nodes are in IR graph, 
3528     // just skip over them and code generates exactly the same 
3529     if( !state.MLP ) {
3530       return;
3531     }
3532
3533     // get the enter node for this exit that has meta data embedded
3534     FlatSESEEnterNode fsen = fsexn.getFlatEnter();
3535
3536     // there may be an SESE in an unreachable method, skip over
3537     if( !mlpa.getAllSESEs().contains( fsen ) ) {
3538       return;
3539     }
3540
3541     // also, if we have encountered a placeholder, just jump it
3542     if( fsen.getIsCallerSESEplaceholder() ) {
3543       return;
3544     }
3545
3546     output.println("   /* SESE exiting */");
3547     
3548     String com = paramsprefix+"->common";
3549
3550     // this SESE cannot be done until all of its children are done
3551     // so grab your own lock with the condition variable for watching
3552     // that the number of your running children is greater than zero    
3553     output.println("   pthread_mutex_lock( &("+com+".lock) );");
3554     output.println("   while( "+com+".numRunningChildren > 0 ) {");
3555     output.println("     pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
3556     output.println("   }");
3557
3558     // copy out-set from local temps into the sese record
3559     Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
3560     while( itr.hasNext() ) {
3561       TempDescriptor temp = itr.next();
3562
3563       // only have to do this for primitives non-arrays
3564       if( !(
3565             temp.getType().isPrimitive() && !temp.getType().isArray()
3566            )
3567         ) {
3568         continue;
3569       }
3570
3571       // have to determine the context enclosing this sese
3572       boolean useParentContext = false;
3573
3574       if( fsen != mlpa.getMainSESE() ) {
3575         assert fsen.getParent() != null;
3576         if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3577           useParentContext = true;
3578         }
3579       }
3580
3581       String from;
3582       if( useParentContext ) {
3583         from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
3584       } else {
3585         from = generateTemp( fsen.getfmEnclosing(),         temp, null );
3586       }
3587
3588       output.println("   "+paramsprefix+
3589                      "->"+temp.getSafeSymbol()+
3590                      " = "+from+";");
3591     }    
3592     
3593     // mark yourself done, your SESE data is now read-only
3594     output.println("   "+com+".doneExecuting = TRUE;");
3595     output.println("   pthread_cond_signal( &("+com+".doneCond) );");
3596     output.println("   pthread_mutex_unlock( &("+com+".lock) );");
3597
3598     // decrement dependency count for all SESE's on your forwarding list
3599     output.println("   while( !isEmpty( "+com+".forwardList ) ) {");
3600     output.println("     SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
3601 //    output.println("     pthread_mutex_lock( &(consumer->lock) );");
3602 //  output.println("     --(consumer->unresolvedDependencies);");
3603 //    output.println("     if( consumer->unresolvedDependencies == 0 ) {");
3604     output.println("     if( atomic_sub_and_test(1, &(consumer->unresolvedDependencies)) ){");
3605     output.println("       workScheduleSubmit( (void*)consumer );");
3606     output.println("     }");
3607 //    output.println("     pthread_mutex_unlock( &(consumer->lock) );");
3608     output.println("   }");
3609     
3610     
3611     // eom
3612     // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
3613     if( fsen != mlpa.getMainSESE() ) {
3614         
3615                 output.println();
3616                 output.println("   /* check memory dependency*/");
3617                 output.println("  {");                  
3618                 output.println("      int idx;");
3619                 output.println("      for(idx=0;idx<___params___->common.rentryIdx;idx++){");
3620                 output.println("           REntry* re=___params___->common.rentryArray[idx];");
3621                 output.println("           RETIRERENTRY(re->queue,re);");
3622                 output.println("      }");
3623                 output.println("   }");
3624                 
3625     }
3626     
3627     // if parent is stalling on you, let them know you're done
3628     if( fsexn.getFlatEnter() != mlpa.getMainSESE() ) {
3629       output.println("   psem_give( &("+paramsprefix+"->common.stallSem) );");
3630     }
3631
3632     // last of all, decrement your parent's number of running children    
3633     output.println("   if( "+paramsprefix+"->common.parent != NULL ) {");
3634     output.println("     if (atomic_sub_and_test(1, &"+paramsprefix+"->common.parent->numRunningChildren)) {");
3635     output.println("       pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
3636     output.println("       pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
3637     output.println("       pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
3638     output.println("     }");
3639     output.println("   }");
3640
3641     // this is a thread-only variable that can be handled when critical sese-to-sese
3642     // data has been taken care of--set sese pointer to remember self over method
3643     // calls to a non-zero, invalid address
3644     output.println("   seseCaller = (SESEcommon*) 0x1;");    
3645     
3646   }
3647  
3648   public void generateFlatWriteDynamicVarNode( FlatMethod fm,  
3649                                                LocalityBinding lb, 
3650                                                FlatWriteDynamicVarNode fwdvn,
3651                                                PrintWriter output
3652                                              ) {
3653     if( !state.MLP ) {
3654       // should node should not be in an IR graph if the
3655       // MLP flag is not set
3656       throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
3657     }
3658         
3659     Hashtable<TempDescriptor, VSTWrapper> writeDynamic = fwdvn.getVar2src();
3660
3661     assert writeDynamic != null;
3662
3663     Iterator wdItr = writeDynamic.entrySet().iterator();
3664     while( wdItr.hasNext() ) {
3665       Map.Entry           me     = (Map.Entry)      wdItr.next();
3666       TempDescriptor      refVar = (TempDescriptor) me.getKey();
3667       VSTWrapper          vstW   = (VSTWrapper)     me.getValue();
3668       VariableSourceToken vst    =                  vstW.vst;
3669
3670       /*
3671       // only do this if the variable in question should be tracked,
3672       // meaning that it was explicitly added to the dynamic var set
3673       if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
3674         continue;
3675       }
3676       */
3677
3678       if( vst == null ) {
3679         // if there is no given source, this variable is ready so
3680         // mark src pointer NULL to signify that the var is up-to-date
3681         output.println("     "+refVar+"_srcSESE = NULL;");
3682         continue;
3683       }
3684
3685       // otherwise we track where it will come from
3686       SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
3687       output.println("     "+refVar+"_srcSESE = "+instance+";");    
3688       output.println("     "+refVar+"_srcOffset = (int) &((("+
3689                      vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
3690     }   
3691   }
3692
3693   
3694   private void generateFlatCheckNode(FlatMethod fm,  LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
3695     if (state.CONSCHECK) {
3696       String specname=fcn.getSpec();
3697       String varname="repairstate___";
3698       output.println("{");
3699       output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
3700
3701       TempDescriptor[] temps=fcn.getTemps();
3702       String[] vars=fcn.getVars();
3703       for(int i=0; i<temps.length; i++) {
3704         output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
3705       }
3706
3707       output.println("if (doanalysis"+specname+"("+varname+")) {");
3708       output.println("free"+specname+"_state("+varname+");");
3709       output.println("} else {");
3710       output.println("/* Bad invariant */");
3711       output.println("free"+specname+"_state("+varname+");");
3712       output.println("abort_task();");
3713       output.println("}");
3714       output.println("}");
3715     }
3716   }
3717
3718   private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
3719
3720     if( state.MLP && !nonSESEpass ) {
3721       output.println("     seseCaller = (SESEcommon*)"+paramsprefix+";");
3722     }
3723
3724     MethodDescriptor md=fc.getMethod();
3725     ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
3726     ClassDescriptor cn=md.getClassDesc();
3727     output.println("{");
3728     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3729       if (lb!=null) {
3730         LocalityBinding fclb=locality.getBinding(lb, fc);
3731         output.print("       struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3732       } else
3733         output.print("       struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3734
3735       output.print(objectparams.numPointers());
3736       output.print(", "+localsprefixaddr);
3737       if (md.getThis()!=null) {
3738         output.print(", ");
3739         output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
3740       }
3741       if (fc.getThis()!=null&&md.getThis()==null) {
3742         System.out.println("WARNING!!!!!!!!!!!!");
3743         System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
3744       }
3745
3746
3747       for(int i=0; i<fc.numArgs(); i++) {
3748         Descriptor var=md.getParameter(i);
3749         TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3750         if (objectparams.isParamPtr(paramtemp)) {
3751           TempDescriptor targ=fc.getArg(i);
3752           output.print(", ");
3753           TypeDescriptor td=md.getParamType(i);
3754           if (td.isTag())
3755             output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()  +" *)"+generateTemp(fm, targ,lb));
3756           else
3757             output.print("(struct "+md.getParamType(i).getSafeSymbol()  +" *)"+generateTemp(fm, targ,lb));
3758         }
3759       }
3760       output.println("};");
3761     }
3762     output.print("       ");
3763
3764
3765     if (fc.getReturnTemp()!=null)
3766       output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
3767
3768     /* Do we need to do virtual dispatch? */
3769     if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
3770       //no
3771       if (lb!=null) {
3772         LocalityBinding fclb=locality.getBinding(lb, fc);
3773         output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3774       } else {
3775         output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3776       }
3777     } else {
3778       //yes
3779       output.print("((");
3780       if (md.getReturnType().isClass()||md.getReturnType().isArray())
3781         output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3782       else
3783         output.print(md.getReturnType().getSafeSymbol()+" ");
3784       output.print("(*)(");
3785
3786       boolean printcomma=false;
3787       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3788         if (lb!=null) {
3789           LocalityBinding fclb=locality.getBinding(lb, fc);
3790           output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3791         } else
3792           output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3793         printcomma=true;
3794       }
3795
3796       for(int i=0; i<objectparams.numPrimitives(); i++) {
3797         TempDescriptor temp=objectparams.getPrimitive(i);
3798         if (printcomma)
3799           output.print(", ");
3800         printcomma=true;
3801         if (temp.getType().isClass()||temp.getType().isArray())
3802           output.print("struct " + temp.getType().getSafeSymbol()+" * ");
3803         else
3804           output.print(temp.getType().getSafeSymbol());
3805       }
3806
3807
3808       if (lb!=null) {
3809         LocalityBinding fclb=locality.getBinding(lb, fc);
3810         output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
3811       } else
3812         output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
3813     }
3814
3815     output.print("(");
3816     boolean needcomma=false;
3817     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3818       output.print("&__parameterlist__");
3819       needcomma=true;
3820     }
3821
3822     if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
3823       if (fc.getThis()!=null) {
3824         TypeDescriptor ptd=md.getThis().getType();
3825         if (needcomma)
3826           output.print(",");
3827         if (ptd.isClass()&&!ptd.isArray())
3828           output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3829         output.print(generateTemp(fm,fc.getThis(),lb));
3830         needcomma=true;
3831       }
3832     }
3833
3834     for(int i=0; i<fc.numArgs(); i++) {
3835       Descriptor var=md.getParameter(i);
3836       TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3837       if (objectparams.isParamPrim(paramtemp)) {
3838         TempDescriptor targ=fc.getArg(i);
3839         if (needcomma)
3840           output.print(", ");
3841
3842         TypeDescriptor ptd=md.getParamType(i);
3843         if (ptd.isClass()&&!ptd.isArray())
3844           output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3845         output.print(generateTemp(fm, targ,lb));
3846         needcomma=true;
3847       }
3848     }
3849     output.println(");");
3850     output.println("   }");
3851   }
3852
3853   private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
3854     Set subclasses=typeutil.getSubClasses(thiscd);
3855     if (subclasses==null)
3856       return true;
3857     for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
3858       ClassDescriptor cd=(ClassDescriptor)classit.next();
3859       Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
3860       for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
3861         MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
3862         if (md.matches(matchmd))
3863           return false;
3864       }
3865     }
3866     return true;
3867   }
3868
3869   private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
3870     if (state.SINGLETM) {
3871       //single machine transactional memory case
3872       String field=ffn.getField().getSafeSymbol();
3873       String src=generateTemp(fm, ffn.getSrc(),lb);
3874       String dst=generateTemp(fm, ffn.getDst(),lb);
3875
3876       output.println(dst+"="+ src +"->"+field+ ";");
3877       if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
3878           locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
3879         if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
3880             (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
3881           output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
3882         } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
3883           if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
3884             output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
3885           } else
3886             output.println("TRANSREADRD("+dst+", "+dst+");");
3887         }
3888       }
3889     } else if (state.DSM) {
3890       Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
3891       if (status==LocalityAnalysis.GLOBAL) {
3892         String field=ffn.getField().getSafeSymbol();
3893         String src=generateTemp(fm, ffn.getSrc(),lb);
3894         String dst=generateTemp(fm, ffn.getDst(),lb);
3895
3896         if (ffn.getField().getType().isPtr()) {
3897
3898           //TODO: Uncomment this when we have runtime support
3899           //if (ffn.getSrc()==ffn.getDst()) {
3900           //output.println("{");
3901           //output.println("void * temp="+src+";");
3902           //output.println("if (temp&0x1) {");
3903           //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
3904           //output.println(src+"->"+field+"="+temp+";");
3905           //output.println("}");
3906           //output.println(dst+"=temp;");
3907           //output.println("}");
3908           //} else {
3909           output.println(dst+"="+ src +"->"+field+ ";");
3910           //output.println("if ("+dst+"&0x1) {");
3911           //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
3912       output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3913           //output.println(src+"->"+field+"="+src+"->"+field+";");
3914           //output.println("}");
3915           //}
3916         } else {
3917           output.println(dst+"="+ src+"->"+field+";");
3918         }
3919       } else if (status==LocalityAnalysis.LOCAL) {
3920         if (ffn.getField().getType().isPtr()&&
3921             ffn.getField().isGlobal()) {
3922           String field=ffn.getField().getSafeSymbol();
3923           String src=generateTemp(fm, ffn.getSrc(),lb);
3924           String dst=generateTemp(fm, ffn.getDst(),lb);
3925           output.println(dst+"="+ src +"->"+field+ ";");
3926           if (locality.getAtomic(lb).get(ffn).intValue()>0)
3927             //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
3928             output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3929         } else
3930           output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3931       } else if (status==LocalityAnalysis.EITHER) {
3932         //Code is reading from a null pointer
3933         output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
3934         output.println("#ifndef RAW");
3935         output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
3936         output.println("#endif");
3937         //This should throw a suitable null pointer error
3938         output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3939       } else
3940         throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
3941     } else
3942       output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3943   }
3944
3945
3946   private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
3947     if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
3948       throw new Error("Can't set array length");
3949     if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3950       //Single Machine Transaction Case
3951       boolean srcptr=fsfn.getSrc().getType().isPtr();
3952       String src=generateTemp(fm,fsfn.getSrc(),lb);
3953       String dst=generateTemp(fm,fsfn.getDst(),lb);
3954       output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
3955       if (srcptr&&!fsfn.getSrc().getType().isNull()) {
3956         output.println("{");
3957         if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
3958             locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
3959           output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3960         } else {
3961           output.println("INTPTR srcoid=(INTPTR)"+src+";");
3962         }
3963       }
3964       if (wb.needBarrier(fsfn)&&
3965           locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
3966         if (state.EVENTMONITOR) {
3967           output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
3968         }
3969         output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
3970       }
3971       if (srcptr&!fsfn.getSrc().getType().isNull()) {
3972         output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
3973         output.println("}");
3974       } else {
3975         output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3976       }
3977     } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3978       Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
3979       Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
3980       boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
3981
3982       String src=generateTemp(fm,fsfn.getSrc(),lb);
3983       String dst=generateTemp(fm,fsfn.getDst(),lb);
3984       if (srcglobal) {
3985         output.println("{");
3986         output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3987       }
3988       if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
3989         String glbdst=dst;
3990         //mark it dirty
3991         if (wb.needBarrier(fsfn))
3992           output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
3993         if (srcglobal) {
3994           output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
3995         } else
3996           output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3997       } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
3998         /** Check if we need to copy */
3999         output.println("if(!"+dst+"->"+localcopystr+") {");
4000         /* Link object into list */
4001         String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4002         output.println(revertptr+"=revertlist;");
4003         if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4004           output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4005         else
4006           output.println("COPY_OBJ("+dst+");");
4007         output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4008         output.println("revertlist=(struct ___Object___ *)"+dst+";");
4009         output.println("}");
4010         if (srcglobal)
4011           output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4012         else
4013           output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4014       } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
4015         //writing to a null...bad
4016         output.println("if ("+dst+") {");
4017         output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
4018         if (srcglobal)
4019           output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4020         else
4021           output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4022       }
4023       if (srcglobal) {
4024         output.println("}");
4025       }
4026     } else {
4027       if (state.FASTCHECK) {
4028         String dst=generateTemp(fm, fsfn.getDst(),lb);
4029         output.println("if(!"+dst+"->"+localcopystr+") {");
4030         /* Link object into list */
4031         if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4032           output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4033         else
4034           output.println("COPY_OBJ("+dst+");");
4035         output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4036         output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4037         output.println("}");
4038       }
4039       output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4040     }
4041   }
4042
4043   private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
4044     TypeDescriptor elementtype=fen.getSrc().getType().dereference();
4045     String type="";
4046
4047     if (elementtype.isArray()||elementtype.isClass())
4048       type="void *";
4049     else
4050       type=elementtype.getSafeSymbol()+" ";
4051
4052     if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
4053       output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
4054       output.println("failedboundschk();");
4055     }
4056     if (state.SINGLETM) {
4057       //Single machine transaction case
4058       String dst=generateTemp(fm, fen.getDst(),lb);
4059       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))) {
4060         output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4061       } else {
4062         output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
4063       }
4064
4065       if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
4066           locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
4067         if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
4068           output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
4069         } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
4070           if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
4071             output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4072           } else
4073             output.println("TRANSREADRD("+dst+", "+dst+");");
4074         }
4075       }
4076     } else if (state.DSM) {
4077       Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
4078       if (status==LocalityAnalysis.GLOBAL) {
4079         String dst=generateTemp(fm, fen.getDst(),lb);
4080         if (elementtype.isPtr()) {
4081           output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4082           //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
4083           output.println("TRANSREAD("+dst+", "+dst+");");
4084         } else {
4085           output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4086         }
4087       } else if (status==LocalityAnalysis.LOCAL) {
4088         output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4089       } else if (status==LocalityAnalysis.EITHER) {
4090         //Code is reading from a null pointer
4091         output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
4092         output.println("#ifndef RAW");
4093         output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4094         output.println("#endif");
4095         //This should throw a suitable null pointer error
4096         output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4097       } else
4098         throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4099     } else {
4100       output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4101     }
4102   }
4103
4104   private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
4105     //TODO: need dynamic check to make sure this assignment is actually legal
4106     //Because Object[] could actually be something more specific...ie. Integer[]
4107
4108     TypeDescriptor elementtype=fsen.getDst().getType().dereference();
4109     String type="";
4110
4111     if (elementtype.isArray()||elementtype.isClass())
4112       type="void *";
4113     else
4114       type=elementtype.getSafeSymbol()+" ";
4115
4116     if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
4117       output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
4118       output.println("failedboundschk();");
4119     }
4120
4121     if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4122       //Transaction set element case
4123       if (wb.needBarrier(fsen)&&
4124           locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
4125         output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
4126       }
4127       if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
4128         output.println("{");
4129         String src=generateTemp(fm, fsen.getSrc(), lb);
4130         if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
4131             locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
4132           output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4133         } else {
4134           output.println("INTPTR srcoid=(INTPTR)"+src+";");
4135         }
4136         if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4137           output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
4138         } else {
4139           output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4140         }
4141         output.println("}");
4142       } else {
4143         if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4144           output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
4145         } else {
4146           output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4147         }
4148       }
4149     } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4150       Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
4151       Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
4152       boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4153       boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
4154       boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
4155       
4156       if (dstglobal) {
4157         if (wb.needBarrier(fsen))
4158           output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
4159       } else if (dstlocal) {
4160         /** Check if we need to copy */
4161         String dst=generateTemp(fm, fsen.getDst(),lb);
4162         output.println("if(!"+dst+"->"+localcopystr+") {");
4163         /* Link object into list */
4164         String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4165         output.println(revertptr+"=revertlist;");
4166         if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
4167         output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4168         else
4169           output.println("COPY_OBJ("+dst+");");
4170         output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4171         output.println("revertlist=(struct ___Object___ *)"+dst+";");
4172         output.println("}");
4173       } else {
4174         System.out.println("Node: "+fsen);
4175         System.out.println(lb);
4176         System.out.println("statusdst="+statusdst);
4177         System.out.println(fm.printMethod());
4178         throw new Error("Unknown array type");
4179       }
4180       if (srcglobal) {
4181         output.println("{");
4182         String src=generateTemp(fm, fsen.getSrc(), lb);
4183         output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4184         output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4185         output.println("}");
4186       } else {
4187         output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4188       }
4189     } else {
4190       if (state.FASTCHECK) {
4191         String dst=generateTemp(fm, fsen.getDst(),lb);
4192         output.println("if(!"+dst+"->"+localcopystr+") {");
4193         /* Link object into list */
4194         if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4195           output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4196         else
4197           output.println("COPY_OBJ("+dst+");");
4198         output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4199         output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4200         output.println("}");
4201       }
4202       output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4203     }
4204   }
4205
4206   protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
4207     if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4208       //Stash pointer in case of GC
4209       String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4210       output.println(revertptr+"=revertlist;");
4211     }
4212     if (state.SINGLETM) {
4213       if (fn.getType().isArray()) {
4214         int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4215         if (locality.getAtomic(lb).get(fn).intValue()>0) {
4216           //inside transaction
4217           output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4218         } else {
4219           //outside transaction
4220           output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4221         }
4222       } else {
4223         if (locality.getAtomic(lb).get(fn).intValue()>0) {
4224           //inside transaction
4225           output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4226         } else {
4227           //outside transaction
4228           output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4229         }
4230       }
4231     } else if (fn.getType().isArray()) {
4232       int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4233       if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4234         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4235       } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4236         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4237       } else {
4238         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4239       }
4240     } else {
4241       if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4242         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
4243       } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4244         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4245       } else {
4246         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
4247       }
4248     }
4249     if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4250       String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4251       String dst=generateTemp(fm,fn.getDst(),lb);
4252       output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4253       output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4254       output.println("revertlist=(struct ___Object___ *)"+dst+";");
4255     }
4256     if (state.FASTCHECK) {
4257       String dst=generateTemp(fm,fn.getDst(),lb);
4258       output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4259       output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4260       output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4261     }
4262   }
4263
4264   private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
4265     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4266       output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
4267     } else {
4268       output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
4269     }
4270   }
4271
4272   private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
4273     if (fon.getRight()!=null) {
4274       if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
4275         if (fon.getLeft().getType().isLong())
4276           output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4277         else
4278           output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4279
4280       } else if (dc!=null) {
4281         output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
4282         if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4283             output.print("(void *)");
4284         if (dc.getNeedLeftSrcTrans(lb, fon))
4285           output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
4286         else
4287           output.print(generateTemp(fm, fon.getLeft(),lb));
4288         output.print(")"+fon.getOp().toString()+"(");
4289         if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4290             output.print("(void *)");
4291         if (dc.getNeedRightSrcTrans(lb, fon))
4292           output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
4293         else
4294           output.println(generateTemp(fm,fon.getRight(),lb)+");");
4295       } else
4296         output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
4297     } else if (fon.getOp().getOp()==Operation.ASSIGN)
4298       output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4299     else if (fon.getOp().getOp()==Operation.UNARYPLUS)
4300       output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4301     else if (fon.getOp().getOp()==Operation.UNARYMINUS)
4302       output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
4303     else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
4304       output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
4305     else if (fon.getOp().getOp()==Operation.COMP)
4306       output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
4307     else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
4308       output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
4309     } else
4310       output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
4311   }
4312
4313   private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
4314     /* TODO: Do type check here */
4315     if (fcn.getType().isArray()) {
4316       output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4317     } else if (fcn.getType().isClass())
4318       output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4319     else
4320       output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
4321   }
4322
4323   private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
4324     if (fln.getValue()==null)
4325       output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4326     else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
4327       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4328         if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4329           //Stash pointer in case of GC
4330           String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4331           output.println(revertptr+"=revertlist;");
4332         }
4333         output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4334         if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4335           //Stash pointer in case of GC
4336           String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4337           output.println("revertlist="+revertptr+";");
4338         }
4339       } else {
4340         output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4341       }
4342     } else if (fln.getType().isBoolean()) {
4343       if (((Boolean)fln.getValue()).booleanValue())
4344         output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
4345       else
4346         output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4347     } else if (fln.getType().isChar()) {
4348       String st=FlatLiteralNode.escapeString(fln.getValue().toString());
4349       output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
4350     } else if (fln.getType().isLong()) {
4351       output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
4352     } else
4353       output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
4354   }
4355
4356   protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
4357     if (frn.getReturnTemp()!=null) {
4358       if (frn.getReturnTemp().getType().isPtr())
4359         output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4360       else
4361         output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4362     } else {
4363       output.println("return;");
4364     }
4365   }
4366
4367   protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4368     int left=-1;
4369     int right=-1;
4370     //only record if this group has more than one exit
4371     if (branchanalysis.numJumps(fcb)>1) {
4372       left=branchanalysis.jumpValue(fcb, 0);
4373       right=branchanalysis.jumpValue(fcb, 1);
4374     }
4375     output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
4376     if (right!=-1)
4377       output.println("STOREBRANCH("+right+");");
4378     output.println("goto "+label+";");
4379     output.println("}");
4380     if (left!=-1)
4381       output.println("STOREBRANCH("+left+");");
4382   }
4383
4384   protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4385     output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
4386   }
4387
4388   /** This method generates header information for the method or
4389    * task referenced by the Descriptor des. */
4390   private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
4391     generateHeader(fm, lb, des, output, false);
4392   }
4393
4394   private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
4395     /* Print header */
4396     ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
4397     MethodDescriptor md=null;
4398     TaskDescriptor task=null;
4399     if (des instanceof MethodDescriptor)
4400       md=(MethodDescriptor) des;
4401     else
4402       task=(TaskDescriptor) des;
4403
4404     ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
4405
4406     if (md!=null&&md.getReturnType()!=null) {
4407       if (md.getReturnType().isClass()||md.getReturnType().isArray())
4408         output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4409       else
4410         output.print(md.getReturnType().getSafeSymbol()+" ");
4411     } else
4412       //catch the constructor case
4413       output.print("void ");
4414     if (md!=null) {
4415       if (state.DSM||state.SINGLETM) {
4416         output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4417       } else
4418         output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4419     } else
4420       output.print(task.getSafeSymbol()+"(");
4421     
4422     boolean printcomma=false;
4423     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4424       if (md!=null) {
4425         if (state.DSM||state.SINGLETM) {
4426           output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4427         } else
4428           output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4429       } else
4430         output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
4431       printcomma=true;
4432     }
4433
4434     if (md!=null) {
4435       /* Method */
4436       for(int i=0; i<objectparams.numPrimitives(); i++) {
4437         TempDescriptor temp=objectparams.getPrimitive(i);
4438         if (printcomma)
4439           output.print(", ");
4440         printcomma=true;
4441         if (temp.getType().isClass()||temp.getType().isArray())
4442           output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
4443         else
4444           output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
4445       }
4446       output.println(") {");
4447     } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4448       /* Imprecise Task */
4449       output.println("void * parameterarray[]) {");
4450       /* Unpack variables */
4451       for(int i=0; i<objectparams.numPrimitives(); i++) {
4452         TempDescriptor temp=objectparams.getPrimitive(i);
4453         output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
4454       }
4455       for(int i=0; i<fm.numTags(); i++) {
4456         TempDescriptor temp=fm.getTag(i);
4457         int offset=i+objectparams.numPrimitives();
4458         output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
4459       }
4460
4461       if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
4462         maxtaskparams=objectparams.numPrimitives()+fm.numTags();
4463     } else output.println(") {");
4464   }
4465
4466   public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
4467     output.println("/* FlatFlagActionNode */");
4468
4469
4470     /* Process tag changes */
4471     Relation tagsettable=new Relation();
4472     Relation tagcleartable=new Relation();
4473
4474     Iterator tagsit=ffan.getTempTagPairs();
4475     while (tagsit.hasNext()) {
4476       TempTagPair ttp=(TempTagPair) tagsit.next();
4477       TempDescriptor objtmp=ttp.getTemp();
4478       TagDescriptor tag=ttp.getTag();
4479       TempDescriptor tagtmp=ttp.getTagTemp();
4480       boolean tagstatus=ffan.getTagChange(ttp);
4481       if (tagstatus) {
4482         tagsettable.put(objtmp, tagtmp);
4483       } else {
4484         tagcleartable.put(objtmp, tagtmp);
4485       }
4486     }
4487
4488
4489     Hashtable flagandtable=new Hashtable();
4490     Hashtable flagortable=new Hashtable();
4491
4492     /* Process flag changes */
4493     Iterator flagsit=ffan.getTempFlagPairs();
4494     while(flagsit.hasNext()) {
4495       TempFlagPair tfp=(TempFlagPair)flagsit.next();
4496       TempDescriptor temp=tfp.getTemp();
4497       Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
4498       FlagDescriptor flag=tfp.getFlag();
4499       if (flag==null) {
4500         //Newly allocate objects that don't set any flags case
4501         if (flagortable.containsKey(temp)) {
4502           throw new Error();
4503         }
4504         int mask=0;
4505         flagortable.put(temp,new Integer(mask));
4506       } else {
4507         int flagid=1<<((Integer)flagtable.get(flag)).intValue();
4508         boolean flagstatus=ffan.getFlagChange(tfp);
4509         if (flagstatus) {
4510           int mask=0;
4511           if (flagortable.containsKey(temp)) {
4512             mask=((Integer)flagortable.get(temp)).intValue();
4513           }
4514           mask|=flagid;
4515           flagortable.put(temp,new Integer(mask));
4516         } else {
4517           int mask=0xFFFFFFFF;
4518           if (flagandtable.containsKey(temp)) {
4519             mask=((Integer)flagandtable.get(temp)).intValue();
4520           }
4521           mask&=(0xFFFFFFFF^flagid);
4522           flagandtable.put(temp,new Integer(mask));
4523         }
4524       }
4525     }
4526
4527
4528     HashSet flagtagset=new HashSet();
4529     flagtagset.addAll(flagortable.keySet());
4530     flagtagset.addAll(flagandtable.keySet());
4531     flagtagset.addAll(tagsettable.keySet());
4532     flagtagset.addAll(tagcleartable.keySet());
4533
4534     Iterator ftit=flagtagset.iterator();
4535     while(ftit.hasNext()) {
4536       TempDescriptor temp=(TempDescriptor)ftit.next();
4537
4538
4539       Set tagtmps=tagcleartable.get(temp);
4540       if (tagtmps!=null) {
4541         Iterator tagit=tagtmps.iterator();
4542         while(tagit.hasNext()) {
4543           TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4544           if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4545             output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4546           else
4547             output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4548         }
4549       }
4550
4551       tagtmps=tagsettable.get(temp);
4552       if (tagtmps!=null) {
4553         Iterator tagit=tagtmps.iterator();
4554         while(tagit.hasNext()) {
4555           TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4556           if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4557             output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4558           else
4559             output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
4560         }
4561       }
4562
4563       int ormask=0;
4564       int andmask=0xFFFFFFF;
4565
4566       if (flagortable.containsKey(temp))
4567         ormask=((Integer)flagortable.get(temp)).intValue();
4568       if (flagandtable.containsKey(temp))
4569         andmask=((Integer)flagandtable.get(temp)).intValue();
4570       generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
4571       generateObjectDistribute(ffan, fm, lb, temp, output);
4572     }
4573   }
4574
4575   protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
4576                                    PrintWriter output, int ormask, int andmask) {
4577     if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
4578       output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4579     } else {
4580       output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4581     }
4582   }
4583
4584   protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
4585     output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
4586   }
4587
4588   void generateOptionalHeader(PrintWriter headers) {
4589
4590     //GENERATE HEADERS
4591     headers.println("#include \"task.h\"\n\n");
4592     headers.println("#ifndef _OPTIONAL_STRUCT_");
4593     headers.println("#define _OPTIONAL_STRUCT_");
4594
4595     //STRUCT PREDICATEMEMBER
4596     headers.println("struct predicatemember{");
4597     headers.println("int type;");
4598     headers.println("int numdnfterms;");
4599     headers.println("int * flags;");
4600     headers.println("int numtags;");
4601     headers.println("int * tags;\n};\n\n");
4602
4603     //STRUCT OPTIONALTASKDESCRIPTOR
4604     headers.println("struct optionaltaskdescriptor{");
4605     headers.println("struct taskdescriptor * task;");
4606     headers.println("int index;");
4607     headers.println("int numenterflags;");
4608     headers.println("int * enterflags;");
4609     headers.println("int numpredicatemembers;");
4610     headers.println("struct predicatemember ** predicatememberarray;");
4611     headers.println("};\n\n");
4612
4613     //STRUCT TASKFAILURE
4614     headers.println("struct taskfailure {");
4615     headers.println("struct taskdescriptor * task;");
4616     headers.println("int index;");
4617     headers.println("int numoptionaltaskdescriptors;");
4618     headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4619
4620     //STRUCT FSANALYSISWRAPPER
4621     headers.println("struct fsanalysiswrapper{");
4622     headers.println("int  flags;");
4623     headers.println("int numtags;");
4624     headers.println("int * tags;");
4625     headers.println("int numtaskfailures;");
4626     headers.println("struct taskfailure ** taskfailurearray;");
4627     headers.println("int numoptionaltaskdescriptors;");
4628     headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4629
4630     //STRUCT CLASSANALYSISWRAPPER
4631     headers.println("struct classanalysiswrapper{");
4632     headers.println("int type;");
4633     headers.println("int numotd;");
4634     headers.println("struct optionaltaskdescriptor ** otdarray;");
4635     headers.println("int numfsanalysiswrappers;");
4636     headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
4637
4638     headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
4639
4640     Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
4641     while(taskit.hasNext()) {
4642       TaskDescriptor td=(TaskDescriptor)taskit.next();
4643       headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
4644     }
4645
4646   }
4647
4648   //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
4649   int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
4650     int predicateindex = 0;
4651     //iterate through the classes concerned by the predicate
4652     Set c_vard = predicate.vardescriptors;
4653     Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
4654     int current_slot=0;
4655
4656     for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
4657       VarDescriptor vard = (VarDescriptor)vard_it.next();
4658       TypeDescriptor typed = vard.getType();
4659
4660       //generate for flags
4661       HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
4662       output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4663       int numberterms=0;
4664       if (fen_hashset!=null) {
4665         for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
4666           FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
4667           if (fen!=null) {
4668             DNFFlag dflag=fen.getDNF();
4669             numberterms+=dflag.size();
4670
4671             Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
4672
4673             for(int j=0; j<dflag.size(); j++) {
4674               if (j!=0)
4675                 output.println(",");
4676               Vector term=dflag.get(j);
4677               int andmask=0;
4678               int checkmask=0;
4679               for(int k=0; k<term.size(); k++) {
4680                 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
4681                 FlagDescriptor fd=dfa.getFlag();
4682                 boolean negated=dfa.getNegated();
4683                 int flagid=1<<((Integer)flags.get(fd)).intValue();
4684                 andmask|=flagid;
4685                 if (!negated)
4686                   checkmask|=flagid;
4687               }
4688               output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
4689             }
4690           }
4691         }
4692       }
4693       output.println("};\n");
4694
4695       //generate for tags
4696       TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
4697       output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4698       int numtags = 0;
4699       if (tagel!=null) {
4700         for(int j=0; j<tagel.numTags(); j++) {
4701           if (j!=0)
4702             output.println(",");
4703           TempDescriptor tmp=tagel.getTemp(j);
4704           if (!slotnumber.containsKey(tmp)) {
4705             Integer slotint=new Integer(current_slot++);
4706             slotnumber.put(tmp,slotint);
4707           }
4708           int slot=slotnumber.get(tmp).intValue();
4709           output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
4710         }
4711         numtags = tagel.numTags();
4712       }
4713       output.println("};");
4714
4715       //store the result into a predicatemember struct
4716       output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4717       output.println("/*type*/"+typed.getClassDesc().getId()+",");
4718       output.println("/* number of dnf terms */"+numberterms+",");
4719       output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4720       output.println("/* number of tag */"+numtags+",");
4721       output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4722       output.println("};\n");
4723       predicateindex++;
4724     }
4725
4726
4727     //generate an array that stores the entire predicate
4728     output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4729     for( int j = 0; j<predicateindex; j++) {
4730       if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4731       else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4732     }
4733     output.println("};\n");
4734     return predicateindex;
4735   }
4736
4737
4738   void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
4739     generateOptionalHeader(headers);
4740     //GENERATE STRUCTS
4741     output.println("#include \"optionalstruct.h\"\n\n");
4742     output.println("#include \"stdlib.h\"\n");
4743
4744     HashSet processedcd = new HashSet();
4745     int maxotd=0;
4746     Enumeration e = safeexecution.keys();
4747     while (e.hasMoreElements()) {
4748       int numotd=0;
4749       //get the class
4750       ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
4751       Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp);       //will be used several times
4752
4753       //Generate the struct of optionals
4754       Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4755       numotd = c_otd.size();
4756       if(maxotd<numotd) maxotd = numotd;
4757       if( !c_otd.isEmpty() ) {
4758         for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4759           OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4760
4761           //generate the int arrays for the predicate
4762           Predicate predicate = otd.predicate;
4763           int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
4764           TreeSet<Integer> fsset=new TreeSet<Integer>();
4765           //iterate through possible FSes corresponding to
4766           //the state when entering
4767
4768           for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
4769             FlagState fs = (FlagState)fses.next();
4770             int flagid=0;
4771             for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4772               FlagDescriptor flagd = (FlagDescriptor)flags.next();
4773               int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4774               flagid|=id;
4775             }
4776             fsset.add(new Integer(flagid));
4777             //tag information not needed because tag
4778             //changes are not tolerated.
4779           }
4780
4781           output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4782           boolean needcomma=false;
4783           for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
4784             if(needcomma)
4785               output.print(", ");
4786             output.println(it.next());
4787           }
4788
4789           output.println("};\n");
4790
4791
4792           //generate optionaltaskdescriptor that actually
4793           //includes exit fses, predicate and the task
4794           //concerned
4795           output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4796           output.println("&task_"+otd.td.getSafeSymbol()+",");
4797           output.println("/*index*/"+otd.getIndex()+",");
4798           output.println("/*number of enter flags*/"+fsset.size()+",");
4799           output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4800           output.println("/*number of members */"+predicateindex+",");
4801           output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4802           output.println("};\n");
4803         }
4804       } else
4805         continue;
4806       // if there are no optionals, there is no need to build the rest of the struct
4807
4808       output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
4809       c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4810       if( !c_otd.isEmpty() ) {
4811         boolean needcomma=false;
4812         for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4813           OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4814           if(needcomma)
4815             output.println(",");
4816           needcomma=true;
4817           output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4818         }
4819       }
4820       output.println("};\n");
4821
4822       //get all the possible flagstates reachable by an object
4823       Hashtable hashtbtemp = safeexecution.get(cdtemp);
4824       int fscounter = 0;
4825       TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
4826       fsts.addAll(hashtbtemp.keySet());
4827       for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
4828         FlagState fs = (FlagState)fsit.next();
4829         fscounter++;
4830
4831         //get the set of OptionalTaskDescriptors corresponding
4832         HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
4833         //iterate through the OptionalTaskDescriptors and
4834         //store the pointers to the optionals struct (see on
4835         //top) into an array
4836
4837         output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
4838         for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
4839           OptionalTaskDescriptor mm = mos.next();
4840           if(!mos.hasNext())
4841             output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
4842           else
4843             output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4844         }
4845
4846         output.println("};\n");
4847
4848         //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
4849
4850         int flagid=0;
4851         for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4852           FlagDescriptor flagd = (FlagDescriptor)flags.next();
4853           int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4854           flagid|=id;
4855         }
4856
4857         //process tag information
4858
4859         int tagcounter = 0;
4860         boolean first = true;
4861         Enumeration tag_enum = fs.getTags();
4862         output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4863         while(tag_enum.hasMoreElements()) {
4864           tagcounter++;
4865           TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
4866           if(first==true)
4867             first = false;
4868           else
4869             output.println(", ");
4870           output.println("/*tagid*/"+state.getTagId(tagd));
4871         }
4872         output.println("};");
4873
4874         Set<TaskIndex> tiset=sa.getTaskIndex(fs);
4875         for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4876           TaskIndex ti=itti.next();
4877           if (ti.isRuntime())
4878             continue;
4879
4880           Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
4881
4882           output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
4883           boolean needcomma=false;
4884           for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
4885             OptionalTaskDescriptor otd=otdit.next();
4886             if(needcomma)
4887               output.print(", ");
4888             needcomma=true;
4889             output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4890           }
4891           output.println("};");
4892
4893           output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
4894           output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
4895           output.print(ti.getIndex()+", ");
4896           output.print(otdset.size()+", ");
4897           output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
4898           output.println("};");
4899         }
4900
4901         tiset=sa.getTaskIndex(fs);
4902         boolean needcomma=false;
4903         int runtimeti=0;
4904         output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4905         for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4906           TaskIndex ti=itti.next();
4907           if (ti.isRuntime()) {
4908             runtimeti++;
4909             continue;
4910           }
4911           if (needcomma)
4912             output.print(", ");
4913           needcomma=true;
4914           output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
4915         }
4916         output.println("};\n");
4917
4918         //Store the result in fsanalysiswrapper
4919
4920         output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
4921         output.println("/*flag*/"+flagid+",");
4922         output.println("/* number of tags*/"+tagcounter+",");
4923         output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4924         output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
4925         output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4926         output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
4927         output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
4928         output.println("};\n");
4929
4930       }
4931
4932       //Build the array of fsanalysiswrappers
4933       output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
4934       boolean needcomma=false;
4935       for(int i = 0; i<fscounter; i++) {
4936         if (needcomma) output.print(",");
4937         output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
4938         needcomma=true;
4939       }
4940       output.println("};");
4941
4942       //Build the classanalysiswrapper referring to the previous array
4943       output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
4944       output.println("/*type*/"+cdtemp.getId()+",");
4945       output.println("/*numotd*/"+numotd+",");
4946       output.println("otdarray"+cdtemp.getSafeSymbol()+",");
4947       output.println("/* number of fsanalysiswrappers */"+fscounter+",");
4948       output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
4949       processedcd.add(cdtemp);
4950     }
4951
4952     //build an array containing every classes for which code has been build
4953     output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
4954     for(int i=0; i<state.numClasses(); i++) {
4955       ClassDescriptor cn=cdarray[i];
4956       if (i>0)
4957         output.print(", ");
4958       if ((cn != null) && (processedcd.contains(cn)))
4959         output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
4960       else
4961         output.print("NULL");
4962     }
4963     output.println("};");
4964
4965     output.println("#define MAXOTD "+maxotd);
4966     headers.println("#endif");
4967   }
4968
4969   public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
4970     Relation r=new Relation();
4971     for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
4972       OptionalTaskDescriptor otd=otdit.next();
4973       TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
4974       r.put(ti, otd);
4975     }
4976
4977     LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
4978     for(Iterator it=r.keySet().iterator(); it.hasNext();) {
4979       Set s=r.get(it.next());
4980       for(Iterator it2=s.iterator(); it2.hasNext();) {
4981         OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
4982         l.add(otd);
4983       }
4984     }
4985
4986     return l;
4987   }
4988
4989   protected void outputTransCode(PrintWriter output) {
4990   }
4991 }
4992
4993
4994
4995
4996
4997