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