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