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