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