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