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