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