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