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