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