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