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