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