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