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