changes in SESE lock scheme using clique covering.
[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\",deadMachine[nRecovery]);");
422       outmethod.println("  printf(\"Recovery Time = %.2f\\n\",elapsedTime[nRecovery]);");
423       outmethod.println(" }\n");
424       outmethod.println("fflush(stdout);");
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("     seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3353     output.println("     psem_init( &(seseToIssue->common.stallSem) );");
3354
3355     output.println("     seseToIssue->common.forwardList = createQueue();");
3356     //eom
3357     output.println("     seseToIssue->common.connectedList = createQueue();");
3358     //
3359     output.println("     seseToIssue->common.unresolvedDependencies = 0;");
3360     output.println("     pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3361     output.println("     seseToIssue->common.doneExecuting = FALSE;");    
3362     output.println("     pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3363     output.println("     seseToIssue->common.numRunningChildren = 0;");
3364     output.println("     seseToIssue->common.parent = parentCommon;");
3365
3366     // all READY in-vars should be copied now and be done with it
3367     Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3368     while( tempItr.hasNext() ) {
3369       TempDescriptor temp = tempItr.next();
3370
3371       // when we are issuing the main SESE or an SESE with placeholder
3372       // caller SESE as parent, generate temp child child's eclosing method,
3373       // otherwise use the parent's enclosing method as the context
3374       boolean useParentContext = false;
3375
3376       if( fsen != mlpa.getMainSESE() ) {
3377         assert fsen.getParent() != null;
3378         if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3379           useParentContext = true;
3380         }
3381       }
3382
3383       if( useParentContext ) {
3384         output.println("     seseToIssue->"+temp+" = "+
3385                        generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");   
3386       } else {
3387         output.println("     seseToIssue->"+temp+" = "+
3388                        generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3389       }
3390     }
3391     
3392     // count up memory conflict dependencies,
3393     // eom
3394     ConflictGraph graph=null;
3395     FlatSESEEnterNode parent=fsen.getParent();
3396     if(parent!=null){
3397         if(parent.isCallerSESEplaceholder){
3398                 graph=mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
3399         }else{
3400                 graph=mlpa.getConflictGraphResults().get(parent);
3401         }
3402     }
3403                 if (graph != null) {
3404                         
3405                         HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
3406                         
3407                         output.println();
3408                         output.println("     /*add waiting queue element*/");
3409                         output.println("     struct Queue*  newWaitingItemQueue=createQueue();");
3410                         
3411                         Set<WaitingElement> waitingQueueSet=graph.getWaitingElementSetBySESEID(fsen
3412                                         .getIdentifier(),seseLockSet);
3413                         if (waitingQueueSet.size() > 0) {
3414                                 output.println("     {");
3415                                 output.println("     waitingQueueItemID++;");
3416                                 output.println("     ConflictNode* node;");
3417                                 output.println("     WaitingElement* newElement=NULL;");
3418                                 output.println("     struct Queue* list=NULL;");
3419                                 output.println("     struct QueueItem* newQItem=NULL;");
3420                                 output
3421                                                 .println("     pthread_mutex_lock( &(parentCommon->lock) );");
3422                                 for (Iterator iterator = waitingQueueSet.iterator(); iterator
3423                                                 .hasNext();) {
3424                                         WaitingElement waitingElement = (WaitingElement) iterator.next();
3425                                         output.println("     list=createQueue();");
3426                                         for (Iterator iterator2 = waitingElement.getAllocList().iterator(); iterator2
3427                                                         .hasNext();) {
3428                                                 Integer allocID = (Integer) iterator2
3429                                                                 .next();
3430                                                 output.println("     node=mlpCreateConflictNode( "+allocID+" );");
3431                                                 output.println("     addNewItem(list,node);");
3432                                         }
3433                                         output.println("     seseToIssue->common.waitingQueueItemID=waitingQueueItemID;");
3434                                         output.println("     newElement=mlpCreateWaitingElement( "+waitingElement.getStatus()+", seseToIssue, list, waitingQueueItemID );");
3435                                         
3436                                         output
3437                                                         .println("     newQItem=addWaitingQueueElement(parentCommon->allocSiteArray,numRelatedWaitingQueue,"
3438                                                                         + waitingElement.getWaitingID() + ",newElement);");
3439                                         output
3440                                                         .println("     addNewItem(newWaitingItemQueue,newQItem);");
3441                                         output
3442                                                         .println("     ++(seseToIssue->common.unresolvedDependencies);");
3443                                         output
3444                                         .println();
3445                                 }
3446                                 output
3447                                                 .println("     pthread_mutex_unlock( &(parentCommon->lock) );");
3448                                 output.println("     }");
3449                         }
3450                         
3451                         output.println("     /*decide whether it is runnable or not in regarding to memory conflicts*/");
3452                         output.println("     {");
3453                         output.println("      pthread_mutex_lock( &(parentCommon->lock)  );");
3454                         output.println("      if( !isEmpty(newWaitingItemQueue) ){");
3455                         output.println("         int idx;");
3456                         output.println("         for(idx = 0 ; idx < numRelatedWaitingQueue ; idx++){");
3457                         output.println("            struct Queue *allocQueue=parentCommon->allocSiteArray[idx].waitingQueue;");
3458                         output.println("            if( !isEmpty(allocQueue) ){");
3459                         output.println("               struct QueueItem* nextQItem=getHead(allocQueue);");
3460                         output.println("               while( nextQItem != NULL ){");
3461                         output.println("                  if(contains(newWaitingItemQueue,nextQItem) && isRunnable(allocQueue,nextQItem)){");
3462                         output.println("                     --(seseToIssue->common.unresolvedDependencies);");
3463                         output.println("                  }");
3464                         output.println("                     nextQItem=getNextQueueItem(nextQItem);");
3465                         output.println("               }");
3466                         output.println("         }");
3467                         output.println("       }");
3468                         output.println("     pthread_mutex_unlock( &(parentCommon->lock)  );");
3469                         output.println("     }");
3470                         output.println("     }");
3471                         output.println();
3472                         
3473                 }
3474
3475     // before potentially adding this SESE to other forwarding lists,
3476     //  create it's lock and take it immediately
3477     output.println("     pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3478     output.println("     pthread_mutex_lock( &(seseToIssue->common.lock) );");
3479
3480     if( fsen != mlpa.getMainSESE() ) {
3481       // count up outstanding dependencies, static first, then dynamic
3482       Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3483       while( staticSrcsItr.hasNext() ) {
3484         SESEandAgePair srcPair = staticSrcsItr.next();
3485         output.println("     {");
3486         output.println("       SESEcommon* src = (SESEcommon*)"+srcPair+";");
3487         output.println("       pthread_mutex_lock( &(src->lock) );");
3488         output.println("       if( !isEmpty( src->forwardList ) &&");
3489         output.println("           seseToIssue == peekItem( src->forwardList ) ) {");
3490         output.println("         printf( \"This shouldnt already be here\\n\");");
3491         output.println("         exit( -1 );");
3492         output.println("       }");
3493         output.println("       if( !src->doneExecuting ) {");
3494         output.println("         addNewItem( src->forwardList, seseToIssue );");
3495         output.println("         ++(seseToIssue->common.unresolvedDependencies);");
3496         output.println("       }");
3497         output.println("       pthread_mutex_unlock( &(src->lock) );");
3498         output.println("     }");
3499
3500         // whether or not it is an outstanding dependency, make sure
3501         // to pass the static name to the child's record
3502         output.println("     seseToIssue->"+srcPair+" = "+srcPair+";");
3503       }
3504
3505       // dynamic sources might already be accounted for in the static list,
3506       // so only add them to forwarding lists if they're not already there
3507       Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3508       while( dynVarsItr.hasNext() ) {
3509         TempDescriptor dynInVar = dynVarsItr.next();
3510         output.println("     {");
3511         output.println("       SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3512
3513         // the dynamic source is NULL if it comes from your own space--you can't pass
3514         // the address off to the new child, because you're not done executing and
3515         // might change the variable, so copy it right now
3516         output.println("       if( src != NULL ) {");
3517         output.println("         pthread_mutex_lock( &(src->lock) );");
3518         output.println("         if( isEmpty( src->forwardList ) ||");
3519         output.println("             seseToIssue != peekItem( src->forwardList ) ) {");
3520         output.println("           if( !src->doneExecuting ) {");
3521         output.println("             addNewItem( src->forwardList, seseToIssue );");
3522         output.println("             ++(seseToIssue->common.unresolvedDependencies);");
3523         output.println("           }");
3524         output.println("         }");
3525         output.println("         pthread_mutex_unlock( &(src->lock) );");       
3526         output.println("         seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3527         output.println("       } else {");
3528
3529         boolean useParentContext = false;
3530         if( fsen != mlpa.getMainSESE() ) {
3531           assert fsen.getParent() != null;
3532           if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3533             useParentContext = true;
3534           }
3535         }       
3536         if( useParentContext ) {
3537           output.println("         seseToIssue->"+dynInVar+" = "+
3538                          generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3539         } else {
3540           output.println("         seseToIssue->"+dynInVar+" = "+
3541                          generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3542         }
3543         
3544         output.println("       }");
3545         output.println("     }");
3546         
3547         // even if the value is already copied, make sure your NULL source
3548         // gets passed so child knows it already has the dynamic value
3549         output.println("     seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3550       }
3551       
3552       // maintain pointers for for finding dynamic SESE 
3553       // instances from static names      
3554       SESEandAgePair p = new SESEandAgePair( fsen, 0 );
3555       if(  fsen.getParent() != null && 
3556            //!fsen.getParent().getIsCallerSESEplaceholder() &&
3557            fsen.getParent().getNeededStaticNames().contains( p ) 
3558         ) {       
3559
3560         for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3561           SESEandAgePair p1 = new SESEandAgePair( fsen, i   );
3562           SESEandAgePair p2 = new SESEandAgePair( fsen, i-1 );
3563           output.println("     "+p1+" = "+p2+";");
3564         }      
3565         output.println("     "+p+" = seseToIssue;");
3566       }
3567  
3568     }
3569
3570     // if there were no outstanding dependencies, issue here
3571     output.println("     if( seseToIssue->common.unresolvedDependencies == 0 ) {");
3572     output.println("       workScheduleSubmit( (void*)seseToIssue );");
3573     output.println("     }");
3574
3575     // release this SESE for siblings to update its dependencies or,
3576     // eventually, for it to mark itself finished
3577     output.println("     pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3578     output.println("   }");
3579     
3580   }
3581
3582   public void generateFlatSESEExitNode( FlatMethod fm,  
3583                                         LocalityBinding lb, 
3584                                         FlatSESEExitNode fsexn, 
3585                                         PrintWriter output
3586                                       ) {
3587
3588     // if MLP flag is off, okay that SESE nodes are in IR graph, 
3589     // just skip over them and code generates exactly the same 
3590     if( !state.MLP ) {
3591       return;
3592     }
3593
3594     // get the enter node for this exit that has meta data embedded
3595     FlatSESEEnterNode fsen = fsexn.getFlatEnter();
3596
3597     // there may be an SESE in an unreachable method, skip over
3598     if( !mlpa.getAllSESEs().contains( fsen ) ) {
3599       return;
3600     }
3601
3602     // also, if we have encountered a placeholder, just jump it
3603     if( fsen.getIsCallerSESEplaceholder() ) {
3604       return;
3605     }
3606
3607     output.println("   /* SESE exiting */");
3608
3609     String com = paramsprefix+"->common";
3610
3611     // this SESE cannot be done until all of its children are done
3612     // so grab your own lock with the condition variable for watching
3613     // that the number of your running children is greater than zero    
3614     output.println("   pthread_mutex_lock( &("+com+".lock) );");
3615     output.println("   while( "+com+".numRunningChildren > 0 ) {");
3616     output.println("     pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
3617     output.println("   }");
3618
3619     // copy out-set from local temps into the sese record
3620     Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
3621     while( itr.hasNext() ) {
3622       TempDescriptor temp = itr.next();
3623
3624       // only have to do this for primitives
3625       if( !temp.getType().isPrimitive() ) {
3626         continue;
3627       }
3628
3629       // have to determine the context enclosing this sese
3630       boolean useParentContext = false;
3631
3632       if( fsen != mlpa.getMainSESE() ) {
3633         assert fsen.getParent() != null;
3634         if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3635           useParentContext = true;
3636         }
3637       }
3638
3639       String from;
3640       if( useParentContext ) {
3641         from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
3642       } else {
3643         from = generateTemp( fsen.getfmEnclosing(),         temp, null );
3644       }
3645
3646       output.println("   "+paramsprefix+
3647                      "->"+temp.getSafeSymbol()+
3648                      " = "+from+";");
3649     }    
3650     
3651     // mark yourself done, your SESE data is now read-only
3652     output.println("   "+com+".doneExecuting = TRUE;");
3653     output.println("   pthread_cond_signal( &("+com+".doneCond) );");
3654     output.println("   pthread_mutex_unlock( &("+com+".lock) );");
3655
3656     // decrement dependency count for all SESE's on your forwarding list
3657     output.println("   while( !isEmpty( "+com+".forwardList ) ) {");
3658     output.println("     SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
3659     output.println("     pthread_mutex_lock( &(consumer->lock) );");
3660     output.println("     --(consumer->unresolvedDependencies);");
3661     output.println("     if( consumer->unresolvedDependencies == 0 ) {");
3662     output.println("       workScheduleSubmit( (void*)consumer );");
3663     output.println("     }");
3664     output.println("     pthread_mutex_unlock( &(consumer->lock) );");
3665     output.println("   }");
3666     
3667     // eom
3668     // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
3669     if( fsen != mlpa.getMainSESE() ) {
3670         
3671         output.println();    
3672         output.println("   /* check memory dependency*/");
3673         output.println("  {");
3674         output.println("   pthread_mutex_lock( &(___params___->common.parent->lock) );");
3675         output.println("   int idx;");
3676         output.println("   int giveCount=0;");
3677         output.println("   struct Queue* launchQueue=createQueue();");
3678         output.println("   struct QueueItem* nextQueueItem;");
3679         output.println("   for(idx = 0 ; idx < ___params___->common.parent->numRelatedWaitingQueue ; idx++){");
3680         output.println("     if(!isEmpty(___params___->common.parent->allocSiteArray[idx].waitingQueue)){");
3681         output.println("        struct QueueItem* qItem=getHead(___params___->common.parent->allocSiteArray[idx].waitingQueue);");
3682         output.println("        while(qItem!=NULL){");
3683         output.println("           WaitingElement* item=qItem->objectptr;");
3684         output.println("           SESEcommon* seseItem=(SESEcommon*)item->seseRec;");
3685         output.println("           if(seseItem->classID==___params___->common.classID && item->id==___params___->common.waitingQueueItemID){");
3686         output.println("              removeItem(___params___->common.parent->allocSiteArray[idx].waitingQueue,qItem);");
3687         output.println("           }");
3688         output.println("           qItem=getNextQueueItem(qItem);");
3689         output.println("        }");
3690         output.println("        if( !isEmpty(___params___->common.parent->allocSiteArray[idx].waitingQueue) ){");
3691         
3692         output.println("           struct QueueItem* nextQItem=getHead(___params___->common.parent->allocSiteArray[idx].waitingQueue);");
3693         output.println("           while(nextQItem!=NULL){");
3694         output.println("              WaitingElement* nextItem=nextQItem->objectptr;");
3695         output.println("              SESEcommon* seseNextItem=(SESEcommon*)nextItem->seseRec;");
3696 //      output.println("              int isResolved=resolveWaitingQueue(___params___->common.parent->allocSiteArray[idx].waitingQueue,nextQItem);");
3697         output.println("              int isResolved=isRunnable(___params___->common.parent->allocSiteArray[idx].waitingQueue,nextQItem);");
3698         output.println("              if(seseNextItem->classID==___params___->common.parent->classID){"); // stall site
3699         output.println("                 if(isResolved){");
3700         output.println("                    struct QueueItem* stallItem=findItem(___params___->common.parent->allocSiteArray[idx].waitingQueue,nextItem);");
3701         output.println("                    removeItem(___params___->common.parent->allocSiteArray[idx].waitingQueue,stallItem);");
3702         output.println("                    giveCount++;");
3703         output.println("                 }");
3704         output.println("                 if(!isEmpty(___params___->common.parent->allocSiteArray[idx].waitingQueue)){");
3705 //      output.println("                    nextQItem=getHead(___params___->common.parent->allocSiteArray[idx].waitingQueue);");
3706         output.println("                    nextQItem=getNextQueueItem(nextQItem);");
3707         output.println("                 }else{");
3708         output.println("                    nextQItem=NULL;");
3709         output.println("                 }");
3710         output.println("              }else{");
3711         output.println("                 if(isResolved){");
3712         output.println("                    pthread_mutex_lock( &(seseNextItem->lock) );");
3713         output.println("                    if(seseNextItem->unresolvedDependencies > 0){");
3714         output.println("                       --(seseNextItem->unresolvedDependencies);");
3715         output.println("                       if( seseNextItem->unresolvedDependencies == 0){");
3716         //output.println("                          workScheduleSubmit( (void*)nextItem);");
3717         output.println("                            addNewItem(launchQueue,(void*)seseNextItem);");
3718         output.println("                       }");
3719         output.println("                    }");
3720         output.println("                    pthread_mutex_unlock( &(seseNextItem->lock) );");
3721         output.println("                 }");
3722         output.println("                 nextQItem=getNextQueueItem(nextQItem);");
3723         output.println("               }");
3724         output.println("           } "); // end of while(nextQItem!=NULL)
3725         output.println("        }");
3726         output.println("     }");
3727 //      output.println("  }");
3728         output.println("  }");
3729         output.println("  pthread_mutex_unlock( &(___params___->common.parent->lock)  );");
3730         output.println("  if(!isEmpty(launchQueue)){");
3731         output.println("     struct QueueItem* qItem=getHead(launchQueue);");
3732         output.println("     while(qItem!=NULL){");
3733         output.println("        workScheduleSubmit(qItem->objectptr);");
3734         output.println("        qItem=getNextQueueItem(qItem);");
3735         output.println("     }");
3736         output.println("  }");
3737         output.println("  if(giveCount>0){");
3738         output.println("    psem_give(&(___params___->common.parent->memoryStallSiteSem));");
3739         output.println("  }");
3740         output.println("  }");
3741         
3742     }
3743     
3744     // if parent is stalling on you, let them know you're done
3745     if( fsexn.getFlatEnter() != mlpa.getMainSESE() ) {
3746       output.println("   psem_give( &("+paramsprefix+"->common.stallSem) );");
3747     }
3748
3749     // last of all, decrement your parent's number of running children    
3750     output.println("   if( "+paramsprefix+"->common.parent != NULL ) {");
3751     output.println("     pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
3752     output.println("     --("+paramsprefix+"->common.parent->numRunningChildren);");
3753     output.println("     pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
3754     output.println("     pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
3755     output.println("   }");    
3756
3757     // this is a thread-only variable that can be handled when critical sese-to-sese
3758     // data has been taken care of--set sese pointer to remember self over method
3759     // calls to a non-zero, invalid address
3760     output.println("   seseCaller = (SESEcommon*) 0x1;");    
3761     
3762   }
3763
3764   public void generateFlatWriteDynamicVarNode( FlatMethod fm,  
3765                                                LocalityBinding lb, 
3766                                                FlatWriteDynamicVarNode fwdvn,
3767                                                PrintWriter output
3768                                              ) {
3769     if( !state.MLP ) {
3770       // should node should not be in an IR graph if the
3771       // MLP flag is not set
3772       throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
3773     }
3774         
3775     Hashtable<TempDescriptor, VariableSourceToken> writeDynamic = 
3776       fwdvn.getVar2src();
3777
3778     assert writeDynamic != null;
3779
3780     Iterator wdItr = writeDynamic.entrySet().iterator();
3781     while( wdItr.hasNext() ) {
3782       Map.Entry           me     = (Map.Entry)           wdItr.next();
3783       TempDescriptor      refVar = (TempDescriptor)      me.getKey();
3784       VariableSourceToken vst    = (VariableSourceToken) me.getValue();
3785       
3786       FlatSESEEnterNode current = fwdvn.getEnclosingSESE();
3787
3788       // only do this if the variable in question should be tracked,
3789       // meaning that it was explicitly added to the dynamic var set
3790       if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
3791         continue;
3792       }
3793
3794       SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );      
3795
3796       output.println("   {");
3797
3798       if( current.equals( vst.getSESE() ) ) {
3799         // if the src comes from this SESE, it's a method local variable,
3800         // mark src pointer NULL to signify that the var is up-to-date
3801         output.println("     "+vst.getAddrVar()+"_srcSESE = NULL;");
3802
3803       } else {
3804         // otherwise we track where it will come from
3805         output.println("     "+vst.getAddrVar()+"_srcSESE = "+instance+";");    
3806         output.println("     "+vst.getAddrVar()+"_srcOffset = (int) &((("+
3807                        vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
3808       }
3809
3810       output.println("   }");
3811     }   
3812   }
3813
3814   
3815   private void generateFlatCheckNode(FlatMethod fm,  LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
3816     if (state.CONSCHECK) {
3817       String specname=fcn.getSpec();
3818       String varname="repairstate___";
3819       output.println("{");
3820       output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
3821
3822       TempDescriptor[] temps=fcn.getTemps();
3823       String[] vars=fcn.getVars();
3824       for(int i=0; i<temps.length; i++) {
3825         output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
3826       }
3827
3828       output.println("if (doanalysis"+specname+"("+varname+")) {");
3829       output.println("free"+specname+"_state("+varname+");");
3830       output.println("} else {");
3831       output.println("/* Bad invariant */");
3832       output.println("free"+specname+"_state("+varname+");");
3833       output.println("abort_task();");
3834       output.println("}");
3835       output.println("}");
3836     }
3837   }
3838
3839   private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
3840
3841     if( state.MLP && !nonSESEpass ) {
3842       output.println("     seseCaller = (SESEcommon*)"+paramsprefix+";");
3843     }
3844
3845     MethodDescriptor md=fc.getMethod();
3846     ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
3847     ClassDescriptor cn=md.getClassDesc();
3848     output.println("{");
3849     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3850       if (lb!=null) {
3851         LocalityBinding fclb=locality.getBinding(lb, fc);
3852         output.print("       struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3853       } else
3854         output.print("       struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3855
3856       output.print(objectparams.numPointers());
3857       output.print(", "+localsprefixaddr);
3858       if (md.getThis()!=null) {
3859         output.print(", ");
3860         output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
3861       }
3862       if (fc.getThis()!=null&&md.getThis()==null) {
3863         System.out.println("WARNING!!!!!!!!!!!!");
3864         System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
3865       }
3866
3867
3868       for(int i=0; i<fc.numArgs(); i++) {
3869         Descriptor var=md.getParameter(i);
3870         TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3871         if (objectparams.isParamPtr(paramtemp)) {
3872           TempDescriptor targ=fc.getArg(i);
3873           output.print(", ");
3874           TypeDescriptor td=md.getParamType(i);
3875           if (td.isTag())
3876             output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()  +" *)"+generateTemp(fm, targ,lb));
3877           else
3878             output.print("(struct "+md.getParamType(i).getSafeSymbol()  +" *)"+generateTemp(fm, targ,lb));
3879         }
3880       }
3881       output.println("};");
3882     }
3883     output.print("       ");
3884
3885
3886     if (fc.getReturnTemp()!=null)
3887       output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
3888
3889     /* Do we need to do virtual dispatch? */
3890     if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
3891       //no
3892       if (lb!=null) {
3893         LocalityBinding fclb=locality.getBinding(lb, fc);
3894         output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3895       } else {
3896         output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3897       }
3898     } else {
3899       //yes
3900       output.print("((");
3901       if (md.getReturnType().isClass()||md.getReturnType().isArray())
3902         output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3903       else
3904         output.print(md.getReturnType().getSafeSymbol()+" ");
3905       output.print("(*)(");
3906
3907       boolean printcomma=false;
3908       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3909         if (lb!=null) {
3910           LocalityBinding fclb=locality.getBinding(lb, fc);
3911           output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3912         } else
3913           output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3914         printcomma=true;
3915       }
3916
3917       for(int i=0; i<objectparams.numPrimitives(); i++) {
3918         TempDescriptor temp=objectparams.getPrimitive(i);
3919         if (printcomma)
3920           output.print(", ");
3921         printcomma=true;
3922         if (temp.getType().isClass()||temp.getType().isArray())
3923           output.print("struct " + temp.getType().getSafeSymbol()+" * ");
3924         else
3925           output.print(temp.getType().getSafeSymbol());
3926       }
3927
3928
3929       if (lb!=null) {
3930         LocalityBinding fclb=locality.getBinding(lb, fc);
3931         output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
3932       } else
3933         output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
3934     }
3935
3936     output.print("(");
3937     boolean needcomma=false;
3938     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3939       output.print("&__parameterlist__");
3940       needcomma=true;
3941     }
3942
3943     if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
3944       if (fc.getThis()!=null) {
3945         TypeDescriptor ptd=md.getThis().getType();
3946         if (needcomma)
3947           output.print(",");
3948         if (ptd.isClass()&&!ptd.isArray())
3949           output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3950         output.print(generateTemp(fm,fc.getThis(),lb));
3951         needcomma=true;
3952       }
3953     }
3954
3955     for(int i=0; i<fc.numArgs(); i++) {
3956       Descriptor var=md.getParameter(i);
3957       TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3958       if (objectparams.isParamPrim(paramtemp)) {
3959         TempDescriptor targ=fc.getArg(i);
3960         if (needcomma)
3961           output.print(", ");
3962
3963         TypeDescriptor ptd=md.getParamType(i);
3964         if (ptd.isClass()&&!ptd.isArray())
3965           output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3966         output.print(generateTemp(fm, targ,lb));
3967         needcomma=true;
3968       }
3969     }
3970     output.println(");");
3971     output.println("   }");
3972   }
3973
3974   private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
3975     Set subclasses=typeutil.getSubClasses(thiscd);
3976     if (subclasses==null)
3977       return true;
3978     for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
3979       ClassDescriptor cd=(ClassDescriptor)classit.next();
3980       Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
3981       for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
3982         MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
3983         if (md.matches(matchmd))
3984           return false;
3985       }
3986     }
3987     return true;
3988   }
3989
3990   private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
3991     if (state.SINGLETM) {
3992       //single machine transactional memory case
3993       String field=ffn.getField().getSafeSymbol();
3994       String src=generateTemp(fm, ffn.getSrc(),lb);
3995       String dst=generateTemp(fm, ffn.getDst(),lb);
3996
3997       output.println(dst+"="+ src +"->"+field+ ";");
3998       if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
3999           locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
4000         if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
4001             (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
4002           output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
4003         } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
4004           if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
4005             output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4006           } else
4007             output.println("TRANSREADRD("+dst+", "+dst+");");
4008         }
4009       }
4010     } else if (state.DSM) {
4011       Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
4012       if (status==LocalityAnalysis.GLOBAL) {
4013         String field=ffn.getField().getSafeSymbol();
4014         String src=generateTemp(fm, ffn.getSrc(),lb);
4015         String dst=generateTemp(fm, ffn.getDst(),lb);
4016
4017         if (ffn.getField().getType().isPtr()) {
4018
4019           //TODO: Uncomment this when we have runtime support
4020           //if (ffn.getSrc()==ffn.getDst()) {
4021           //output.println("{");
4022           //output.println("void * temp="+src+";");
4023           //output.println("if (temp&0x1) {");
4024           //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
4025           //output.println(src+"->"+field+"="+temp+";");
4026           //output.println("}");
4027           //output.println(dst+"=temp;");
4028           //output.println("}");
4029           //} else {
4030           output.println(dst+"="+ src +"->"+field+ ";");
4031           //output.println("if ("+dst+"&0x1) {");
4032           //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4033       output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4034           //output.println(src+"->"+field+"="+src+"->"+field+";");
4035           //output.println("}");
4036           //}
4037         } else {
4038           output.println(dst+"="+ src+"->"+field+";");
4039         }
4040       } else if (status==LocalityAnalysis.LOCAL) {
4041         if (ffn.getField().getType().isPtr()&&
4042             ffn.getField().isGlobal()) {
4043           String field=ffn.getField().getSafeSymbol();
4044           String src=generateTemp(fm, ffn.getSrc(),lb);
4045           String dst=generateTemp(fm, ffn.getDst(),lb);
4046           output.println(dst+"="+ src +"->"+field+ ";");
4047           if (locality.getAtomic(lb).get(ffn).intValue()>0)
4048             //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4049             output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4050         } else
4051           output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4052       } else if (status==LocalityAnalysis.EITHER) {
4053         //Code is reading from a null pointer
4054         output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
4055         output.println("#ifndef RAW");
4056         output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4057         output.println("#endif");
4058         //This should throw a suitable null pointer error
4059         output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4060       } else
4061         throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4062     } else
4063       output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4064   }
4065
4066
4067   private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
4068     if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
4069       throw new Error("Can't set array length");
4070     if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4071       //Single Machine Transaction Case
4072       boolean srcptr=fsfn.getSrc().getType().isPtr();
4073       String src=generateTemp(fm,fsfn.getSrc(),lb);
4074       String dst=generateTemp(fm,fsfn.getDst(),lb);
4075       output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
4076       if (srcptr&&!fsfn.getSrc().getType().isNull()) {
4077         output.println("{");
4078         if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
4079             locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
4080           output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4081         } else {
4082           output.println("INTPTR srcoid=(INTPTR)"+src+";");
4083         }
4084       }
4085       if (wb.needBarrier(fsfn)&&
4086           locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
4087         if (state.EVENTMONITOR) {
4088           output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
4089         }
4090         output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
4091       }
4092       if (srcptr&!fsfn.getSrc().getType().isNull()) {
4093         output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4094         output.println("}");
4095       } else {
4096         output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4097       }
4098     } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4099       Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
4100       Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
4101       boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4102
4103       String src=generateTemp(fm,fsfn.getSrc(),lb);
4104       String dst=generateTemp(fm,fsfn.getDst(),lb);
4105       if (srcglobal) {
4106         output.println("{");
4107         output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4108       }
4109       if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
4110         String glbdst=dst;
4111         //mark it dirty
4112         if (wb.needBarrier(fsfn))
4113           output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
4114         if (srcglobal) {
4115           output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4116         } else
4117           output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4118       } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
4119         /** Check if we need to copy */
4120         output.println("if(!"+dst+"->"+localcopystr+") {");
4121         /* Link object into list */
4122         String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4123         output.println(revertptr+"=revertlist;");
4124         if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4125           output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4126         else
4127           output.println("COPY_OBJ("+dst+");");
4128         output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4129         output.println("revertlist=(struct ___Object___ *)"+dst+";");
4130         output.println("}");
4131         if (srcglobal)
4132           output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4133         else
4134           output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4135       } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
4136         //writing to a null...bad
4137         output.println("if ("+dst+") {");
4138         output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
4139         if (srcglobal)
4140           output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4141         else
4142           output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4143       }
4144       if (srcglobal) {
4145         output.println("}");
4146       }
4147     } else {
4148       if (state.FASTCHECK) {
4149         String dst=generateTemp(fm, fsfn.getDst(),lb);
4150         output.println("if(!"+dst+"->"+localcopystr+") {");
4151         /* Link object into list */
4152         if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4153           output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4154         else
4155           output.println("COPY_OBJ("+dst+");");
4156         output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4157         output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4158         output.println("}");
4159       }
4160       output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4161     }
4162   }
4163
4164   private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
4165     TypeDescriptor elementtype=fen.getSrc().getType().dereference();
4166     String type="";
4167
4168     if (elementtype.isArray()||elementtype.isClass())
4169       type="void *";
4170     else
4171       type=elementtype.getSafeSymbol()+" ";
4172
4173     if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
4174       output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
4175       output.println("failedboundschk();");
4176     }
4177     if (state.SINGLETM) {
4178       //Single machine transaction case
4179       String dst=generateTemp(fm, fen.getDst(),lb);
4180       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))) {
4181         output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4182       } else {
4183         output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
4184       }
4185
4186       if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
4187           locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
4188         if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
4189           output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
4190         } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
4191           if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
4192             output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4193           } else
4194             output.println("TRANSREADRD("+dst+", "+dst+");");
4195         }
4196       }
4197     } else if (state.DSM) {
4198       Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
4199       if (status==LocalityAnalysis.GLOBAL) {
4200         String dst=generateTemp(fm, fen.getDst(),lb);
4201         if (elementtype.isPtr()) {
4202           output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4203           //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
4204           output.println("TRANSREAD("+dst+", "+dst+");");
4205         } else {
4206           output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4207         }
4208       } else if (status==LocalityAnalysis.LOCAL) {
4209         output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4210       } else if (status==LocalityAnalysis.EITHER) {
4211         //Code is reading from a null pointer
4212         output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
4213         output.println("#ifndef RAW");
4214         output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4215         output.println("#endif");
4216         //This should throw a suitable null pointer error
4217         output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4218       } else
4219         throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4220     } else {
4221       output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4222     }
4223   }
4224
4225   private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
4226     //TODO: need dynamic check to make sure this assignment is actually legal
4227     //Because Object[] could actually be something more specific...ie. Integer[]
4228
4229     TypeDescriptor elementtype=fsen.getDst().getType().dereference();
4230     String type="";
4231
4232     if (elementtype.isArray()||elementtype.isClass())
4233       type="void *";
4234     else
4235       type=elementtype.getSafeSymbol()+" ";
4236
4237     if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
4238       output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
4239       output.println("failedboundschk();");
4240     }
4241
4242     if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4243       //Transaction set element case
4244       if (wb.needBarrier(fsen)&&
4245           locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
4246         output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
4247       }
4248       if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
4249         output.println("{");
4250         String src=generateTemp(fm, fsen.getSrc(), lb);
4251         if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
4252             locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
4253           output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4254         } else {
4255           output.println("INTPTR srcoid=(INTPTR)"+src+";");
4256         }
4257         if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4258           output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
4259         } else {
4260           output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4261         }
4262         output.println("}");
4263       } else {
4264         if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4265           output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
4266         } else {
4267           output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4268         }
4269       }
4270     } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4271       Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
4272       Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
4273       boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4274       boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
4275       boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
4276       
4277       if (dstglobal) {
4278         if (wb.needBarrier(fsen))
4279           output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
4280       } else if (dstlocal) {
4281         /** Check if we need to copy */
4282         String dst=generateTemp(fm, fsen.getDst(),lb);
4283         output.println("if(!"+dst+"->"+localcopystr+") {");
4284         /* Link object into list */
4285         String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4286         output.println(revertptr+"=revertlist;");
4287         if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
4288         output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4289         else
4290           output.println("COPY_OBJ("+dst+");");
4291         output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4292         output.println("revertlist=(struct ___Object___ *)"+dst+";");
4293         output.println("}");
4294       } else {
4295         System.out.println("Node: "+fsen);
4296         System.out.println(lb);
4297         System.out.println("statusdst="+statusdst);
4298         System.out.println(fm.printMethod());
4299         throw new Error("Unknown array type");
4300       }
4301       if (srcglobal) {
4302         output.println("{");
4303         String src=generateTemp(fm, fsen.getSrc(), lb);
4304         output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4305         output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4306         output.println("}");
4307       } else {
4308         output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4309       }
4310     } else {
4311       if (state.FASTCHECK) {
4312         String dst=generateTemp(fm, fsen.getDst(),lb);
4313         output.println("if(!"+dst+"->"+localcopystr+") {");
4314         /* Link object into list */
4315         if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4316           output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4317         else
4318           output.println("COPY_OBJ("+dst+");");
4319         output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4320         output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4321         output.println("}");
4322       }
4323       output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4324     }
4325   }
4326
4327   protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
4328     if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4329       //Stash pointer in case of GC
4330       String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4331       output.println(revertptr+"=revertlist;");
4332     }
4333     if (state.SINGLETM) {
4334       if (fn.getType().isArray()) {
4335         int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4336         if (locality.getAtomic(lb).get(fn).intValue()>0) {
4337           //inside transaction
4338           output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4339         } else {
4340           //outside transaction
4341           output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4342         }
4343       } else {
4344         if (locality.getAtomic(lb).get(fn).intValue()>0) {
4345           //inside transaction
4346           output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4347         } else {
4348           //outside transaction
4349           output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4350         }
4351       }
4352     } else if (fn.getType().isArray()) {
4353       int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4354       if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4355         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4356       } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4357         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4358       } else {
4359         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4360       }
4361     } else {
4362       if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4363         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
4364       } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4365         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4366       } else {
4367         output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
4368       }
4369     }
4370     if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4371       String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4372       String dst=generateTemp(fm,fn.getDst(),lb);
4373       output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4374       output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4375       output.println("revertlist=(struct ___Object___ *)"+dst+";");
4376     }
4377     if (state.FASTCHECK) {
4378       String dst=generateTemp(fm,fn.getDst(),lb);
4379       output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4380       output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4381       output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4382     }
4383   }
4384
4385   private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
4386     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4387       output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
4388     } else {
4389       output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
4390     }
4391   }
4392
4393   private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
4394     if (fon.getRight()!=null) {
4395       if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
4396         if (fon.getLeft().getType().isLong())
4397           output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4398         else
4399           output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4400
4401       } else if (dc!=null) {
4402         output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
4403         if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4404             output.print("(void *)");
4405         if (dc.getNeedLeftSrcTrans(lb, fon))
4406           output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
4407         else
4408           output.print(generateTemp(fm, fon.getLeft(),lb));
4409         output.print(")"+fon.getOp().toString()+"(");
4410         if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4411             output.print("(void *)");
4412         if (dc.getNeedRightSrcTrans(lb, fon))
4413           output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
4414         else
4415           output.println(generateTemp(fm,fon.getRight(),lb)+");");
4416       } else
4417         output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
4418     } else if (fon.getOp().getOp()==Operation.ASSIGN)
4419       output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4420     else if (fon.getOp().getOp()==Operation.UNARYPLUS)
4421       output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4422     else if (fon.getOp().getOp()==Operation.UNARYMINUS)
4423       output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
4424     else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
4425       output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
4426     else if (fon.getOp().getOp()==Operation.COMP)
4427       output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
4428     else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
4429       output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
4430     } else
4431       output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
4432   }
4433
4434   private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
4435     /* TODO: Do type check here */
4436     if (fcn.getType().isArray()) {
4437       output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4438     } else if (fcn.getType().isClass())
4439       output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4440     else
4441       output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
4442   }
4443
4444   private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
4445     if (fln.getValue()==null)
4446       output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4447     else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
4448       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4449         if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4450           //Stash pointer in case of GC
4451           String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4452           output.println(revertptr+"=revertlist;");
4453         }
4454         output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4455         if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4456           //Stash pointer in case of GC
4457           String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4458           output.println("revertlist="+revertptr+";");
4459         }
4460       } else {
4461         output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4462       }
4463     } else if (fln.getType().isBoolean()) {
4464       if (((Boolean)fln.getValue()).booleanValue())
4465         output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
4466       else
4467         output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4468     } else if (fln.getType().isChar()) {
4469       String st=FlatLiteralNode.escapeString(fln.getValue().toString());
4470       output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
4471     } else if (fln.getType().isLong()) {
4472       output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
4473     } else
4474       output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
4475   }
4476
4477   protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
4478     if (frn.getReturnTemp()!=null) {
4479       if (frn.getReturnTemp().getType().isPtr())
4480         output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4481       else
4482         output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4483     } else {
4484       output.println("return;");
4485     }
4486   }
4487
4488   protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4489     int left=-1;
4490     int right=-1;
4491     //only record if this group has more than one exit
4492     if (branchanalysis.numJumps(fcb)>1) {
4493       left=branchanalysis.jumpValue(fcb, 0);
4494       right=branchanalysis.jumpValue(fcb, 1);
4495     }
4496     output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
4497     if (right!=-1)
4498       output.println("STOREBRANCH("+right+");");
4499     output.println("goto "+label+";");
4500     output.println("}");
4501     if (left!=-1)
4502       output.println("STOREBRANCH("+left+");");
4503   }
4504
4505   protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4506     output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
4507   }
4508
4509   /** This method generates header information for the method or
4510    * task referenced by the Descriptor des. */
4511   private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
4512     generateHeader(fm, lb, des, output, false);
4513   }
4514
4515   private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
4516     /* Print header */
4517     ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
4518     MethodDescriptor md=null;
4519     TaskDescriptor task=null;
4520     if (des instanceof MethodDescriptor)
4521       md=(MethodDescriptor) des;
4522     else
4523       task=(TaskDescriptor) des;
4524
4525     ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
4526
4527     if (md!=null&&md.getReturnType()!=null) {
4528       if (md.getReturnType().isClass()||md.getReturnType().isArray())
4529         output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4530       else
4531         output.print(md.getReturnType().getSafeSymbol()+" ");
4532     } else
4533       //catch the constructor case
4534       output.print("void ");
4535     if (md!=null) {
4536       if (state.DSM||state.SINGLETM) {
4537         output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4538       } else
4539         output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4540     } else
4541       output.print(task.getSafeSymbol()+"(");
4542     
4543     boolean printcomma=false;
4544     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4545       if (md!=null) {
4546         if (state.DSM||state.SINGLETM) {
4547           output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4548         } else
4549           output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4550       } else
4551         output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
4552       printcomma=true;
4553     }
4554
4555     if (md!=null) {
4556       /* Method */
4557       for(int i=0; i<objectparams.numPrimitives(); i++) {
4558         TempDescriptor temp=objectparams.getPrimitive(i);
4559         if (printcomma)
4560           output.print(", ");
4561         printcomma=true;
4562         if (temp.getType().isClass()||temp.getType().isArray())
4563           output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
4564         else
4565           output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
4566       }
4567       output.println(") {");
4568     } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4569       /* Imprecise Task */
4570       output.println("void * parameterarray[]) {");
4571       /* Unpack variables */
4572       for(int i=0; i<objectparams.numPrimitives(); i++) {
4573         TempDescriptor temp=objectparams.getPrimitive(i);
4574         output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
4575       }
4576       for(int i=0; i<fm.numTags(); i++) {
4577         TempDescriptor temp=fm.getTag(i);
4578         int offset=i+objectparams.numPrimitives();
4579         output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
4580       }
4581
4582       if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
4583         maxtaskparams=objectparams.numPrimitives()+fm.numTags();
4584     } else output.println(") {");
4585   }
4586
4587   public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
4588     output.println("/* FlatFlagActionNode */");
4589
4590
4591     /* Process tag changes */
4592     Relation tagsettable=new Relation();
4593     Relation tagcleartable=new Relation();
4594
4595     Iterator tagsit=ffan.getTempTagPairs();
4596     while (tagsit.hasNext()) {
4597       TempTagPair ttp=(TempTagPair) tagsit.next();
4598       TempDescriptor objtmp=ttp.getTemp();
4599       TagDescriptor tag=ttp.getTag();
4600       TempDescriptor tagtmp=ttp.getTagTemp();
4601       boolean tagstatus=ffan.getTagChange(ttp);
4602       if (tagstatus) {
4603         tagsettable.put(objtmp, tagtmp);
4604       } else {
4605         tagcleartable.put(objtmp, tagtmp);
4606       }
4607     }
4608
4609
4610     Hashtable flagandtable=new Hashtable();
4611     Hashtable flagortable=new Hashtable();
4612
4613     /* Process flag changes */
4614     Iterator flagsit=ffan.getTempFlagPairs();
4615     while(flagsit.hasNext()) {
4616       TempFlagPair tfp=(TempFlagPair)flagsit.next();
4617       TempDescriptor temp=tfp.getTemp();
4618       Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
4619       FlagDescriptor flag=tfp.getFlag();
4620       if (flag==null) {
4621         //Newly allocate objects that don't set any flags case
4622         if (flagortable.containsKey(temp)) {
4623           throw new Error();
4624         }
4625         int mask=0;
4626         flagortable.put(temp,new Integer(mask));
4627       } else {
4628         int flagid=1<<((Integer)flagtable.get(flag)).intValue();
4629         boolean flagstatus=ffan.getFlagChange(tfp);
4630         if (flagstatus) {
4631           int mask=0;
4632           if (flagortable.containsKey(temp)) {
4633             mask=((Integer)flagortable.get(temp)).intValue();
4634           }
4635           mask|=flagid;
4636           flagortable.put(temp,new Integer(mask));
4637         } else {
4638           int mask=0xFFFFFFFF;
4639           if (flagandtable.containsKey(temp)) {
4640             mask=((Integer)flagandtable.get(temp)).intValue();
4641           }
4642           mask&=(0xFFFFFFFF^flagid);
4643           flagandtable.put(temp,new Integer(mask));
4644         }
4645       }
4646     }
4647
4648
4649     HashSet flagtagset=new HashSet();
4650     flagtagset.addAll(flagortable.keySet());
4651     flagtagset.addAll(flagandtable.keySet());
4652     flagtagset.addAll(tagsettable.keySet());
4653     flagtagset.addAll(tagcleartable.keySet());
4654
4655     Iterator ftit=flagtagset.iterator();
4656     while(ftit.hasNext()) {
4657       TempDescriptor temp=(TempDescriptor)ftit.next();
4658
4659
4660       Set tagtmps=tagcleartable.get(temp);
4661       if (tagtmps!=null) {
4662         Iterator tagit=tagtmps.iterator();
4663         while(tagit.hasNext()) {
4664           TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4665           if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4666             output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4667           else
4668             output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4669         }
4670       }
4671
4672       tagtmps=tagsettable.get(temp);
4673       if (tagtmps!=null) {
4674         Iterator tagit=tagtmps.iterator();
4675         while(tagit.hasNext()) {
4676           TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4677           if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4678             output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4679           else
4680             output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
4681         }
4682       }
4683
4684       int ormask=0;
4685       int andmask=0xFFFFFFF;
4686
4687       if (flagortable.containsKey(temp))
4688         ormask=((Integer)flagortable.get(temp)).intValue();
4689       if (flagandtable.containsKey(temp))
4690         andmask=((Integer)flagandtable.get(temp)).intValue();
4691       generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
4692       generateObjectDistribute(ffan, fm, lb, temp, output);
4693     }
4694   }
4695
4696   protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
4697                                    PrintWriter output, int ormask, int andmask) {
4698     if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
4699       output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4700     } else {
4701       output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4702     }
4703   }
4704
4705   protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
4706     output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
4707   }
4708
4709   void generateOptionalHeader(PrintWriter headers) {
4710
4711     //GENERATE HEADERS
4712     headers.println("#include \"task.h\"\n\n");
4713     headers.println("#ifndef _OPTIONAL_STRUCT_");
4714     headers.println("#define _OPTIONAL_STRUCT_");
4715
4716     //STRUCT PREDICATEMEMBER
4717     headers.println("struct predicatemember{");
4718     headers.println("int type;");
4719     headers.println("int numdnfterms;");
4720     headers.println("int * flags;");
4721     headers.println("int numtags;");
4722     headers.println("int * tags;\n};\n\n");
4723
4724     //STRUCT OPTIONALTASKDESCRIPTOR
4725     headers.println("struct optionaltaskdescriptor{");
4726     headers.println("struct taskdescriptor * task;");
4727     headers.println("int index;");
4728     headers.println("int numenterflags;");
4729     headers.println("int * enterflags;");
4730     headers.println("int numpredicatemembers;");
4731     headers.println("struct predicatemember ** predicatememberarray;");
4732     headers.println("};\n\n");
4733
4734     //STRUCT TASKFAILURE
4735     headers.println("struct taskfailure {");
4736     headers.println("struct taskdescriptor * task;");
4737     headers.println("int index;");
4738     headers.println("int numoptionaltaskdescriptors;");
4739     headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4740
4741     //STRUCT FSANALYSISWRAPPER
4742     headers.println("struct fsanalysiswrapper{");
4743     headers.println("int  flags;");
4744     headers.println("int numtags;");
4745     headers.println("int * tags;");
4746     headers.println("int numtaskfailures;");
4747     headers.println("struct taskfailure ** taskfailurearray;");
4748     headers.println("int numoptionaltaskdescriptors;");
4749     headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4750
4751     //STRUCT CLASSANALYSISWRAPPER
4752     headers.println("struct classanalysiswrapper{");
4753     headers.println("int type;");
4754     headers.println("int numotd;");
4755     headers.println("struct optionaltaskdescriptor ** otdarray;");
4756     headers.println("int numfsanalysiswrappers;");
4757     headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
4758
4759     headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
4760
4761     Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
4762     while(taskit.hasNext()) {
4763       TaskDescriptor td=(TaskDescriptor)taskit.next();
4764       headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
4765     }
4766
4767   }
4768
4769   //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
4770   int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
4771     int predicateindex = 0;
4772     //iterate through the classes concerned by the predicate
4773     Set c_vard = predicate.vardescriptors;
4774     Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
4775     int current_slot=0;
4776
4777     for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
4778       VarDescriptor vard = (VarDescriptor)vard_it.next();
4779       TypeDescriptor typed = vard.getType();
4780
4781       //generate for flags
4782       HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
4783       output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4784       int numberterms=0;
4785       if (fen_hashset!=null) {
4786         for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
4787           FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
4788           if (fen!=null) {
4789             DNFFlag dflag=fen.getDNF();
4790             numberterms+=dflag.size();
4791
4792             Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
4793
4794             for(int j=0; j<dflag.size(); j++) {
4795               if (j!=0)
4796                 output.println(",");
4797               Vector term=dflag.get(j);
4798               int andmask=0;
4799               int checkmask=0;
4800               for(int k=0; k<term.size(); k++) {
4801                 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
4802                 FlagDescriptor fd=dfa.getFlag();
4803                 boolean negated=dfa.getNegated();
4804                 int flagid=1<<((Integer)flags.get(fd)).intValue();
4805                 andmask|=flagid;
4806                 if (!negated)
4807                   checkmask|=flagid;
4808               }
4809               output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
4810             }
4811           }
4812         }
4813       }
4814       output.println("};\n");
4815
4816       //generate for tags
4817       TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
4818       output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4819       int numtags = 0;
4820       if (tagel!=null) {
4821         for(int j=0; j<tagel.numTags(); j++) {
4822           if (j!=0)
4823             output.println(",");
4824           TempDescriptor tmp=tagel.getTemp(j);
4825           if (!slotnumber.containsKey(tmp)) {
4826             Integer slotint=new Integer(current_slot++);
4827             slotnumber.put(tmp,slotint);
4828           }
4829           int slot=slotnumber.get(tmp).intValue();
4830           output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
4831         }
4832         numtags = tagel.numTags();
4833       }
4834       output.println("};");
4835
4836       //store the result into a predicatemember struct
4837       output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4838       output.println("/*type*/"+typed.getClassDesc().getId()+",");
4839       output.println("/* number of dnf terms */"+numberterms+",");
4840       output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4841       output.println("/* number of tag */"+numtags+",");
4842       output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4843       output.println("};\n");
4844       predicateindex++;
4845     }
4846
4847
4848     //generate an array that stores the entire predicate
4849     output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4850     for( int j = 0; j<predicateindex; j++) {
4851       if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4852       else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4853     }
4854     output.println("};\n");
4855     return predicateindex;
4856   }
4857
4858
4859   void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
4860     generateOptionalHeader(headers);
4861     //GENERATE STRUCTS
4862     output.println("#include \"optionalstruct.h\"\n\n");
4863     output.println("#include \"stdlib.h\"\n");
4864
4865     HashSet processedcd = new HashSet();
4866     int maxotd=0;
4867     Enumeration e = safeexecution.keys();
4868     while (e.hasMoreElements()) {
4869       int numotd=0;
4870       //get the class
4871       ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
4872       Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp);       //will be used several times
4873
4874       //Generate the struct of optionals
4875       Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4876       numotd = c_otd.size();
4877       if(maxotd<numotd) maxotd = numotd;
4878       if( !c_otd.isEmpty() ) {
4879         for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4880           OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4881
4882           //generate the int arrays for the predicate
4883           Predicate predicate = otd.predicate;
4884           int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
4885           TreeSet<Integer> fsset=new TreeSet<Integer>();
4886           //iterate through possible FSes corresponding to
4887           //the state when entering
4888
4889           for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
4890             FlagState fs = (FlagState)fses.next();
4891             int flagid=0;
4892             for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4893               FlagDescriptor flagd = (FlagDescriptor)flags.next();
4894               int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4895               flagid|=id;
4896             }
4897             fsset.add(new Integer(flagid));
4898             //tag information not needed because tag
4899             //changes are not tolerated.
4900           }
4901
4902           output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4903           boolean needcomma=false;
4904           for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
4905             if(needcomma)
4906               output.print(", ");
4907             output.println(it.next());
4908           }
4909
4910           output.println("};\n");
4911
4912
4913           //generate optionaltaskdescriptor that actually
4914           //includes exit fses, predicate and the task
4915           //concerned
4916           output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4917           output.println("&task_"+otd.td.getSafeSymbol()+",");
4918           output.println("/*index*/"+otd.getIndex()+",");
4919           output.println("/*number of enter flags*/"+fsset.size()+",");
4920           output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4921           output.println("/*number of members */"+predicateindex+",");
4922           output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4923           output.println("};\n");
4924         }
4925       } else
4926         continue;
4927       // if there are no optionals, there is no need to build the rest of the struct
4928
4929       output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
4930       c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4931       if( !c_otd.isEmpty() ) {
4932         boolean needcomma=false;
4933         for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4934           OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4935           if(needcomma)
4936             output.println(",");
4937           needcomma=true;
4938           output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4939         }
4940       }
4941       output.println("};\n");
4942
4943       //get all the possible flagstates reachable by an object
4944       Hashtable hashtbtemp = safeexecution.get(cdtemp);
4945       int fscounter = 0;
4946       TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
4947       fsts.addAll(hashtbtemp.keySet());
4948       for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
4949         FlagState fs = (FlagState)fsit.next();
4950         fscounter++;
4951
4952         //get the set of OptionalTaskDescriptors corresponding
4953         HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
4954         //iterate through the OptionalTaskDescriptors and
4955         //store the pointers to the optionals struct (see on
4956         //top) into an array
4957
4958         output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
4959         for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
4960           OptionalTaskDescriptor mm = mos.next();
4961           if(!mos.hasNext())
4962             output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
4963           else
4964             output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4965         }
4966
4967         output.println("};\n");
4968
4969         //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
4970
4971         int flagid=0;
4972         for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4973           FlagDescriptor flagd = (FlagDescriptor)flags.next();
4974           int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4975           flagid|=id;
4976         }
4977
4978         //process tag information
4979
4980         int tagcounter = 0;
4981         boolean first = true;
4982         Enumeration tag_enum = fs.getTags();
4983         output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4984         while(tag_enum.hasMoreElements()) {
4985           tagcounter++;
4986           TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
4987           if(first==true)
4988             first = false;
4989           else
4990             output.println(", ");
4991           output.println("/*tagid*/"+state.getTagId(tagd));
4992         }
4993         output.println("};");
4994
4995         Set<TaskIndex> tiset=sa.getTaskIndex(fs);
4996         for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4997           TaskIndex ti=itti.next();
4998           if (ti.isRuntime())
4999             continue;
5000
5001           Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
5002
5003           output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
5004           boolean needcomma=false;
5005           for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
5006             OptionalTaskDescriptor otd=otdit.next();
5007             if(needcomma)
5008               output.print(", ");
5009             needcomma=true;
5010             output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5011           }
5012           output.println("};");
5013
5014           output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
5015           output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
5016           output.print(ti.getIndex()+", ");
5017           output.print(otdset.size()+", ");
5018           output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
5019           output.println("};");
5020         }
5021
5022         tiset=sa.getTaskIndex(fs);
5023         boolean needcomma=false;
5024         int runtimeti=0;
5025         output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5026         for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5027           TaskIndex ti=itti.next();
5028           if (ti.isRuntime()) {
5029             runtimeti++;
5030             continue;
5031           }
5032           if (needcomma)
5033             output.print(", ");
5034           needcomma=true;
5035           output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
5036         }
5037         output.println("};\n");
5038
5039         //Store the result in fsanalysiswrapper
5040
5041         output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
5042         output.println("/*flag*/"+flagid+",");
5043         output.println("/* number of tags*/"+tagcounter+",");
5044         output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5045         output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
5046         output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5047         output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
5048         output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
5049         output.println("};\n");
5050
5051       }
5052
5053       //Build the array of fsanalysiswrappers
5054       output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
5055       boolean needcomma=false;
5056       for(int i = 0; i<fscounter; i++) {
5057         if (needcomma) output.print(",");
5058         output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
5059         needcomma=true;
5060       }
5061       output.println("};");
5062
5063       //Build the classanalysiswrapper referring to the previous array
5064       output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
5065       output.println("/*type*/"+cdtemp.getId()+",");
5066       output.println("/*numotd*/"+numotd+",");
5067       output.println("otdarray"+cdtemp.getSafeSymbol()+",");
5068       output.println("/* number of fsanalysiswrappers */"+fscounter+",");
5069       output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
5070       processedcd.add(cdtemp);
5071     }
5072
5073     //build an array containing every classes for which code has been build
5074     output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
5075     for(int i=0; i<state.numClasses(); i++) {
5076       ClassDescriptor cn=cdarray[i];
5077       if (i>0)
5078         output.print(", ");
5079       if ((cn != null) && (processedcd.contains(cn)))
5080         output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
5081       else
5082         output.print("NULL");
5083     }
5084     output.println("};");
5085
5086     output.println("#define MAXOTD "+maxotd);
5087     headers.println("#endif");
5088   }
5089
5090   public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
5091     Relation r=new Relation();
5092     for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
5093       OptionalTaskDescriptor otd=otdit.next();
5094       TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
5095       r.put(ti, otd);
5096     }
5097
5098     LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
5099     for(Iterator it=r.keySet().iterator(); it.hasNext();) {
5100       Set s=r.get(it.next());
5101       for(Iterator it2=s.iterator(); it2.hasNext();) {
5102         OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
5103         l.add(otd);
5104       }
5105     }
5106
5107     return l;
5108   }
5109
5110   protected void outputTransCode(PrintWriter output) {
5111   }
5112 }
5113
5114
5115
5116
5117
5118