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