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