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