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