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