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