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