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;
13 import Analysis.TaskStateAnalysis.FlagState;
14 import Analysis.TaskStateAnalysis.FlagComparator;
15 import Analysis.TaskStateAnalysis.OptionalTaskDescriptor;
16 import Analysis.TaskStateAnalysis.Predicate;
17 import Analysis.TaskStateAnalysis.SafetyAnalysis;
18 import Analysis.TaskStateAnalysis.TaskIndex;
19 import Analysis.Locality.LocalityAnalysis;
20 import Analysis.Locality.LocalityBinding;
21 import Analysis.Locality.DiscoverConflicts;
22 import Analysis.Locality.DelayComputation;
23 import Analysis.CallGraph.CallGraph;
24 import Analysis.Prefetch.*;
25 import Analysis.Loops.WriteBarrier;
26 import Analysis.Loops.GlobalFieldType;
27 import Analysis.Locality.TypeAnalysis;
28 import Analysis.MLP.MLPAnalysis;
29 import Analysis.MLP.VariableSourceToken;
30 import Analysis.MLP.CodePlan;
31 import Analysis.MLP.SESEandAgePair;
33 public class BuildCode {
36 Hashtable paramstable;
41 String localsprefix="___locals___";
42 String localsprefixaddr="&"+localsprefix;
43 String localsprefixderef=localsprefix+".";
44 String fcrevert="___fcrevert___";
45 String paramsprefix="___params___";
46 String oidstr="___nextobject___";
47 String nextobjstr="___nextobject___";
48 String localcopystr="___localcopy___";
49 public static boolean GENERATEPRECISEGC=false;
50 public static String PREFIX="";
51 public static String arraytype="ArrayObject";
52 public static int flagcount = 0;
55 protected int maxtaskparams=0;
56 private int maxcount=0;
57 ClassDescriptor[] cdarray;
58 TypeDescriptor[] arraytable;
59 LocalityAnalysis locality;
60 Hashtable<LocalityBinding, TempDescriptor> reverttable;
61 Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>> backuptable;
65 String mlperrstr = "if(status != 0) { "+
66 "sprintf(errmsg, \"MLP error at %s:%d\", __FILE__, __LINE__); "+
67 "perror(errmsg); exit(-1); }";
68 Hashtable<FlatSESEEnterNode, FlatMethod> sese2bogusFlatMeth;
69 boolean nonSESEpass=true;
72 DiscoverConflicts recorddc;
73 DelayComputation delaycomp;
76 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa) {
77 this(st, temptovar, typeutil, null, sa, pa, null);
80 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa) {
81 this(st, temptovar, typeutil, null, sa, pa, mlpa);
84 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, PrefetchAnalysis pa, MLPAnalysis mlpa) {
85 this(st, temptovar, typeutil, locality, null, pa, mlpa);
88 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa) {
93 callgraph=new CallGraph(state);
95 oidstr="___objlocation___";
96 this.temptovar=temptovar;
97 paramstable=new Hashtable();
98 tempstable=new Hashtable();
99 fieldorder=new Hashtable();
100 flagorder=new Hashtable();
101 this.typeutil=typeutil;
102 virtualcalls=new Virtual(state,locality);
103 if (locality!=null) {
104 this.locality=locality;
105 this.reverttable=new Hashtable<LocalityBinding, TempDescriptor>();
106 this.backuptable=new Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>>();
107 this.wb=new WriteBarrier(locality, st);
109 if (state.SINGLETM&&state.DCOPTS) {
110 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
111 this.dc=new DiscoverConflicts(locality, st, typeanalysis);
114 if (state.DELAYCOMP) {
115 //TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
116 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
117 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
118 delaycomp=new DelayComputation(locality, st, typeanalysis, gft);
119 delaycomp.doAnalysis();
120 dc=delaycomp.getConflicts();
121 recorddc=new DiscoverConflicts(locality, st, typeanalysis, delaycomp.getCannotDelayMap(), true, true);
125 sese2bogusFlatMeth = new Hashtable<FlatSESEEnterNode, FlatMethod>();
129 /** The buildCode method outputs C code for all the methods. The Flat
130 * versions of the methods must already be generated and stored in
131 * the State object. */
133 public void buildCode() {
134 /* Create output streams to write to */
135 PrintWriter outclassdefs=null;
136 PrintWriter outstructs=null;
137 PrintWriter outrepairstructs=null;
138 PrintWriter outmethodheader=null;
139 PrintWriter outmethod=null;
140 PrintWriter outvirtual=null;
141 PrintWriter outtask=null;
142 PrintWriter outtaskdefs=null;
143 PrintWriter outoptionalarrays=null;
144 PrintWriter optionalheaders=null;
147 outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
148 outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
149 outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
150 outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
151 outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
153 outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
154 outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
155 if (state.OPTIONAL) {
156 outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
157 optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
160 if (state.structfile!=null) {
161 outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
163 } catch (Exception e) {
168 /* Build the virtual dispatch tables */
169 buildVirtualTables(outvirtual);
171 /* Output includes */
172 outmethodheader.println("#ifndef METHODHEADERS_H");
173 outmethodheader.println("#define METHODHEADERS_H");
174 outmethodheader.println("#include \"structdefs.h\"");
176 outmethodheader.println("#include \"dstm.h\"");
177 if (state.SINGLETM) {
178 outmethodheader.println("#include \"tm.h\"");
179 outmethodheader.println("#include \"delaycomp.h\"");
181 if (state.ABORTREADERS) {
182 outmethodheader.println("#include \"abortreaders.h\"");
183 outmethodheader.println("#include <setjmp.h>");
186 outmethodheader.println("#include <stdlib.h>");
187 outmethodheader.println("#include <stdio.h>");
188 outmethodheader.println("#include \"mlp_runtime.h\"");
191 /* Output Structures */
192 outputStructs(outstructs);
194 // Output the C class declarations
195 // These could mutually reference each other
196 outputClassDeclarations(outclassdefs);
198 // Output function prototypes and structures for parameters
199 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
200 while(it.hasNext()) {
201 ClassDescriptor cn=(ClassDescriptor)it.next();
202 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader);
204 outclassdefs.close();
207 /* Map flags to integers */
208 /* The runtime keeps track of flags using these integers */
209 it=state.getClassSymbolTable().getDescriptorsIterator();
210 while(it.hasNext()) {
211 ClassDescriptor cn=(ClassDescriptor)it.next();
215 generateTaskStructs(outstructs, outmethodheader);
217 /* Outputs generic task structures if this is a task
219 outputTaskTypes(outtask);
222 /* Build the actual methods */
223 outputMethods(outmethod);
225 // Output function prototypes and structures for SESE's and code
229 // first generate code for each sese's internals
230 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
231 FlatSESEEnterNode fsen = seseit.next();
232 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
235 // then write the invokeSESE switch to decouple scheduler
236 // from having to do unique details of sese invocation
237 generateSESEinvocationMethod(outmethodheader, outmethod);
241 /* Output code for tasks */
242 outputTaskCode(outtaskdefs, outmethod);
244 /* Record maximum number of task parameters */
245 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
246 } else if (state.main!=null) {
247 /* Generate main method */
248 outputMainMethod(outmethod);
251 /* Generate information for task with optional parameters */
252 if (state.TASK&&state.OPTIONAL) {
253 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
254 outoptionalarrays.close();
257 /* Output structure definitions for repair tool */
258 if (state.structfile!=null) {
259 buildRepairStructs(outrepairstructs);
260 outrepairstructs.close();
264 outmethodheader.println("#endif");
265 outmethodheader.close();
267 outstructs.println("#endif");
272 /* This code just generates the main C method for java programs.
273 * The main C method packs up the arguments into a string array
274 * and passes it to the java main method. */
276 private void outputMainMethod(PrintWriter outmethod) {
277 outmethod.println("int main(int argc, const char *argv[]) {");
278 outmethod.println(" int i;");
280 outmethod.println(" mlpInit( "+mlpa.getAllSESEs().size()+", "+mlpa.getMaxSESEage()+" );");
283 outmethod.println("#ifdef TRANSSTATS \n");
284 outmethod.println("handle();\n");
285 outmethod.println("#endif\n");
287 if (state.THREAD||state.DSM||state.SINGLETM) {
288 outmethod.println("initializethreads();");
291 outmethod.println("if (dstmStartup(argv[1])) {");
292 if (GENERATEPRECISEGC) {
293 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
295 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
298 if (GENERATEPRECISEGC) {
299 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
301 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
305 outmethod.println(" for(i=2;i<argc;i++) {");
307 outmethod.println(" for(i=1;i<argc;i++) {");
308 outmethod.println(" int length=strlen(argv[i]);");
309 if (GENERATEPRECISEGC) {
310 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
312 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
315 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
317 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
318 outmethod.println(" }");
320 MethodDescriptor md=typeutil.getMain();
321 ClassDescriptor cd=typeutil.getMainClass();
323 outmethod.println(" {");
324 if (GENERATEPRECISEGC) {
325 if (state.DSM||state.SINGLETM) {
326 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
328 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
329 outmethod.println("1, NULL,"+"stringarray};");
330 if (state.DSM||state.SINGLETM)
331 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
333 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
335 if (state.DSM||state.SINGLETM)
336 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
338 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
340 outmethod.println(" }");
343 outmethod.println("}");
346 if (state.THREAD||state.DSM||state.SINGLETM) {
347 outmethod.println("pthread_mutex_lock(&gclistlock);");
348 outmethod.println("threadcount--;");
349 outmethod.println("pthread_cond_signal(&gccond);");
350 outmethod.println("pthread_mutex_unlock(&gclistlock);");
353 if (state.DSM||state.SINGLETM) {
354 outmethod.println("#ifdef TRANSSTATS \n");
355 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
356 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
357 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
358 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
360 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
361 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
362 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
363 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
364 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
365 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
366 } else if (state.SINGLETM) {
367 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
368 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
369 outmethod.println("#ifdef STMSTATS\n");
370 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
371 outmethod.println(" printf(\"typesCausingAbort[%d]= %d\\n\", i, typesCausingAbort[i]);\n");
372 outmethod.println("}\n");
373 outmethod.println("#endif\n");
374 outmethod.println("fflush(stdout);");
376 outmethod.println("#endif\n");
379 if (state.THREAD||state.SINGLETM)
380 outmethod.println("pthread_exit(NULL);");
382 outmethod.println("}");
385 /* This method outputs code for each task. */
387 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
388 /* Compile task based program */
389 outtaskdefs.println("#include \"task.h\"");
390 outtaskdefs.println("#include \"methodheaders.h\"");
391 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
392 while(taskit.hasNext()) {
393 TaskDescriptor td=(TaskDescriptor)taskit.next();
394 FlatMethod fm=state.getMethodFlat(td);
395 generateFlatMethod(fm, null, outmethod);
396 generateTaskDescriptor(outtaskdefs, fm, td);
399 //Output task descriptors
400 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
401 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
403 while(taskit.hasNext()) {
404 TaskDescriptor td=(TaskDescriptor)taskit.next();
408 outtaskdefs.println(",");
409 outtaskdefs.print("&task_"+td.getSafeSymbol());
411 outtaskdefs.println("};");
413 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
416 /* This method outputs most of the methods.c file. This includes
417 * some standard includes and then an array with the sizes of
418 * objets and array that stores supertype and then the code for
419 * the Java methods.. */
421 protected void outputMethods(PrintWriter outmethod) {
422 outmethod.println("#include \"methodheaders.h\"");
423 outmethod.println("#include \"virtualtable.h\"");
424 outmethod.println("#include \"runtime.h\"");
426 outmethod.println("#include \"addPrefetchEnhance.h\"");
427 outmethod.println("#include \"localobjects.h\"");
429 if (state.FASTCHECK) {
430 outmethod.println("#include \"localobjects.h\"");
432 if(state.MULTICORE) {
433 outmethod.println("#include \"task.h\"");
434 outmethod.println("#include \"multicoreruntime.h\"");
435 outmethod.println("#include \"runtime_arch.h\"");
437 if (state.THREAD||state.DSM||state.SINGLETM)
438 outmethod.println("#include <thread.h>");
439 if (state.main!=null) {
440 outmethod.println("#include <string.h>");
442 if (state.CONSCHECK) {
443 outmethod.println("#include \"checkers.h\"");
446 outmethod.println("#include <stdlib.h>");
447 outmethod.println("#include <stdio.h>");
448 outmethod.println("#include \"mlp_runtime.h\"");
452 //Store the sizes of classes & array elements
453 generateSizeArray(outmethod);
455 //Store table of supertypes
456 generateSuperTypeTable(outmethod);
458 //Store the layout of classes
459 generateLayoutStructs(outmethod);
461 /* Generate code for methods */
462 if (state.DSM||state.SINGLETM) {
463 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
464 LocalityBinding lb=lbit.next();
465 MethodDescriptor md=lb.getMethod();
466 FlatMethod fm=state.getMethodFlat(md);
468 if (!md.getModifiers().isNative()) {
469 generateFlatMethod(fm, lb, outmethod);
473 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
474 while(classit.hasNext()) {
475 ClassDescriptor cn=(ClassDescriptor)classit.next();
476 Iterator methodit=cn.getMethods();
477 while(methodit.hasNext()) {
478 /* Classify parameters */
479 MethodDescriptor md=(MethodDescriptor)methodit.next();
480 FlatMethod fm=state.getMethodFlat(md);
481 if (!md.getModifiers().isNative()) {
482 generateFlatMethod(fm, null, outmethod);
489 protected void outputStructs(PrintWriter outstructs) {
490 outstructs.println("#ifndef STRUCTDEFS_H");
491 outstructs.println("#define STRUCTDEFS_H");
492 outstructs.println("#include \"classdefs.h\"");
493 outstructs.println("#ifndef INTPTR");
494 outstructs.println("#ifdef BIT64");
495 outstructs.println("#define INTPTR long");
496 outstructs.println("#else");
497 outstructs.println("#define INTPTR int");
498 outstructs.println("#endif");
499 outstructs.println("#endif");
501 /* Output #defines that the runtime uses to determine type
502 * numbers for various objects it needs */
503 outstructs.println("#define MAXCOUNT "+maxcount);
504 if (state.DSM||state.SINGLETM) {
505 LocalityBinding lb=new LocalityBinding(typeutil.getRun(), false);
507 lb.setGlobalThis(LocalityAnalysis.GLOBAL);
508 else if (state.SINGLETM)
509 lb.setGlobalThis(LocalityAnalysis.NORMAL);
510 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lb));
513 outstructs.println("#define STRINGARRAYTYPE "+
514 (state.getArrayNumber(
515 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
517 outstructs.println("#define OBJECTARRAYTYPE "+
518 (state.getArrayNumber(
519 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
522 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
523 outstructs.println("#define CHARARRAYTYPE "+
524 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
526 outstructs.println("#define BYTEARRAYTYPE "+
527 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
529 outstructs.println("#define BYTEARRAYARRAYTYPE "+
530 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
532 outstructs.println("#define NUMCLASSES "+state.numClasses());
533 int totalClassSize = state.numClasses() + state.numArrays();
534 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
536 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
537 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
538 outstructs.println("#define TAGARRAYTYPE "+
539 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
543 protected void outputClassDeclarations(PrintWriter outclassdefs) {
544 if (state.THREAD||state.DSM||state.SINGLETM)
545 outclassdefs.println("#include <pthread.h>");
546 outclassdefs.println("#ifndef INTPTR");
547 outclassdefs.println("#ifdef BIT64");
548 outclassdefs.println("#define INTPTR long");
549 outclassdefs.println("#else");
550 outclassdefs.println("#define INTPTR int");
551 outclassdefs.println("#endif");
552 outclassdefs.println("#endif");
554 outclassdefs.println("#include \"optionalstruct.h\"");
555 outclassdefs.println("struct "+arraytype+";");
556 /* Start by declaring all structs */
557 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
558 while(it.hasNext()) {
559 ClassDescriptor cn=(ClassDescriptor)it.next();
560 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
562 outclassdefs.println("");
563 //Print out definition for array type
564 outclassdefs.println("struct "+arraytype+" {");
565 outclassdefs.println(" int type;");
567 outclassdefs.println(" pthread_t tid;");
568 outclassdefs.println(" void * lockentry;");
569 outclassdefs.println(" int lockcount;");
572 outclassdefs.println(" int flag;");
573 if(!state.MULTICORE) {
574 outclassdefs.println(" void * flagptr;");
576 outclassdefs.println(" int version;");
577 outclassdefs.println(" struct ___Object___ * original;");
578 //outclassdefs.println(" int numlocks;"); // array for locks
579 outclassdefs.println(" int * lock;");
582 outclassdefs.println(" int numfses;");
583 outclassdefs.println(" int * fses;");
586 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
588 outclassdefs.println(" int ___length___;");
589 outclassdefs.println("};\n");
590 outclassdefs.println("extern int classsize[];");
591 outclassdefs.println("extern int hasflags[];");
592 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
593 outclassdefs.println("extern int supertypes[];");
596 /** Prints out definitions for generic task structures */
598 private void outputTaskTypes(PrintWriter outtask) {
599 outtask.println("#ifndef _TASK_H");
600 outtask.println("#define _TASK_H");
601 outtask.println("struct parameterdescriptor {");
602 outtask.println("int type;");
603 outtask.println("int numberterms;");
604 outtask.println("int *intarray;");
605 outtask.println("void * queue;");
606 outtask.println("int numbertags;");
607 outtask.println("int *tagarray;");
608 outtask.println("};");
610 outtask.println("struct taskdescriptor {");
611 outtask.println("void * taskptr;");
612 outtask.println("int numParameters;");
613 outtask.println(" int numTotal;");
614 outtask.println("struct parameterdescriptor **descriptorarray;");
615 outtask.println("char * name;");
616 outtask.println("};");
617 outtask.println("extern struct taskdescriptor * taskarray[];");
618 outtask.println("extern numtasks;");
619 outtask.println("#endif");
623 private void buildRepairStructs(PrintWriter outrepairstructs) {
624 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
625 while(classit.hasNext()) {
626 ClassDescriptor cn=(ClassDescriptor)classit.next();
627 outrepairstructs.println("structure "+cn.getSymbol()+" {");
628 outrepairstructs.println(" int __type__;");
630 outrepairstructs.println(" int __flag__;");
631 if(!state.MULTICORE) {
632 outrepairstructs.println(" int __flagptr__;");
635 printRepairStruct(cn, outrepairstructs);
636 outrepairstructs.println("}\n");
639 for(int i=0; i<state.numArrays(); i++) {
640 TypeDescriptor tdarray=arraytable[i];
641 TypeDescriptor tdelement=tdarray.dereference();
642 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
643 outrepairstructs.println(" int __type__;");
644 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
645 outrepairstructs.println(" int length;");
647 // Need to add support to repair tool for this
648 if (tdelement.isClass()||tdelement.isArray())
649 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
651 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
653 outrepairstructs.println("}\n");
657 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
658 ClassDescriptor sp=cn.getSuperDesc();
660 printRepairStruct(sp, output);
662 Vector fields=(Vector)fieldorder.get(cn);
664 for(int i=0; i<fields.size(); i++) {
665 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
666 if (fd.getType().isArray()) {
667 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
668 } else if (fd.getType().isClass())
669 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
670 else if (fd.getType().isFloat())
671 output.println(" int "+fd.getSymbol()+"; /* really float */");
673 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
677 /** This method outputs TaskDescriptor information */
678 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
679 for (int i=0; i<task.numParameters(); i++) {
680 VarDescriptor param_var=task.getParameter(i);
681 TypeDescriptor param_type=task.getParamType(i);
682 FlagExpressionNode param_flag=task.getFlag(param_var);
683 TagExpressionList param_tag=task.getTag(param_var);
686 if (param_flag==null) {
687 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
688 output.println("0x0, 0x0 };");
691 DNFFlag dflag=param_flag.getDNF();
692 dnfterms=dflag.size();
694 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
695 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
696 for(int j=0; j<dflag.size(); j++) {
699 Vector term=dflag.get(j);
702 for(int k=0; k<term.size(); k++) {
703 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
704 FlagDescriptor fd=dfa.getFlag();
705 boolean negated=dfa.getNegated();
706 int flagid=1<<((Integer)flags.get(fd)).intValue();
711 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
713 output.println("};");
716 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
717 //BUG...added next line to fix, test with any task program
719 for(int j=0; j<param_tag.numTags(); j++) {
722 /* for each tag we need */
723 /* which slot it is */
724 /* what type it is */
725 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
726 TempDescriptor tmp=param_tag.getTemp(j);
727 int slot=fm.getTagInt(tmp);
728 output.println(slot+", "+state.getTagId(tvd.getTag()));
730 output.println("};");
732 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
733 output.println("/* type */"+param_type.getClassDesc().getId()+",");
734 output.println("/* number of DNF terms */"+dnfterms+",");
735 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
736 output.println("0,");
737 //BUG, added next line to fix and else statement...test
738 //with any task program
740 output.println("/* number of tags */"+param_tag.numTags()+",");
742 output.println("/* number of tags */ 0,");
743 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
744 output.println("};");
748 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
749 for (int i=0; i<task.numParameters(); i++) {
752 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
754 output.println("};");
756 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
757 output.println("&"+task.getSafeSymbol()+",");
758 output.println("/* number of parameters */" +task.numParameters() + ",");
759 int numtotal=task.numParameters()+fm.numTags();
760 output.println("/* number total parameters */" +numtotal + ",");
761 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
762 output.println("\""+task.getSymbol()+"\"");
763 output.println("};");
767 /** The buildVirtualTables method outputs the virtual dispatch
768 * tables for methods. */
770 protected void buildVirtualTables(PrintWriter outvirtual) {
771 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
772 while(classit.hasNext()) {
773 ClassDescriptor cd=(ClassDescriptor)classit.next();
774 if (virtualcalls.getMethodCount(cd)>maxcount)
775 maxcount=virtualcalls.getMethodCount(cd);
777 MethodDescriptor[][] virtualtable=null;
778 LocalityBinding[][] lbvirtualtable=null;
779 if (state.DSM||state.SINGLETM)
780 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
782 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
784 /* Fill in virtual table */
785 classit=state.getClassSymbolTable().getDescriptorsIterator();
786 while(classit.hasNext()) {
787 ClassDescriptor cd=(ClassDescriptor)classit.next();
788 if (state.DSM||state.SINGLETM)
789 fillinRow(cd, lbvirtualtable, cd.getId());
791 fillinRow(cd, virtualtable, cd.getId());
794 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
795 Iterator arrayit=state.getArrayIterator();
796 while(arrayit.hasNext()) {
797 TypeDescriptor td=(TypeDescriptor)arrayit.next();
798 int id=state.getArrayNumber(td);
799 if (state.DSM||state.SINGLETM)
800 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
802 fillinRow(objectcd, virtualtable, id+state.numClasses());
805 outvirtual.print("void * virtualtable[]={");
806 boolean needcomma=false;
807 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
808 for(int j=0; j<maxcount; j++) {
810 outvirtual.print(", ");
811 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
812 LocalityBinding lb=lbvirtualtable[i][j];
813 MethodDescriptor md=lb.getMethod();
814 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
815 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
816 MethodDescriptor md=virtualtable[i][j];
817 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
819 outvirtual.print("0");
823 outvirtual.println("");
825 outvirtual.println("};");
829 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
830 /* Get inherited methods */
831 if (cd.getSuperDesc()!=null)
832 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
833 /* Override them with our methods */
834 for(Iterator it=cd.getMethods(); it.hasNext();) {
835 MethodDescriptor md=(MethodDescriptor)it.next();
836 if (md.isStatic()||md.getReturnType()==null)
838 int methodnum=virtualcalls.getMethodNumber(md);
839 virtualtable[rownum][methodnum]=md;
843 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
844 /* Get inherited methods */
845 if (cd.getSuperDesc()!=null)
846 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
847 /* Override them with our methods */
848 if (locality.getClassBindings(cd)!=null)
849 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
850 LocalityBinding lb=lbit.next();
851 MethodDescriptor md=lb.getMethod();
852 //Is the method static or a constructor
853 if (md.isStatic()||md.getReturnType()==null)
855 int methodnum=virtualcalls.getLocalityNumber(lb);
856 virtualtable[rownum][methodnum]=lb;
860 /** Generate array that contains the sizes of class objects. The
861 * object allocation functions in the runtime use this
864 private void generateSizeArray(PrintWriter outclassdefs) {
865 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
866 outclassdefs.print("#ifdef TRANSSTATS \n");
867 outclassdefs.print("extern int numTransAbort;\n");
868 outclassdefs.print("extern int numTransCommit;\n");
869 outclassdefs.print("extern int nSoftAbort;\n");
871 outclassdefs.print("extern int nchashSearch;\n");
872 outclassdefs.print("extern int nmhashSearch;\n");
873 outclassdefs.print("extern int nprehashSearch;\n");
874 outclassdefs.print("extern int nRemoteSend;\n");
875 outclassdefs.print("extern int bytesSent;\n");
876 outclassdefs.print("extern int bytesRecv;\n");
877 outclassdefs.print("extern void handle();\n");
878 } else if (state.SINGLETM) {
879 outclassdefs.println("extern int nSoftAbortAbort;");
880 outclassdefs.println("extern int nSoftAbortCommit;");
881 outclassdefs.println("#ifdef STMSTATS\n");
882 outclassdefs.println("extern int typesCausingAbort[];");
883 outclassdefs.println("#endif\n");
885 outclassdefs.print("#endif\n");
886 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
888 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
889 cdarray=new ClassDescriptor[state.numClasses()];
890 while(it.hasNext()) {
891 ClassDescriptor cd=(ClassDescriptor)it.next();
892 cdarray[cd.getId()]=cd;
895 arraytable=new TypeDescriptor[state.numArrays()];
897 Iterator arrayit=state.getArrayIterator();
898 while(arrayit.hasNext()) {
899 TypeDescriptor td=(TypeDescriptor)arrayit.next();
900 int id=state.getArrayNumber(td);
906 /* Print out types */
907 outclassdefs.println("/* ");
908 for(int i=0; i<state.numClasses(); i++) {
909 ClassDescriptor cd=cdarray[i];
910 outclassdefs.println(cd +" "+i);
913 for(int i=0; i<state.numArrays(); i++) {
914 TypeDescriptor arraytd=arraytable[i];
915 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
918 outclassdefs.println("*/");
921 outclassdefs.print("int classsize[]={");
923 boolean needcomma=false;
924 for(int i=0; i<state.numClasses(); i++) {
926 outclassdefs.print(", ");
927 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
932 for(int i=0; i<state.numArrays(); i++) {
934 outclassdefs.print(", ");
935 TypeDescriptor tdelement=arraytable[i].dereference();
936 if (tdelement.isArray()||tdelement.isClass())
937 outclassdefs.print("sizeof(void *)");
939 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
943 outclassdefs.println("};");
945 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
947 outclassdefs.print("int typearray[]={");
948 for(int i=0; i<state.numClasses(); i++) {
949 ClassDescriptor cd=cdarray[i];
950 ClassDescriptor supercd=cd.getSuperDesc();
952 outclassdefs.print(", ");
954 outclassdefs.print("-1");
956 outclassdefs.print(supercd.getId());
960 for(int i=0; i<state.numArrays(); i++) {
961 TypeDescriptor arraytd=arraytable[i];
962 ClassDescriptor arraycd=arraytd.getClassDesc();
965 outclassdefs.print(", ");
966 outclassdefs.print(objectclass.getId());
970 ClassDescriptor cd=arraycd.getSuperDesc();
973 TypeDescriptor supertd=new TypeDescriptor(cd);
974 supertd.setArrayCount(arraytd.getArrayCount());
975 type=state.getArrayNumber(supertd);
977 type+=state.numClasses();
980 cd=cd.getSuperDesc();
983 outclassdefs.print(", ");
984 outclassdefs.print(type);
988 outclassdefs.println("};");
993 outclassdefs.print("int typearray2[]={");
994 for(int i=0; i<state.numArrays(); i++) {
995 TypeDescriptor arraytd=arraytable[i];
996 ClassDescriptor arraycd=arraytd.getClassDesc();
999 outclassdefs.print(", ");
1000 outclassdefs.print("-1");
1004 ClassDescriptor cd=arraycd.getSuperDesc();
1005 int level=arraytd.getArrayCount()-1;
1007 for(; level>0; level--) {
1008 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1009 supertd.setArrayCount(level);
1010 type=state.getArrayNumber(supertd);
1012 type+=state.numClasses();
1017 outclassdefs.print(", ");
1018 outclassdefs.print(type);
1022 outclassdefs.println("};");
1025 /** Constructs params and temp objects for each method or task.
1026 * These objects tell the compiler which temps need to be
1029 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1030 MethodDescriptor md=fm.getMethod();
1031 TaskDescriptor task=fm.getTask();
1032 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1033 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1035 paramstable.put(lb, objectparams);
1036 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1037 } else if (md!=null)
1038 paramstable.put(md, objectparams);
1040 paramstable.put(task, objectparams);
1042 for(int i=0; i<fm.numParameters(); i++) {
1043 TempDescriptor temp=fm.getParameter(i);
1044 TypeDescriptor type=temp.getType();
1045 if (type.isPtr()&&GENERATEPRECISEGC)
1046 objectparams.addPtr(temp);
1048 objectparams.addPrim(temp);
1049 if(lb!=null&&saveset.contains(temp)) {
1050 backuptable.get(lb).put(temp, temp.createNew());
1054 for(int i=0; i<fm.numTags(); i++) {
1055 TempDescriptor temp=fm.getTag(i);
1056 if (GENERATEPRECISEGC)
1057 objectparams.addPtr(temp);
1059 objectparams.addPrim(temp);
1062 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1064 tempstable.put(lb, objecttemps);
1066 tempstable.put(md, objecttemps);
1068 tempstable.put(task, objecttemps);
1070 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1071 FlatNode fn=(FlatNode)nodeit.next();
1072 TempDescriptor[] writes=fn.writesTemps();
1073 for(int i=0; i<writes.length; i++) {
1074 TempDescriptor temp=writes[i];
1075 TypeDescriptor type=temp.getType();
1076 if (type.isPtr()&&GENERATEPRECISEGC)
1077 objecttemps.addPtr(temp);
1079 objecttemps.addPrim(temp);
1080 if(lb!=null&&saveset.contains(temp)&&
1081 !backuptable.get(lb).containsKey(temp))
1082 backuptable.get(lb).put(temp, temp.createNew());
1086 /* Create backup temps */
1088 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1089 TempDescriptor tmp=tmpit.next();
1090 TypeDescriptor type=tmp.getType();
1091 if (type.isPtr()&&GENERATEPRECISEGC)
1092 objecttemps.addPtr(tmp);
1094 objecttemps.addPrim(tmp);
1096 /* Create temp to hold revert table */
1097 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1098 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1099 if (GENERATEPRECISEGC)
1100 objecttemps.addPtr(reverttmp);
1102 objecttemps.addPrim(reverttmp);
1103 reverttable.put(lb, reverttmp);
1108 /** This method outputs the following information about classes
1110 * (1) For classes, what are the locations of pointers.
1111 * (2) For arrays, does the array contain pointers or primitives.
1112 * (3) For classes, does the class contain flags.
1115 private void generateLayoutStructs(PrintWriter output) {
1116 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1117 while(it.hasNext()) {
1118 ClassDescriptor cn=(ClassDescriptor)it.next();
1119 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1120 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1122 while(allit.hasNext()) {
1123 FieldDescriptor fd=(FieldDescriptor)allit.next();
1124 TypeDescriptor type=fd.getType();
1125 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1130 output.print(count);
1131 allit=cn.getFieldTable().getAllDescriptorsIterator();
1132 while(allit.hasNext()) {
1133 FieldDescriptor fd=(FieldDescriptor)allit.next();
1134 TypeDescriptor type=fd.getType();
1135 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1138 output.println(",");
1139 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1142 output.println("};");
1144 output.println("unsigned INTPTR * pointerarray[]={");
1145 boolean needcomma=false;
1146 for(int i=0; i<state.numClasses(); i++) {
1147 ClassDescriptor cn=cdarray[i];
1149 output.println(",");
1151 output.print(cn.getSafeSymbol()+"_pointers");
1154 for(int i=0; i<state.numArrays(); i++) {
1156 output.println(", ");
1157 TypeDescriptor tdelement=arraytable[i].dereference();
1158 if (tdelement.isArray()||tdelement.isClass())
1159 output.print("((unsigned INTPTR *)1)");
1165 output.println("};");
1167 output.println("int hasflags[]={");
1168 for(int i=0; i<state.numClasses(); i++) {
1169 ClassDescriptor cn=cdarray[i];
1171 output.println(", ");
1178 output.println("};");
1181 /** Print out table to give us supertypes */
1182 private void generateSuperTypeTable(PrintWriter output) {
1183 output.println("int supertypes[]={");
1184 boolean needcomma=false;
1185 for(int i=0; i<state.numClasses(); i++) {
1186 ClassDescriptor cn=cdarray[i];
1188 output.println(",");
1190 if (cn.getSuperDesc()!=null) {
1191 ClassDescriptor cdsuper=cn.getSuperDesc();
1192 output.print(cdsuper.getId());
1196 output.println("};");
1199 /** Force consistent field ordering between inherited classes. */
1201 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1203 ClassDescriptor sp=cn.getSuperDesc();
1205 printClassStruct(sp, classdefout);
1207 if (!fieldorder.containsKey(cn)) {
1208 Vector fields=new Vector();
1209 fieldorder.put(cn,fields);
1210 if (sp==null&&!state.TASK) {
1211 fields.add(cn.getFieldTable().get("cachedCode"));
1213 Iterator fieldit=cn.getFields();
1214 while(fieldit.hasNext()) {
1215 FieldDescriptor fd=(FieldDescriptor)fieldit.next();
1216 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol()))&&
1217 (!fd.getSymbol().equals("cachedCode")||state.TASK))
1221 Vector fields=(Vector)fieldorder.get(cn);
1223 for(int i=0; i<fields.size(); i++) {
1224 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1225 if (fd.getType().isClass()||fd.getType().isArray())
1226 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1228 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1233 /* Map flags to integers consistently between inherited
1236 protected void mapFlags(ClassDescriptor cn) {
1237 ClassDescriptor sp=cn.getSuperDesc();
1241 if (!flagorder.containsKey(cn)) {
1242 Hashtable flags=new Hashtable();
1243 flagorder.put(cn,flags);
1245 Hashtable superflags=(Hashtable)flagorder.get(sp);
1246 Iterator superflagit=superflags.keySet().iterator();
1247 while(superflagit.hasNext()) {
1248 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1249 Integer number=(Integer)superflags.get(fd);
1250 flags.put(fd, number);
1251 if ((number.intValue()+1)>max)
1252 max=number.intValue()+1;
1256 Iterator flagit=cn.getFlags();
1257 while(flagit.hasNext()) {
1258 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1259 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1260 flags.put(fd, new Integer(max++));
1266 /** This function outputs (1) structures that parameters are
1267 * passed in (when PRECISE GC is enabled) and (2) function
1268 * prototypes for the methods */
1270 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1271 /* Output class structure */
1272 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1273 classdefout.println(" int type;");
1275 classdefout.println(" pthread_t tid;");
1276 classdefout.println(" void * lockentry;");
1277 classdefout.println(" int lockcount;");
1281 classdefout.println(" int flag;");
1282 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1283 classdefout.println(" void * flagptr;");
1284 } else if (state.MULTICORE) {
1285 classdefout.println(" int version;");
1286 classdefout.println(" struct ___Object___ * original;");
1287 //classdefout.println(" int numlocks;"); // array for locks
1288 classdefout.println(" int * lock;");
1290 if (state.OPTIONAL) {
1291 classdefout.println(" int numfses;");
1292 classdefout.println(" int * fses;");
1295 printClassStruct(cn, classdefout);
1296 classdefout.println("};\n");
1298 if (state.DSM||state.SINGLETM) {
1299 /* Cycle through LocalityBindings */
1300 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1301 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1303 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1304 LocalityBinding lb=lbit.next();
1305 MethodDescriptor md=lb.getMethod();
1306 if (md.getModifiers().isNative()) {
1307 //make sure we only print a native method once
1308 if (nativemethods.contains(md)) {
1309 FlatMethod fm=state.getMethodFlat(md);
1310 generateTempStructs(fm, lb);
1313 nativemethods.add(md);
1315 generateMethod(cn, md, lb, headersout, output);
1318 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1319 MethodDescriptor md=(MethodDescriptor)methodit.next();
1320 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1321 //Need to build param structure for library code
1322 FlatMethod fm=state.getMethodFlat(md);
1323 generateTempStructs(fm, null);
1324 generateMethodParam(cn, md, null, output);
1329 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1330 MethodDescriptor md=(MethodDescriptor)methodit.next();
1331 generateMethod(cn, md, null, headersout, output);
1335 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1336 /* Output parameter structure */
1337 if (GENERATEPRECISEGC) {
1338 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1339 if ((state.DSM||state.SINGLETM)&&lb!=null)
1340 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1342 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1343 output.println(" INTPTR size;");
1344 output.println(" void * next;");
1345 for(int i=0; i<objectparams.numPointers(); i++) {
1346 TempDescriptor temp=objectparams.getPointer(i);
1347 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1349 output.println("};\n");
1353 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1354 FlatMethod fm=state.getMethodFlat(md);
1355 generateTempStructs(fm, lb);
1357 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1358 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1360 generateMethodParam(cn, md, lb, output);
1362 /* Output temp structure */
1363 if (GENERATEPRECISEGC) {
1364 if (state.DSM||state.SINGLETM)
1365 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1367 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1368 output.println(" INTPTR size;");
1369 output.println(" void * next;");
1370 for(int i=0; i<objecttemps.numPointers(); i++) {
1371 TempDescriptor temp=objecttemps.getPointer(i);
1372 if (temp.getType().isNull())
1373 output.println(" void * "+temp.getSafeSymbol()+";");
1375 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1377 output.println("};\n");
1380 /********* Output method declaration ***********/
1381 if (state.DSM||state.SINGLETM) {
1382 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1384 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1386 /* First the return type */
1387 if (md.getReturnType()!=null) {
1388 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1389 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1391 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1393 //catch the constructor case
1394 headersout.print("void ");
1396 /* Next the method name */
1397 if (state.DSM||state.SINGLETM) {
1398 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1400 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1402 boolean printcomma=false;
1403 if (GENERATEPRECISEGC) {
1404 if (state.DSM||state.SINGLETM) {
1405 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1407 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1411 /* Output parameter list*/
1412 for(int i=0; i<objectparams.numPrimitives(); i++) {
1413 TempDescriptor temp=objectparams.getPrimitive(i);
1415 headersout.print(", ");
1417 if (temp.getType().isClass()||temp.getType().isArray())
1418 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1420 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1422 headersout.println(");\n");
1426 /** This function outputs (1) structures that parameters are
1427 * passed in (when PRECISE GC is enabled) and (2) function
1428 * prototypes for the tasks */
1430 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1431 /* Cycle through tasks */
1432 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1434 while(taskit.hasNext()) {
1435 /* Classify parameters */
1436 TaskDescriptor task=(TaskDescriptor)taskit.next();
1437 FlatMethod fm=state.getMethodFlat(task);
1438 generateTempStructs(fm, null);
1440 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1441 TempObject objecttemps=(TempObject) tempstable.get(task);
1443 /* Output parameter structure */
1444 if (GENERATEPRECISEGC) {
1445 output.println("struct "+task.getSafeSymbol()+"_params {");
1447 output.println(" INTPTR size;");
1448 output.println(" void * next;");
1449 for(int i=0; i<objectparams.numPointers(); i++) {
1450 TempDescriptor temp=objectparams.getPointer(i);
1451 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1454 output.println("};\n");
1455 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1456 maxtaskparams=objectparams.numPointers()+fm.numTags();
1460 /* Output temp structure */
1461 if (GENERATEPRECISEGC) {
1462 output.println("struct "+task.getSafeSymbol()+"_locals {");
1463 output.println(" INTPTR size;");
1464 output.println(" void * next;");
1465 for(int i=0; i<objecttemps.numPointers(); i++) {
1466 TempDescriptor temp=objecttemps.getPointer(i);
1467 if (temp.getType().isNull())
1468 output.println(" void * "+temp.getSafeSymbol()+";");
1469 else if(temp.getType().isTag())
1470 output.println(" struct "+
1471 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1473 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1475 output.println("};\n");
1478 /* Output task declaration */
1479 headersout.print("void " + task.getSafeSymbol()+"(");
1481 boolean printcomma=false;
1482 if (GENERATEPRECISEGC) {
1483 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1485 headersout.print("void * parameterarray[]");
1486 headersout.println(");\n");
1490 /***** Generate code for FlatMethod fm. *****/
1492 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1493 static int atomicmethodcount=0;
1495 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1496 if (State.PRINTFLAT)
1497 System.out.println(fm.printMethod());
1498 MethodDescriptor md=fm.getMethod();
1499 TaskDescriptor task=fm.getTask();
1500 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1501 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1503 HashSet<AtomicRecord> arset=null;
1505 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1507 if (atomicmethodmap==null)
1508 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1510 //fix these so we get right strings for local variables
1511 localsprefixaddr=localsprefix;
1512 localsprefixderef=localsprefix+"->";
1513 arset=new HashSet<AtomicRecord>();
1515 //Generate commit methods here
1516 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1517 FlatNode fn=fnit.next();
1518 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1519 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0) {
1520 //We have an atomic enter
1521 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1522 Set<FlatNode> exitset=faen.getExits();
1524 String methodname=md.getSymbol()+(atomicmethodcount++);
1525 AtomicRecord ar=new AtomicRecord();
1529 atomicmethodmap.put(faen, ar);
1531 //build data structure declaration
1532 output.println("struct atomicprimitives_"+methodname+" {");
1534 Set<FlatNode> recordset=delaycomp.livecode(lb);
1535 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1536 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1537 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1539 ar.reallivein=new HashSet(liveinto);
1541 ar.liveoutvirtualread=liveoutvirtualread;
1543 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1544 TempDescriptor tmp=it.next();
1545 //remove the pointers
1546 if (tmp.getType().isPtr()) {
1549 //let's print it here
1550 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1553 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1554 TempDescriptor tmp=it.next();
1555 //remove the pointers
1556 if (tmp.getType().isPtr()) {
1558 } else if (!liveinto.contains(tmp)) {
1559 //let's print it here
1560 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1563 output.println("};");
1565 //print out method name
1566 output.println("void "+methodname+"(struct "+ cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix+", struct "+ cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals *"+localsprefix+", struct atomicprimitives_"+methodname+" * primitives) {");
1567 //build code for commit method
1569 //first define local primitives
1570 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1571 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1572 TempDescriptor tmp=tmpit.next();
1573 if (!tmp.getType().isPtr()) {
1574 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1575 //read from live into set
1576 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1579 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1583 //turn off write barrier generation
1585 generateCode(faen, fm, lb, exitset, output, false);
1586 //turn on write barrier generation
1588 output.println("}\n\n");
1592 //redefine these back to normal
1594 localsprefixaddr="&"+localsprefix;
1595 localsprefixderef=localsprefix+".";
1597 generateHeader(fm, lb, md!=null ? md : task,output);
1598 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1600 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1601 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1602 AtomicRecord ar=arit.next();
1603 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1607 if (GENERATEPRECISEGC) {
1608 if (md!=null&&(state.DSM||state.SINGLETM))
1609 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1610 else if (md!=null&&!(state.DSM||state.SINGLETM))
1611 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1613 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1615 output.print(objecttemp.numPointers()+",");
1616 output.print(paramsprefix);
1617 for(int j=0; j<objecttemp.numPointers(); j++)
1618 output.print(", NULL");
1619 output.println("};");
1622 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1623 TempDescriptor td=objecttemp.getPrimitive(i);
1624 TypeDescriptor type=td.getType();
1626 output.println(" void * "+td.getSafeSymbol()+";");
1627 else if (type.isClass()||type.isArray())
1628 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1630 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1633 /* Check to see if we need to do a GC if this is a
1634 * multi-threaded program...*/
1636 if ((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC) {
1637 //Don't bother if we aren't in recursive methods...The loops case will catch it
1638 if (callgraph.getAllMethods(md).contains(md)) {
1639 if (state.DSM&&lb.isAtomic())
1640 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1642 output.println("if (needtocollect) checkcollect("+localsprefixaddr+");");
1646 generateCode(fm.getNext(0), fm, lb, null, output, true);
1648 output.println("}\n\n");
1651 // when a new mlp thread is created for an issued SESE, it is started
1652 // by running this method which blocks on a cond variable until
1653 // it is allowed to transition to execute. Then a case statement
1654 // allows it to invoke the method with the proper SESE body, and after
1655 // exiting the SESE method, executes proper SESE exit code before the
1656 // thread can be destroyed
1657 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
1658 PrintWriter outmethod
1661 outmethodheader.println("void invokeSESEmethod( void* vargs );");
1662 outmethod.println( "void invokeSESEmethod( void* vargs ) {");
1663 outmethod.println( " int status;");
1664 outmethod.println( " char errmsg[128];");
1665 outmethod.println( " invokeSESEargs* args = (invokeSESEargs*) vargs;");
1668 // wait on a condition variable that dispatcher will signal
1669 // then this SESE instance's dependencies are resolved
1670 outmethod.println( " status = pthread_mutex_lock( args->invokee->startCondVarLock );");
1671 outmethod.println( " "+mlperrstr);
1672 outmethod.println( " while( !(args->invokee->startedExecuting) ){");
1673 outmethod.println( " status = pthread_cond_wait( args->invokee->startCondVar, args->invokee->startCondVarLock );");
1674 outmethod.println( " "+mlperrstr);
1675 outmethod.println( " }");
1678 // generate a case for each SESE class that can be invoked
1679 outmethod.println( " switch( args->classID ) {");
1680 outmethod.println( " ");
1681 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
1682 FlatSESEEnterNode fsen = seseit.next();
1683 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
1684 outmethod.println( " case "+fsen.getIdentifier()+":");
1685 generateSESEinvocation(fsen, outmethod);
1686 outmethod.println( " break;");
1687 outmethod.println( "");
1690 // default case should never be taken, error out
1691 outmethod.println( " default:");
1692 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
1693 outmethod.println( " exit(-30);");
1694 outmethod.println( " break;");
1695 outmethod.println( " }");
1696 outmethod.println( "}\n\n");
1699 private void generateSESEinvocation(FlatSESEEnterNode fsen,
1703 FlatMethod fm = fsen.getEnclosingFlatMeth();
1704 MethodDescriptor md = fm.getMethod();
1705 ClassDescriptor cn = md.getClassDesc();
1707 FlatMethod bogusfm = sese2bogusFlatMeth.get(fsen);
1708 MethodDescriptor bogusmd = bogusfm.getMethod();
1709 ParamsObject objectparams = (ParamsObject)paramstable.get(bogusmd);
1711 // first copy SESE record into param structure
1714 // then invoke the sese's method
1715 output.print(" "+cn.getSafeSymbol()+bogusmd.getSafeSymbol()+"_"+bogusmd.getSafeMethodDescriptor());
1716 output.print("( args->invokee, ");
1718 // first argument is parameter structure
1719 output.print("(struct "+cn.getSafeSymbol()+bogusmd.getSafeSymbol()+"__params*)");
1720 output.print("&(args->invokee->paramStruct)");
1722 // other arguments are primitive parameters
1723 for(int i=0; i<objectparams.numPrimitives(); i++) {
1724 TempDescriptor td=objectparams.getPrimitive(i);
1725 TypeDescriptor type=td.getType();
1726 assert type.isPrimitive();
1727 output.print( ", (("+fsen.namespaceStructNameString()+
1728 "*)args->invokee->namespace)->"+td );
1731 output.println(");");
1734 protected void generateMethodSESE(FlatSESEEnterNode fsen,
1736 PrintWriter outputStructs,
1737 PrintWriter outputMethHead,
1738 PrintWriter outputMethods
1742 FlatMethod fm = fsen.getEnclosingFlatMeth();
1743 MethodDescriptor md = fm.getMethod();
1744 ClassDescriptor cn = md.getClassDesc();
1747 //Creates bogus method descriptor to index into tables
1748 Modifiers bogusmod=new Modifiers();
1749 MethodDescriptor bogusmd=new MethodDescriptor(bogusmod,
1750 new TypeDescriptor(TypeDescriptor.VOID),
1751 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier());
1752 bogusmd.setClassDesc(cn);
1753 FlatMethod bogusfm=new FlatMethod(bogusmd, null);
1754 sese2bogusFlatMeth.put(fsen, bogusfm);
1757 //Build paramsobj for bogus method descriptor
1758 ParamsObject objectparams=new ParamsObject(bogusmd, tag++);
1759 paramstable.put(bogusmd, objectparams);
1761 for(int i=0; i<fsen.numParameters(); i++) {
1762 TempDescriptor temp=fsen.getParameter(i);
1763 TypeDescriptor type=temp.getType();
1764 if (type.isPtr()&&GENERATEPRECISEGC) {
1765 objectparams.addPtr(temp);
1767 objectparams.addPrim(temp);
1772 //Build normal temp object for bogus method descriptor
1773 TempObject objecttemps=new TempObject(objectparams,bogusmd,tag++);
1774 tempstable.put(bogusmd, objecttemps);
1776 for(Iterator nodeit=fsen.getNodeSet().iterator(); nodeit.hasNext();) {
1777 FlatNode fn=(FlatNode)nodeit.next();
1778 TempDescriptor[] writes=fn.writesTemps();
1779 for(int i=0; i<writes.length; i++) {
1780 TempDescriptor temp=writes[i];
1781 TypeDescriptor type=temp.getType();
1782 if (type.isPtr()&&GENERATEPRECISEGC)
1783 objecttemps.addPtr(temp);
1785 objecttemps.addPrim(temp);
1789 // declare namespace struct
1790 outputStructs.println(fsen.namespaceStructDeclarationString());
1792 //Generate code for parameters structure
1793 generateMethodParam(cn, bogusmd, null, outputStructs);
1795 //Generate code for locals structure
1796 outputStructs.println("struct "+cn.getSafeSymbol()+bogusmd.getSafeSymbol()+"_"+bogusmd.getSafeMethodDescriptor()+"_locals {");
1797 outputStructs.println(" INTPTR size;");
1798 outputStructs.println(" void * next;");
1799 for(int i=0; i<objecttemps.numPointers(); i++) {
1800 TempDescriptor temp=objecttemps.getPointer(i);
1801 if (temp.getType().isNull())
1802 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1804 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1806 outputStructs.println("};\n");
1809 // write method declaration to header file
1810 outputMethHead.print("void ");
1811 outputMethHead.print(cn.getSafeSymbol()+bogusmd.getSafeSymbol()+"_"+bogusmd.getSafeMethodDescriptor()+"(");
1812 outputMethHead.print("SESErecord* currentSESE, ");
1813 boolean printcomma=false;
1814 if (GENERATEPRECISEGC) {
1815 outputMethHead.print("struct "+cn.getSafeSymbol()+
1816 bogusmd.getSafeSymbol()+"_"+
1817 bogusmd.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1820 // Output parameter list
1821 for(int i=0; i<objectparams.numPrimitives(); i++) {
1822 TempDescriptor temp=objectparams.getPrimitive(i);
1824 outputMethHead.print(", ");
1826 if (temp.getType().isClass()||temp.getType().isArray())
1827 outputMethHead.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1829 outputMethHead.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1831 outputMethHead.println(");\n");
1834 generateFlatMethodSESE(bogusfm, cn, fsen, fsen.getFlatExit(), outputMethods);
1837 private void generateFlatMethodSESE(FlatMethod fm,
1839 FlatSESEEnterNode seseEnter,
1840 FlatSESEExitNode seseExit,
1844 MethodDescriptor md=fm.getMethod();
1845 ParamsObject objectparams=(ParamsObject)paramstable.get(md);
1846 generateHeader(fm, null, md, output, true);
1847 TempObject objecttemp=(TempObject) tempstable.get(md);
1850 if (GENERATEPRECISEGC) {
1851 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1852 output.print(objecttemp.numPointers()+",");
1853 output.print(paramsprefix);
1854 for(int j=0; j<objecttemp.numPointers(); j++)
1855 output.print(", NULL");
1856 output.println("};");
1859 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1860 TempDescriptor td=objecttemp.getPrimitive(i);
1861 TypeDescriptor type=td.getType();
1863 output.println(" void * "+td.getSafeSymbol()+";");
1864 else if (type.isClass()||type.isArray())
1865 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1867 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1871 // declare variables for naming SESE's
1872 Iterator<SESEandAgePair> pItr = seseEnter.getNeededStaticNames().iterator();
1873 while( pItr.hasNext() ) {
1874 SESEandAgePair p = pItr.next();
1875 output.println(" SESErecord* "+p+";");
1879 // Check to see if we need to do a GC if this is a
1880 // multi-threaded program...
1881 if (GENERATEPRECISEGC) {
1882 //Don't bother if we aren't in recursive methods...The loops case will catch it
1883 if (callgraph.getAllMethods(md).contains(md)) {
1884 output.println("if (needtocollect) checkcollect("+localsprefixaddr+");");
1888 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
1889 exitset.add(seseExit);
1890 generateCode(seseEnter.getNext(0), fm, null, exitset, output, true);
1893 output.println("}\n\n");
1896 protected void generateCode(FlatNode first,
1899 Set<FlatNode> stopset,
1900 PrintWriter output, boolean firstpass) {
1902 // for any method, allocate temps to use when
1903 // issuing a new SESE sometime during the execution
1904 // of that method, whether it be a user-defined method
1905 // or a method representing the body of an SESE
1906 // TODO: only do this if we know the method actually
1907 // contains an SESE issue, not currently an annotation
1909 output.println(" SESErecord* tempSESE;");
1910 output.println(" invokeSESEargs* tempSESEargs;");
1913 /* Assign labels to FlatNode's if necessary.*/
1914 Hashtable<FlatNode, Integer> nodetolabel=assignLabels(first, stopset);
1916 Set<FlatNode> storeset=null;
1917 HashSet<FlatNode> genset=null;
1918 Set<FlatNode> unionset=null;
1920 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1921 storeset=delaycomp.livecode(lb);
1922 genset=new HashSet<FlatNode>();
1924 genset.addAll(delaycomp.getCannotDelay(lb));
1925 genset.addAll(delaycomp.getOther(lb));
1927 genset.addAll(delaycomp.getNotReady(lb));
1929 unionset=new HashSet<FlatNode>();
1930 unionset.addAll(storeset);
1931 unionset.addAll(genset);
1934 /* Do the actual code generation */
1935 FlatNode current_node=null;
1936 HashSet tovisit=new HashSet();
1937 HashSet visited=new HashSet();
1939 tovisit.add(first.getNext(0));
1942 while(current_node!=null||!tovisit.isEmpty()) {
1943 if (current_node==null) {
1944 current_node=(FlatNode)tovisit.iterator().next();
1945 tovisit.remove(current_node);
1946 } else if (tovisit.contains(current_node)) {
1947 tovisit.remove(current_node);
1949 visited.add(current_node);
1950 if (nodetolabel.containsKey(current_node)) {
1951 output.println("L"+nodetolabel.get(current_node)+":");
1953 if (state.INSTRUCTIONFAILURE) {
1954 if (state.THREAD||state.DSM||state.SINGLETM) {
1955 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
1957 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
1959 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
1961 if (!state.DELAYCOMP||firstpass) {
1962 generateFlatNode(fm, lb, current_node, output);
1964 //store primitive variables in out set
1965 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
1966 Set<TempDescriptor> liveout=ar.liveout;
1967 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
1968 TempDescriptor tmp=tmpit.next();
1969 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
1972 if (current_node.kind()!=FKind.FlatReturnNode) {
1973 output.println(" return;");
1976 } else if(current_node.numNext()==1) {
1978 if (state.MLP && current_node.kind()==FKind.FlatSESEEnterNode) {
1979 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
1980 generateFlatNode(fm, lb, current_node, output);
1981 nextnode=fsen.getFlatExit().getNext(0);
1982 } else if (state.DELAYCOMP) {
1983 boolean specialprimitive=false;
1984 //skip literals...no need to add extra overhead
1985 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
1986 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
1987 if (!typedesc.isClass()&&!typedesc.isArray()) {
1988 specialprimitive=true;
1992 if (genset==null||genset.contains(current_node)||specialprimitive)
1993 generateFlatNode(fm, lb, current_node, output);
1994 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
1995 TempDescriptor wrtmp=current_node.writesTemps()[0];
1997 //need to store value written by previous node
1998 if (wrtmp.getType().isPtr()) {
1999 //only lock the objects that may actually need locking
2000 if (recorddc.getNeedTrans(lb, current_node)) {
2001 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");");
2003 output.println("STOREPTRNOTRANS("+generateTemp(fm, wrtmp,lb)+");");
2006 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");");
2009 //need to read value read by previous node
2010 if (wrtmp.getType().isPtr()) {
2011 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");");
2013 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");");
2017 nextnode=current_node.getNext(0);
2020 generateFlatNode(fm, lb, current_node, output);
2021 nextnode=current_node.getNext(0);
2023 if (visited.contains(nextnode)) {
2024 output.println("goto L"+nodetolabel.get(nextnode)+";");
2027 current_node=nextnode;
2028 } else if (current_node.numNext()==2) {
2030 if (state.DELAYCOMP) {
2031 boolean computeside=false;
2033 //need to record which way it should go
2034 if (genset==null||genset.contains(current_node)) {
2035 if (storeset!=null&&storeset.contains(current_node)) {
2036 //need to store which way branch goes
2037 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2039 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2041 //which side to execute
2045 if (genset.contains(current_node)) {
2046 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2047 } else if (storeset.contains(current_node)) {
2049 output.println("RESTOREANDBRANCH(L"+nodetolabel.get(current_node.getNext(1))+");");
2051 //which side to execute
2056 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2058 if (leftset.size()==0)
2060 if (visited.contains(current_node.getNext(branch))) {
2061 //already visited -- build jump
2062 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2065 current_node=current_node.getNext(branch);
2068 if (!visited.contains(current_node.getNext(1)))
2069 tovisit.add(current_node.getNext(1));
2070 if (visited.contains(current_node.getNext(0))) {
2071 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2074 current_node=current_node.getNext(0);
2078 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2079 if (!visited.contains(current_node.getNext(1)))
2080 tovisit.add(current_node.getNext(1));
2081 if (visited.contains(current_node.getNext(0))) {
2082 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2085 current_node=current_node.getNext(0);
2087 } else throw new Error();
2091 /** This method assigns labels to FlatNodes */
2092 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2093 return assignLabels(first, null);
2096 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2097 HashSet tovisit=new HashSet();
2098 HashSet visited=new HashSet();
2100 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2103 /*Assign labels first. A node needs a label if the previous
2104 * node has two exits or this node is a join point. */
2106 while(!tovisit.isEmpty()) {
2107 FlatNode fn=(FlatNode)tovisit.iterator().next();
2112 if(lastset!=null&&lastset.contains(fn)) {
2113 // if last is not null and matches, don't go
2114 // any further for assigning labels
2118 for(int i=0; i<fn.numNext(); i++) {
2119 FlatNode nn=fn.getNext(i);
2122 //1) Edge >1 of node
2123 nodetolabel.put(nn,new Integer(labelindex++));
2125 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2129 nodetolabel.put(nn,new Integer(labelindex++));
2137 /** Generate text string that corresponds to the TempDescriptor td. */
2138 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2139 MethodDescriptor md=fm.getMethod();
2140 TaskDescriptor task=fm.getTask();
2141 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2143 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2144 //System.out.println("generateTemp returns " + td.getSafeSymbol());
2145 return td.getSafeSymbol();
2148 if (objecttemps.isLocalPtr(td)) {
2149 return localsprefixderef+td.getSafeSymbol();
2152 if (objecttemps.isParamPtr(td)) {
2153 return paramsprefix+"->"+td.getSafeSymbol();
2159 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2161 case FKind.FlatAtomicEnterNode:
2162 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
2165 case FKind.FlatAtomicExitNode:
2166 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
2169 case FKind.FlatInstanceOfNode:
2170 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
2173 case FKind.FlatSESEEnterNode:
2174 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
2177 case FKind.FlatSESEExitNode:
2178 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
2181 case FKind.FlatGlobalConvNode:
2182 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
2185 case FKind.FlatTagDeclaration:
2186 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
2189 case FKind.FlatCall:
2190 generateFlatCall(fm, lb, (FlatCall) fn,output);
2193 case FKind.FlatFieldNode:
2194 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
2197 case FKind.FlatElementNode:
2198 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
2201 case FKind.FlatSetElementNode:
2202 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
2205 case FKind.FlatSetFieldNode:
2206 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
2210 generateFlatNew(fm, lb, (FlatNew) fn,output);
2213 case FKind.FlatOpNode:
2214 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
2217 case FKind.FlatCastNode:
2218 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
2221 case FKind.FlatLiteralNode:
2222 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
2225 case FKind.FlatReturnNode:
2226 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
2230 output.println("/* nop */");
2233 case FKind.FlatExit:
2234 output.println("/* exit */");
2237 case FKind.FlatBackEdge:
2238 if ((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC) {
2239 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
2240 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
2242 output.println("if (needtocollect) checkcollect("+localsprefixaddr+");");
2244 output.println("/* nop */");
2247 case FKind.FlatCheckNode:
2248 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
2251 case FKind.FlatFlagActionNode:
2252 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
2255 case FKind.FlatPrefetchNode:
2256 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
2259 case FKind.FlatOffsetNode:
2260 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
2269 CodePlan cp = mlpa.getCodePlan( fn );
2272 Set<VariableSourceToken> writeDynamic = cp.getWriteToDynamicSrc();
2273 if( writeDynamic != null ) {
2280 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
2281 output.println("/* FlatOffsetNode */");
2282 FieldDescriptor fd=fofn.getField();
2283 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
2284 output.println("/* offset */");
2287 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
2288 if (state.PREFETCH) {
2289 Vector oids = new Vector();
2290 Vector fieldoffset = new Vector();
2291 Vector endoffset = new Vector();
2292 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
2293 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
2294 PrefetchPair pp = (PrefetchPair) it.next();
2295 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
2296 /* Find prefetches that can generate oid */
2297 if(statusbase == LocalityAnalysis.GLOBAL) {
2298 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
2300 } else if (statusbase == LocalityAnalysis.LOCAL) {
2301 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
2308 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
2309 output.println("{");
2310 output.println("/* prefetch */");
2311 output.println("/* prefetchid_" + fpn.siteid + " */");
2312 output.println("void * prefptr;");
2313 output.println("int tmpindex;");
2315 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
2316 /*Create C code for oid array */
2317 output.print(" unsigned int oidarray_[] = {");
2318 boolean needcomma=false;
2319 for (Iterator it = oids.iterator(); it.hasNext();) {
2322 output.print(it.next());
2325 output.println("};");
2327 /*Create C code for endoffset values */
2328 output.print(" unsigned short endoffsetarry_[] = {");
2330 for (Iterator it = endoffset.iterator(); it.hasNext();) {
2333 output.print(it.next());
2336 output.println("};");
2338 /*Create C code for Field Offset Values */
2339 output.print(" short fieldarry_[] = {");
2341 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
2344 output.print(it.next());
2347 output.println("};");
2348 /* make the prefetch call to Runtime */
2349 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
2350 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
2351 output.println(" }");
2352 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
2353 output.println(" } else {");
2354 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
2355 output.println(" }");
2356 output.println("}");
2360 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
2361 short offsetcount = 0;
2365 } else if (localbase) {
2366 for(; breakindex<pp.desc.size(); breakindex++) {
2367 Descriptor desc=pp.getDescAt(breakindex);
2368 if (desc instanceof FieldDescriptor) {
2369 FieldDescriptor fd=(FieldDescriptor)desc;
2370 if (fd.isGlobal()) {
2378 if (breakindex>pp.desc.size()) //all local
2381 TypeDescriptor lasttype=pp.base.getType();
2382 String basestr=generateTemp(fm, pp.base, lb);
2384 boolean maybenull=fm.getMethod().isStatic()||
2385 !pp.base.equals(fm.getParameter(0));
2387 for(int i=0; i<breakindex; i++) {
2388 String indexcheck="";
2390 Descriptor desc=pp.getDescAt(i);
2391 if (desc instanceof FieldDescriptor) {
2392 FieldDescriptor fd=(FieldDescriptor)desc;
2394 if (!teststr.equals(""))
2396 teststr+="((prefptr="+basestr+")!=NULL)";
2397 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
2399 basestr=basestr+"->"+fd.getSafeSymbol();
2402 lasttype=fd.getType();
2404 IndexDescriptor id=(IndexDescriptor)desc;
2405 indexcheck="((tmpindex=";
2406 for(int j=0; j<id.tddesc.size(); j++) {
2407 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
2409 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
2411 if (!teststr.equals(""))
2413 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
2414 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
2416 lasttype=lasttype.dereference();
2421 if (teststr.equals("")) {
2422 oid="((unsigned int)"+basestr+")";
2424 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
2428 for(int i = breakindex; i < pp.desc.size(); i++) {
2429 String newfieldoffset;
2430 Object desc = pp.getDescAt(i);
2431 if(desc instanceof FieldDescriptor) {
2432 FieldDescriptor fd=(FieldDescriptor)desc;
2433 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
2434 lasttype=fd.getType();
2436 newfieldoffset = "";
2437 IndexDescriptor id=(IndexDescriptor)desc;
2438 for(int j = 0; j < id.tddesc.size(); j++) {
2439 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
2441 newfieldoffset += id.offset.toString();
2442 lasttype=lasttype.dereference();
2444 fieldoffset.add(newfieldoffset);
2447 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
2448 base+=pp.desc.size()-breakindex;
2449 endoffset.add(new Short((short)base));
2454 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
2455 if (lb!=fgcn.getLocality())
2457 /* Have to generate flat globalconv */
2458 if (fgcn.getMakePtr()) {
2460 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
2462 if ((dc==null)||dc.getNeedTrans(lb, fgcn)) {
2463 //need to do translation
2464 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
2468 /* Need to convert to OID */
2469 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
2470 if (fgcn.doConvert()||(delaycomp!=null&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
2471 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
2473 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
2479 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
2481 if (fion.getType().isArray()) {
2482 type=state.getArrayNumber(fion.getType())+state.numClasses();
2484 type=fion.getType().getClassDesc().getId();
2487 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
2488 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
2490 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
2493 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
2494 /* Check to see if we need to generate code for this atomic */
2495 if (locality==null) {
2496 output.println("pthread_mutex_lock(&atomiclock);");
2500 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
2504 if (state.DELAYCOMP) {
2505 AtomicRecord ar=atomicmethodmap.get(faen);
2507 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
2508 TempDescriptor tmp=tmpit.next();
2509 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2512 //copy outs that depend on path
2513 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
2514 TempDescriptor tmp=tmpit.next();
2515 if (!ar.livein.contains(tmp))
2516 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2520 /* Backup the temps. */
2521 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
2522 TempDescriptor tmp=tmpit.next();
2523 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
2526 output.println("goto transstart"+faen.getIdentifier()+";");
2528 /******* Print code to retry aborted transaction *******/
2529 output.println("transretry"+faen.getIdentifier()+":");
2532 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
2533 TempDescriptor tmp=tmpit.next();
2534 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
2538 /********* Need to revert local object store ********/
2539 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
2541 output.println("while ("+revertptr+") {");
2542 output.println("struct ___Object___ * tmpptr;");
2543 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
2544 output.println("REVERT_OBJ("+revertptr+");");
2545 output.println(revertptr+"=tmpptr;");
2546 output.println("}");
2548 /******* Tell the runtime to start the transaction *******/
2550 output.println("transstart"+faen.getIdentifier()+":");
2551 output.println("transStart();");
2553 if (state.ABORTREADERS) {
2554 output.println("if (_setjmp(aborttrans)) {");
2555 output.println(" goto transretry"+faen.getIdentifier()+"; }");
2559 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
2560 /* Check to see if we need to generate code for this atomic */
2561 if (locality==null) {
2562 output.println("pthread_mutex_unlock(&atomiclock);");
2565 if (locality.getAtomic(lb).get(faen).intValue()>0)
2567 //store the revert list before we lose the transaction object
2568 String revertptr=null;
2570 revertptr=generateTemp(fm, reverttable.get(lb),lb);
2571 output.println(revertptr+"=revertlist;");
2573 if (state.DELAYCOMP) {
2574 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
2577 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
2579 output.println("if (transCommit()) {");
2580 /* Transaction aborts if it returns true */
2581 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
2583 output.println("} else {");
2584 /* Need to commit local object store */
2585 output.println("while ("+revertptr+") {");
2586 output.println("struct ___Object___ * tmpptr;");
2587 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
2588 output.println("COMMIT_OBJ("+revertptr+");");
2589 output.println(revertptr+"=tmpptr;");
2590 output.println("}");
2592 output.println("}");
2593 if (state.DELAYCOMP) {
2595 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
2596 output.println("else {");
2597 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
2598 TempDescriptor tmp=tmpit.next();
2599 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
2601 output.println("}");
2605 public void generateFlatSESEEnterNode(FlatMethod fm, LocalityBinding lb, FlatSESEEnterNode fsen, PrintWriter output) {
2607 // SESE nodes can be parsed for normal compilation, just skip over them
2611 output.println("\n /* SESE "+fsen.getPrettyIdentifier()+" issue */");
2612 output.println(" tempSESE = mlpCreateSESErecord( "+
2613 fsen.getIdentifier()+", "+
2614 "malloc( sizeof( "+fsen.namespaceStructNameString()+") ), "+
2617 for( int i = 0; i < fsen.numParameters(); ++i ) {
2618 TempDescriptor td = fsen.getParameter( i );
2619 output.println(" (("+fsen.namespaceStructNameString()+
2620 "*)tempSESE->namespace)->"+td+" = "+td+";");
2623 output.println(" mlpIssue( tempSESE );");
2624 //output.println(" tempSESE = mlpSchedule();");
2626 // do a pthread_create wit invokeSESE as the argument
2627 // and pack all args into a single void*
2628 output.println(" tempSESEargs = malloc( sizeof( invokeSESEargs ) );");
2629 output.println(" tempSESEargs->classID = "+fsen.getIdentifier()+";");
2630 output.println(" tempSESEargs->invokee = mlpSchedule();");
2632 if( fsen.getParent() == null ) {
2633 output.println(" tempSESEargs->parent = NULL;");
2635 output.println(" tempSESEargs->parent = currentSESE;");
2638 output.println(" invokeSESEmethod( (void*) tempSESEargs );");
2639 output.println("\n");
2642 public void generateFlatSESEExitNode(FlatMethod fm, LocalityBinding lb, FlatSESEExitNode fsen, PrintWriter output) {
2644 // SESE nodes can be parsed for normal compilation, just skip over them
2649 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
2650 if (state.CONSCHECK) {
2651 String specname=fcn.getSpec();
2652 String varname="repairstate___";
2653 output.println("{");
2654 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
2656 TempDescriptor[] temps=fcn.getTemps();
2657 String[] vars=fcn.getVars();
2658 for(int i=0; i<temps.length; i++) {
2659 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
2662 output.println("if (doanalysis"+specname+"("+varname+")) {");
2663 output.println("free"+specname+"_state("+varname+");");
2664 output.println("} else {");
2665 output.println("/* Bad invariant */");
2666 output.println("free"+specname+"_state("+varname+");");
2667 output.println("abort_task();");
2668 output.println("}");
2669 output.println("}");
2673 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
2674 MethodDescriptor md=fc.getMethod();
2675 ParamsObject objectparams=(ParamsObject)paramstable.get(state.DSM||state.SINGLETM ? locality.getBinding(lb, fc) : md);
2676 ClassDescriptor cn=md.getClassDesc();
2677 output.println("{");
2678 if (GENERATEPRECISEGC) {
2679 if (state.DSM||state.SINGLETM) {
2680 LocalityBinding fclb=locality.getBinding(lb, fc);
2681 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
2683 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
2685 output.print(objectparams.numPointers());
2686 output.print(", "+localsprefixaddr);
2687 if (md.getThis()!=null) {
2689 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
2691 if (fc.getThis()!=null&&md.getThis()==null) {
2692 System.out.println("WARNING!!!!!!!!!!!!");
2693 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
2697 for(int i=0; i<fc.numArgs(); i++) {
2698 Descriptor var=md.getParameter(i);
2699 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
2700 if (objectparams.isParamPtr(paramtemp)) {
2701 TempDescriptor targ=fc.getArg(i);
2703 TypeDescriptor td=md.getParamType(i);
2705 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
2707 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
2710 output.println("};");
2715 if (fc.getReturnTemp()!=null)
2716 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
2718 /* Do we need to do virtual dispatch? */
2719 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
2721 if (state.DSM||state.SINGLETM) {
2722 LocalityBinding fclb=locality.getBinding(lb, fc);
2723 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
2725 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
2730 if (md.getReturnType().isClass()||md.getReturnType().isArray())
2731 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
2733 output.print(md.getReturnType().getSafeSymbol()+" ");
2734 output.print("(*)(");
2736 boolean printcomma=false;
2737 if (GENERATEPRECISEGC) {
2738 if (state.DSM||state.SINGLETM) {
2739 LocalityBinding fclb=locality.getBinding(lb, fc);
2740 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
2742 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
2746 for(int i=0; i<objectparams.numPrimitives(); i++) {
2747 TempDescriptor temp=objectparams.getPrimitive(i);
2751 if (temp.getType().isClass()||temp.getType().isArray())
2752 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
2754 output.print(temp.getType().getSafeSymbol());
2758 if (state.DSM||state.SINGLETM) {
2759 LocalityBinding fclb=locality.getBinding(lb, fc);
2760 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
2762 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
2766 boolean needcomma=false;
2767 if (GENERATEPRECISEGC) {
2768 output.print("&__parameterlist__");
2772 if (!GENERATEPRECISEGC) {
2773 if (fc.getThis()!=null) {
2774 TypeDescriptor ptd=md.getThis().getType();
2777 if (ptd.isClass()&&!ptd.isArray())
2778 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
2779 output.print(generateTemp(fm,fc.getThis(),lb));
2784 for(int i=0; i<fc.numArgs(); i++) {
2785 Descriptor var=md.getParameter(i);
2786 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
2787 if (objectparams.isParamPrim(paramtemp)) {
2788 TempDescriptor targ=fc.getArg(i);
2792 TypeDescriptor ptd=md.getParamType(i);
2793 if (ptd.isClass()&&!ptd.isArray())
2794 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
2795 output.print(generateTemp(fm, targ,lb));
2799 output.println(");");
2800 output.println(" }");
2803 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
2804 Set subclasses=typeutil.getSubClasses(thiscd);
2805 if (subclasses==null)
2807 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
2808 ClassDescriptor cd=(ClassDescriptor)classit.next();
2809 Set possiblematches=cd.getMethodTable().getSet(md.getSymbol());
2810 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
2811 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
2812 if (md.matches(matchmd))
2819 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
2820 if (state.SINGLETM) {
2821 //single machine transactional memory case
2822 String field=ffn.getField().getSafeSymbol();
2823 String src=generateTemp(fm, ffn.getSrc(),lb);
2824 String dst=generateTemp(fm, ffn.getDst(),lb);
2826 output.println(dst+"="+ src +"->"+field+ ";");
2827 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
2828 ((dc==null)||dc.getNeedTrans(lb, ffn))&&
2829 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
2830 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
2832 } else if (state.DSM) {
2833 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
2834 if (status==LocalityAnalysis.GLOBAL) {
2835 String field=ffn.getField().getSafeSymbol();
2836 String src=generateTemp(fm, ffn.getSrc(),lb);
2837 String dst=generateTemp(fm, ffn.getDst(),lb);
2839 if (ffn.getField().getType().isPtr()) {
2841 //TODO: Uncomment this when we have runtime support
2842 //if (ffn.getSrc()==ffn.getDst()) {
2843 //output.println("{");
2844 //output.println("void * temp="+src+";");
2845 //output.println("if (temp&0x1) {");
2846 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
2847 //output.println(src+"->"+field+"="+temp+";");
2848 //output.println("}");
2849 //output.println(dst+"=temp;");
2850 //output.println("}");
2852 output.println(dst+"="+ src +"->"+field+ ";");
2853 //output.println("if ("+dst+"&0x1) {");
2854 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
2855 //output.println(src+"->"+field+"="+src+"->"+field+";");
2856 //output.println("}");
2859 output.println(dst+"="+ src+"->"+field+";");
2861 } else if (status==LocalityAnalysis.LOCAL) {
2862 if (ffn.getField().getType().isPtr()&&
2863 ffn.getField().isGlobal()) {
2864 String field=ffn.getField().getSafeSymbol();
2865 String src=generateTemp(fm, ffn.getSrc(),lb);
2866 String dst=generateTemp(fm, ffn.getDst(),lb);
2867 output.println(dst+"="+ src +"->"+field+ ";");
2868 if (locality.getAtomic(lb).get(ffn).intValue()>0)
2869 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
2871 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
2872 } else if (status==LocalityAnalysis.EITHER) {
2873 //Code is reading from a null pointer
2874 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
2875 output.println("#ifndef RAW");
2876 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
2877 output.println("#endif");
2878 //This should throw a suitable null pointer error
2879 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
2881 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
2883 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
2887 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
2888 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
2889 throw new Error("Can't set array length");
2890 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
2891 //Single Machine Transaction Case
2892 boolean srcptr=fsfn.getSrc().getType().isPtr();
2893 String src=generateTemp(fm,fsfn.getSrc(),lb);
2894 String dst=generateTemp(fm,fsfn.getDst(),lb);
2895 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
2896 output.println("{");
2897 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
2898 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
2899 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
2901 output.println("INTPTR srcoid=(INTPTR)"+src+";");
2904 if (wb.needBarrier(fsfn)&&
2905 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
2906 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
2908 if (srcptr&!fsfn.getSrc().getType().isNull()) {
2909 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
2910 output.println("}");
2912 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
2914 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
2915 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
2916 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
2917 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
2919 String src=generateTemp(fm,fsfn.getSrc(),lb);
2920 String dst=generateTemp(fm,fsfn.getDst(),lb);
2922 output.println("{");
2923 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
2925 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
2928 if (wb.needBarrier(fsfn))
2929 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
2931 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
2933 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
2934 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
2935 /** Check if we need to copy */
2936 output.println("if(!"+dst+"->"+localcopystr+") {");
2937 /* Link object into list */
2938 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
2939 output.println(revertptr+"=revertlist;");
2940 if (GENERATEPRECISEGC)
2941 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
2943 output.println("COPY_OBJ("+dst+");");
2944 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
2945 output.println("revertlist=(struct ___Object___ *)"+dst+";");
2946 output.println("}");
2948 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
2950 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
2951 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
2952 //writing to a null...bad
2953 output.println("if ("+dst+") {");
2954 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
2956 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
2958 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
2961 output.println("}");
2964 if (state.FASTCHECK) {
2965 String dst=generateTemp(fm, fsfn.getDst(),lb);
2966 output.println("if(!"+dst+"->"+localcopystr+") {");
2967 /* Link object into list */
2968 if (GENERATEPRECISEGC)
2969 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
2971 output.println("COPY_OBJ("+dst+");");
2972 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
2973 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
2974 output.println("}");
2976 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
2980 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
2981 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2984 if (elementtype.isArray()||elementtype.isClass())
2987 type=elementtype.getSafeSymbol()+" ";
2989 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
2990 output.println("if ("+generateTemp(fm, fen.getIndex(),lb)+"< 0 | "+generateTemp(fm, fen.getIndex(),lb)+" >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___)");
2991 output.println("failedboundschk();");
2993 if (state.SINGLETM) {
2994 //Single machine transaction case
2995 String dst=generateTemp(fm, fen.getDst(),lb);
2996 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
2998 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
2999 ((dc==null)||dc.getNeedTrans(lb, fen))&&
3000 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
3001 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
3003 } else if (state.DSM) {
3004 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
3005 if (status==LocalityAnalysis.GLOBAL) {
3006 String dst=generateTemp(fm, fen.getDst(),lb);
3008 if (elementtype.isPtr()) {
3009 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3010 output.println("TRANSREAD("+dst+", "+dst+");");
3012 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3014 } else if (status==LocalityAnalysis.LOCAL) {
3015 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3016 } else if (status==LocalityAnalysis.EITHER) {
3017 //Code is reading from a null pointer
3018 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
3019 output.println("#ifndef RAW");
3020 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
3021 output.println("#endif");
3022 //This should throw a suitable null pointer error
3023 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3025 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
3027 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3031 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
3032 //TODO: need dynamic check to make sure this assignment is actually legal
3033 //Because Object[] could actually be something more specific...ie. Integer[]
3035 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
3038 if (elementtype.isArray()||elementtype.isClass())
3041 type=elementtype.getSafeSymbol()+" ";
3043 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
3044 output.println("if ("+generateTemp(fm, fsen.getIndex(),lb)+"< 0 | "+generateTemp(fm, fsen.getIndex(),lb)+" >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___)");
3045 output.println("failedboundschk();");
3048 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
3049 //Transaction set element case
3050 if (wb.needBarrier(fsen)&&
3051 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
3052 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
3054 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
3055 output.println("{");
3056 String src=generateTemp(fm, fsen.getSrc(), lb);
3057 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
3058 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
3059 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3061 output.println("INTPTR srcoid=(INTPTR)"+src+";");
3063 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
3064 output.println("}");
3066 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3068 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
3069 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
3070 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
3071 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
3072 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
3073 boolean dstlocal=statusdst==LocalityAnalysis.LOCAL;
3076 if (wb.needBarrier(fsen))
3077 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
3078 } else if (dstlocal) {
3079 /** Check if we need to copy */
3080 String dst=generateTemp(fm, fsen.getDst(),lb);
3081 output.println("if(!"+dst+"->"+localcopystr+") {");
3082 /* Link object into list */
3083 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3084 output.println(revertptr+"=revertlist;");
3085 if (GENERATEPRECISEGC)
3086 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3088 output.println("COPY_OBJ("+dst+");");
3089 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3090 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3091 output.println("}");
3092 } else throw new Error("Unknown array type");
3094 output.println("{");
3095 String src=generateTemp(fm, fsen.getSrc(), lb);
3096 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3097 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
3098 output.println("}");
3100 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3103 if (state.FASTCHECK) {
3104 String dst=generateTemp(fm, fsen.getDst(),lb);
3105 output.println("if(!"+dst+"->"+localcopystr+") {");
3106 /* Link object into list */
3107 if (GENERATEPRECISEGC)
3108 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3110 output.println("COPY_OBJ("+dst+");");
3111 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3112 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3113 output.println("}");
3115 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3119 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
3120 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
3121 //Stash pointer in case of GC
3122 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3123 output.println(revertptr+"=revertlist;");
3125 if (state.SINGLETM) {
3126 if (fn.getType().isArray()) {
3127 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
3128 if (locality.getAtomic(lb).get(fn).intValue()>0) {
3129 //inside transaction
3130 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3132 //outside transaction
3133 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3136 if (locality.getAtomic(lb).get(fn).intValue()>0) {
3137 //inside transaction
3138 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3140 //outside transaction
3141 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3144 } else if (fn.getType().isArray()) {
3145 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
3146 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
3147 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3148 } else if (GENERATEPRECISEGC) {
3149 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3151 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3154 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
3155 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
3156 } else if (GENERATEPRECISEGC) {
3157 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3159 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
3162 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
3163 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3164 String dst=generateTemp(fm,fn.getDst(),lb);
3165 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
3166 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3167 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3169 if (state.FASTCHECK) {
3170 String dst=generateTemp(fm,fn.getDst(),lb);
3171 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
3172 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3173 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3177 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
3178 if (GENERATEPRECISEGC) {
3179 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
3181 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
3185 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
3186 if (fon.getRight()!=null) {
3187 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
3188 if (fon.getLeft().getType().isLong())
3189 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
3191 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
3193 } else if (dc!=null) {
3194 output.print(generateTemp(fm, fon.getDest(),lb)+" = ");
3195 if (dc.getNeedLeftSrcTrans(lb, fon))
3196 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
3198 output.print(generateTemp(fm, fon.getLeft(),lb));
3199 output.print(fon.getOp().toString());
3200 if (dc.getNeedRightSrcTrans(lb, fon))
3201 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL);");
3203 output.println(generateTemp(fm,fon.getRight(),lb)+";");
3205 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
3206 } else if (fon.getOp().getOp()==Operation.ASSIGN)
3207 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
3208 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
3209 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
3210 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
3211 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
3212 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
3213 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
3214 else if (fon.getOp().getOp()==Operation.COMP)
3215 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
3216 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
3217 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
3219 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
3222 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
3223 /* TODO: Do type check here */
3224 if (fcn.getType().isArray()) {
3226 } else if (fcn.getType().isClass())
3227 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
3229 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
3232 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
3233 if (fln.getValue()==null)
3234 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
3235 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
3236 if (GENERATEPRECISEGC) {
3237 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
3238 //Stash pointer in case of GC
3239 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3240 output.println(revertptr+"=revertlist;");
3242 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
3243 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
3244 //Stash pointer in case of GC
3245 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3246 output.println("revertlist="+revertptr+";");
3249 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
3251 } else if (fln.getType().isBoolean()) {
3252 if (((Boolean)fln.getValue()).booleanValue())
3253 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
3255 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
3256 } else if (fln.getType().isChar()) {
3257 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
3258 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
3259 } else if (fln.getType().isLong()) {
3260 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
3262 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
3265 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
3266 if (frn.getReturnTemp()!=null) {
3267 if (frn.getReturnTemp().getType().isPtr())
3268 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
3270 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
3272 output.println("return;");
3276 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
3277 output.println("STOREANDBRANCH(!"+generateTemp(fm, fcb.getTest(),lb)+", "+label+");");
3280 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
3281 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
3284 /** This method generates header information for the method or
3285 * task referenced by the Descriptor des. */
3286 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
3287 generateHeader(fm, lb, des, output, false);
3290 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
3292 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
3293 MethodDescriptor md=null;
3294 TaskDescriptor task=null;
3295 if (des instanceof MethodDescriptor)
3296 md=(MethodDescriptor) des;
3298 task=(TaskDescriptor) des;
3300 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
3302 if (md!=null&&md.getReturnType()!=null) {
3303 if (md.getReturnType().isClass()||md.getReturnType().isArray())
3304 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3306 output.print(md.getReturnType().getSafeSymbol()+" ");
3308 //catch the constructor case
3309 output.print("void ");
3311 if (state.DSM||state.SINGLETM) {
3312 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
3314 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
3316 output.print(task.getSafeSymbol()+"(");
3318 if (addSESErecord) {
3319 output.print("SESErecord* currentSESE, ");
3322 boolean printcomma=false;
3323 if (GENERATEPRECISEGC) {
3325 if (state.DSM||state.SINGLETM) {
3326 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
3328 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
3330 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
3336 for(int i=0; i<objectparams.numPrimitives(); i++) {
3337 TempDescriptor temp=objectparams.getPrimitive(i);
3341 if (temp.getType().isClass()||temp.getType().isArray())
3342 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
3344 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
3346 output.println(") {");
3347 } else if (!GENERATEPRECISEGC) {
3348 /* Imprecise Task */
3349 output.println("void * parameterarray[]) {");
3350 /* Unpack variables */
3351 for(int i=0; i<objectparams.numPrimitives(); i++) {
3352 TempDescriptor temp=objectparams.getPrimitive(i);
3353 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
3355 for(int i=0; i<fm.numTags(); i++) {
3356 TempDescriptor temp=fm.getTag(i);
3357 int offset=i+objectparams.numPrimitives();
3358 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
3361 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
3362 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
3363 } else output.println(") {");
3366 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
3367 output.println("/* FlatFlagActionNode */");
3370 /* Process tag changes */
3371 Relation tagsettable=new Relation();
3372 Relation tagcleartable=new Relation();
3374 Iterator tagsit=ffan.getTempTagPairs();
3375 while (tagsit.hasNext()) {
3376 TempTagPair ttp=(TempTagPair) tagsit.next();
3377 TempDescriptor objtmp=ttp.getTemp();
3378 TagDescriptor tag=ttp.getTag();
3379 TempDescriptor tagtmp=ttp.getTagTemp();
3380 boolean tagstatus=ffan.getTagChange(ttp);
3382 tagsettable.put(objtmp, tagtmp);
3384 tagcleartable.put(objtmp, tagtmp);
3389 Hashtable flagandtable=new Hashtable();
3390 Hashtable flagortable=new Hashtable();
3392 /* Process flag changes */
3393 Iterator flagsit=ffan.getTempFlagPairs();
3394 while(flagsit.hasNext()) {
3395 TempFlagPair tfp=(TempFlagPair)flagsit.next();
3396 TempDescriptor temp=tfp.getTemp();
3397 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
3398 FlagDescriptor flag=tfp.getFlag();
3400 //Newly allocate objects that don't set any flags case
3401 if (flagortable.containsKey(temp)) {
3405 flagortable.put(temp,new Integer(mask));
3407 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
3408 boolean flagstatus=ffan.getFlagChange(tfp);
3411 if (flagortable.containsKey(temp)) {
3412 mask=((Integer)flagortable.get(temp)).intValue();
3415 flagortable.put(temp,new Integer(mask));
3417 int mask=0xFFFFFFFF;
3418 if (flagandtable.containsKey(temp)) {
3419 mask=((Integer)flagandtable.get(temp)).intValue();
3421 mask&=(0xFFFFFFFF^flagid);
3422 flagandtable.put(temp,new Integer(mask));
3428 HashSet flagtagset=new HashSet();
3429 flagtagset.addAll(flagortable.keySet());
3430 flagtagset.addAll(flagandtable.keySet());
3431 flagtagset.addAll(tagsettable.keySet());
3432 flagtagset.addAll(tagcleartable.keySet());
3434 Iterator ftit=flagtagset.iterator();
3435 while(ftit.hasNext()) {
3436 TempDescriptor temp=(TempDescriptor)ftit.next();
3439 Set tagtmps=tagcleartable.get(temp);
3440 if (tagtmps!=null) {
3441 Iterator tagit=tagtmps.iterator();
3442 while(tagit.hasNext()) {
3443 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
3444 if (GENERATEPRECISEGC)
3445 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
3447 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
3451 tagtmps=tagsettable.get(temp);
3452 if (tagtmps!=null) {
3453 Iterator tagit=tagtmps.iterator();
3454 while(tagit.hasNext()) {
3455 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
3456 if (GENERATEPRECISEGC)
3457 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
3459 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
3464 int andmask=0xFFFFFFF;
3466 if (flagortable.containsKey(temp))
3467 ormask=((Integer)flagortable.get(temp)).intValue();
3468 if (flagandtable.containsKey(temp))
3469 andmask=((Integer)flagandtable.get(temp)).intValue();
3470 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
3471 generateObjectDistribute(ffan, fm, lb, temp, output);
3475 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
3476 PrintWriter output, int ormask, int andmask) {
3477 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
3478 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
3480 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
3484 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
3485 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
3488 void generateOptionalHeader(PrintWriter headers) {
3491 headers.println("#include \"task.h\"\n\n");
3492 headers.println("#ifndef _OPTIONAL_STRUCT_");
3493 headers.println("#define _OPTIONAL_STRUCT_");
3495 //STRUCT PREDICATEMEMBER
3496 headers.println("struct predicatemember{");
3497 headers.println("int type;");
3498 headers.println("int numdnfterms;");
3499 headers.println("int * flags;");
3500 headers.println("int numtags;");
3501 headers.println("int * tags;\n};\n\n");
3503 //STRUCT OPTIONALTASKDESCRIPTOR
3504 headers.println("struct optionaltaskdescriptor{");
3505 headers.println("struct taskdescriptor * task;");
3506 headers.println("int index;");
3507 headers.println("int numenterflags;");
3508 headers.println("int * enterflags;");
3509 headers.println("int numpredicatemembers;");
3510 headers.println("struct predicatemember ** predicatememberarray;");
3511 headers.println("};\n\n");
3513 //STRUCT TASKFAILURE
3514 headers.println("struct taskfailure {");
3515 headers.println("struct taskdescriptor * task;");
3516 headers.println("int index;");
3517 headers.println("int numoptionaltaskdescriptors;");
3518 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
3520 //STRUCT FSANALYSISWRAPPER
3521 headers.println("struct fsanalysiswrapper{");
3522 headers.println("int flags;");
3523 headers.println("int numtags;");
3524 headers.println("int * tags;");
3525 headers.println("int numtaskfailures;");
3526 headers.println("struct taskfailure ** taskfailurearray;");
3527 headers.println("int numoptionaltaskdescriptors;");
3528 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
3530 //STRUCT CLASSANALYSISWRAPPER
3531 headers.println("struct classanalysiswrapper{");
3532 headers.println("int type;");
3533 headers.println("int numotd;");
3534 headers.println("struct optionaltaskdescriptor ** otdarray;");
3535 headers.println("int numfsanalysiswrappers;");
3536 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
3538 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
3540 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
3541 while(taskit.hasNext()) {
3542 TaskDescriptor td=(TaskDescriptor)taskit.next();
3543 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
3548 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
3549 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
3550 int predicateindex = 0;
3551 //iterate through the classes concerned by the predicate
3552 Set c_vard = predicate.vardescriptors;
3553 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
3556 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
3557 VarDescriptor vard = (VarDescriptor)vard_it.next();
3558 TypeDescriptor typed = vard.getType();
3560 //generate for flags
3561 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
3562 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3564 if (fen_hashset!=null) {
3565 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
3566 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
3568 DNFFlag dflag=fen.getDNF();
3569 numberterms+=dflag.size();
3571 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
3573 for(int j=0; j<dflag.size(); j++) {
3575 output.println(",");
3576 Vector term=dflag.get(j);
3579 for(int k=0; k<term.size(); k++) {
3580 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
3581 FlagDescriptor fd=dfa.getFlag();
3582 boolean negated=dfa.getNegated();
3583 int flagid=1<<((Integer)flags.get(fd)).intValue();
3588 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
3593 output.println("};\n");
3596 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
3597 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3600 for(int j=0; j<tagel.numTags(); j++) {
3602 output.println(",");
3603 TempDescriptor tmp=tagel.getTemp(j);
3604 if (!slotnumber.containsKey(tmp)) {
3605 Integer slotint=new Integer(current_slot++);
3606 slotnumber.put(tmp,slotint);
3608 int slot=slotnumber.get(tmp).intValue();
3609 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
3611 numtags = tagel.numTags();
3613 output.println("};");
3615 //store the result into a predicatemember struct
3616 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
3617 output.println("/*type*/"+typed.getClassDesc().getId()+",");
3618 output.println("/* number of dnf terms */"+numberterms+",");
3619 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3620 output.println("/* number of tag */"+numtags+",");
3621 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3622 output.println("};\n");
3627 //generate an array that stores the entire predicate
3628 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3629 for( int j = 0; j<predicateindex; j++) {
3630 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3631 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
3633 output.println("};\n");
3634 return predicateindex;
3638 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
3639 generateOptionalHeader(headers);
3641 output.println("#include \"optionalstruct.h\"\n\n");
3642 output.println("#include \"stdlib.h\"\n");
3644 HashSet processedcd = new HashSet();
3646 Enumeration e = safeexecution.keys();
3647 while (e.hasMoreElements()) {
3650 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
3651 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
3653 //Generate the struct of optionals
3654 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
3655 numotd = c_otd.size();
3656 if(maxotd<numotd) maxotd = numotd;
3657 if( !c_otd.isEmpty() ) {
3658 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
3659 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
3661 //generate the int arrays for the predicate
3662 Predicate predicate = otd.predicate;
3663 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
3664 TreeSet<Integer> fsset=new TreeSet<Integer>();
3665 //iterate through possible FSes corresponding to
3666 //the state when entering
3668 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
3669 FlagState fs = (FlagState)fses.next();
3671 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
3672 FlagDescriptor flagd = (FlagDescriptor)flags.next();
3673 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
3676 fsset.add(new Integer(flagid));
3677 //tag information not needed because tag
3678 //changes are not tolerated.
3681 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3682 boolean needcomma=false;
3683 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
3686 output.println(it.next());
3689 output.println("};\n");
3692 //generate optionaltaskdescriptor that actually
3693 //includes exit fses, predicate and the task
3695 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
3696 output.println("&task_"+otd.td.getSafeSymbol()+",");
3697 output.println("/*index*/"+otd.getIndex()+",");
3698 output.println("/*number of enter flags*/"+fsset.size()+",");
3699 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3700 output.println("/*number of members */"+predicateindex+",");
3701 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3702 output.println("};\n");
3706 // if there are no optionals, there is no need to build the rest of the struct
3708 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
3709 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
3710 if( !c_otd.isEmpty() ) {
3711 boolean needcomma=false;
3712 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
3713 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
3715 output.println(",");
3717 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
3720 output.println("};\n");
3722 //get all the possible flagstates reachable by an object
3723 Hashtable hashtbtemp = safeexecution.get(cdtemp);
3725 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
3726 fsts.addAll(hashtbtemp.keySet());
3727 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
3728 FlagState fs = (FlagState)fsit.next();
3731 //get the set of OptionalTaskDescriptors corresponding
3732 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
3733 //iterate through the OptionalTaskDescriptors and
3734 //store the pointers to the optionals struct (see on
3735 //top) into an array
3737 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
3738 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
3739 OptionalTaskDescriptor mm = mos.next();
3741 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
3743 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3746 output.println("};\n");
3748 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
3751 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
3752 FlagDescriptor flagd = (FlagDescriptor)flags.next();
3753 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
3757 //process tag information
3760 boolean first = true;
3761 Enumeration tag_enum = fs.getTags();
3762 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
3763 while(tag_enum.hasMoreElements()) {
3765 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
3769 output.println(", ");
3770 output.println("/*tagid*/"+state.getTagId(tagd));
3772 output.println("};");
3774 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
3775 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
3776 TaskIndex ti=itti.next();
3780 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
3782 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
3783 boolean needcomma=false;
3784 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
3785 OptionalTaskDescriptor otd=otdit.next();
3789 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
3791 output.println("};");
3793 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
3794 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
3795 output.print(ti.getIndex()+", ");
3796 output.print(otdset.size()+", ");
3797 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
3798 output.println("};");
3801 tiset=sa.getTaskIndex(fs);
3802 boolean needcomma=false;
3804 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
3805 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
3806 TaskIndex ti=itti.next();
3807 if (ti.isRuntime()) {
3814 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
3816 output.println("};\n");
3818 //Store the result in fsanalysiswrapper
3820 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
3821 output.println("/*flag*/"+flagid+",");
3822 output.println("/* number of tags*/"+tagcounter+",");
3823 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
3824 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
3825 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
3826 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
3827 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
3828 output.println("};\n");
3832 //Build the array of fsanalysiswrappers
3833 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
3834 boolean needcomma=false;
3835 for(int i = 0; i<fscounter; i++) {
3836 if (needcomma) output.print(",");
3837 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
3840 output.println("};");
3842 //Build the classanalysiswrapper referring to the previous array
3843 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
3844 output.println("/*type*/"+cdtemp.getId()+",");
3845 output.println("/*numotd*/"+numotd+",");
3846 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
3847 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
3848 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
3849 processedcd.add(cdtemp);
3852 //build an array containing every classes for which code has been build
3853 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
3854 for(int i=0; i<state.numClasses(); i++) {
3855 ClassDescriptor cn=cdarray[i];
3858 if (processedcd.contains(cn))
3859 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
3861 output.print("NULL");
3863 output.println("};");
3865 output.println("#define MAXOTD "+maxotd);
3866 headers.println("#endif");
3869 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
3870 Relation r=new Relation();
3871 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
3872 OptionalTaskDescriptor otd=otdit.next();
3873 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
3877 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
3878 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
3879 Set s=r.get(it.next());
3880 for(Iterator it2=s.iterator(); it2.hasNext();) {
3881 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
3889 protected void outputTransCode(PrintWriter output) {