Bug fix: should use unsigned int instead of int for pointers in shared heap. Also...
[IRC.git] / Robust / src / IR / Flat / BuildCode.java
1 package IR.Flat;
2 import IR.Tree.Modifiers;
3 import IR.Tree.FlagExpressionNode;
4 import IR.Tree.DNFFlag;
5 import IR.Tree.DNFFlagAtom;
6 import IR.Tree.TagExpressionList;
7 import IR.Tree.OffsetNode;
8 import IR.*;
9
10 import java.util.*;
11 import java.io.*;
12
13 import Util.Relation;
14 import Analysis.TaskStateAnalysis.FlagState;
15 import Analysis.TaskStateAnalysis.FlagComparator;
16 import Analysis.TaskStateAnalysis.OptionalTaskDescriptor;
17 import Analysis.TaskStateAnalysis.Predicate;
18 import Analysis.TaskStateAnalysis.SafetyAnalysis;
19 import Analysis.TaskStateAnalysis.TaskIndex;
20 import Analysis.CallGraph.CallGraph;
21 import Analysis.Loops.GlobalFieldType;
22 import Util.CodePrinter;
23
24 public class BuildCode {
25   State state;
26   Hashtable temptovar;
27   Hashtable paramstable;
28   Hashtable tempstable;
29   Hashtable fieldorder;
30   Hashtable flagorder;
31   int tag=0;
32   String localsprefix="___locals___";
33   String localsprefixaddr="&"+localsprefix;
34   String localsprefixderef=localsprefix+".";
35   String fcrevert="___fcrevert___";
36   String paramsprefix="___params___";
37   String nextobjstr="___nextobject___";
38   String localcopystr="___localcopy___";
39   public static boolean GENERATEPRECISEGC=false;
40   public static String PREFIX="";
41   public static String arraytype="ArrayObject";
42   public static int flagcount = 0;
43   Virtual virtualcalls;
44   TypeUtil typeutil;
45   protected int maxtaskparams=0;
46   protected int maxcount=0;
47   ClassDescriptor[] cdarray;
48   ClassDescriptor[] ifarray;
49   TypeDescriptor[] arraytable;
50   SafetyAnalysis sa;
51   CallGraph callgraph;
52   Hashtable<String, ClassDescriptor> printedfieldstbl;
53   int globaldefscount=0;
54   boolean mgcstaticinit = false;
55   
56   int boundschknum = 0;
57
58   public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil) {
59     this(st, temptovar, typeutil, null);
60   }
61
62   public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa) {
63     this.sa=sa;
64     state=st;
65     State.logEvent("Start CallGraph");    
66     callgraph=new CallGraph(state);
67     State.logEvent("Finish CallGraph");    
68     this.temptovar=temptovar;
69     paramstable=new Hashtable();
70     tempstable=new Hashtable();
71     fieldorder=new Hashtable();
72     flagorder=new Hashtable();
73     this.typeutil=typeutil;
74     State.logEvent("CheckMethods");    
75     checkMethods2Gen();
76     State.logEvent("Virtual");    
77     virtualcalls=new Virtual(state, null);
78     printedfieldstbl = new Hashtable<String, ClassDescriptor>();
79   }
80
81   /** The buildCode method outputs C code for all the methods.  The Flat
82    * versions of the methods must already be generated and stored in
83    * the State object. */
84
85
86   public void buildCode() {
87     /* Create output streams to write to */
88     PrintWriter outclassdefs=null;
89     PrintWriter outstructs=null;
90     PrintWriter outrepairstructs=null;
91     PrintWriter outmethodheader=null;
92     PrintWriter outmethod=null;
93     PrintWriter outvirtual=null;
94     PrintWriter outtask=null;
95     PrintWriter outtaskdefs=null;
96     PrintWriter outoptionalarrays=null;
97     PrintWriter optionalheaders=null;
98     PrintWriter outglobaldefs=null;
99     PrintWriter outglobaldefsprim=null;
100     State.logEvent("Beginning of buildCode");
101
102     try {
103       buildCodeSetup(); //EXTENSION POINT
104       outstructs=new CodePrinter(new FileOutputStream(PREFIX+"structdefs.h"), true);
105       outmethodheader=new CodePrinter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
106       outclassdefs=new CodePrinter(new FileOutputStream(PREFIX+"classdefs.h"), true);
107       outglobaldefs=new CodePrinter(new FileOutputStream(PREFIX+"globaldefs.h"), true);
108       outglobaldefsprim=new CodePrinter(new FileOutputStream(PREFIX+"globaldefsprim.h"), true);
109       outmethod=new CodePrinter(new FileOutputStream(PREFIX+"methods.c"), true);
110       outvirtual=new CodePrinter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
111       if (state.TASK) {
112         outtask=new CodePrinter(new FileOutputStream(PREFIX+"task.h"), true);
113         outtaskdefs=new CodePrinter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
114         if (state.OPTIONAL) {
115           outoptionalarrays=new CodePrinter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
116           optionalheaders=new CodePrinter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
117         }
118       }
119       if (state.structfile!=null) {
120         outrepairstructs=new CodePrinter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
121       }
122     } catch (Exception e) {
123       e.printStackTrace();
124       System.exit(-1);
125     }
126
127     /* Fix field safe symbols due to shadowing */
128     FieldShadow.handleFieldShadow(state);
129
130     /* Build the virtual dispatch tables */
131     buildVirtualTables(outvirtual);
132
133     /* Tag the methods that are invoked by static blocks */
134     tagMethodInvokedByStaticBlock();
135
136     /* Output includes */
137     outmethodheader.println("#ifndef METHODHEADERS_H");
138     outmethodheader.println("#define METHODHEADERS_H");
139     outmethodheader.println("#include \"structdefs.h\"");
140
141     if (state.EVENTMONITOR) {
142       outmethodheader.println("#include \"monitor.h\"");
143     }
144
145     additionalIncludesMethodsHeader(outmethodheader);
146
147     /* Output Structures */
148     outputStructs(outstructs);
149
150     // Output the C class declarations
151     // These could mutually reference each other
152
153     outglobaldefs.println("#ifndef __GLOBALDEF_H_");
154     outglobaldefs.println("#define __GLOBALDEF_H_");
155     outglobaldefs.println("");
156     outglobaldefs.println("struct global_defs_t {");
157     outglobaldefs.println("  int size;");
158     outglobaldefs.println("  void * next;");
159     outglobaldefsprim.println("#ifndef __GLOBALDEFPRIM_H_");
160     outglobaldefsprim.println("#define __GLOBALDEFPRIM_H_");
161     outglobaldefsprim.println("");
162     outglobaldefsprim.println("struct global_defsprim_t {");
163
164     outclassdefs.println("#ifndef __CLASSDEF_H_");
165     outclassdefs.println("#define __CLASSDEF_H_");
166     outputClassDeclarations(outclassdefs, outglobaldefs, outglobaldefsprim);
167
168     // Output function prototypes and structures for parameters
169     Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
170     while(it.hasNext()) {
171       ClassDescriptor cn=(ClassDescriptor)it.next();
172       generateCallStructs(cn, outclassdefs, outstructs, outmethodheader, outglobaldefs, outglobaldefsprim);
173     }
174     outclassdefs.println("#include \"globaldefs.h\"");
175     outclassdefs.println("#include \"globaldefsprim.h\"");
176     outclassdefs.println("#endif");
177     outclassdefs.close();
178     
179     outglobaldefs.println("};");
180     outglobaldefs.println("");
181     outglobaldefs.println("extern struct global_defs_t * global_defs_p;");
182     outglobaldefs.println("#endif");
183     outglobaldefs.flush();
184     outglobaldefs.close();
185
186     outglobaldefsprim.println("};");
187     outglobaldefsprim.println("");
188     outglobaldefsprim.println("extern struct global_defsprim_t * global_defsprim_p;");
189     outglobaldefsprim.println("#endif");
190     outglobaldefsprim.flush();
191     outglobaldefsprim.close();
192
193     if (state.TASK) {
194       /* Map flags to integers */
195       /* The runtime keeps track of flags using these integers */
196       it=state.getClassSymbolTable().getDescriptorsIterator();
197       while(it.hasNext()) {
198         ClassDescriptor cn=(ClassDescriptor)it.next();
199         mapFlags(cn);
200       }
201       /* Generate Tasks */
202       generateTaskStructs(outstructs, outmethodheader);
203
204       /* Outputs generic task structures if this is a task
205          program */
206       outputTaskTypes(outtask);
207     }
208
209
210     // an opportunity for subclasses to do extra
211     // initialization
212     preCodeGenInitialization();
213
214     State.logEvent("Start outputMethods");
215     /* Build the actual methods */
216     outputMethods(outmethod);
217     State.logEvent("End outputMethods");
218
219     // opportunity for subclasses to gen extra code
220     additionalCodeGen(outmethodheader,
221                       outstructs,
222                       outmethod);
223
224
225     if (state.TASK) {
226       /* Output code for tasks */
227       outputTaskCode(outtaskdefs, outmethod);
228       outtaskdefs.close();
229       /* Record maximum number of task parameters */
230       outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
231     } else if (state.main!=null) {
232       /* Generate main method */
233       outputMainMethod(outmethod);
234     }
235
236     /* Generate information for task with optional parameters */
237     if (state.TASK&&state.OPTIONAL) {
238       generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
239       outoptionalarrays.close();
240     }
241
242     /* Output structure definitions for repair tool */
243     if (state.structfile!=null) {
244       buildRepairStructs(outrepairstructs);
245       outrepairstructs.close();
246     }
247
248     /* Close files */
249     outmethodheader.println("#endif");
250     outmethodheader.close();
251     outmethod.close();
252     outstructs.println("#endif");
253     outstructs.close();
254
255
256
257     postCodeGenCleanUp();
258     State.logEvent("End of buildCode");
259   }
260
261   /* This method goes though the call graph and check which methods are really
262    * invoked and should be generated
263    */
264   protected void checkMethods2Gen() {
265     MethodDescriptor md=(state.main==null)?null:typeutil.getMain();
266     
267     if(md != null) {
268       // check the methods to be generated
269       state.setGenAllMethods(false);
270     } else {
271       // generate all methods
272       return;
273     }
274     this.state.addMethod2gen(md);
275     
276     Iterator it_classes = this.state.getClassSymbolTable().getDescriptorsIterator();
277     while(it_classes.hasNext()) {
278       ClassDescriptor cd = (ClassDescriptor)it_classes.next();
279       Iterator it_methods = cd.getMethodTable().getDescriptorsIterator();
280       while(it_methods.hasNext()) {
281         md = (MethodDescriptor)it_methods.next();
282         if(md.isStaticBlock() || md.getModifiers().isNative() || this.callgraph.getCallerSet(md).size() > 0
283             || (cd.getSymbol().equals("Thread") && md.getSymbol().equals("staticStart"))) {
284           this.state.addMethod2gen(md);
285         }
286       }
287     }
288   }
289
290
291   /* This method goes though the call graph and tag those methods that are
292    * invoked inside static blocks
293    */
294   protected void tagMethodInvokedByStaticBlock() {
295     Iterator it_sclasses = this.state.getSClassSymbolTable().getDescriptorsIterator();
296     MethodDescriptor current_md=null;
297     HashSet tovisit=new HashSet();
298     HashSet visited=new HashSet();
299     
300     while(it_sclasses.hasNext()) {
301       ClassDescriptor cd = (ClassDescriptor)it_sclasses.next();
302       MethodDescriptor md = (MethodDescriptor)cd.getMethodTable().get("staticblocks");
303       if(md != null) {
304         tovisit.add(md);
305       }
306     }
307     
308     while(!tovisit.isEmpty()) {
309       current_md=(MethodDescriptor)tovisit.iterator().next();
310       tovisit.remove(current_md);
311       visited.add(current_md);
312       Iterator it_callee = this.callgraph.getCalleeSet(current_md).iterator();
313       while(it_callee.hasNext()) {
314         Descriptor d = (Descriptor)it_callee.next();
315         if(d instanceof MethodDescriptor) {
316           if(!visited.contains(d)) {
317             ((MethodDescriptor)d).setIsInvokedByStatic(true);
318             tovisit.add(d);
319           }
320         }
321       }
322     }
323   }
324
325   /* This code generates code for each static block and static field
326    * initialization.*/
327   protected void outputStaticBlocks(PrintWriter outmethod) {
328     //  execute all the static blocks and all the static field initializations
329     // execute all the static blocks and all the static field initializations
330     SymbolTable sctbl = this.state.getSClassSymbolTable();
331     Iterator it_sclasses = sctbl.getDescriptorsIterator();
332     if(it_sclasses.hasNext()) {
333       while(it_sclasses.hasNext()) {
334         ClassDescriptor t_cd = (ClassDescriptor)it_sclasses.next();
335         MethodDescriptor t_md = (MethodDescriptor)t_cd.getMethodTable().get("staticblocks");
336         if(t_md != null) {
337           outmethod.println("   {");
338           if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
339             outmethod.print("       struct "+t_cd.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={");
340             outmethod.println("0, NULL};");
341             outmethod.println("     "+t_cd.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);");
342           } else {
343             outmethod.println("     "+t_cd.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
344           }
345           outmethod.println("   }");
346         }
347       }
348     }
349   }
350
351   /* This code generates code to create a Class object for each class for
352    * getClass() method.
353    * */
354   protected void outputClassObjects(PrintWriter outmethod) {
355     // for each class, initialize its Class object
356     SymbolTable ctbl = this.state.getClassSymbolTable();
357     for(Iterator it_classes = ctbl.getDescriptorsIterator();it_classes.hasNext();) {
358       ClassDescriptor t_cd = (ClassDescriptor)it_classes.next();
359       outmethod.println(" {");
360       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
361         outmethod.println("    struct garbagelist dummy={0,NULL};");
362         outmethod.println("    global_defs_p->"+t_cd.getSafeSymbol()+"classobj = allocate_new(&dummy, " + typeutil.getClass(TypeUtil.ObjectClass).getId() + ");");
363       } else 
364         outmethod.println("    global_defs_p->"+t_cd.getSafeSymbol()+"classobj = allocate_new("+typeutil.getClass(TypeUtil.ObjectClass).getId() + ");");
365       outmethod.println(" }");
366     }
367   }
368
369   /* This code just generates the main C method for java programs.
370    * The main C method packs up the arguments into a string array
371    * and passes it to the java main method. */
372
373   protected void outputMainMethod(PrintWriter outmethod) {
374     outmethod.println("int main(int argc, const char *argv[]) {");
375     outmethod.println("  int i;");
376     outmethod.println("  global_defs_p=calloc(1, sizeof(struct global_defs_t));");
377     outmethod.println("  global_defsprim_p=calloc(1, sizeof(struct global_defsprim_t));");
378     if (GENERATEPRECISEGC) {
379       outmethod.println("  global_defs_p->size="+globaldefscount+";");
380       outmethod.println("  for(i=0;i<"+globaldefscount+";i++) {");
381       outmethod.println("    ((struct garbagelist *)global_defs_p)->array[i]=NULL;");
382       outmethod.println("  }");
383     }
384     outputStaticBlocks(outmethod);
385     outputClassObjects(outmethod);
386
387
388     additionalCodeAtTopOfMain(outmethod);
389
390     if (state.THREAD) {
391       outmethod.println("initializethreads();");
392     }
393
394     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
395       outmethod.println("  struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
396     } else {
397       outmethod.println("  struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
398     }
399     outmethod.println("  for(i=1;i<argc;i++) {");
400     outmethod.println("    int length=strlen(argv[i]);");
401
402     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
403       outmethod.println("    struct ___String___ *newstring=NewString(NULL, argv[i], length);");
404     } else {
405       outmethod.println("    struct ___String___ *newstring=NewString(argv[i], length);");
406     }
407     outmethod.println("    ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
408     outmethod.println("  }");
409
410     MethodDescriptor md=typeutil.getMain();
411     ClassDescriptor cd=typeutil.getMainClass();
412
413     outmethod.println("   {");
414     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
415       outmethod.print("       struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
416       outmethod.println("1, NULL,"+"stringarray};");
417       outmethod.println("     "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
418     } else {
419       outmethod.println("     "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
420     }
421     outmethod.println("   }");
422
423     if (state.THREAD) {
424       outmethod.println("pthread_mutex_lock(&gclistlock);");
425       outmethod.println("threadcount--;");
426       outmethod.println("pthread_cond_signal(&gccond);");
427       outmethod.println("pthread_mutex_unlock(&gclistlock);");
428     }
429
430     if (state.EVENTMONITOR) {
431       outmethod.println("dumpdata();");
432     }
433
434     if (state.THREAD)
435       outmethod.println("pthread_exit(NULL);");
436
437
438     additionalCodeAtBottomOfMain(outmethod);
439
440     outmethod.println("}");
441   }
442
443   /* This method outputs code for each task. */
444
445   protected void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
446     /* Compile task based program */
447     outtaskdefs.println("#include \"task.h\"");
448     outtaskdefs.println("#include \"methodheaders.h\"");
449     Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
450     while(taskit.hasNext()) {
451       TaskDescriptor td=(TaskDescriptor)taskit.next();
452       FlatMethod fm=state.getMethodFlat(td);
453       generateFlatMethod(fm, outmethod);
454       generateTaskDescriptor(outtaskdefs, fm, td);
455     }
456
457     //Output task descriptors
458     taskit=state.getTaskSymbolTable().getDescriptorsIterator();
459     outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
460     boolean first=true;
461     while(taskit.hasNext()) {
462       TaskDescriptor td=(TaskDescriptor)taskit.next();
463       if (first)
464         first=false;
465       else
466         outtaskdefs.println(",");
467       outtaskdefs.print("&task_"+td.getSafeSymbol());
468     }
469     outtaskdefs.println("};");
470
471     outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
472   }
473
474
475   /* This method outputs most of the methods.c file.  This includes
476    * some standard includes and then an array with the sizes of
477    * objets and array that stores supertype and then the code for
478    * the Java methods.. */
479   protected void outputMethods(PrintWriter outmethod) {
480     outmethod.println("#include \"methodheaders.h\"");
481     outmethod.println("#include \"virtualtable.h\"");
482     outmethod.println("#include \"runtime.h\"");
483
484     // always include: compiler directives will leave out
485     // instrumentation when option is not set
486     outmethod.println("#include \"coreprof/coreprof.h\"");
487
488     if (state.FASTCHECK) {
489       outmethod.println("#include \"localobjects.h\"");
490     }
491     if(state.MULTICORE) {
492       if(state.TASK) {
493         outmethod.println("#include \"task.h\"");
494       }
495       outmethod.println("#include \"multicoreruntime.h\"");
496       outmethod.println("#include \"runtime_arch.h\"");
497     }
498     if (state.THREAD||state.DSM||state.SINGLETM) {
499       outmethod.println("#include <thread.h>");
500     }
501     if(state.MGC) {
502       outmethod.println("#include \"thread.h\"");
503     }
504     if (state.main!=null) {
505       outmethod.println("#include <string.h>");
506     }
507     if (state.CONSCHECK) {
508       outmethod.println("#include \"checkers.h\"");
509     }
510
511
512     additionalIncludesMethodsImplementation(outmethod);
513
514     outmethod.println("struct global_defs_t * global_defs_p;");
515     outmethod.println("struct global_defsprim_t * global_defsprim_p;");
516     //Store the sizes of classes & array elements
517     generateSizeArray(outmethod);
518
519     //Store table of supertypes
520     generateSuperTypeTable(outmethod);
521
522     //Store the layout of classes
523     generateLayoutStructs(outmethod);
524
525
526     additionalCodeAtTopMethodsImplementation(outmethod);
527
528     generateMethods(outmethod);
529   }
530
531   protected void generateMethods(PrintWriter outmethod) {
532     /* Generate code for methods */
533     Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
534     while(classit.hasNext()) {
535       ClassDescriptor cn=(ClassDescriptor)classit.next();
536       Iterator methodit=cn.getMethods();
537       while(methodit.hasNext()) {
538         /* Classify parameters */
539         MethodDescriptor md=(MethodDescriptor)methodit.next();
540     if(!this.state.genAllMethods) {
541       boolean foundmatch = false;
542       Set vec_md = this.state.getMethod2gen().getSet(md.getSymbol());
543       for(Iterator matchit=vec_md.iterator(); matchit.hasNext();) {
544         MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
545         if (md.matches(matchmd)) {
546           foundmatch=true;
547           break;
548         }
549       }
550       if(!foundmatch) {
551         continue;
552       }
553     }
554         FlatMethod fm=state.getMethodFlat(md);
555         if (!md.getModifiers().isNative()) {
556           generateFlatMethod(fm, outmethod);
557         }
558       }
559     }
560   }
561
562   protected void outputStructs(PrintWriter outstructs) {
563     outstructs.println("#ifndef STRUCTDEFS_H");
564     outstructs.println("#define STRUCTDEFS_H");
565     outstructs.println("#include \"classdefs.h\"");
566     outstructs.println("#ifndef INTPTR");
567     outstructs.println("#ifdef BIT64");
568     outstructs.println("#define INTPTR long");
569     outstructs.println("#else");
570     outstructs.println("#define INTPTR int");
571     outstructs.println("#endif");
572     outstructs.println("#endif");
573
574
575     additionalIncludesStructsHeader(outstructs);
576
577
578     /* Output #defines that the runtime uses to determine type
579      * numbers for various objects it needs */
580     outstructs.println("#define MAXCOUNT "+maxcount);
581
582     outstructs.println("#define STRINGARRAYTYPE "+
583                        (state.getArrayNumber(
584                           (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
585
586     outstructs.println("#define OBJECTARRAYTYPE "+
587                        (state.getArrayNumber(
588                           (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
589
590
591     outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
592     outstructs.println("#define CHARARRAYTYPE "+
593                        (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
594
595     outstructs.println("#define BYTEARRAYTYPE "+
596                        (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
597
598     outstructs.println("#define BYTEARRAYARRAYTYPE "+
599                        (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
600
601     outstructs.println("#define NUMCLASSES "+state.numClasses());
602     int totalClassSize = state.numClasses() + state.numArrays() + state.numInterfaces();
603     outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
604     if (state.TASK) {
605       outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
606       outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
607       outstructs.println("#define TAGARRAYTYPE "+
608                          (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
609     }
610   }
611
612   protected void outputClassDeclarations(PrintWriter outclassdefs, PrintWriter outglobaldefs, PrintWriter outglobaldefsprim) {
613     if (state.THREAD||state.DSM||state.SINGLETM)
614       outclassdefs.println("#include <pthread.h>");
615     outclassdefs.println("#ifndef INTPTR");
616     outclassdefs.println("#ifdef BIT64");
617     outclassdefs.println("#define INTPTR long");
618     outclassdefs.println("#else");
619     outclassdefs.println("#define INTPTR int");
620     outclassdefs.println("#endif");
621     outclassdefs.println("#endif");
622     if(state.OPTIONAL)
623       outclassdefs.println("#include \"optionalstruct.h\"");
624     outclassdefs.println("struct "+arraytype+";");
625     /* Start by declaring all structs */
626     Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
627     while(it.hasNext()) {
628       ClassDescriptor cn=(ClassDescriptor)it.next();
629       outclassdefs.println("struct "+cn.getSafeSymbol()+";");
630
631       if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
632         // this class has static fields/blocks, need to add a global flag to
633         // indicate if its static fields have been initialized and/or if its
634         // static blocks have been executed
635         outglobaldefsprim.println("  int "+cn.getSafeSymbol()+"static_block_exe_flag;");
636       }
637       
638       // for each class, create a global object
639       outglobaldefs.println("  struct ___Object___ *"+cn.getSafeSymbol()+"classobj;");
640       globaldefscount++;
641     }
642     outclassdefs.println("");
643     //Print out definition for array type
644     outclassdefs.println("struct "+arraytype+" {");
645     outclassdefs.println("  int type;");
646
647
648     additionalClassObjectFields(outclassdefs);
649
650
651     if (state.EVENTMONITOR) {
652       outclassdefs.println("  int objuid;");
653     }
654     if (state.THREAD) {
655       outclassdefs.println("  pthread_t tid;");
656       outclassdefs.println("  void * lockentry;");
657       outclassdefs.println("  int lockcount;");
658     }
659     if(state.MGC) {
660       outclassdefs.println("  int mutex;");
661       outclassdefs.println("  volatile int notifycount;");
662       outclassdefs.println("  volatile int objlock;");
663       if(state.MULTICOREGC) {
664         outclassdefs.println("  int marked;");
665       }
666     }
667     if (state.TASK) {
668       outclassdefs.println("  int flag;");
669       if(!state.MULTICORE) {
670         outclassdefs.println("  void * flagptr;");
671       } else {
672         outclassdefs.println("  int version;");
673         outclassdefs.println("  int * lock;");  // lock entry for this obj
674         outclassdefs.println("  int mutex;");
675         outclassdefs.println("  int lockcount;");
676         if(state.MULTICOREGC) {
677           outclassdefs.println("  int marked;");
678         }
679       }
680       if(state.OPTIONAL) {
681         outclassdefs.println("  int numfses;");
682         outclassdefs.println("  int * fses;");
683       }
684     }
685
686     printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs, outglobaldefs, outglobaldefsprim);
687     printedfieldstbl.clear();
688     printExtraArrayFields(outclassdefs);
689     if (state.ARRAYPAD) {
690       outclassdefs.println("  int paddingforarray;");
691     }
692
693     outclassdefs.println("  int ___length___;");
694     outclassdefs.println("};\n");
695
696     if(state.MGC) {
697       // TODO add version for normal Java later
698       outclassdefs.println("");
699       //Print out definition for Class type
700       outclassdefs.println("struct Class {");
701       outclassdefs.println("  int type;");
702
703
704       additionalClassObjectFields(outclassdefs);
705
706
707       if (state.EVENTMONITOR) {
708         outclassdefs.println("  int objuid;");
709       }
710       if (state.THREAD) {
711         outclassdefs.println("  pthread_t tid;");
712         outclassdefs.println("  void * lockentry;");
713         outclassdefs.println("  int lockcount;");
714       }
715       if(state.MGC) {
716         outclassdefs.println("  int mutex;");
717         outclassdefs.println("  volatile int notifycount;");
718         outclassdefs.println("  volatile int objlock;");
719         if(state.MULTICOREGC) {
720           outclassdefs.println("  int marked;");
721         }
722       }
723       if (state.TASK) {
724         outclassdefs.println("  int flag;");
725         if(!state.MULTICORE) {
726           outclassdefs.println("  void * flagptr;");
727         } else {
728           outclassdefs.println("  int version;");
729           outclassdefs.println("  int * lock;"); // lock entry for this obj
730           outclassdefs.println("  int mutex;");
731           outclassdefs.println("  int lockcount;");
732           if(state.MULTICOREGC) {
733             outclassdefs.println("  int marked;");
734           }
735         }
736         if(state.OPTIONAL) {
737           outclassdefs.println("  int numfses;");
738           outclassdefs.println("  int * fses;");
739         }
740       }
741       printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs, outglobaldefs, outglobaldefsprim);
742       printedfieldstbl.clear();
743       outclassdefs.println("};\n");
744     }
745
746     outclassdefs.println("");
747     outclassdefs.println("extern int classsize[];");
748     outclassdefs.println("extern int hasflags[];");
749     outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
750     outclassdefs.println("extern int* supertypes[];");
751     outclassdefs.println("");
752   }
753
754   /** Prints out definitions for generic task structures */
755
756   protected void outputTaskTypes(PrintWriter outtask) {
757     outtask.println("#ifndef _TASK_H");
758     outtask.println("#define _TASK_H");
759     outtask.println("struct parameterdescriptor {");
760     outtask.println("int type;");
761     outtask.println("int numberterms;");
762     outtask.println("int *intarray;");
763     outtask.println("void * queue;");
764     outtask.println("int numbertags;");
765     outtask.println("int *tagarray;");
766     outtask.println("};");
767
768     outtask.println("struct taskdescriptor {");
769     outtask.println("void * taskptr;");
770     outtask.println("int numParameters;");
771     outtask.println("  int numTotal;");
772     outtask.println("struct parameterdescriptor **descriptorarray;");
773     outtask.println("char * name;");
774     outtask.println("};");
775     outtask.println("extern struct taskdescriptor * taskarray[];");
776     outtask.println("extern numtasks;");
777     outtask.println("#endif");
778   }
779
780
781   protected void buildRepairStructs(PrintWriter outrepairstructs) {
782     Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
783     while(classit.hasNext()) {
784       ClassDescriptor cn=(ClassDescriptor)classit.next();
785       outrepairstructs.println("structure "+cn.getSymbol()+" {");
786       outrepairstructs.println("  int __type__;");
787       if (state.TASK) {
788         outrepairstructs.println("  int __flag__;");
789         if(!state.MULTICORE) {
790           outrepairstructs.println("  int __flagptr__;");
791         }
792       }
793       printRepairStruct(cn, outrepairstructs);
794       outrepairstructs.println("}\n");
795     }
796
797     for(int i=0; i<state.numArrays(); i++) {
798       TypeDescriptor tdarray=arraytable[i];
799       TypeDescriptor tdelement=tdarray.dereference();
800       outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
801       outrepairstructs.println("  int __type__;");
802       printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
803       outrepairstructs.println("  int length;");
804       outrepairstructs.println("}\n");
805     }
806   }
807
808   protected void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
809     ClassDescriptor sp=cn.getSuperDesc();
810     if (sp!=null)
811       printRepairStruct(sp, output);
812
813     Vector fields=(Vector)fieldorder.get(cn);
814
815     for(int i=0; i<fields.size(); i++) {
816       FieldDescriptor fd=(FieldDescriptor)fields.get(i);
817       if (fd.getType().isArray()) {
818         output.println("  "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
819       } else if (fd.getType().isClass())
820         output.println("  "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
821       else if (fd.getType().isFloat())
822         output.println("  int "+fd.getSymbol()+"; /* really float */");
823       else
824         output.println("  "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
825     }
826   }
827
828   /** This method outputs TaskDescriptor information */
829   protected void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
830     for (int i=0; i<task.numParameters(); i++) {
831       VarDescriptor param_var=task.getParameter(i);
832       TypeDescriptor param_type=task.getParamType(i);
833       FlagExpressionNode param_flag=task.getFlag(param_var);
834       TagExpressionList param_tag=task.getTag(param_var);
835
836       int dnfterms;
837       if (param_flag==null) {
838         output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
839         output.println("0x0, 0x0 };");
840         dnfterms=1;
841       } else {
842         DNFFlag dflag=param_flag.getDNF();
843         dnfterms=dflag.size();
844
845         Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
846         output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
847         for(int j=0; j<dflag.size(); j++) {
848           if (j!=0)
849             output.println(",");
850           Vector term=dflag.get(j);
851           int andmask=0;
852           int checkmask=0;
853           for(int k=0; k<term.size(); k++) {
854             DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
855             FlagDescriptor fd=dfa.getFlag();
856             boolean negated=dfa.getNegated();
857             int flagid=1<<((Integer)flags.get(fd)).intValue();
858             andmask|=flagid;
859             if (!negated)
860               checkmask|=flagid;
861           }
862           output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
863         }
864         output.println("};");
865       }
866
867       output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
868       if (param_tag!=null)
869         for(int j=0; j<param_tag.numTags(); j++) {
870           if (j!=0)
871             output.println(",");
872           /* for each tag we need */
873           /* which slot it is */
874           /* what type it is */
875           TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
876           TempDescriptor tmp=param_tag.getTemp(j);
877           int slot=fm.getTagInt(tmp);
878           output.println(slot+", "+state.getTagId(tvd.getTag()));
879         }
880       output.println("};");
881
882       output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
883       output.println("/* type */"+param_type.getClassDesc().getId()+",");
884       output.println("/* number of DNF terms */"+dnfterms+",");
885       output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
886       output.println("0,");
887       if (param_tag!=null)
888         output.println("/* number of tags */"+param_tag.numTags()+",");
889       else
890         output.println("/* number of tags */ 0,");
891       output.println("parametertag_"+i+"_"+task.getSafeSymbol());
892       output.println("};");
893     }
894
895
896     output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
897     for (int i=0; i<task.numParameters(); i++) {
898       if (i!=0)
899         output.println(",");
900       output.print("&parameter_"+i+"_"+task.getSafeSymbol());
901     }
902     output.println("};");
903
904     output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
905     output.println("&"+task.getSafeSymbol()+",");
906     output.println("/* number of parameters */" +task.numParameters() + ",");
907     int numtotal=task.numParameters()+fm.numTags();
908     output.println("/* number total parameters */" +numtotal + ",");
909     output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
910     output.println("\""+task.getSymbol()+"\"");
911     output.println("};");
912   }
913
914
915   /** The buildVirtualTables method outputs the virtual dispatch
916    * tables for methods. */
917
918   protected void buildVirtualTables(PrintWriter outvirtual) {
919     Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
920     while(classit.hasNext()) {
921       ClassDescriptor cd=(ClassDescriptor)classit.next();
922       if (virtualcalls.getMethodCount(cd)>maxcount)
923         maxcount=virtualcalls.getMethodCount(cd);
924     }
925     MethodDescriptor[][] virtualtable=null;
926     virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
927
928     /* Fill in virtual table */
929     classit=state.getClassSymbolTable().getDescriptorsIterator();
930     while(classit.hasNext()) {
931       ClassDescriptor cd=(ClassDescriptor)classit.next();
932       if(cd.isInterface()) {
933         continue;
934       }        
935       fillinRow(cd, virtualtable, cd.getId());
936     }
937
938     ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
939     Iterator arrayit=state.getArrayIterator();
940     while(arrayit.hasNext()) {
941       TypeDescriptor td=(TypeDescriptor)arrayit.next();
942       int id=state.getArrayNumber(td);
943       fillinRow(objectcd, virtualtable, id+state.numClasses());
944     }
945
946     outvirtual.print("void * virtualtable[]={");
947     boolean needcomma=false;
948     for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
949       for(int j=0; j<maxcount; j++) {
950         if (needcomma)
951           outvirtual.print(", ");
952         if (virtualtable[i][j]!=null) {
953           MethodDescriptor md=virtualtable[i][j];
954           outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
955         } else {
956           outvirtual.print("0");
957         }
958         needcomma=true;
959       }
960       outvirtual.println("");
961     }
962     outvirtual.println("};");
963     outvirtual.close();
964   }
965
966   protected void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
967     /* Get inherited methods */
968     Iterator it_sifs = cd.getSuperInterfaces();
969     while(it_sifs.hasNext()) {
970       ClassDescriptor superif = (ClassDescriptor)it_sifs.next();
971       fillinRow(superif, virtualtable, rownum);
972     }
973     if (cd.getSuperDesc()!=null)
974       fillinRow(cd.getSuperDesc(), virtualtable, rownum);
975     /* Override them with our methods */
976     for(Iterator it=cd.getMethods(); it.hasNext(); ) {
977       MethodDescriptor md=(MethodDescriptor)it.next();
978       if (md.isStatic()||md.getReturnType()==null)
979         continue;
980       boolean foundmatch = false;
981       if(this.state.genAllMethods) {
982         foundmatch = true;
983       } else {
984         Set vec_md = this.state.getMethod2gen().getSet(md.getSymbol());
985         for(Iterator matchit=vec_md.iterator(); matchit.hasNext();) {
986           MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
987           if (md.matches(matchmd)) {
988             foundmatch=true;
989             break;
990           }
991         }
992       }
993       if(!foundmatch) {
994         continue;
995       }
996       int methodnum = virtualcalls.getMethodNumber(md);
997       virtualtable[rownum][methodnum]=md;
998     }
999   }
1000
1001   /** Generate array that contains the sizes of class objects.  The
1002    * object allocation functions in the runtime use this
1003    * information. */
1004
1005   protected void generateSizeArray(PrintWriter outclassdefs) {
1006     outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
1007     generateSizeArrayExtensions(outclassdefs);
1008
1009     Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1010     cdarray=new ClassDescriptor[state.numClasses()];
1011     ifarray = new ClassDescriptor[state.numInterfaces()];
1012     cdarray[0] = null;
1013     int interfaceid = 0;
1014     while(it.hasNext()) {
1015       ClassDescriptor cd=(ClassDescriptor)it.next();
1016       if(cd.isInterface()) {
1017         ifarray[cd.getId()] = cd;
1018       } else {
1019         cdarray[cd.getId()] = cd;
1020       }
1021     }
1022
1023     arraytable=new TypeDescriptor[state.numArrays()];
1024
1025     Iterator arrayit=state.getArrayIterator();
1026     while(arrayit.hasNext()) {
1027       TypeDescriptor td=(TypeDescriptor)arrayit.next();
1028       int id=state.getArrayNumber(td);
1029       arraytable[id]=td;
1030     }
1031
1032     /* Print out types */
1033     outclassdefs.println("/* ");
1034     for(int i=0; i<state.numClasses(); i++) {
1035       ClassDescriptor cd=cdarray[i];
1036       if(cd == null) {
1037         outclassdefs.println("NULL " + i);
1038       } else {
1039         outclassdefs.println(cd +"  "+i);
1040       }
1041     }
1042
1043     for(int i=0; i<state.numArrays(); i++) {
1044       TypeDescriptor arraytd=arraytable[i];
1045       outclassdefs.println(arraytd.toPrettyString() +"  "+(i+state.numClasses()));
1046     }
1047     
1048     for(int i=0; i<state.numInterfaces(); i++) {
1049       ClassDescriptor ifcd = ifarray[i];
1050       outclassdefs.println(ifcd +"  "+(i+state.numClasses()+state.numArrays()));
1051     }
1052
1053     outclassdefs.println("*/");
1054
1055
1056     outclassdefs.print("int classsize[]={");
1057
1058     boolean needcomma=false;
1059     for(int i=0; i<state.numClasses(); i++) {
1060       if (needcomma)
1061         outclassdefs.print(", ");
1062       if(i>0) {
1063         outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1064       } else {
1065         outclassdefs.print("0");
1066       }
1067       needcomma=true;
1068     }
1069
1070
1071     for(int i=0; i<state.numArrays(); i++) {
1072       if (needcomma)
1073         outclassdefs.print(", ");
1074       TypeDescriptor tdelement=arraytable[i].dereference();
1075       if (tdelement.isArray()||tdelement.isClass()||tdelement.isNull())
1076         outclassdefs.print("sizeof(void *)");
1077       else
1078         outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1079       needcomma=true;
1080     }
1081     
1082     for(int i=0; i<state.numInterfaces(); i++) {
1083       if (needcomma)
1084         outclassdefs.print(", ");
1085       outclassdefs.print("sizeof(struct "+ifarray[i].getSafeSymbol()+")");
1086       needcomma=true;
1087     }
1088
1089     outclassdefs.println("};");
1090
1091     ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1092     needcomma=false;
1093     outclassdefs.print("int typearray[]={");
1094     for(int i=0; i<state.numClasses(); i++) {
1095       ClassDescriptor cd=cdarray[i];
1096       ClassDescriptor supercd=i>0 ? cd.getSuperDesc() : null;
1097       if(supercd != null && supercd.isInterface()) {
1098         throw new Error("Super class can not be interfaces");
1099       }
1100       if (needcomma)
1101         outclassdefs.print(", ");
1102       if (supercd==null)
1103         outclassdefs.print("-1");
1104       else
1105         outclassdefs.print(supercd.getId());
1106       needcomma=true;
1107     }
1108
1109     for(int i=0; i<state.numArrays(); i++) {
1110       TypeDescriptor arraytd=arraytable[i];
1111       ClassDescriptor arraycd=arraytd.getClassDesc();
1112       if (arraycd==null) {
1113         if (needcomma)
1114           outclassdefs.print(", ");
1115         outclassdefs.print(objectclass.getId());
1116         needcomma=true;
1117         continue;
1118       }
1119       ClassDescriptor cd=arraycd.getSuperDesc();
1120       int type=-1;
1121       while(cd!=null) {
1122         TypeDescriptor supertd=new TypeDescriptor(cd);
1123         supertd.setArrayCount(arraytd.getArrayCount());
1124         type=state.getArrayNumber(supertd);
1125         if (type!=-1) {
1126           type+=state.numClasses();
1127           break;
1128         }
1129         cd=cd.getSuperDesc();
1130       }
1131       if (needcomma)
1132         outclassdefs.print(", ");
1133       outclassdefs.print(type);
1134       needcomma=true;
1135     }
1136     
1137     for(int i=0; i<state.numInterfaces(); i++) {
1138       ClassDescriptor cd=ifarray[i];
1139       ClassDescriptor supercd=cd.getSuperDesc();
1140       if(supercd != null && supercd.isInterface()) {
1141         throw new Error("Super class can not be interfaces");
1142       }
1143       if (needcomma)
1144     outclassdefs.print(", ");
1145       if (supercd==null)
1146     outclassdefs.print("-1");
1147       else
1148     outclassdefs.print(supercd.getId());
1149       needcomma=true;
1150     }
1151
1152     outclassdefs.println("};");
1153
1154     needcomma=false;
1155
1156
1157     outclassdefs.print("int typearray2[]={");
1158     for(int i=0; i<state.numArrays(); i++) {
1159       TypeDescriptor arraytd=arraytable[i];
1160       ClassDescriptor arraycd=arraytd.getClassDesc();
1161       if (arraycd==null) {
1162         if (needcomma)
1163           outclassdefs.print(", ");
1164         outclassdefs.print("-1");
1165         needcomma=true;
1166         continue;
1167       }
1168       ClassDescriptor cd=arraycd.getSuperDesc();
1169       int level=arraytd.getArrayCount()-1;
1170       int type=-1;
1171       for(; level>0; level--) {
1172         TypeDescriptor supertd=new TypeDescriptor(objectclass);
1173         supertd.setArrayCount(level);
1174         type=state.getArrayNumber(supertd);
1175         if (type!=-1) {
1176           type+=state.numClasses();
1177           break;
1178         }
1179       }
1180       if (needcomma)
1181         outclassdefs.print(", ");
1182       outclassdefs.print(type);
1183       needcomma=true;
1184     }
1185
1186     outclassdefs.println("};");
1187   }
1188
1189   /** Constructs params and temp objects for each method or task.
1190    * These objects tell the compiler which temps need to be
1191    * allocated.  */
1192
1193   protected void generateTempStructs(FlatMethod fm) {
1194     MethodDescriptor md=fm.getMethod();
1195     TaskDescriptor task=fm.getTask();
1196     ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1197     if (md!=null)
1198       paramstable.put(md, objectparams);
1199     else
1200       paramstable.put(task, objectparams);
1201
1202     for(int i=0; i<fm.numParameters(); i++) {
1203       TempDescriptor temp=fm.getParameter(i);
1204       TypeDescriptor type=temp.getType();
1205       if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1206         objectparams.addPtr(temp);
1207       else
1208         objectparams.addPrim(temp);
1209     }
1210
1211     for(int i=0; i<fm.numTags(); i++) {
1212       TempDescriptor temp=fm.getTag(i);
1213       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1214         objectparams.addPtr(temp);
1215       else
1216         objectparams.addPrim(temp);
1217     }
1218
1219     TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1220     if (md!=null)
1221       tempstable.put(md, objecttemps);
1222     else
1223       tempstable.put(task, objecttemps);
1224
1225     for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext(); ) {
1226       FlatNode fn=(FlatNode)nodeit.next();
1227       TempDescriptor[] writes=fn.writesTemps();
1228       for(int i=0; i<writes.length; i++) {
1229         TempDescriptor temp=writes[i];
1230         TypeDescriptor type=temp.getType();
1231         if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1232           objecttemps.addPtr(temp);
1233         else
1234           objecttemps.addPrim(temp);
1235       }
1236     }
1237   }
1238
1239   /** This method outputs the following information about classes
1240    * and arrays:
1241    * (1) For classes, what are the locations of pointers.
1242    * (2) For arrays, does the array contain pointers or primitives.
1243    * (3) For classes, does the class contain flags.
1244    */
1245
1246   protected void generateLayoutStructs(PrintWriter output) {
1247     Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1248     while(it.hasNext()) {
1249       ClassDescriptor cn=(ClassDescriptor)it.next();
1250       output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1251       Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1252       int count=0;
1253       while(allit.hasNext()) {
1254         FieldDescriptor fd=(FieldDescriptor)allit.next();
1255     if(fd.isStatic()) {
1256       continue;
1257     }
1258         TypeDescriptor type=fd.getType();
1259         if (type.isPtr())
1260           count++;
1261       }
1262       output.print(count);
1263       allit=cn.getFieldTable().getAllDescriptorsIterator();
1264       while(allit.hasNext()) {
1265         FieldDescriptor fd=(FieldDescriptor)allit.next();
1266     if(fd.isStatic()) {
1267       continue;
1268     }
1269         TypeDescriptor type=fd.getType();
1270         if (type.isPtr()) {
1271           output.println(",");
1272           output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+
1273                        fd.getSafeSymbol()+"))");
1274         }
1275       }
1276       output.println("};");
1277     }
1278     output.println("unsigned INTPTR * pointerarray[]={");
1279     boolean needcomma=false;
1280     for(int i=0; i<state.numClasses(); i++) {
1281       ClassDescriptor cn=cdarray[i];
1282       if (needcomma)
1283         output.println(",");
1284       needcomma=true;
1285       if(cn != null) {
1286         output.print(cn.getSafeSymbol()+"_pointers");
1287       } else {
1288         output.print("NULL");
1289       }
1290     }
1291
1292     for(int i=0; i<state.numArrays(); i++) {
1293       if (needcomma)
1294         output.println(", ");
1295       TypeDescriptor tdelement=arraytable[i].dereference();
1296       if (tdelement.isArray()||tdelement.isClass())
1297         output.print("((unsigned INTPTR *)1)");
1298       else
1299         output.print("0");
1300       needcomma=true;
1301     }
1302
1303     output.println("};");
1304     needcomma=false;
1305     output.println("int hasflags[]={");
1306     for(int i=0; i<state.numClasses(); i++) {
1307       ClassDescriptor cn=cdarray[i];
1308       if (needcomma)
1309         output.println(", ");
1310       needcomma=true;
1311       if ((cn != null) && (cn.hasFlags()))
1312         output.print("1");
1313       else
1314         output.print("0");
1315     }
1316     output.println("};");
1317   }
1318   
1319   private int checkarraysupertype(ClassDescriptor arraycd, TypeDescriptor arraytd) {
1320     int type=-1;
1321     
1322     TypeDescriptor supertd=new TypeDescriptor(arraycd);
1323     supertd.setArrayCount(arraytd.getArrayCount());
1324     type=state.getArrayNumber(supertd);
1325     if (type!=-1) {
1326       return type;
1327     }
1328     
1329     ClassDescriptor cd = arraycd.getSuperDesc();
1330     if(cd != null) {
1331       type = checkarraysupertype(cd, arraytd);
1332       if(type != -1) {
1333         return type;
1334       }
1335     }
1336
1337     Iterator it_sifs = arraycd.getSuperInterfaces();
1338     while(it_sifs.hasNext()) {
1339       ClassDescriptor ifcd = (ClassDescriptor)it_sifs.next();
1340       type = checkarraysupertype(ifcd, arraytd);
1341       if(type != -1) {
1342         return type;
1343       }
1344     }
1345     
1346     return type;
1347   }
1348
1349
1350   /** Print out table to give us supertypes */
1351   protected void generateSuperTypeTable(PrintWriter output) {
1352     ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1353     for(int i=0; i<state.numClasses(); i++) {
1354       ClassDescriptor cn=cdarray[i];
1355       if(cn == null) {
1356         continue;
1357       }
1358       output.print("int supertypes" + cn.getSafeSymbol() + "[] = {");
1359       boolean ncomma = false;
1360       int snum = 0;
1361       if((cn != null) && (cn.getSuperDesc() != null)) {
1362         snum++;
1363       }
1364       Iterator it_sifs = cn != null? cn.getSuperInterfaces() : null;
1365       while(it_sifs != null && it_sifs.hasNext()) {
1366         snum++;
1367         it_sifs.next();
1368       }
1369       output.print(snum);
1370       ncomma = true;
1371       if ((cn != null) && (cn.getSuperDesc()!=null)) {
1372         if(ncomma) {
1373           output.print(",");
1374         }
1375         ClassDescriptor cdsuper=cn.getSuperDesc();
1376         output.print(cdsuper.getId());
1377       } 
1378       it_sifs = cn != null? cn.getSuperInterfaces() : null;
1379       while(it_sifs != null && it_sifs.hasNext()) {
1380         if(ncomma) {
1381           output.print(",");
1382         }
1383         output.print(((ClassDescriptor)it_sifs.next()).getId()+state.numClasses()+state.numArrays());
1384       }
1385       
1386       output.println("};");
1387     }
1388     
1389     for(int i=0; i<state.numArrays(); i++) {
1390       TypeDescriptor arraytd=arraytable[i];
1391       ClassDescriptor arraycd=arraytd.getClassDesc();
1392       output.print("int supertypes___arraytype___" + (i+state.numClasses()) + "[] = {");
1393       boolean ncomma = false;
1394       int snum = 0;
1395       if (arraycd==null) {
1396         snum++;
1397         output.print(snum);
1398         output.print(", ");
1399         output.print(objectclass.getId());
1400         output.println("};");
1401         continue;
1402       }
1403       if((arraycd != null) && (arraycd.getSuperDesc() != null)) {
1404         snum++;
1405       }
1406       Iterator it_sifs = arraycd != null? arraycd.getSuperInterfaces() : null;
1407       while(it_sifs != null && it_sifs.hasNext()) {
1408         snum++;
1409         it_sifs.next();
1410       }
1411       output.print(snum);
1412       ncomma = true;
1413       if ((arraycd != null) && (arraycd.getSuperDesc()!=null)) {
1414         ClassDescriptor cd=arraycd.getSuperDesc();
1415         int type=-1;
1416         if(cd!=null) {
1417           type = checkarraysupertype(cd, arraytd);
1418           if(type != -1) {
1419             type += state.numClasses();
1420           }
1421         }
1422         if (ncomma)
1423           output.print(", ");
1424         output.print(type);
1425       } 
1426       it_sifs = arraycd != null? arraycd.getSuperInterfaces() : null;
1427       while(it_sifs != null && it_sifs.hasNext()) {
1428         ClassDescriptor ifcd = (ClassDescriptor)it_sifs.next();
1429         int type = checkarraysupertype(ifcd , arraytd);
1430         if(type != -1) {
1431           type += state.numClasses();
1432         }
1433         if (ncomma)
1434           output.print(", ");
1435         output.print(type);
1436       }
1437       output.println("};");
1438     }
1439     
1440     for(int i=0; i<state.numInterfaces(); i++) {
1441       ClassDescriptor cn=ifarray[i];
1442       if(cn == null) {
1443         continue;
1444       }
1445       output.print("int supertypes" + cn.getSafeSymbol() + "[] = {");
1446       boolean ncomma = false;
1447       int snum = 0;
1448       if((cn != null) && (cn.getSuperDesc() != null)) {
1449         snum++;
1450       }
1451       Iterator it_sifs = cn != null? cn.getSuperInterfaces() : null;
1452       while(it_sifs != null && it_sifs.hasNext()) {
1453         snum++;
1454         it_sifs.next();
1455       }
1456       output.print(snum);
1457       ncomma = true;
1458       if ((cn != null) && (cn.getSuperDesc()!=null)) {
1459         if(ncomma) {
1460           output.print(",");
1461         }
1462         ClassDescriptor cdsuper=cn.getSuperDesc();
1463         output.print(cdsuper.getId());
1464       } 
1465       it_sifs = cn != null? cn.getSuperInterfaces() : null;
1466       while(it_sifs != null && it_sifs.hasNext()) {
1467         if(ncomma) {
1468           output.print(",");
1469         }
1470         output.print(((ClassDescriptor)it_sifs.next()).getId()+state.numClasses()+state.numArrays());
1471       }
1472       
1473       output.println("};");
1474     }
1475     
1476     output.println("int* supertypes[]={");
1477     boolean needcomma=false;
1478     for(int i=0; i<state.numClasses(); i++) {
1479       ClassDescriptor cn=cdarray[i];
1480       if (needcomma)
1481         output.println(",");
1482       needcomma=true;
1483       if(cn != null) {
1484         output.print("supertypes" + cn.getSafeSymbol());
1485       } else {
1486         output.print(0);
1487       }
1488     }
1489     
1490     for(int i=0; i<state.numArrays(); i++) {
1491       if (needcomma)
1492         output.println(",");
1493       needcomma = true;
1494       output.print("supertypes___arraytype___" + (i+state.numClasses()));
1495     }
1496     
1497     for(int i=0; i<state.numInterfaces(); i++) {
1498       ClassDescriptor cn=ifarray[i];
1499       if (needcomma)
1500     output.println(",");
1501       needcomma=true;
1502       output.print("supertypes" + cn.getSafeSymbol());
1503     }
1504     output.println("};");
1505   }
1506
1507   /** Force consistent field ordering between inherited classes. */
1508
1509   protected void printClassStruct(ClassDescriptor cn, PrintWriter classdefout, PrintWriter globaldefout, PrintWriter globaldefprimout) {
1510
1511     ClassDescriptor sp=cn.getSuperDesc();
1512     if (sp!=null)
1513       printClassStruct(sp, classdefout, /*globaldefout*/ null, null);
1514
1515     SymbolTable sitbl = cn.getSuperInterfaceTable();
1516     Iterator it_sifs = sitbl.getDescriptorsIterator();
1517     while(it_sifs.hasNext()) {
1518       ClassDescriptor si = (ClassDescriptor)it_sifs.next();
1519       printClassStruct(si, classdefout, /*globaldefout*/ null, null);
1520     }
1521
1522     if (!fieldorder.containsKey(cn)) {
1523       Vector fields=new Vector();
1524       fieldorder.put(cn,fields);
1525
1526       Vector fieldvec=cn.getFieldVec();
1527       for(int i=0; i<fieldvec.size(); i++) {
1528         FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1529         if((sp != null) && sp.getFieldTable().contains(fd.getSymbol())) {
1530           // a shadow field
1531         } else {
1532           it_sifs = sitbl.getDescriptorsIterator();
1533           boolean hasprinted = false;
1534           while(it_sifs.hasNext()) {
1535             ClassDescriptor si = (ClassDescriptor)it_sifs.next();
1536             if(si.getFieldTable().contains(fd.getSymbol())) {
1537               hasprinted = true;
1538               break;
1539             }
1540           }
1541           if(hasprinted) {
1542             // this field has been defined in the super class
1543           } else {
1544             fields.add(fd);
1545           }
1546         }
1547       }
1548     }
1549     //Vector fields=(Vector)fieldorder.get(cn);
1550
1551     Vector fields = cn.getFieldVec();
1552
1553     for(int i=0; i<fields.size(); i++) {
1554       FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1555       String fstring = fd.getSafeSymbol();
1556       if(printedfieldstbl.containsKey(fstring)) {
1557         printedfieldstbl.put(fstring, cn);
1558         continue;
1559       } else {
1560         printedfieldstbl.put(fstring, cn);
1561       }
1562       if (fd.getType().isClass()
1563           && fd.getType().getClassDesc().isEnum()) {
1564         classdefout.println("  int " + fd.getSafeSymbol() + ";");
1565       } else if (fd.getType().isClass()||fd.getType().isArray()) {
1566         if (fd.isStatic()) {
1567           // TODO add version for normal Java later
1568           // static field
1569           if(globaldefout != null) {
1570             if(fd.isVolatile()) {
1571               globaldefout.println("  volatile struct "+fd.getType().getSafeSymbol()+ " * "+fd.getSafeSymbol()+";");
1572             } else {
1573               globaldefout.println("  struct "+fd.getType().getSafeSymbol()+ " * "+fd.getSafeSymbol()+";");
1574             }
1575             globaldefscount++;
1576           }
1577         } else if (fd.isVolatile()) {
1578           //volatile field
1579           classdefout.println("  volatile struct "+fd.getType().getSafeSymbol()+ " * "+fd.getSafeSymbol()+";");
1580         } else {
1581           classdefout.println("  struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1582         }
1583       } else if (fd.isStatic()) {
1584         // TODO add version for normal Java later
1585         // static field
1586         if(globaldefout != null) {
1587           if(fd.isVolatile()) {
1588             globaldefprimout.println("  volatile "+fd.getType().getSafeSymbol()+ " "+fd.getSafeSymbol()+";");
1589           } else {
1590             globaldefprimout.println("  "+fd.getType().getSafeSymbol()+ " "+fd.getSafeSymbol()+";");
1591           }
1592         }
1593       } else if (fd.isVolatile()) {
1594         //volatile field
1595         classdefout.println("  volatile "+fd.getType().getSafeSymbol()+ " "+fd.getSafeSymbol()+";");
1596       } else
1597         classdefout.println("  "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1598     }
1599   }
1600
1601
1602   /* Map flags to integers consistently between inherited
1603    * classes. */
1604
1605   protected void mapFlags(ClassDescriptor cn) {
1606     ClassDescriptor sp=cn.getSuperDesc();
1607     if (sp!=null)
1608       mapFlags(sp);
1609     int max=0;
1610     if (!flagorder.containsKey(cn)) {
1611       Hashtable flags=new Hashtable();
1612       flagorder.put(cn,flags);
1613       if (sp!=null) {
1614         Hashtable superflags=(Hashtable)flagorder.get(sp);
1615         Iterator superflagit=superflags.keySet().iterator();
1616         while(superflagit.hasNext()) {
1617           FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1618           Integer number=(Integer)superflags.get(fd);
1619           flags.put(fd, number);
1620           if ((number.intValue()+1)>max)
1621             max=number.intValue()+1;
1622         }
1623       }
1624
1625       Iterator flagit=cn.getFlags();
1626       while(flagit.hasNext()) {
1627         FlagDescriptor fd=(FlagDescriptor)flagit.next();
1628         if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1629           flags.put(fd, new Integer(max++));
1630       }
1631     }
1632   }
1633
1634
1635   /** This function outputs (1) structures that parameters are
1636    * passed in (when PRECISE GC is enabled) and (2) function
1637    * prototypes for the methods */
1638
1639   protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout, PrintWriter globaldefout, PrintWriter globaldefprimout) {
1640     /* Output class structure */
1641     classdefout.println("struct "+cn.getSafeSymbol()+" {");
1642     classdefout.println("  int type;");
1643
1644
1645     additionalClassObjectFields(classdefout);
1646
1647
1648     if (state.EVENTMONITOR) {
1649       classdefout.println("  int objuid;");
1650     }
1651     if (state.THREAD) {
1652       classdefout.println("  pthread_t tid;");
1653       classdefout.println("  void * lockentry;");
1654       classdefout.println("  int lockcount;");
1655     }
1656     if (state.MGC) {
1657       classdefout.println("  int mutex;");
1658       classdefout.println("  volatile int notifycount;");
1659       classdefout.println("  volatile int objlock;");
1660       if(state.MULTICOREGC) {
1661         classdefout.println("  int marked;");
1662       }
1663     }
1664     if (state.TASK) {
1665       classdefout.println("  int flag;");
1666       if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1667         classdefout.println("  void * flagptr;");
1668       } else if (state.MULTICORE) {
1669         classdefout.println("  int version;");
1670         classdefout.println("  int * lock;"); // lock entry for this obj
1671         classdefout.println("  int mutex;");
1672         classdefout.println("  int lockcount;");
1673         if(state.MULTICOREGC) {
1674           classdefout.println("  int marked;");
1675         }
1676       }
1677       if (state.OPTIONAL) {
1678         classdefout.println("  int numfses;");
1679         classdefout.println("  int * fses;");
1680       }
1681     }
1682     printClassStruct(cn, classdefout, globaldefout, globaldefprimout);
1683     printedfieldstbl.clear(); // = new Hashtable<String, ClassDescriptor>();
1684     classdefout.println("};\n");
1685     generateCallStructsMethods(cn, output, headersout);
1686   }
1687
1688
1689   protected void generateCallStructsMethods(ClassDescriptor cn, PrintWriter output, PrintWriter headersout) {
1690     for(Iterator methodit=cn.getMethods(); methodit.hasNext(); ) {
1691       MethodDescriptor md=(MethodDescriptor)methodit.next();
1692       boolean foundmatch = false;
1693       if(this.state.genAllMethods) {
1694         foundmatch = true;
1695       } else {
1696         Set vec_md = this.state.getMethod2gen().getSet(md.getSymbol());
1697         for(Iterator matchit=vec_md.iterator(); matchit.hasNext();) {
1698           MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
1699           if (md.matches(matchmd)) {
1700             foundmatch=true;
1701             break;
1702           }
1703         }
1704       }
1705       if(foundmatch) {
1706         generateMethod(cn, md, headersout, output);
1707       }
1708     }
1709   }
1710
1711   protected void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, PrintWriter output) {
1712     /* Output parameter structure */
1713     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1714       if(md.isInvokedByStatic() && !md.isStaticBlock() && !md.getModifiers().isNative()) {
1715         // generate the staticinit version
1716         String mdstring = md.getSafeMethodDescriptor() + "staticinit";
1717         
1718         ParamsObject objectparams=(ParamsObject) paramstable.get(md);
1719         output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params {");
1720         output.println("  int size;");
1721         output.println("  void * next;");
1722         for(int i=0; i<objectparams.numPointers(); i++) {
1723           TempDescriptor temp=objectparams.getPointer(i);
1724           if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
1725             output.println("  int " + temp.getSafeSymbol() + ";");
1726           } else {
1727             output.println("  struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1728           }
1729         }
1730         output.println("};\n");
1731       }
1732       
1733       ParamsObject objectparams=(ParamsObject) paramstable.get(md);
1734       output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1735       output.println("  int size;");
1736       output.println("  void * next;");
1737       for(int i=0; i<objectparams.numPointers(); i++) {
1738         TempDescriptor temp=objectparams.getPointer(i);
1739         if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
1740           output.println("  int " + temp.getSafeSymbol() + ";");
1741         } else {
1742           output.println("  struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1743         }
1744       }
1745       output.println("};\n");
1746     }
1747   }
1748
1749   protected void generateMethod(ClassDescriptor cn, MethodDescriptor md, PrintWriter headersout, PrintWriter output) {
1750     FlatMethod fm=state.getMethodFlat(md);
1751     generateTempStructs(fm);
1752
1753     ParamsObject objectparams=(ParamsObject) paramstable.get(md);
1754     TempObject objecttemps=(TempObject) tempstable.get(md);
1755     
1756     boolean printcomma = false;
1757     
1758     generateMethodParam(cn, md, output);
1759     
1760     if(md.isInvokedByStatic() && !md.isStaticBlock() && !md.getModifiers().isNative()) {
1761       // generate the staticinit version
1762       String mdstring = md.getSafeMethodDescriptor() + "staticinit";
1763
1764       /* Output temp structure */
1765       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1766         output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_locals {");
1767         output.println("  int size;");
1768         output.println("  void * next;");
1769         for(int i=0; i<objecttemps.numPointers(); i++) {
1770           TempDescriptor temp=objecttemps.getPointer(i);
1771           if (!temp.getType().isArray() && temp.getType().isNull())
1772             output.println("  void * "+temp.getSafeSymbol()+";");
1773           else
1774             output.println("  struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1775         }
1776         output.println("};\n");
1777       }
1778       
1779       headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+" 1");
1780       /* First the return type */
1781       if (md.getReturnType()!=null) {
1782         if(md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) {
1783           headersout.println("  int ");
1784         } else if (md.getReturnType().isClass()||md.getReturnType().isArray())
1785           headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1786         else
1787           headersout.print(md.getReturnType().getSafeSymbol()+" ");
1788       } else
1789         //catch the constructor case
1790         headersout.print("void ");
1791
1792       /* Next the method name */
1793       headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"(");
1794       printcomma=false;
1795       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1796         headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params * "+paramsprefix);
1797         printcomma=true;
1798       }
1799
1800       /*  Output parameter list*/
1801       for(int i=0; i<objectparams.numPrimitives(); i++) {
1802         TempDescriptor temp=objectparams.getPrimitive(i);
1803         if (printcomma)
1804           headersout.print(", ");
1805         printcomma=true;
1806         if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
1807           headersout.print("int " + temp.getSafeSymbol());
1808         } else if (temp.getType().isClass()||temp.getType().isArray())
1809           headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1810         else
1811           headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1812       }
1813       headersout.println(");\n");
1814     }
1815
1816     /* Output temp structure */
1817     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1818       output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1819       output.println("  int size;");
1820       output.println("  void * next;");
1821       for(int i=0; i<objecttemps.numPointers(); i++) {
1822         TempDescriptor temp=objecttemps.getPointer(i);
1823         if (!temp.getType().isArray() && temp.getType().isNull())
1824           output.println("  void * "+temp.getSafeSymbol()+";");
1825         else
1826           output.println("  struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1827       }
1828       output.println("};\n");
1829     }
1830
1831     /********* Output method declaration ***********/
1832     headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1833     /* First the return type */
1834     if (md.getReturnType()!=null) {
1835       if(md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) {
1836         headersout.println("  int ");
1837       } else if (md.getReturnType().isClass()||md.getReturnType().isArray())
1838         headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1839       else
1840         headersout.print(md.getReturnType().getSafeSymbol()+" ");
1841     } else
1842       //catch the constructor case
1843       headersout.print("void ");
1844
1845     /* Next the method name */
1846     headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1847     printcomma=false;
1848     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1849       headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1850       printcomma=true;
1851     }
1852
1853     /*  Output parameter list*/
1854     for(int i=0; i<objectparams.numPrimitives(); i++) {
1855       TempDescriptor temp=objectparams.getPrimitive(i);
1856       if (printcomma)
1857         headersout.print(", ");
1858       printcomma=true;
1859       if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
1860         headersout.print("int " + temp.getSafeSymbol());
1861       } else if (temp.getType().isClass()||temp.getType().isArray())
1862         headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1863       else
1864         headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1865     }
1866     headersout.println(");\n");
1867   }
1868
1869
1870   /** This function outputs (1) structures that parameters are
1871    * passed in (when PRECISE GC is enabled) and (2) function
1872    * prototypes for the tasks */
1873
1874   protected void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1875     /* Cycle through tasks */
1876     Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1877
1878     while(taskit.hasNext()) {
1879       /* Classify parameters */
1880       TaskDescriptor task=(TaskDescriptor)taskit.next();
1881       FlatMethod fm=state.getMethodFlat(task);
1882       generateTempStructs(fm);
1883
1884       ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1885       TempObject objecttemps=(TempObject) tempstable.get(task);
1886
1887       /* Output parameter structure */
1888       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1889         output.println("struct "+task.getSafeSymbol()+"_params {");
1890         output.println("  int size;");
1891         output.println("  void * next;");
1892         for(int i=0; i<objectparams.numPointers(); i++) {
1893           TempDescriptor temp=objectparams.getPointer(i);
1894           output.println("  struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1895         }
1896
1897         output.println("};\n");
1898         if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1899           maxtaskparams=objectparams.numPointers()+fm.numTags();
1900         }
1901       }
1902
1903       /* Output temp structure */
1904       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1905         output.println("struct "+task.getSafeSymbol()+"_locals {");
1906         output.println("  int size;");
1907         output.println("  void * next;");
1908         for(int i=0; i<objecttemps.numPointers(); i++) {
1909           TempDescriptor temp=objecttemps.getPointer(i);
1910           if (!temp.getType().isArray() && temp.getType().isNull())
1911             output.println("  void * "+temp.getSafeSymbol()+";");
1912           else if(temp.getType().isTag())
1913             output.println("  struct "+
1914                            (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1915           else
1916             output.println("  struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1917         }
1918         output.println("};\n");
1919       }
1920
1921       /* Output task declaration */
1922       headersout.print("void " + task.getSafeSymbol()+"(");
1923
1924       boolean printcomma=false;
1925       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1926         headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1927       } else
1928         headersout.print("void * parameterarray[]");
1929       headersout.println(");\n");
1930     }
1931   }
1932
1933   protected void generateFlatMethod(FlatMethod fm, PrintWriter output) {
1934     if (State.PRINTFLAT)
1935       System.out.println(fm.printMethod());
1936     MethodDescriptor md=fm.getMethod();
1937     TaskDescriptor task=fm.getTask();
1938     ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1939     ParamsObject objectparams=(ParamsObject)paramstable.get(md!=null ? md : task);
1940     
1941     if((md != null) && md.isInvokedByStatic() && !md.isStaticBlock() && !md.getModifiers().isNative()) {
1942       // generate a special static init version
1943       mgcstaticinit = true;
1944       String mdstring = md.getSafeMethodDescriptor() + "staticinit";
1945       
1946       generateHeader(fm, md!=null ? md : task,output);
1947       TempObject objecttemp=(TempObject) tempstable.get(md!=null ? md : task);
1948       
1949       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1950         output.print("   struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_locals "+localsprefix+"={");
1951         output.print(objecttemp.numPointers()+",");
1952         output.print(paramsprefix);
1953         for(int j=0; j<objecttemp.numPointers(); j++)
1954           output.print(", NULL");
1955         output.println("};");
1956       }
1957
1958       for(int i=0; i<objecttemp.numPrimitives(); i++) {
1959         TempDescriptor td=objecttemp.getPrimitive(i);
1960         TypeDescriptor type=td.getType();
1961         if (type.isNull() && !type.isArray())
1962           output.println("   void * "+td.getSafeSymbol()+";");
1963         else if (type.isClass() && type.getClassDesc().isEnum()) {
1964           output.println("   int " + td.getSafeSymbol() + ";");
1965         } else if (type.isClass()||type.isArray())
1966           output.println("   struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1967         else
1968           output.println("   "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1969       }
1970
1971       additionalCodeAtTopFlatMethodBody(output, fm);
1972
1973       /* Check to see if we need to do a GC if this is a
1974        * multi-threaded program...*/
1975
1976       if (((state.OOOJAVA||state.THREAD)&&GENERATEPRECISEGC)
1977           || this.state.MULTICOREGC) {
1978         //Don't bother if we aren't in recursive methods...The loops case will catch it
1979         if (callgraph.getAllMethods(md).contains(md)) {
1980           if (this.state.MULTICOREGC) {
1981             output.println("if(gcflag) gc("+localsprefixaddr+");");
1982           } else {
1983             output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1984           }
1985         }
1986       }
1987       
1988       generateCode(fm.getNext(0), fm, null, output);
1989
1990       output.println("}\n\n");
1991       
1992       mgcstaticinit = false;
1993     }
1994     
1995     generateHeader(fm, md!=null ? md : task,output);
1996     TempObject objecttemp=(TempObject) tempstable.get(md!=null ? md : task);
1997
1998     if((md != null) && (md.isStaticBlock())) {
1999       mgcstaticinit = true;
2000     }
2001
2002     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2003       if (md!=null)
2004         output.print("   struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2005       else
2006         output.print("   struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
2007       output.print(objecttemp.numPointers()+",");
2008       output.print(paramsprefix);
2009       for(int j=0; j<objecttemp.numPointers(); j++)
2010         output.print(", NULL");
2011       output.println("};");
2012     }
2013
2014     for(int i=0; i<objecttemp.numPrimitives(); i++) {
2015       TempDescriptor td=objecttemp.getPrimitive(i);
2016       TypeDescriptor type=td.getType();
2017       if (type.isNull() && !type.isArray())
2018         output.println("   void * "+td.getSafeSymbol()+";");
2019       else if (type.isClass() && type.getClassDesc().isEnum()) {
2020         output.println("   int " + td.getSafeSymbol() + ";");
2021       } else if (type.isClass()||type.isArray())
2022         output.println("   struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2023       else
2024         output.println("   "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2025     }
2026
2027     additionalCodeAtTopFlatMethodBody(output, fm);
2028
2029     /* Check to see if we need to do a GC if this is a
2030      * multi-threaded program...*/
2031
2032     if (((state.OOOJAVA||state.THREAD)&&GENERATEPRECISEGC)
2033         || this.state.MULTICOREGC) {
2034       //Don't bother if we aren't in recursive methods...The loops case will catch it
2035       if (callgraph.getAllMethods(md).contains(md)) {
2036         if (this.state.MULTICOREGC) {
2037           output.println("if(gcflag) gc("+localsprefixaddr+");");
2038         } else {
2039           output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2040         }
2041       }
2042     }
2043
2044     if(fm.getMethod().isStaticBlock()) {
2045       // a static block, check if it has been executed
2046       output.println("  if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag != 0) {");
2047       output.println("    return;");
2048       output.println("  }");
2049       output.println("");
2050     }
2051
2052     generateCode(fm.getNext(0), fm, null, output);
2053
2054     output.println("}\n\n");
2055     
2056     mgcstaticinit = false;
2057   }
2058
2059   protected void generateCode(FlatNode first,
2060                               FlatMethod fm,
2061                               Set<FlatNode> stopset,
2062                               PrintWriter output) {
2063
2064     /* Assign labels to FlatNode's if necessary.*/
2065
2066     Hashtable<FlatNode, Integer> nodetolabel;
2067
2068     nodetolabel=assignLabels(first, stopset);
2069
2070     Set<FlatNode> storeset=null;
2071     HashSet<FlatNode> genset=null;
2072     HashSet<FlatNode> refset=null;
2073     Set<FlatNode> unionset=null;
2074
2075     /* Do the actual code generation */
2076     FlatNode current_node=null;
2077     HashSet tovisit=new HashSet();
2078     HashSet visited=new HashSet();
2079     tovisit.add(first);
2080     while(current_node!=null||!tovisit.isEmpty()) {
2081       if (current_node==null) {
2082         current_node=(FlatNode)tovisit.iterator().next();
2083         tovisit.remove(current_node);
2084       } else if (tovisit.contains(current_node)) {
2085         tovisit.remove(current_node);
2086       }
2087       visited.add(current_node);
2088       if (nodetolabel.containsKey(current_node)) {
2089         output.println("L"+nodetolabel.get(current_node)+":");
2090       }
2091       if (state.INSTRUCTIONFAILURE) {
2092         if (state.THREAD) {
2093           output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2094         } else
2095           output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2096       }
2097       if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2098         output.print("   ");
2099         generateFlatNode(fm, current_node, output);
2100
2101         if (state.OOOJAVA && stopset!=null) {
2102           assert first.getPrev(0) instanceof FlatSESEEnterNode;
2103           assert current_node       instanceof FlatSESEExitNode;
2104           FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev(0);
2105           FlatSESEExitNode fsxn = (FlatSESEExitNode)  current_node;
2106           assert fsen.getFlatExit().equals(fsxn);
2107           assert fsxn.getFlatEnter().equals(fsen);
2108         }
2109         if (current_node.kind()!=FKind.FlatReturnNode) {
2110           if((fm.getMethod() != null) && (fm.getMethod().isStaticBlock())) {
2111             // a static block, check if it has been executed
2112             output.println("  global_defsprim_p->" + fm.getMethod().getClassDesc().getSafeSymbol()+"static_block_exe_flag = 1;");
2113             output.println("");
2114           }
2115           output.println("   return;");
2116         }
2117         current_node=null;
2118       } else if(current_node.numNext()==1) {
2119         FlatNode nextnode;
2120         if (state.OOOJAVA &&
2121             current_node.kind()==FKind.FlatSESEEnterNode) {
2122           FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2123           generateFlatNode(fm, current_node, output);
2124           nextnode=fsen.getFlatExit().getNext(0);
2125         } else {
2126           output.print("   ");
2127           generateFlatNode(fm, current_node, output);
2128           nextnode=current_node.getNext(0);
2129         }
2130         if (visited.contains(nextnode)) {
2131           output.println("goto L"+nodetolabel.get(nextnode)+";");
2132           current_node=null;
2133         } else
2134           current_node=nextnode;
2135       } else if (current_node.numNext()==2) {
2136         /* Branch */
2137         output.print("   ");
2138         generateFlatCondBranch(fm, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2139         if (!visited.contains(current_node.getNext(1)))
2140           tovisit.add(current_node.getNext(1));
2141         if (visited.contains(current_node.getNext(0))) {
2142           output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2143           current_node=null;
2144         } else
2145           current_node=current_node.getNext(0);
2146       } else throw new Error();
2147     }
2148   }
2149
2150   protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2151     HashSet tovisit=new HashSet();
2152     HashSet visited=new HashSet();
2153     int labelindex=0;
2154     Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2155     tovisit.add(first);
2156
2157     /*Assign labels first.  A node needs a label if the previous
2158      * node has two exits or this node is a join point. */
2159
2160     while(!tovisit.isEmpty()) {
2161       FlatNode fn=(FlatNode)tovisit.iterator().next();
2162       tovisit.remove(fn);
2163       visited.add(fn);
2164
2165
2166       if(lastset!=null&&lastset.contains(fn)) {
2167         // if last is not null and matches, don't go
2168         // any further for assigning labels
2169         continue;
2170       }
2171
2172       for(int i=0; i<fn.numNext(); i++) {
2173         FlatNode nn=fn.getNext(i);
2174
2175         if(i>0) {
2176           //1) Edge >1 of node
2177           nodetolabel.put(nn,new Integer(labelindex++));
2178         }
2179         if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2180           tovisit.add(nn);
2181         } else {
2182           //2) Join point
2183           nodetolabel.put(nn,new Integer(labelindex++));
2184         }
2185       }
2186     }
2187     return nodetolabel;
2188   }
2189
2190   /** Generate text string that corresponds to the TempDescriptor td. */
2191   protected String generateTemp(FlatMethod fm, TempDescriptor td) {
2192     MethodDescriptor md=fm.getMethod();
2193     TaskDescriptor task=fm.getTask();
2194     TempObject objecttemps=(TempObject) tempstable.get(md!=null ? md : task);
2195
2196     if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2197       return td.getSafeSymbol();
2198     }
2199
2200     if (objecttemps.isLocalPtr(td)) {
2201       return localsprefixderef+td.getSafeSymbol();
2202     }
2203
2204     if (objecttemps.isParamPtr(td)) {
2205       return paramsprefix+"->"+td.getSafeSymbol();
2206     }
2207
2208     throw new Error();
2209   }
2210
2211
2212
2213   protected void generateFlatNode(FlatMethod fm, FlatNode fn, PrintWriter output) {
2214     if(state.LINENUM) printSourceLineNumber(fm,fn,output);
2215     additionalCodePreNode(fm, fn, output);
2216
2217     switch(fn.kind()) {
2218     case FKind.FlatAtomicEnterNode:
2219       generateFlatAtomicEnterNode(fm, (FlatAtomicEnterNode) fn, output);
2220       break;
2221
2222     case FKind.FlatAtomicExitNode:
2223       generateFlatAtomicExitNode(fm, (FlatAtomicExitNode) fn, output);
2224       break;
2225
2226     case FKind.FlatInstanceOfNode:
2227       generateFlatInstanceOfNode(fm, (FlatInstanceOfNode)fn, output);
2228       break;
2229
2230     case FKind.FlatSESEEnterNode:
2231       generateFlatSESEEnterNode(fm, (FlatSESEEnterNode)fn, output);
2232       break;
2233
2234     case FKind.FlatSESEExitNode:
2235       generateFlatSESEExitNode(fm, (FlatSESEExitNode)fn, output);
2236       break;
2237
2238     case FKind.FlatWriteDynamicVarNode:
2239       generateFlatWriteDynamicVarNode(fm, (FlatWriteDynamicVarNode)fn, output);
2240       break;
2241
2242     case FKind.FlatGlobalConvNode:
2243       generateFlatGlobalConvNode(fm, (FlatGlobalConvNode) fn, output);
2244       break;
2245
2246     case FKind.FlatTagDeclaration:
2247       generateFlatTagDeclaration(fm, (FlatTagDeclaration) fn,output);
2248       break;
2249
2250     case FKind.FlatCall:
2251       generateFlatCall(fm, (FlatCall) fn,output);
2252       break;
2253
2254     case FKind.FlatFieldNode:
2255       generateFlatFieldNode(fm, (FlatFieldNode) fn,output);
2256       break;
2257
2258     case FKind.FlatElementNode:
2259       generateFlatElementNode(fm, (FlatElementNode) fn,output);
2260       break;
2261
2262     case FKind.FlatSetElementNode:
2263       generateFlatSetElementNode(fm, (FlatSetElementNode) fn,output);
2264       break;
2265
2266     case FKind.FlatSetFieldNode:
2267       generateFlatSetFieldNode(fm, (FlatSetFieldNode) fn,output);
2268       break;
2269
2270     case FKind.FlatNew:
2271       generateFlatNew(fm, (FlatNew) fn,output);
2272       break;
2273
2274     case FKind.FlatOpNode:
2275       generateFlatOpNode(fm, (FlatOpNode) fn,output);
2276       break;
2277
2278     case FKind.FlatCastNode:
2279       generateFlatCastNode(fm, (FlatCastNode) fn,output);
2280       break;
2281
2282     case FKind.FlatLiteralNode:
2283       generateFlatLiteralNode(fm, (FlatLiteralNode) fn,output);
2284       break;
2285
2286     case FKind.FlatReturnNode:
2287       generateFlatReturnNode(fm, (FlatReturnNode) fn,output);
2288       break;
2289
2290     case FKind.FlatNop:
2291       output.println("/* nop */");
2292       break;
2293
2294     case FKind.FlatGenReachNode:
2295       // this node is just for generating a reach graph
2296       // in disjointness analysis at a particular program point
2297       break;
2298
2299     case FKind.FlatExit:
2300       output.println("/* exit */");
2301       break;
2302
2303     case FKind.FlatBackEdge:
2304       generateFlatBackEdge(fm, (FlatBackEdge)fn, output);
2305       break;
2306
2307     case FKind.FlatCheckNode:
2308       generateFlatCheckNode(fm, (FlatCheckNode) fn, output);
2309       break;
2310
2311     case FKind.FlatFlagActionNode:
2312       generateFlatFlagActionNode(fm, (FlatFlagActionNode) fn, output);
2313       break;
2314
2315     case FKind.FlatPrefetchNode:
2316       generateFlatPrefetchNode(fm, (FlatPrefetchNode) fn, output);
2317       break;
2318
2319     case FKind.FlatOffsetNode:
2320       generateFlatOffsetNode(fm, (FlatOffsetNode)fn, output);
2321       break;
2322
2323     default:
2324       throw new Error();
2325     }
2326
2327     additionalCodePostNode(fm, fn, output);
2328   }
2329
2330   public void generateFlatBackEdge(FlatMethod fm, FlatBackEdge fn, PrintWriter output) {
2331     if (((state.OOOJAVA||state.THREAD)&&GENERATEPRECISEGC)
2332         || (this.state.MULTICOREGC)) {
2333       if(this.state.MULTICOREGC) {
2334         output.println("if (gcflag) gc("+localsprefixaddr+");");
2335       } else {
2336         output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2337       }
2338     } else
2339       output.println("/* nop */");
2340   }
2341
2342   public void generateFlatOffsetNode(FlatMethod fm, FlatOffsetNode fofn, PrintWriter output) {
2343     output.println("/* FlatOffsetNode */");
2344     FieldDescriptor fd=fofn.getField();
2345     if(!fd.isStatic()) {
2346     output.println(generateTemp(fm, fofn.getDst())+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+
2347                    fd.getSafeSymbol()+");");
2348     }
2349     output.println("/* offset */");
2350   }
2351
2352   public void generateFlatPrefetchNode(FlatMethod fm, FlatPrefetchNode fpn, PrintWriter output) {
2353   }
2354
2355   public void generateFlatGlobalConvNode(FlatMethod fm, FlatGlobalConvNode fgcn, PrintWriter output) {
2356   }
2357
2358   public void generateFlatInstanceOfNode(FlatMethod fm,  FlatInstanceOfNode fion, PrintWriter output) {
2359     int type;
2360     int otype;
2361     if (fion.getType().isArray()) {
2362       type=state.getArrayNumber(fion.getType())+state.numClasses();
2363     } else if (fion.getType().getClassDesc().isInterface()) {
2364       type=fion.getType().getClassDesc().getId()+state.numClasses()+state.numArrays();
2365     } else {
2366       type=fion.getType().getClassDesc().getId();
2367     }
2368     if (fion.getSrc().getType().isArray()) {
2369       otype=state.getArrayNumber(fion.getSrc().getType())+state.numClasses();
2370     } else if (fion.getSrc().getType().getClassDesc().isInterface()) {
2371       otype=fion.getSrc().getType().getClassDesc().getId()+state.numClasses()+state.numArrays();
2372     } else {
2373       otype=fion.getSrc().getType().getClassDesc().getId();
2374     }
2375
2376     if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
2377       output.println(generateTemp(fm, fion.getDst())+"=(" + generateTemp(fm,fion.getSrc()) + "!= NULL);");
2378     else {
2379       output.println(generateTemp(fm, fion.getDst())+"=instanceof("+generateTemp(fm,fion.getSrc())+","+type+");");
2380     }
2381   }
2382
2383   public void generateFlatAtomicEnterNode(FlatMethod fm, FlatAtomicEnterNode faen, PrintWriter output) {
2384   }
2385
2386   public void generateFlatAtomicExitNode(FlatMethod fm,  FlatAtomicExitNode faen, PrintWriter output) {
2387   }
2388
2389   public void generateFlatSESEEnterNode(FlatMethod fm,
2390                                         FlatSESEEnterNode fsen,
2391                                         PrintWriter output) {
2392     // if OOOJAVA flag is off, okay that SESE nodes are in IR graph,
2393     // just skip over them and code generates exactly the same
2394   }
2395
2396   public void generateFlatSESEExitNode(FlatMethod fm,
2397                                        FlatSESEExitNode fsexn,
2398                                        PrintWriter output) {
2399     // if OOOJAVA flag is off, okay that SESE nodes are in IR graph,
2400     // just skip over them and code generates exactly the same
2401   }
2402
2403   public void generateFlatWriteDynamicVarNode(FlatMethod fm,
2404                                               FlatWriteDynamicVarNode fwdvn,
2405                                               PrintWriter output) {
2406   }
2407
2408
2409   protected void generateFlatCheckNode(FlatMethod fm,  FlatCheckNode fcn, PrintWriter output) {
2410     if (state.CONSCHECK) {
2411       String specname=fcn.getSpec();
2412       String varname="repairstate___";
2413       output.println("{");
2414       output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
2415
2416       TempDescriptor[] temps=fcn.getTemps();
2417       String[] vars=fcn.getVars();
2418       for(int i=0; i<temps.length; i++) {
2419         output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i])+";");
2420       }
2421
2422       output.println("if (doanalysis"+specname+"("+varname+")) {");
2423       output.println("free"+specname+"_state("+varname+");");
2424       output.println("} else {");
2425       output.println("/* Bad invariant */");
2426       output.println("free"+specname+"_state("+varname+");");
2427       output.println("abort_task();");
2428       output.println("}");
2429       output.println("}");
2430     }
2431   }
2432
2433   protected void generateFlatCall(FlatMethod fm, FlatCall fc, PrintWriter output) {
2434     MethodDescriptor md=fc.getMethod();
2435     ParamsObject objectparams=(ParamsObject)paramstable.get(md);
2436     ClassDescriptor cn=md.getClassDesc();
2437     String mdstring = md.getSafeMethodDescriptor();
2438     if(mgcstaticinit && !md.isStaticBlock() && !md.getModifiers().isNative()) {
2439       mdstring += "staticinit";
2440     }
2441
2442     // if the called method is a static block or a static method or a constructor
2443     // need to check if it can be invoked inside some static block
2444     if((md.isStatic() || md.isStaticBlock() || md.isConstructor()) &&
2445        ((fm.getMethod() != null) && ((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())))) {
2446       if(!md.isInvokedByStatic()) {
2447         System.err.println("Error: a method that is invoked inside a static block is not tagged!");
2448       }
2449       // is a static block or is invoked in some static block
2450       ClassDescriptor cd = fm.getMethod().getClassDesc();
2451       if(cd == cn) {
2452         // the same class, do nothing
2453       } else if(mgcstaticinit) {
2454         // generate static init check code if it has not done static init in main()
2455         if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
2456           // need to check if the class' static fields have been initialized and/or
2457           // its static blocks have been executed
2458           output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
2459           if(cn.getNumStaticBlocks() != 0) {
2460             MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
2461         if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2462           output.print("       struct "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={");
2463           output.println("0, NULL};");
2464           output.println("     "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);");
2465         } else {
2466           output.println("  "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
2467         }
2468           } else {
2469             output.println("  global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
2470           }
2471           output.println("}");
2472         }
2473       }
2474     }
2475     if((md.getSymbol().equals("MonitorEnter") || md.getSymbol().equals("MonitorExit")) && fc.getThis().getSymbol().equals("classobj")) {
2476       output.println("{");
2477       // call MonitorEnter/MonitorExit on a class obj
2478       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2479         output.print("       struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
2480         output.println("1," + localsprefixaddr + ", global_defs_p->"+ fc.getThis().getType().getClassDesc().getSafeSymbol() +"classobj};");
2481         output.println("     "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
2482       } else {
2483       output.println("       " + cn.getSafeSymbol()+md.getSafeSymbol()+"_"
2484                      + md.getSafeMethodDescriptor() + "((struct ___Object___*)(global_defs_p->"
2485                      + fc.getThis().getType().getClassDesc().getSafeSymbol() +"classobj));");
2486       }
2487       output.println("}");
2488       return;
2489     }
2490     
2491     output.println("{");
2492     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2493       output.print("       struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params __parameterlist__={");
2494       output.print(objectparams.numPointers());
2495       output.print(", "+localsprefixaddr);
2496       if (md.getThis()!=null) {
2497         output.print(", ");
2498         output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis()));
2499       }
2500       if (fc.getThis()!=null&&md.getThis()==null) {
2501         System.out.println("WARNING!!!!!!!!!!!!");
2502         System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
2503       }
2504
2505
2506       for(int i=0; i<fc.numArgs(); i++) {
2507         Descriptor var=md.getParameter(i);
2508         TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
2509         if (objectparams.isParamPtr(paramtemp)) {
2510           TempDescriptor targ=fc.getArg(i);
2511           output.print(", ");
2512           TypeDescriptor td=md.getParamType(i);
2513           if (td.isTag())
2514             output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()  +" *)"+generateTemp(fm, targ));
2515           else
2516             output.print("(struct "+md.getParamType(i).getSafeSymbol()  +" *)"+generateTemp(fm, targ));
2517         }
2518       }
2519       output.println("};");
2520     }
2521     output.print("       ");
2522
2523
2524     if (fc.getReturnTemp()!=null)
2525       output.print(generateTemp(fm,fc.getReturnTemp())+"=");
2526
2527     /* Do we need to do virtual dispatch? */
2528     if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)||fc.getSuper()) {
2529       //no
2530       output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring);
2531     } else {
2532       //yes
2533       output.print("((");
2534       if (md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) {
2535         output.print("int ");
2536       } else if (md.getReturnType().isClass()||md.getReturnType().isArray())
2537         output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
2538       else
2539         output.print(md.getReturnType().getSafeSymbol()+" ");
2540       output.print("(*)(");
2541
2542       boolean printcomma=false;
2543       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2544         output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params * ");
2545         printcomma=true;
2546       }
2547
2548       for(int i=0; i<objectparams.numPrimitives(); i++) {
2549         TempDescriptor temp=objectparams.getPrimitive(i);
2550         if (printcomma)
2551           output.print(", ");
2552         printcomma=true;
2553         if (temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
2554           output.print("int ");
2555         } else if (temp.getType().isClass()||temp.getType().isArray())
2556           output.print("struct " + temp.getType().getSafeSymbol()+" * ");
2557         else
2558           output.print(temp.getType().getSafeSymbol());
2559       }
2560
2561
2562       output.print("))virtualtable["+generateTemp(fm,fc.getThis())+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
2563     }
2564
2565     output.print("(");
2566     boolean needcomma=false;
2567     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2568       output.print("&__parameterlist__");
2569       needcomma=true;
2570     }
2571
2572     if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
2573       if (fc.getThis()!=null) {
2574         TypeDescriptor ptd=null;
2575         if(md.getThis() != null) {
2576           ptd = md.getThis().getType();
2577         } else {
2578           ptd = fc.getThis().getType();
2579         }
2580         if (needcomma)
2581           output.print(",");
2582         if(ptd.isClass() && ptd.getClassDesc().isEnum()) {
2583           // do nothing
2584         } else if (ptd.isClass()&&!ptd.isArray())
2585           output.print("(struct "+ptd.getSafeSymbol()+" *) ");
2586         output.print(generateTemp(fm,fc.getThis()));
2587         needcomma=true;
2588       }
2589     }
2590
2591     for(int i=0; i<fc.numArgs(); i++) {
2592       Descriptor var=md.getParameter(i);
2593       TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
2594       if (objectparams.isParamPrim(paramtemp)) {
2595         TempDescriptor targ=fc.getArg(i);
2596         if (needcomma)
2597           output.print(", ");
2598
2599         TypeDescriptor ptd=md.getParamType(i);
2600         if (ptd.isClass() && ptd.getClassDesc().isEnum()) {
2601           // do nothing
2602         } else if (ptd.isClass()&&!ptd.isArray())
2603           output.print("(struct "+ptd.getSafeSymbol()+" *) ");
2604         output.print(generateTemp(fm, targ));
2605         needcomma=true;
2606       }
2607     }
2608     output.println(");");
2609     output.println("   }");
2610   }
2611
2612   protected boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
2613     if(thiscd.isInterface()) {
2614       // for interfaces, always need virtual dispatch
2615       return false;
2616     } else {
2617     Set subclasses=typeutil.getSubClasses(thiscd);
2618     if (subclasses==null)
2619       return true;
2620     for(Iterator classit=subclasses.iterator(); classit.hasNext(); ) {
2621       ClassDescriptor cd=(ClassDescriptor)classit.next();
2622       Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
2623       for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) {
2624         MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
2625         if (md.matches(matchmd))
2626           return false;
2627       }
2628     }
2629     }
2630     return true;
2631   }
2632
2633   protected void generateFlatFieldNode(FlatMethod fm, FlatFieldNode ffn, PrintWriter output) {
2634     
2635     if(ffn.getField().isStatic()) {
2636       // static field
2637       if((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())) {
2638         // is a static block or is invoked in some static block
2639         ClassDescriptor cd = fm.getMethod().getClassDesc();
2640         ClassDescriptor cn = ffn.getSrc().getType().getClassDesc();
2641         if(cd == cn) {
2642           // the same class, do nothing
2643         } else if(mgcstaticinit) {
2644       // generate the static init check code if has not done the static init in main()
2645           if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
2646             // need to check if the class' static fields have been initialized and/or
2647             // its static blocks have been executed
2648             output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
2649             if(cn.getNumStaticBlocks() != 0) {
2650               MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
2651           if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2652             output.print("       struct "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={");
2653             output.println("0, NULL};");
2654             output.println("     "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);");
2655           } else {
2656             output.println("  "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
2657           }
2658             } else {
2659               output.println("  global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
2660             }
2661             output.println("}");
2662           }
2663         }
2664       }
2665       // redirect to the global_defs_p structure
2666         if (ffn.getField().getType().isPtr())
2667           output.println(generateTemp(fm, ffn.getDst())+"=global_defs_p->"+ffn.getField().getSafeSymbol()+";");
2668         else
2669           output.println(generateTemp(fm, ffn.getDst())+"=global_defsprim_p->"+ffn.getField().getSafeSymbol()+";");
2670     } else if (ffn.getField().isEnum()) {
2671       // an Enum value, directly replace the field access as int
2672       output.println(generateTemp(fm, ffn.getDst()) + "=" + ffn.getField().enumValue() + ";");
2673     } else {
2674       output.println("#ifdef MULTICORE_DEBUG");
2675       output.println("if (" + generateTemp(fm,ffn.getSrc()) + " == NULL) {");
2676       output.println("printf(\" NULL ptr error: %s, %s, %d \\n\", __FILE__, __func__, __LINE__);");
2677       if(state.MULTICOREGC) {
2678         output.println("failednullptr(&___locals___);");
2679       } else {
2680         output.println("failednullptr(NULL);");
2681       }
2682       output.println("}");
2683       output.println("#endif //MULTICORE_DEBUG");
2684       output.println(generateTemp(fm, ffn.getDst())+"="+ generateTemp(fm,ffn.getSrc())+"->"+ ffn.getField().getSafeSymbol()+";");
2685     }
2686   }
2687
2688
2689   protected void generateFlatSetFieldNode(FlatMethod fm, FlatSetFieldNode fsfn, PrintWriter output) {
2690     if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
2691       throw new Error("Can't set array length");
2692     if (state.FASTCHECK) {
2693       String dst=generateTemp(fm, fsfn.getDst());
2694       output.println("if(!"+dst+"->"+localcopystr+") {");
2695       /* Link object into list */
2696       if (GENERATEPRECISEGC || this.state.MULTICOREGC)
2697         output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
2698       else
2699         output.println("COPY_OBJ("+dst+");");
2700       output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
2701       output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
2702       output.println("}");
2703     }
2704
2705     if(fsfn.getField().isStatic()) {
2706       // static field
2707       if((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())) {
2708         // is a static block or is invoked in some static block
2709         ClassDescriptor cd = fm.getMethod().getClassDesc();
2710         ClassDescriptor cn = fsfn.getDst().getType().getClassDesc();
2711         if(cd == cn) {
2712           // the same class, do nothing
2713         } else if(mgcstaticinit){
2714       // generate static init check code if has not done the static init in main()
2715           if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
2716             // need to check if the class' static fields have been initialized and/or
2717             // its static blocks have been executed
2718             output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
2719             if(cn.getNumStaticBlocks() != 0) {
2720               MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
2721           if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2722             output.print("       struct "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={");
2723             output.println("0, NULL};");
2724             output.println("     "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);");
2725           } else {
2726             output.println("  "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
2727           }
2728             } else {
2729               output.println("  global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
2730             }
2731             output.println("}");
2732           }
2733         }
2734       }
2735       // redirect to the global_defs_p structure
2736         if (fsfn.getField().getType().isPtr())
2737           output.println("global_defs_p->" +
2738                          fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";");
2739         else
2740           output.println("global_defsprim_p->" +
2741                          fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";");
2742     } else {
2743       output.println("#ifdef MULTICORE_DEBUG");
2744       output.println("if (" + generateTemp(fm,fsfn.getDst()) + " == NULL) {");
2745       output.println("printf(\" NULL ptr error: %s, %s, %d \\n\", __FILE__, __func__, __LINE__);");
2746       if(state.MULTICOREGC) {
2747         output.println("failednullptr(&___locals___);");
2748       } else {
2749         output.println("failednullptr(NULL);");
2750       }
2751       output.println("}");
2752       output.println("#endif //MULTICORE_DEBUG");
2753       output.println(generateTemp(fm, fsfn.getDst())+"->"+
2754                      fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";");
2755     }
2756   }
2757
2758
2759   protected void generateFlatElementNode(FlatMethod fm, FlatElementNode fen, PrintWriter output) {
2760     TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2761     String type="";
2762
2763     if (elementtype.isClass() && elementtype.getClassDesc().isEnum()) {
2764       type="int ";
2765     } else if (elementtype.isArray()||elementtype.isClass())
2766       type="void *";
2767     else
2768       type=elementtype.getSafeSymbol()+" ";
2769
2770     if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
2771       output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex())+") >= "+generateTemp(fm,fen.getSrc()) + "->___length___))");
2772       output.println("failedboundschk(" + (boundschknum++) + ");");
2773     }
2774     output.println(generateTemp(fm, fen.getDst())+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc())+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex())+"];");
2775   }
2776
2777   protected void generateFlatSetElementNode(FlatMethod fm, FlatSetElementNode fsen, PrintWriter output) {
2778     //TODO: need dynamic check to make sure this assignment is actually legal
2779     //Because Object[] could actually be something more specific...ie. Integer[]
2780
2781     TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2782     String type="";
2783
2784     if (elementtype.isClass() && elementtype.getClassDesc().isEnum()) {
2785       type="int ";
2786     } else if (elementtype.isArray()||elementtype.isClass() || (elementtype.isNull()))
2787       type="void *";
2788     else
2789       type=elementtype.getSafeSymbol()+" ";
2790
2791     if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
2792       output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex())+") >= "+generateTemp(fm,fsen.getDst()) + "->___length___))");
2793       output.println("failedboundschk(" + (boundschknum++) + ");");
2794     }
2795     if (state.FASTCHECK) {
2796       String dst=generateTemp(fm, fsen.getDst());
2797       output.println("if(!"+dst+"->"+localcopystr+") {");
2798       /* Link object into list */
2799       if (GENERATEPRECISEGC || this.state.MULTICOREGC)
2800         output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
2801       else
2802         output.println("COPY_OBJ("+dst+");");
2803       output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
2804       output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
2805       output.println("}");
2806     }
2807     output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst())+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex())+"]="+generateTemp(fm,fsen.getSrc())+";");
2808   }
2809
2810
2811   protected void generateFlatNew(FlatMethod fm, FlatNew fn, PrintWriter output) {
2812     if (fn.getType().isArray()) {
2813       int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
2814       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2815         output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize())+");");
2816       } else {
2817         output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize())+");");
2818       }
2819     } else {
2820       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2821         output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
2822       } else {
2823         output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
2824       }
2825     }
2826     if (state.FASTCHECK) {
2827       String dst=generateTemp(fm,fn.getDst());
2828       output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
2829       output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
2830       output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
2831     }
2832   }
2833
2834   protected void generateFlatTagDeclaration(FlatMethod fm, FlatTagDeclaration fn, PrintWriter output) {
2835     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2836       output.println(generateTemp(fm,fn.getDst())+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
2837     } else {
2838       output.println(generateTemp(fm,fn.getDst())+"=allocate_tag("+state.getTagId(fn.getType())+");");
2839     }
2840   }
2841
2842   protected void generateFlatOpNode(FlatMethod fm, FlatOpNode fon, PrintWriter output) {
2843     if (fon.getRight()!=null) {
2844       if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
2845         if (fon.getLeft().getType().isLong())
2846           output.println(generateTemp(fm, fon.getDest())+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft())+")>>"+generateTemp(fm,fon.getRight())+";");
2847         else
2848           output.println(generateTemp(fm, fon.getDest())+" = ((unsigned int)"+generateTemp(fm, fon.getLeft())+")>>"+generateTemp(fm,fon.getRight())+";");
2849
2850       } else
2851         output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+fon.getOp().toString()+generateTemp(fm,fon.getRight())+";");
2852     } else if (fon.getOp().getOp()==Operation.ASSIGN)
2853       output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+";");
2854     else if (fon.getOp().getOp()==Operation.UNARYPLUS)
2855       output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+";");
2856     else if (fon.getOp().getOp()==Operation.UNARYMINUS)
2857       output.println(generateTemp(fm, fon.getDest())+" = -"+generateTemp(fm, fon.getLeft())+";");
2858     else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
2859       output.println(generateTemp(fm, fon.getDest())+" = !"+generateTemp(fm, fon.getLeft())+";");
2860     else if (fon.getOp().getOp()==Operation.COMP)
2861       output.println(generateTemp(fm, fon.getDest())+" = ~"+generateTemp(fm, fon.getLeft())+";");
2862     else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
2863       output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+"->fses==NULL;");
2864     } else
2865       output.println(generateTemp(fm, fon.getDest())+fon.getOp().toString()+generateTemp(fm, fon.getLeft())+";");
2866   }
2867
2868   protected void generateFlatCastNode(FlatMethod fm, FlatCastNode fcn, PrintWriter output) {
2869     /* TODO: Do type check here */
2870     if (fcn.getType().isArray()) {
2871       output.println(generateTemp(fm,fcn.getDst())+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc())+";");
2872     } else if (fcn.getType().isClass() && fcn.getType().getClassDesc().isEnum()) {
2873       output.println(generateTemp(fm,fcn.getDst())+"=(int)"+generateTemp(fm,fcn.getSrc())+";");
2874     } else if (fcn.getType().isClass())
2875       output.println(generateTemp(fm,fcn.getDst())+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc())+";");
2876     else
2877       output.println(generateTemp(fm,fcn.getDst())+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc())+";");
2878   }
2879
2880   protected void generateFlatLiteralNode(FlatMethod fm, FlatLiteralNode fln, PrintWriter output) {
2881     if (fln.getValue()==null)
2882       output.println(generateTemp(fm, fln.getDst())+"=0;");
2883     else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
2884       if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2885         output.println(generateTemp(fm, fln.getDst())+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
2886       } else {
2887         output.println(generateTemp(fm, fln.getDst())+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
2888       }
2889     } else if (fln.getType().isBoolean()) {
2890       if (((Boolean)fln.getValue()).booleanValue())
2891         output.println(generateTemp(fm, fln.getDst())+"=1;");
2892       else
2893         output.println(generateTemp(fm, fln.getDst())+"=0;");
2894     } else if (fln.getType().isChar()) {
2895       String st=FlatLiteralNode.escapeString(fln.getValue().toString());
2896       output.println(generateTemp(fm, fln.getDst())+"='"+st+"';");
2897     } else if (fln.getType().isLong()) {
2898       output.println(generateTemp(fm, fln.getDst())+"="+fln.getValue()+"LL;");
2899     } else
2900       output.println(generateTemp(fm, fln.getDst())+"="+fln.getValue()+";");
2901   }
2902
2903   protected void generateFlatReturnNode(FlatMethod fm, FlatReturnNode frn, PrintWriter output) {
2904     if((fm.getMethod() != null) && (fm.getMethod().isStaticBlock())) {
2905       // a static block, check if it has been executed
2906       output.println("  global_defsprim_p->" + fm.getMethod().getClassDesc().getSafeSymbol()+"static_block_exe_flag = 1;");
2907       output.println("");
2908     }
2909     
2910     if (frn.getReturnTemp()!=null) {
2911       if (frn.getReturnTemp().getType().isPtr())
2912         output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp())+";");
2913       else
2914         output.println("return "+generateTemp(fm, frn.getReturnTemp())+";");
2915     } else {
2916       output.println("return;");
2917     }
2918   }
2919
2920   protected void generateFlatCondBranch(FlatMethod fm, FlatCondBranch fcb, String label, PrintWriter output) {
2921     output.println("if (!"+generateTemp(fm, fcb.getTest())+") goto "+label+";");
2922   }
2923
2924   /** This method generates header information for the method or
2925    * task referenced by the Descriptor des. */
2926   protected void generateHeader(FlatMethod fm, Descriptor des, PrintWriter output) {
2927     generateHeader(fm, des, output, false);
2928   }
2929
2930   protected void generateHeader(FlatMethod fm, Descriptor des, PrintWriter output, boolean addSESErecord) {
2931     /* Print header */
2932     ParamsObject objectparams=(ParamsObject)paramstable.get(des);
2933     MethodDescriptor md=null;
2934     TaskDescriptor task=null;
2935     if (des instanceof MethodDescriptor)
2936       md=(MethodDescriptor) des;
2937     else
2938       task=(TaskDescriptor) des;
2939     String mdstring = md != null ? md.getSafeMethodDescriptor() : null;
2940
2941     ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
2942
2943     if (md!=null&&md.getReturnType()!=null) {
2944       if (md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) {
2945         output.print("int ");
2946       } else if (md.getReturnType().isClass()||md.getReturnType().isArray())
2947         output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
2948       else
2949         output.print(md.getReturnType().getSafeSymbol()+" ");
2950     } else
2951       //catch the constructor case
2952       output.print("void ");
2953     if (md!=null) {
2954       if(mgcstaticinit && !md.isStaticBlock() && !md.getModifiers().isNative()) {
2955         mdstring += "staticinit";
2956       }
2957       output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"(");
2958     } else
2959       output.print(task.getSafeSymbol()+"(");
2960
2961     boolean printcomma=false;
2962     if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2963       if (md!=null) {
2964         output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params * "+paramsprefix);
2965       } else
2966         output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
2967       printcomma=true;
2968     }
2969
2970     if (md!=null) {
2971       /* Method */
2972       for(int i=0; i<objectparams.numPrimitives(); i++) {
2973         TempDescriptor temp=objectparams.getPrimitive(i);
2974         if (printcomma)
2975           output.print(", ");
2976         printcomma=true;
2977         if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
2978           output.print("int " + temp.getSafeSymbol());
2979         } else if (temp.getType().isClass()||temp.getType().isArray())
2980           output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
2981         else
2982           output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
2983       }
2984       output.println(") {");
2985     } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
2986       /* Imprecise Task */
2987       output.println("void * parameterarray[]) {");
2988       /* Unpack variables */
2989       for(int i=0; i<objectparams.numPrimitives(); i++) {
2990         TempDescriptor temp=objectparams.getPrimitive(i);
2991         if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
2992           output.print("int " + temp.getSafeSymbol() + "=parameterarray["+i+"];");
2993         } else {
2994           output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
2995         }
2996       }
2997       for(int i=0; i<fm.numTags(); i++) {
2998         TempDescriptor temp=fm.getTag(i);
2999         int offset=i+objectparams.numPrimitives();
3000         output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
3001       }
3002
3003       if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
3004         maxtaskparams=objectparams.numPrimitives()+fm.numTags();
3005     } else output.println(") {");
3006   }
3007
3008   public void generateFlatFlagActionNode(FlatMethod fm, FlatFlagActionNode ffan, PrintWriter output) {
3009     output.println("/* FlatFlagActionNode */");
3010
3011
3012     /* Process tag changes */
3013     Relation tagsettable=new Relation();
3014     Relation tagcleartable=new Relation();
3015
3016     Iterator tagsit=ffan.getTempTagPairs();
3017     while (tagsit.hasNext()) {
3018       TempTagPair ttp=(TempTagPair) tagsit.next();
3019       TempDescriptor objtmp=ttp.getTemp();
3020       TagDescriptor tag=ttp.getTag();
3021       TempDescriptor tagtmp=ttp.getTagTemp();
3022       boolean tagstatus=ffan.getTagChange(ttp);
3023       if (tagstatus) {
3024         tagsettable.put(objtmp, tagtmp);
3025       } else {
3026         tagcleartable.put(objtmp, tagtmp);
3027       }
3028     }
3029
3030
3031     Hashtable flagandtable=new Hashtable();
3032     Hashtable flagortable=new Hashtable();
3033
3034     /* Process flag changes */
3035     Iterator flagsit=ffan.getTempFlagPairs();
3036     while(flagsit.hasNext()) {
3037       TempFlagPair tfp=(TempFlagPair)flagsit.next();
3038       TempDescriptor temp=tfp.getTemp();
3039       Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
3040       FlagDescriptor flag=tfp.getFlag();
3041       if (flag==null) {
3042         //Newly allocate objects that don't set any flags case
3043         if (flagortable.containsKey(temp)) {
3044           throw new Error();
3045         }
3046         int mask=0;
3047         flagortable.put(temp,new Integer(mask));
3048       } else {
3049         int flagid=1<<((Integer)flagtable.get(flag)).intValue();
3050         boolean flagstatus=ffan.getFlagChange(tfp);
3051         if (flagstatus) {
3052           int mask=0;
3053           if (flagortable.containsKey(temp)) {
3054             mask=((Integer)flagortable.get(temp)).intValue();
3055           }
3056           mask|=flagid;
3057           flagortable.put(temp,new Integer(mask));
3058         } else {
3059           int mask=0xFFFFFFFF;
3060           if (flagandtable.containsKey(temp)) {
3061             mask=((Integer)flagandtable.get(temp)).intValue();
3062           }
3063           mask&=(0xFFFFFFFF^flagid);
3064           flagandtable.put(temp,new Integer(mask));
3065         }
3066       }
3067     }
3068
3069
3070     HashSet flagtagset=new HashSet();
3071     flagtagset.addAll(flagortable.keySet());
3072     flagtagset.addAll(flagandtable.keySet());
3073     flagtagset.addAll(tagsettable.keySet());
3074     flagtagset.addAll(tagcleartable.keySet());
3075
3076     Iterator ftit=flagtagset.iterator();
3077     while(ftit.hasNext()) {
3078       TempDescriptor temp=(TempDescriptor)ftit.next();
3079
3080
3081       Set tagtmps=tagcleartable.get(temp);
3082       if (tagtmps!=null) {
3083         Iterator tagit=tagtmps.iterator();
3084         while(tagit.hasNext()) {
3085           TempDescriptor tagtmp=(TempDescriptor)tagit.next();
3086           if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
3087             output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");");
3088           else
3089             output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");");
3090         }
3091       }
3092
3093       tagtmps=tagsettable.get(temp);
3094       if (tagtmps!=null) {
3095         Iterator tagit=tagtmps.iterator();
3096         while(tagit.hasNext()) {
3097           TempDescriptor tagtmp=(TempDescriptor)tagit.next();
3098           if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
3099             output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");");
3100           else
3101             output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");");
3102         }
3103       }
3104
3105       int ormask=0;
3106       int andmask=0xFFFFFFF;
3107
3108       if (flagortable.containsKey(temp))
3109         ormask=((Integer)flagortable.get(temp)).intValue();
3110       if (flagandtable.containsKey(temp))
3111         andmask=((Integer)flagandtable.get(temp)).intValue();
3112       generateFlagOrAnd(ffan, fm, temp, output, ormask, andmask);
3113       generateObjectDistribute(ffan, fm, temp, output);
3114     }
3115   }
3116
3117   protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, TempDescriptor temp,
3118                                    PrintWriter output, int ormask, int andmask) {
3119     if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
3120       output.println("flagorandinit("+generateTemp(fm, temp)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
3121     } else {
3122       output.println("flagorand("+generateTemp(fm, temp)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
3123     }
3124   }
3125
3126   protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, TempDescriptor temp, PrintWriter output) {
3127     output.println("enqueueObject("+generateTemp(fm, temp)+");");
3128   }
3129
3130   void generateOptionalHeader(PrintWriter headers) {
3131
3132     //GENERATE HEADERS
3133     headers.println("#include \"task.h\"\n\n");
3134     headers.println("#ifndef _OPTIONAL_STRUCT_");
3135     headers.println("#define _OPTIONAL_STRUCT_");
3136
3137     //STRUCT PREDICATEMEMBER
3138     headers.println("struct predicatemember{");
3139     headers.println("int type;");
3140     headers.println("int numdnfterms;");
3141     headers.println("int * flags;");
3142     headers.println("int numtags;");
3143     headers.println("int * tags;\n};\n\n");
3144
3145     //STRUCT OPTIONALTASKDESCRIPTOR
3146     headers.println("struct optionaltaskdescriptor{");
3147     headers.println("struct taskdescriptor * task;");
3148     headers.println("int index;");
3149     headers.println("int numenterflags;");
3150     headers.println("int * enterflags;");
3151     headers.println("int numpredicatemembers;");
3152     headers.println("struct predicatemember ** predicatememberarray;");
3153     headers.println("};\n\n");
3154
3155     //STRUCT TASKFAILURE
3156     headers.println("struct taskfailure {");
3157     headers.println("struct taskdescriptor * task;");
3158     headers.println("int index;");
3159     headers.println("int numoptionaltaskdescriptors;");
3160     headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
3161
3162     //STRUCT FSANALYSISWRAPPER
3163     headers.println("struct fsanalysiswrapper{");
3164     headers.println("int  flags;");
3165     headers.println("int numtags;");
3166     headers.println("int * tags;");
3167     headers.println("int numtaskfailures;");
3168     headers.println("struct taskfailure ** taskfailurearray;");
3169     headers.println("int numoptionaltaskdescriptors;");
3170     headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
3171
3172     //STRUCT CLASSANALYSISWRAPPER
3173     headers.println("struct classanalysiswrapper{");
3174     headers.println("int type;");
3175     headers.println("int numotd;");
3176     headers.println("struct optionaltaskdescriptor ** otdarray;");
3177     headers.println("int numfsanalysiswrappers;");
3178     headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
3179
3180     headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
3181
3182     Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
3183     while(taskit.hasNext()) {
3184       TaskDescriptor td=(TaskDescriptor)taskit.next();
3185       headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
3186     }
3187
3188   }
3189
3190   //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
3191   int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
3192     int predicateindex = 0;
3193     //iterate through the classes concerned by the predicate
3194     Set c_vard = predicate.vardescriptors;
3195     Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
3196     int current_slot=0;
3197
3198     for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext(); ) {
3199       VarDescriptor vard = (VarDescriptor)vard_it.next();
3200       TypeDescriptor typed = vard.getType();
3201
3202       //generate for flags
3203       HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
3204       output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3205       int numberterms=0;
3206       if (fen_hashset!=null) {
3207         for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext(); ) {
3208           FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
3209           if (fen!=null) {
3210             DNFFlag dflag=fen.getDNF();
3211             numberterms+=dflag.size();
3212
3213             Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
3214
3215             for(int j=0; j<dflag.size(); j++) {
3216               if (j!=0)
3217                 output.println(",");
3218               Vector term=dflag.get(j);
3219               int andmask=0;
3220               int checkmask=0;
3221               for(int k=0; k<term.size(); k++) {
3222                 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
3223                 FlagDescriptor fd=dfa.getFlag();
3224                 boolean negated=dfa.getNegated();
3225                 int flagid=1<<((Integer)flags.get(fd)).intValue();
3226                 andmask|=flagid;
3227                 if (!negated)
3228                   checkmask|=flagid;
3229               }
3230               output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
3231             }
3232           }
3233         }
3234       }
3235       output.println("};\n");
3236
3237       //generate for tags
3238       TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
3239       output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3240       int numtags = 0;
3241       if (tagel!=null) {
3242         for(int j=0; j<tagel.numTags(); j++) {
3243           if (j!=0)
3244             output.println(",");
3245           TempDescriptor tmp=tagel.getTemp(j);
3246           if (!slotnumber.containsKey(tmp)) {
3247             Integer slotint=new Integer(current_slot++);
3248             slotnumber.put(tmp,slotint);
3249           }
3250           int slot=slotnumber.get(tmp).intValue();
3251           output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
3252         }
3253         numtags = tagel.numTags();
3254       }
3255       output.println("};");
3256
3257       //store the result into a predicatemember struct
3258       output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
3259       output.println("/*type*/"+typed.getClassDesc().getId()+",");
3260       output.println("/* number of dnf terms */"+numberterms+",");
3261       output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3262       output.println("/* number of tag */"+numtags+",");
3263       output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3264       output.println("};\n");
3265       predicateindex++;
3266     }
3267
3268
3269     //generate an array that stores the entire predicate
3270     output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3271     for( int j = 0; j<predicateindex; j++) {
3272       if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3273       else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
3274     }
3275     output.println("};\n");
3276     return predicateindex;
3277   }
3278
3279
3280   void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
3281     generateOptionalHeader(headers);
3282     //GENERATE STRUCTS
3283     output.println("#include \"optionalstruct.h\"\n\n");
3284     output.println("#include \"stdlib.h\"\n");
3285
3286     HashSet processedcd = new HashSet();
3287     int maxotd=0;
3288     Enumeration e = safeexecution.keys();
3289     while (e.hasMoreElements()) {
3290       int numotd=0;
3291       //get the class
3292       ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
3293       Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp);       //will be used several times
3294
3295       //Generate the struct of optionals
3296       Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
3297       numotd = c_otd.size();
3298       if(maxotd<numotd) maxotd = numotd;
3299       if( !c_otd.isEmpty() ) {
3300         for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext(); ) {
3301           OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
3302
3303           //generate the int arrays for the predicate
3304           Predicate predicate = otd.predicate;
3305           int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
3306           TreeSet<Integer> fsset=new TreeSet<Integer>();
3307           //iterate through possible FSes corresponding to
3308           //the state when entering
3309
3310           for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext(); ) {
3311             FlagState fs = (FlagState)fses.next();
3312             int flagid=0;
3313             for(Iterator flags = fs.getFlags(); flags.hasNext(); ) {
3314               FlagDescriptor flagd = (FlagDescriptor)flags.next();
3315               int id=1<<((Integer)flaginfo.get(flagd)).intValue();
3316               flagid|=id;
3317             }
3318             fsset.add(new Integer(flagid));
3319             //tag information not needed because tag
3320             //changes are not tolerated.
3321           }
3322
3323           output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3324           boolean needcomma=false;
3325           for(Iterator<Integer> it=fsset.iterator(); it.hasNext(); ) {
3326             if(needcomma)
3327               output.print(", ");
3328             output.println(it.next());
3329           }
3330
3331           output.println("};\n");
3332
3333
3334           //generate optionaltaskdescriptor that actually
3335           //includes exit fses, predicate and the task
3336           //concerned
3337           output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
3338           output.println("&task_"+otd.td.getSafeSymbol()+",");
3339           output.println("/*index*/"+otd.getIndex()+",");
3340           output.println("/*number of enter flags*/"+fsset.size()+",");
3341           output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3342           output.println("/*number of members */"+predicateindex+",");
3343           output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3344           output.println("};\n");
3345         }
3346       } else
3347         continue;
3348       // if there are no optionals, there is no need to build the rest of the struct
3349
3350       output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
3351       c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
3352       if( !c_otd.isEmpty() ) {
3353         boolean needcomma=false;
3354         for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext(); ) {
3355           OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
3356           if(needcomma)
3357             output.println(",");
3358           needcomma=true;
3359           output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
3360         }
3361       }
3362       output.println("};\n");
3363
3364       //get all the possible flagstates reachable by an object
3365       Hashtable hashtbtemp = safeexecution.get(cdtemp);
3366       int fscounter = 0;
3367       TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
3368       fsts.addAll(hashtbtemp.keySet());
3369       for(Iterator fsit=fsts.iterator(); fsit.hasNext(); ) {
3370         FlagState fs = (FlagState)fsit.next();
3371         fscounter++;
3372
3373         //get the set of OptionalTaskDescriptors corresponding
3374         HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
3375         //iterate through the OptionalTaskDescriptors and
3376         //store the pointers to the optionals struct (see on
3377         //top) into an array
3378
3379         output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
3380         for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext(); ) {
3381           OptionalTaskDescriptor mm = mos.next();
3382           if(!mos.hasNext())
3383             output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
3384           else
3385             output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3386         }
3387
3388         output.println("};\n");
3389
3390         //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
3391
3392         int flagid=0;
3393         for(Iterator flags = fs.getFlags(); flags.hasNext(); ) {
3394           FlagDescriptor flagd = (FlagDescriptor)flags.next();
3395           int id=1<<((Integer)flaginfo.get(flagd)).intValue();
3396           flagid|=id;
3397         }
3398
3399         //process tag information
3400
3401         int tagcounter = 0;
3402         boolean first = true;
3403         Enumeration tag_enum = fs.getTags();
3404         output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
3405         while(tag_enum.hasMoreElements()) {
3406           tagcounter++;
3407           TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
3408           if(first==true)
3409             first = false;
3410           else
3411             output.println(", ");
3412           output.println("/*tagid*/"+state.getTagId(tagd));
3413         }
3414         output.println("};");
3415
3416         Set<TaskIndex> tiset=sa.getTaskIndex(fs);
3417         for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext(); ) {
3418           TaskIndex ti=itti.next();
3419           if (ti.isRuntime())
3420             continue;
3421
3422           Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
3423
3424           output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
3425           boolean needcomma=false;
3426           for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext(); ) {
3427             OptionalTaskDescriptor otd=otdit.next();
3428             if(needcomma)
3429               output.print(", ");
3430             needcomma=true;
3431             output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
3432           }
3433           output.println("};");
3434
3435           output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
3436           output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
3437           output.print(ti.getIndex()+", ");
3438           output.print(otdset.size()+", ");
3439           output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
3440           output.println("};");
3441         }
3442
3443         tiset=sa.getTaskIndex(fs);
3444         boolean needcomma=false;
3445         int runtimeti=0;
3446         output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
3447         for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext(); ) {
3448           TaskIndex ti=itti.next();
3449           if (ti.isRuntime()) {
3450             runtimeti++;
3451             continue;
3452           }
3453           if (needcomma)
3454             output.print(", ");
3455           needcomma=true;
3456           output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
3457         }
3458         output.println("};\n");
3459
3460         //Store the result in fsanalysiswrapper
3461
3462         output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
3463         output.println("/*flag*/"+flagid+",");
3464         output.println("/* number of tags*/"+tagcounter+",");
3465         output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
3466         output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
3467         output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
3468         output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
3469         output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
3470         output.println("};\n");
3471
3472       }
3473
3474       //Build the array of fsanalysiswrappers
3475       output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
3476       boolean needcomma=false;
3477       for(int i = 0; i<fscounter; i++) {
3478         if (needcomma) output.print(",");
3479         output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
3480         needcomma=true;
3481       }
3482       output.println("};");
3483
3484       //Build the classanalysiswrapper referring to the previous array
3485       output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
3486       output.println("/*type*/"+cdtemp.getId()+",");
3487       output.println("/*numotd*/"+numotd+",");
3488       output.println("otdarray"+cdtemp.getSafeSymbol()+",");
3489       output.println("/* number of fsanalysiswrappers */"+fscounter+",");
3490       output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
3491       processedcd.add(cdtemp);
3492     }
3493
3494     //build an array containing every classes for which code has been build
3495     output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
3496     for(int i=0; i<state.numClasses(); i++) {
3497       ClassDescriptor cn=cdarray[i];
3498       if (i>0)
3499         output.print(", ");
3500       if ((cn != null) && (processedcd.contains(cn)))
3501         output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
3502       else
3503         output.print("NULL");
3504     }
3505     output.println("};");
3506
3507     output.println("#define MAXOTD "+maxotd);
3508     headers.println("#endif");
3509   }
3510
3511   public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
3512     Relation r=new Relation();
3513     for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext(); ) {
3514       OptionalTaskDescriptor otd=otdit.next();
3515       TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
3516       r.put(ti, otd);
3517     }
3518
3519     LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
3520     for(Iterator it=r.keySet().iterator(); it.hasNext(); ) {
3521       Set s=r.get(it.next());
3522       for(Iterator it2=s.iterator(); it2.hasNext(); ) {
3523         OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
3524         l.add(otd);
3525       }
3526     }
3527
3528     return l;
3529   }
3530
3531   // override these methods in a subclass of BuildCode
3532   // to generate code for additional systems
3533   protected void printExtraArrayFields(PrintWriter outclassdefs) {
3534   }
3535   protected void outputTransCode(PrintWriter output) {
3536   }
3537   protected void buildCodeSetup() {
3538   }
3539   protected void generateSizeArrayExtensions(PrintWriter outclassdefs) {
3540   }
3541   protected void additionalIncludesMethodsHeader(PrintWriter outmethodheader) {
3542   }
3543   protected void preCodeGenInitialization() {
3544   }
3545   protected void postCodeGenCleanUp() {
3546   }
3547   protected void additionalCodeGen(PrintWriter outmethodheader,
3548                                    PrintWriter outstructs,
3549                                    PrintWriter outmethod) {
3550   }
3551   protected void additionalCodeAtTopOfMain(PrintWriter outmethod) {
3552   }
3553   protected void additionalCodeAtBottomOfMain(PrintWriter outmethod) {
3554   }
3555   protected void additionalIncludesMethodsImplementation(PrintWriter outmethod) {
3556   }
3557   protected void additionalIncludesStructsHeader(PrintWriter outstructs) {
3558   }
3559   protected void additionalClassObjectFields(PrintWriter outclassdefs) {
3560   }
3561   protected void additionalCodeAtTopMethodsImplementation(PrintWriter outmethod) {
3562   }
3563   protected void additionalCodeAtTopFlatMethodBody(PrintWriter output, FlatMethod fm) {
3564   }
3565   protected void additionalCodePreNode(FlatMethod fm, FlatNode fn, PrintWriter output) {
3566   }
3567   protected void additionalCodePostNode(FlatMethod fm, FlatNode fn, PrintWriter output) {
3568   }
3569   
3570   private void printSourceLineNumber(FlatMethod fm, FlatNode fn, PrintWriter output) {
3571     // we do not print out line number if no one explicitly set the number
3572     if(fn.getNumLine()!=-1){
3573       
3574       int lineNum=fn.getNumLine();
3575
3576       // do not generate the line number if it is same as the previous one
3577       boolean needtoprint;
3578       if(fn.prev.size()==0){
3579         needtoprint=true;
3580       }else{
3581         needtoprint=false;
3582       }
3583
3584       for(int i=0;i<fn.prev.size();i++){
3585         int prevLineNum=((FlatNode)fn.prev.get(i)).getNumLine();
3586         if(prevLineNum!=lineNum){
3587           needtoprint=true;
3588           break;
3589         }
3590       }
3591       if(needtoprint){
3592         output.println("// "+fm.getMethod().getClassDesc().getSourceFileName()+":"+fn.getNumLine());
3593       }
3594     }
3595   }
3596   
3597 }
3598
3599
3600
3601
3602
3603