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 boolean nonSESEpass=true;
71 DiscoverConflicts recorddc;
72 DelayComputation delaycomp;
75 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa) {
76 this(st, temptovar, typeutil, null, sa, pa, null);
79 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa) {
80 this(st, temptovar, typeutil, null, sa, pa, mlpa);
83 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, PrefetchAnalysis pa, MLPAnalysis mlpa) {
84 this(st, temptovar, typeutil, locality, null, pa, mlpa);
87 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa) {
92 callgraph=new CallGraph(state);
94 oidstr="___objlocation___";
95 this.temptovar=temptovar;
96 paramstable=new Hashtable();
97 tempstable=new Hashtable();
98 fieldorder=new Hashtable();
99 flagorder=new Hashtable();
100 this.typeutil=typeutil;
101 virtualcalls=new Virtual(state,locality);
102 if (locality!=null) {
103 this.locality=locality;
104 this.reverttable=new Hashtable<LocalityBinding, TempDescriptor>();
105 this.backuptable=new Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>>();
106 this.wb=new WriteBarrier(locality, st);
108 if (state.SINGLETM&&state.DCOPTS) {
109 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
110 this.dc=new DiscoverConflicts(locality, st, typeanalysis, null);
113 if (state.DELAYCOMP) {
114 //TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
115 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
116 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
117 delaycomp=new DelayComputation(locality, st, typeanalysis, gft);
118 delaycomp.doAnalysis();
119 dc=delaycomp.getConflicts();
120 recorddc=new DiscoverConflicts(locality, st, typeanalysis, delaycomp.getCannotDelayMap(), true, true, null);
121 recorddc.doAnalysis();
125 /** The buildCode method outputs C code for all the methods. The Flat
126 * versions of the methods must already be generated and stored in
127 * the State object. */
129 public void buildCode() {
130 /* Create output streams to write to */
131 PrintWriter outclassdefs=null;
132 PrintWriter outstructs=null;
133 PrintWriter outrepairstructs=null;
134 PrintWriter outmethodheader=null;
135 PrintWriter outmethod=null;
136 PrintWriter outvirtual=null;
137 PrintWriter outtask=null;
138 PrintWriter outtaskdefs=null;
139 PrintWriter outoptionalarrays=null;
140 PrintWriter optionalheaders=null;
143 outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
144 outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
145 outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
146 outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
147 outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
149 outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
150 outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
151 if (state.OPTIONAL) {
152 outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
153 optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
156 if (state.structfile!=null) {
157 outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
159 } catch (Exception e) {
164 /* Build the virtual dispatch tables */
165 buildVirtualTables(outvirtual);
167 /* Output includes */
168 outmethodheader.println("#ifndef METHODHEADERS_H");
169 outmethodheader.println("#define METHODHEADERS_H");
170 outmethodheader.println("#include \"structdefs.h\"");
172 outmethodheader.println("#include \"dstm.h\"");
173 if (state.SINGLETM) {
174 outmethodheader.println("#include \"tm.h\"");
175 outmethodheader.println("#include \"delaycomp.h\"");
177 if (state.ABORTREADERS) {
178 outmethodheader.println("#include \"abortreaders.h\"");
179 outmethodheader.println("#include <setjmp.h>");
182 outmethodheader.println("#include <stdlib.h>");
183 outmethodheader.println("#include <stdio.h>");
184 outmethodheader.println("#include <string.h>");
185 outmethodheader.println("#include \"mlp_runtime.h\"");
186 outmethodheader.println("#include \"psemaphore.h\"");
189 /* Output Structures */
190 outputStructs(outstructs);
192 // Output the C class declarations
193 // These could mutually reference each other
194 outputClassDeclarations(outclassdefs);
196 // Output function prototypes and structures for parameters
197 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
198 while(it.hasNext()) {
199 ClassDescriptor cn=(ClassDescriptor)it.next();
200 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader);
202 outclassdefs.close();
205 /* Map flags to integers */
206 /* The runtime keeps track of flags using these integers */
207 it=state.getClassSymbolTable().getDescriptorsIterator();
208 while(it.hasNext()) {
209 ClassDescriptor cn=(ClassDescriptor)it.next();
213 generateTaskStructs(outstructs, outmethodheader);
215 /* Outputs generic task structures if this is a task
217 outputTaskTypes(outtask);
221 // have to initialize some SESE compiler data before
222 // analyzing normal methods, which must happen before
223 // generating SESE internal code
224 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
225 FlatSESEEnterNode fsen = seseit.next();
226 initializeSESE( fsen );
230 /* Build the actual methods */
231 outputMethods(outmethod);
233 // Output function prototypes and structures for SESE's and code
236 // used to differentiate, during code generation, whether we are
237 // passing over SESE body code, or non-SESE code
240 // first generate code for each sese's internals
241 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
242 FlatSESEEnterNode fsen = seseit.next();
243 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
246 // then write the invokeSESE switch to decouple scheduler
247 // from having to do unique details of sese invocation
248 generateSESEinvocationMethod(outmethodheader, outmethod);
252 /* Output code for tasks */
253 outputTaskCode(outtaskdefs, outmethod);
255 /* Record maximum number of task parameters */
256 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
257 } else if (state.main!=null) {
258 /* Generate main method */
259 outputMainMethod(outmethod);
262 /* Generate information for task with optional parameters */
263 if (state.TASK&&state.OPTIONAL) {
264 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
265 outoptionalarrays.close();
268 /* Output structure definitions for repair tool */
269 if (state.structfile!=null) {
270 buildRepairStructs(outrepairstructs);
271 outrepairstructs.close();
275 outmethodheader.println("#endif");
276 outmethodheader.close();
278 outstructs.println("#endif");
283 /* This code just generates the main C method for java programs.
284 * The main C method packs up the arguments into a string array
285 * and passes it to the java main method. */
287 private void outputMainMethod(PrintWriter outmethod) {
288 outmethod.println("int main(int argc, const char *argv[]) {");
289 outmethod.println(" int i;");
292 //outmethod.println(" pthread_once( &mlpOnceObj, mlpInitOncePerThread );");
293 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
297 outmethod.println("#ifdef TRANSSTATS \n");
298 outmethod.println("handle();\n");
299 outmethod.println("#endif\n");
301 if (state.THREAD||state.DSM||state.SINGLETM) {
302 outmethod.println("initializethreads();");
305 outmethod.println("if (dstmStartup(argv[1])) {");
306 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
307 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
309 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
312 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
313 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
315 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
319 outmethod.println(" for(i=2;i<argc;i++) {");
321 outmethod.println(" for(i=1;i<argc;i++) {");
322 outmethod.println(" int length=strlen(argv[i]);");
323 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
324 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
326 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
329 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
331 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
332 outmethod.println(" }");
334 MethodDescriptor md=typeutil.getMain();
335 ClassDescriptor cd=typeutil.getMainClass();
337 outmethod.println(" {");
338 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
339 if (state.DSM||state.SINGLETM) {
340 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
342 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
343 outmethod.println("1, NULL,"+"stringarray};");
344 if (state.DSM||state.SINGLETM)
345 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
347 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
349 if (state.DSM||state.SINGLETM)
350 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
352 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
354 outmethod.println(" }");
357 outmethod.println("}");
360 if (state.THREAD||state.DSM||state.SINGLETM) {
361 outmethod.println("pthread_mutex_lock(&gclistlock);");
362 outmethod.println("threadcount--;");
363 outmethod.println("pthread_cond_signal(&gccond);");
364 outmethod.println("pthread_mutex_unlock(&gclistlock);");
367 if (state.DSM||state.SINGLETM) {
368 outmethod.println("#ifdef TRANSSTATS \n");
369 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
370 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
371 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
372 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
374 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
375 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
376 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
377 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
378 outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
379 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
380 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
381 } else if (state.SINGLETM) {
382 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
383 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
384 outmethod.println("#ifdef STMSTATS\n");
385 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
386 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
387 outmethod.println("}\n");
388 outmethod.println("#endif\n");
389 outmethod.println("fflush(stdout);");
391 outmethod.println("#endif\n");
394 if (state.THREAD||state.SINGLETM)
395 outmethod.println("pthread_exit(NULL);");
398 outmethod.println(" workScheduleBegin();");
401 outmethod.println("}");
404 /* This method outputs code for each task. */
406 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
407 /* Compile task based program */
408 outtaskdefs.println("#include \"task.h\"");
409 outtaskdefs.println("#include \"methodheaders.h\"");
410 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
411 while(taskit.hasNext()) {
412 TaskDescriptor td=(TaskDescriptor)taskit.next();
413 FlatMethod fm=state.getMethodFlat(td);
414 generateFlatMethod(fm, null, outmethod);
415 generateTaskDescriptor(outtaskdefs, fm, td);
418 //Output task descriptors
419 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
420 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
422 while(taskit.hasNext()) {
423 TaskDescriptor td=(TaskDescriptor)taskit.next();
427 outtaskdefs.println(",");
428 outtaskdefs.print("&task_"+td.getSafeSymbol());
430 outtaskdefs.println("};");
432 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
435 /* This method outputs most of the methods.c file. This includes
436 * some standard includes and then an array with the sizes of
437 * objets and array that stores supertype and then the code for
438 * the Java methods.. */
440 protected void outputMethods(PrintWriter outmethod) {
441 outmethod.println("#include \"methodheaders.h\"");
442 outmethod.println("#include \"virtualtable.h\"");
443 outmethod.println("#include \"runtime.h\"");
445 outmethod.println("#include \"addPrefetchEnhance.h\"");
446 outmethod.println("#include \"localobjects.h\"");
448 if (state.FASTCHECK) {
449 outmethod.println("#include \"localobjects.h\"");
451 if(state.MULTICORE) {
452 outmethod.println("#include \"task.h\"");
453 outmethod.println("#include \"multicoreruntime.h\"");
454 outmethod.println("#include \"runtime_arch.h\"");
456 if (state.THREAD||state.DSM||state.SINGLETM)
457 outmethod.println("#include <thread.h>");
458 if (state.main!=null) {
459 outmethod.println("#include <string.h>");
461 if (state.CONSCHECK) {
462 outmethod.println("#include \"checkers.h\"");
465 outmethod.println("#include <stdlib.h>");
466 outmethod.println("#include <stdio.h>");
467 outmethod.println("#include \"mlp_runtime.h\"");
468 outmethod.println("#include \"psemaphore.h\"");
472 //Store the sizes of classes & array elements
473 generateSizeArray(outmethod);
475 //Store table of supertypes
476 generateSuperTypeTable(outmethod);
478 //Store the layout of classes
479 generateLayoutStructs(outmethod);
481 /* Generate code for methods */
482 if (state.DSM||state.SINGLETM) {
483 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
484 LocalityBinding lb=lbit.next();
485 MethodDescriptor md=lb.getMethod();
486 FlatMethod fm=state.getMethodFlat(md);
488 if (!md.getModifiers().isNative()) {
489 generateFlatMethod(fm, lb, outmethod);
493 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
494 while(classit.hasNext()) {
495 ClassDescriptor cn=(ClassDescriptor)classit.next();
496 Iterator methodit=cn.getMethods();
497 while(methodit.hasNext()) {
498 /* Classify parameters */
499 MethodDescriptor md=(MethodDescriptor)methodit.next();
500 FlatMethod fm=state.getMethodFlat(md);
501 if (!md.getModifiers().isNative()) {
502 generateFlatMethod(fm, null, outmethod);
509 protected void outputStructs(PrintWriter outstructs) {
510 outstructs.println("#ifndef STRUCTDEFS_H");
511 outstructs.println("#define STRUCTDEFS_H");
512 outstructs.println("#include \"classdefs.h\"");
513 outstructs.println("#ifndef INTPTR");
514 outstructs.println("#ifdef BIT64");
515 outstructs.println("#define INTPTR long");
516 outstructs.println("#else");
517 outstructs.println("#define INTPTR int");
518 outstructs.println("#endif");
519 outstructs.println("#endif");
521 outstructs.println("#include \"mlp_runtime.h\"");
522 outstructs.println("#include \"psemaphore.h\"");
525 /* Output #defines that the runtime uses to determine type
526 * numbers for various objects it needs */
527 outstructs.println("#define MAXCOUNT "+maxcount);
528 if (state.DSM||state.SINGLETM) {
529 LocalityBinding lb=new LocalityBinding(typeutil.getRun(), false);
531 lb.setGlobalThis(LocalityAnalysis.GLOBAL);
532 else if (state.SINGLETM)
533 lb.setGlobalThis(LocalityAnalysis.NORMAL);
534 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lb));
537 outstructs.println("#define STRINGARRAYTYPE "+
538 (state.getArrayNumber(
539 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
541 outstructs.println("#define OBJECTARRAYTYPE "+
542 (state.getArrayNumber(
543 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
546 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
547 outstructs.println("#define CHARARRAYTYPE "+
548 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
550 outstructs.println("#define BYTEARRAYTYPE "+
551 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
553 outstructs.println("#define BYTEARRAYARRAYTYPE "+
554 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
556 outstructs.println("#define NUMCLASSES "+state.numClasses());
557 int totalClassSize = state.numClasses() + state.numArrays();
558 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
560 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
561 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
562 outstructs.println("#define TAGARRAYTYPE "+
563 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
567 protected void outputClassDeclarations(PrintWriter outclassdefs) {
568 if (state.THREAD||state.DSM||state.SINGLETM)
569 outclassdefs.println("#include <pthread.h>");
570 outclassdefs.println("#ifndef INTPTR");
571 outclassdefs.println("#ifdef BIT64");
572 outclassdefs.println("#define INTPTR long");
573 outclassdefs.println("#else");
574 outclassdefs.println("#define INTPTR int");
575 outclassdefs.println("#endif");
576 outclassdefs.println("#endif");
578 outclassdefs.println("#include \"optionalstruct.h\"");
579 outclassdefs.println("struct "+arraytype+";");
580 /* Start by declaring all structs */
581 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
582 while(it.hasNext()) {
583 ClassDescriptor cn=(ClassDescriptor)it.next();
584 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
586 outclassdefs.println("");
587 //Print out definition for array type
588 outclassdefs.println("struct "+arraytype+" {");
589 outclassdefs.println(" int type;");
591 outclassdefs.println(" pthread_t tid;");
592 outclassdefs.println(" void * lockentry;");
593 outclassdefs.println(" int lockcount;");
596 outclassdefs.println(" int flag;");
597 if(!state.MULTICORE) {
598 outclassdefs.println(" void * flagptr;");
600 outclassdefs.println(" int version;");
601 outclassdefs.println(" int * lock;"); // lock entry for this obj
602 outclassdefs.println(" int mutex;");
603 outclassdefs.println(" int lockcount;");
604 if(state.MULTICOREGC) {
605 outclassdefs.println(" int marked;");
609 outclassdefs.println(" int numfses;");
610 outclassdefs.println(" int * fses;");
613 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
616 outclassdefs.println(" int paddingforarray;");
618 outclassdefs.println(" int ___length___;");
619 outclassdefs.println("};\n");
620 outclassdefs.println("extern int classsize[];");
621 outclassdefs.println("extern int hasflags[];");
622 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
623 outclassdefs.println("extern int supertypes[];");
626 /** Prints out definitions for generic task structures */
628 private void outputTaskTypes(PrintWriter outtask) {
629 outtask.println("#ifndef _TASK_H");
630 outtask.println("#define _TASK_H");
631 outtask.println("struct parameterdescriptor {");
632 outtask.println("int type;");
633 outtask.println("int numberterms;");
634 outtask.println("int *intarray;");
635 outtask.println("void * queue;");
636 outtask.println("int numbertags;");
637 outtask.println("int *tagarray;");
638 outtask.println("};");
640 outtask.println("struct taskdescriptor {");
641 outtask.println("void * taskptr;");
642 outtask.println("int numParameters;");
643 outtask.println(" int numTotal;");
644 outtask.println("struct parameterdescriptor **descriptorarray;");
645 outtask.println("char * name;");
646 outtask.println("};");
647 outtask.println("extern struct taskdescriptor * taskarray[];");
648 outtask.println("extern numtasks;");
649 outtask.println("#endif");
653 private void buildRepairStructs(PrintWriter outrepairstructs) {
654 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
655 while(classit.hasNext()) {
656 ClassDescriptor cn=(ClassDescriptor)classit.next();
657 outrepairstructs.println("structure "+cn.getSymbol()+" {");
658 outrepairstructs.println(" int __type__;");
660 outrepairstructs.println(" int __flag__;");
661 if(!state.MULTICORE) {
662 outrepairstructs.println(" int __flagptr__;");
665 printRepairStruct(cn, outrepairstructs);
666 outrepairstructs.println("}\n");
669 for(int i=0; i<state.numArrays(); i++) {
670 TypeDescriptor tdarray=arraytable[i];
671 TypeDescriptor tdelement=tdarray.dereference();
672 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
673 outrepairstructs.println(" int __type__;");
674 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
675 outrepairstructs.println(" int length;");
677 // Need to add support to repair tool for this
678 if (tdelement.isClass()||tdelement.isArray())
679 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
681 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
683 outrepairstructs.println("}\n");
687 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
688 ClassDescriptor sp=cn.getSuperDesc();
690 printRepairStruct(sp, output);
692 Vector fields=(Vector)fieldorder.get(cn);
694 for(int i=0; i<fields.size(); i++) {
695 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
696 if (fd.getType().isArray()) {
697 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
698 } else if (fd.getType().isClass())
699 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
700 else if (fd.getType().isFloat())
701 output.println(" int "+fd.getSymbol()+"; /* really float */");
703 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
707 /** This method outputs TaskDescriptor information */
708 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
709 for (int i=0; i<task.numParameters(); i++) {
710 VarDescriptor param_var=task.getParameter(i);
711 TypeDescriptor param_type=task.getParamType(i);
712 FlagExpressionNode param_flag=task.getFlag(param_var);
713 TagExpressionList param_tag=task.getTag(param_var);
716 if (param_flag==null) {
717 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
718 output.println("0x0, 0x0 };");
721 DNFFlag dflag=param_flag.getDNF();
722 dnfterms=dflag.size();
724 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
725 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
726 for(int j=0; j<dflag.size(); j++) {
729 Vector term=dflag.get(j);
732 for(int k=0; k<term.size(); k++) {
733 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
734 FlagDescriptor fd=dfa.getFlag();
735 boolean negated=dfa.getNegated();
736 int flagid=1<<((Integer)flags.get(fd)).intValue();
741 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
743 output.println("};");
746 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
747 //BUG...added next line to fix, test with any task program
749 for(int j=0; j<param_tag.numTags(); j++) {
752 /* for each tag we need */
753 /* which slot it is */
754 /* what type it is */
755 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
756 TempDescriptor tmp=param_tag.getTemp(j);
757 int slot=fm.getTagInt(tmp);
758 output.println(slot+", "+state.getTagId(tvd.getTag()));
760 output.println("};");
762 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
763 output.println("/* type */"+param_type.getClassDesc().getId()+",");
764 output.println("/* number of DNF terms */"+dnfterms+",");
765 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
766 output.println("0,");
767 //BUG, added next line to fix and else statement...test
768 //with any task program
770 output.println("/* number of tags */"+param_tag.numTags()+",");
772 output.println("/* number of tags */ 0,");
773 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
774 output.println("};");
778 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
779 for (int i=0; i<task.numParameters(); i++) {
782 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
784 output.println("};");
786 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
787 output.println("&"+task.getSafeSymbol()+",");
788 output.println("/* number of parameters */" +task.numParameters() + ",");
789 int numtotal=task.numParameters()+fm.numTags();
790 output.println("/* number total parameters */" +numtotal + ",");
791 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
792 output.println("\""+task.getSymbol()+"\"");
793 output.println("};");
797 /** The buildVirtualTables method outputs the virtual dispatch
798 * tables for methods. */
800 protected void buildVirtualTables(PrintWriter outvirtual) {
801 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
802 while(classit.hasNext()) {
803 ClassDescriptor cd=(ClassDescriptor)classit.next();
804 if (virtualcalls.getMethodCount(cd)>maxcount)
805 maxcount=virtualcalls.getMethodCount(cd);
807 MethodDescriptor[][] virtualtable=null;
808 LocalityBinding[][] lbvirtualtable=null;
809 if (state.DSM||state.SINGLETM)
810 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
812 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
814 /* Fill in virtual table */
815 classit=state.getClassSymbolTable().getDescriptorsIterator();
816 while(classit.hasNext()) {
817 ClassDescriptor cd=(ClassDescriptor)classit.next();
818 if (state.DSM||state.SINGLETM)
819 fillinRow(cd, lbvirtualtable, cd.getId());
821 fillinRow(cd, virtualtable, cd.getId());
824 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
825 Iterator arrayit=state.getArrayIterator();
826 while(arrayit.hasNext()) {
827 TypeDescriptor td=(TypeDescriptor)arrayit.next();
828 int id=state.getArrayNumber(td);
829 if (state.DSM||state.SINGLETM)
830 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
832 fillinRow(objectcd, virtualtable, id+state.numClasses());
835 outvirtual.print("void * virtualtable[]={");
836 boolean needcomma=false;
837 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
838 for(int j=0; j<maxcount; j++) {
840 outvirtual.print(", ");
841 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
842 LocalityBinding lb=lbvirtualtable[i][j];
843 MethodDescriptor md=lb.getMethod();
844 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
845 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
846 MethodDescriptor md=virtualtable[i][j];
847 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
849 outvirtual.print("0");
853 outvirtual.println("");
855 outvirtual.println("};");
859 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
860 /* Get inherited methods */
861 if (cd.getSuperDesc()!=null)
862 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
863 /* Override them with our methods */
864 for(Iterator it=cd.getMethods(); it.hasNext();) {
865 MethodDescriptor md=(MethodDescriptor)it.next();
866 if (md.isStatic()||md.getReturnType()==null)
868 int methodnum=virtualcalls.getMethodNumber(md);
869 virtualtable[rownum][methodnum]=md;
873 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
874 /* Get inherited methods */
875 if (cd.getSuperDesc()!=null)
876 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
877 /* Override them with our methods */
878 if (locality.getClassBindings(cd)!=null)
879 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
880 LocalityBinding lb=lbit.next();
881 MethodDescriptor md=lb.getMethod();
882 //Is the method static or a constructor
883 if (md.isStatic()||md.getReturnType()==null)
885 int methodnum=virtualcalls.getLocalityNumber(lb);
886 virtualtable[rownum][methodnum]=lb;
890 /** Generate array that contains the sizes of class objects. The
891 * object allocation functions in the runtime use this
894 private void generateSizeArray(PrintWriter outclassdefs) {
895 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
896 outclassdefs.print("#ifdef TRANSSTATS \n");
897 outclassdefs.print("extern int numTransAbort;\n");
898 outclassdefs.print("extern int numTransCommit;\n");
899 outclassdefs.print("extern int nSoftAbort;\n");
901 outclassdefs.print("extern int nchashSearch;\n");
902 outclassdefs.print("extern int nmhashSearch;\n");
903 outclassdefs.print("extern int nprehashSearch;\n");
904 outclassdefs.print("extern int nRemoteSend;\n");
905 outclassdefs.print("extern int getResponse;\n");
906 outclassdefs.print("extern int bytesSent;\n");
907 outclassdefs.print("extern int bytesRecv;\n");
908 outclassdefs.print("extern void handle();\n");
909 } else if (state.SINGLETM) {
910 outclassdefs.println("extern int nSoftAbortAbort;");
911 outclassdefs.println("extern int nSoftAbortCommit;");
912 outclassdefs.println("#ifdef STMSTATS\n");
913 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
914 outclassdefs.println("#endif\n");
916 outclassdefs.print("#endif\n");
917 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
919 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
920 cdarray=new ClassDescriptor[state.numClasses()];
922 while(it.hasNext()) {
923 ClassDescriptor cd=(ClassDescriptor)it.next();
924 cdarray[cd.getId()]=cd;
927 arraytable=new TypeDescriptor[state.numArrays()];
929 Iterator arrayit=state.getArrayIterator();
930 while(arrayit.hasNext()) {
931 TypeDescriptor td=(TypeDescriptor)arrayit.next();
932 int id=state.getArrayNumber(td);
938 /* Print out types */
939 outclassdefs.println("/* ");
940 for(int i=0; i<state.numClasses(); i++) {
941 ClassDescriptor cd=cdarray[i];
943 outclassdefs.println("NULL " + i);
945 outclassdefs.println(cd +" "+i);
949 for(int i=0; i<state.numArrays(); i++) {
950 TypeDescriptor arraytd=arraytable[i];
951 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
954 outclassdefs.println("*/");
957 outclassdefs.print("int classsize[]={");
959 boolean needcomma=false;
960 for(int i=0; i<state.numClasses(); i++) {
962 outclassdefs.print(", ");
964 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
966 outclassdefs.print("0");
972 for(int i=0; i<state.numArrays(); i++) {
974 outclassdefs.print(", ");
975 TypeDescriptor tdelement=arraytable[i].dereference();
976 if (tdelement.isArray()||tdelement.isClass())
977 outclassdefs.print("sizeof(void *)");
979 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
983 outclassdefs.println("};");
985 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
987 outclassdefs.print("int typearray[]={");
988 for(int i=0; i<state.numClasses(); i++) {
989 ClassDescriptor cd=cdarray[i];
990 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
992 outclassdefs.print(", ");
994 outclassdefs.print("-1");
996 outclassdefs.print(supercd.getId());
1000 for(int i=0; i<state.numArrays(); i++) {
1001 TypeDescriptor arraytd=arraytable[i];
1002 ClassDescriptor arraycd=arraytd.getClassDesc();
1003 if (arraycd==null) {
1005 outclassdefs.print(", ");
1006 outclassdefs.print(objectclass.getId());
1010 ClassDescriptor cd=arraycd.getSuperDesc();
1013 TypeDescriptor supertd=new TypeDescriptor(cd);
1014 supertd.setArrayCount(arraytd.getArrayCount());
1015 type=state.getArrayNumber(supertd);
1017 type+=state.numClasses();
1020 cd=cd.getSuperDesc();
1023 outclassdefs.print(", ");
1024 outclassdefs.print(type);
1028 outclassdefs.println("};");
1033 outclassdefs.print("int typearray2[]={");
1034 for(int i=0; i<state.numArrays(); i++) {
1035 TypeDescriptor arraytd=arraytable[i];
1036 ClassDescriptor arraycd=arraytd.getClassDesc();
1037 if (arraycd==null) {
1039 outclassdefs.print(", ");
1040 outclassdefs.print("-1");
1044 ClassDescriptor cd=arraycd.getSuperDesc();
1045 int level=arraytd.getArrayCount()-1;
1047 for(; level>0; level--) {
1048 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1049 supertd.setArrayCount(level);
1050 type=state.getArrayNumber(supertd);
1052 type+=state.numClasses();
1057 outclassdefs.print(", ");
1058 outclassdefs.print(type);
1062 outclassdefs.println("};");
1065 /** Constructs params and temp objects for each method or task.
1066 * These objects tell the compiler which temps need to be
1069 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1070 MethodDescriptor md=fm.getMethod();
1071 TaskDescriptor task=fm.getTask();
1072 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1073 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1075 paramstable.put(lb, objectparams);
1076 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1077 } else if (md!=null)
1078 paramstable.put(md, objectparams);
1080 paramstable.put(task, objectparams);
1082 for(int i=0; i<fm.numParameters(); i++) {
1083 TempDescriptor temp=fm.getParameter(i);
1084 TypeDescriptor type=temp.getType();
1085 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1086 objectparams.addPtr(temp);
1088 objectparams.addPrim(temp);
1089 if(lb!=null&&saveset.contains(temp)) {
1090 backuptable.get(lb).put(temp, temp.createNew());
1094 for(int i=0; i<fm.numTags(); i++) {
1095 TempDescriptor temp=fm.getTag(i);
1096 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1097 objectparams.addPtr(temp);
1099 objectparams.addPrim(temp);
1102 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1104 tempstable.put(lb, objecttemps);
1106 tempstable.put(md, objecttemps);
1108 tempstable.put(task, objecttemps);
1110 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1111 FlatNode fn=(FlatNode)nodeit.next();
1112 TempDescriptor[] writes=fn.writesTemps();
1113 for(int i=0; i<writes.length; i++) {
1114 TempDescriptor temp=writes[i];
1115 TypeDescriptor type=temp.getType();
1116 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1117 objecttemps.addPtr(temp);
1119 objecttemps.addPrim(temp);
1120 if(lb!=null&&saveset.contains(temp)&&
1121 !backuptable.get(lb).containsKey(temp))
1122 backuptable.get(lb).put(temp, temp.createNew());
1126 /* Create backup temps */
1128 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1129 TempDescriptor tmp=tmpit.next();
1130 TypeDescriptor type=tmp.getType();
1131 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1132 objecttemps.addPtr(tmp);
1134 objecttemps.addPrim(tmp);
1136 /* Create temp to hold revert table */
1137 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1138 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1139 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1140 objecttemps.addPtr(reverttmp);
1142 objecttemps.addPrim(reverttmp);
1143 reverttable.put(lb, reverttmp);
1148 /** This method outputs the following information about classes
1150 * (1) For classes, what are the locations of pointers.
1151 * (2) For arrays, does the array contain pointers or primitives.
1152 * (3) For classes, does the class contain flags.
1155 private void generateLayoutStructs(PrintWriter output) {
1156 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1157 while(it.hasNext()) {
1158 ClassDescriptor cn=(ClassDescriptor)it.next();
1159 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1160 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1162 while(allit.hasNext()) {
1163 FieldDescriptor fd=(FieldDescriptor)allit.next();
1164 TypeDescriptor type=fd.getType();
1165 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1170 output.print(count);
1171 allit=cn.getFieldTable().getAllDescriptorsIterator();
1172 while(allit.hasNext()) {
1173 FieldDescriptor fd=(FieldDescriptor)allit.next();
1174 TypeDescriptor type=fd.getType();
1175 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1178 output.println(",");
1179 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1182 output.println("};");
1184 output.println("unsigned INTPTR * pointerarray[]={");
1185 boolean needcomma=false;
1186 for(int i=0; i<state.numClasses(); i++) {
1187 ClassDescriptor cn=cdarray[i];
1189 output.println(",");
1192 output.print(cn.getSafeSymbol()+"_pointers");
1194 output.print("NULL");
1198 for(int i=0; i<state.numArrays(); i++) {
1200 output.println(", ");
1201 TypeDescriptor tdelement=arraytable[i].dereference();
1202 if (tdelement.isArray()||tdelement.isClass())
1203 output.print("((unsigned INTPTR *)1)");
1209 output.println("};");
1211 output.println("int hasflags[]={");
1212 for(int i=0; i<state.numClasses(); i++) {
1213 ClassDescriptor cn=cdarray[i];
1215 output.println(", ");
1217 if ((cn != null) && (cn.hasFlags()))
1222 output.println("};");
1225 /** Print out table to give us supertypes */
1226 private void generateSuperTypeTable(PrintWriter output) {
1227 output.println("int supertypes[]={");
1228 boolean needcomma=false;
1229 for(int i=0; i<state.numClasses(); i++) {
1230 ClassDescriptor cn=cdarray[i];
1232 output.println(",");
1234 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1235 ClassDescriptor cdsuper=cn.getSuperDesc();
1236 output.print(cdsuper.getId());
1240 output.println("};");
1243 /** Force consistent field ordering between inherited classes. */
1245 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1247 ClassDescriptor sp=cn.getSuperDesc();
1249 printClassStruct(sp, classdefout);
1251 if (!fieldorder.containsKey(cn)) {
1252 Vector fields=new Vector();
1253 fieldorder.put(cn,fields);
1254 Vector fieldvec=cn.getFieldVec();
1255 for(int i=0;i<fieldvec.size();i++) {
1256 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1257 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1261 Vector fields=(Vector)fieldorder.get(cn);
1263 for(int i=0; i<fields.size(); i++) {
1264 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1265 if (fd.getType().isClass()||fd.getType().isArray())
1266 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1268 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1273 /* Map flags to integers consistently between inherited
1276 protected void mapFlags(ClassDescriptor cn) {
1277 ClassDescriptor sp=cn.getSuperDesc();
1281 if (!flagorder.containsKey(cn)) {
1282 Hashtable flags=new Hashtable();
1283 flagorder.put(cn,flags);
1285 Hashtable superflags=(Hashtable)flagorder.get(sp);
1286 Iterator superflagit=superflags.keySet().iterator();
1287 while(superflagit.hasNext()) {
1288 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1289 Integer number=(Integer)superflags.get(fd);
1290 flags.put(fd, number);
1291 if ((number.intValue()+1)>max)
1292 max=number.intValue()+1;
1296 Iterator flagit=cn.getFlags();
1297 while(flagit.hasNext()) {
1298 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1299 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1300 flags.put(fd, new Integer(max++));
1306 /** This function outputs (1) structures that parameters are
1307 * passed in (when PRECISE GC is enabled) and (2) function
1308 * prototypes for the methods */
1310 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1311 /* Output class structure */
1312 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1313 classdefout.println(" int type;");
1315 classdefout.println(" pthread_t tid;");
1316 classdefout.println(" void * lockentry;");
1317 classdefout.println(" int lockcount;");
1321 classdefout.println(" int flag;");
1322 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1323 classdefout.println(" void * flagptr;");
1324 } else if (state.MULTICORE) {
1325 classdefout.println(" int version;");
1326 classdefout.println(" int * lock;"); // lock entry for this obj
1327 classdefout.println(" int mutex;");
1328 classdefout.println(" int lockcount;");
1329 if(state.MULTICOREGC) {
1330 classdefout.println(" int marked;");
1333 if (state.OPTIONAL) {
1334 classdefout.println(" int numfses;");
1335 classdefout.println(" int * fses;");
1338 printClassStruct(cn, classdefout);
1339 classdefout.println("};\n");
1341 if (state.DSM||state.SINGLETM) {
1342 /* Cycle through LocalityBindings */
1343 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1344 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1346 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1347 LocalityBinding lb=lbit.next();
1348 MethodDescriptor md=lb.getMethod();
1349 if (md.getModifiers().isNative()) {
1350 //make sure we only print a native method once
1351 if (nativemethods.contains(md)) {
1352 FlatMethod fm=state.getMethodFlat(md);
1353 generateTempStructs(fm, lb);
1356 nativemethods.add(md);
1358 generateMethod(cn, md, lb, headersout, output);
1361 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1362 MethodDescriptor md=(MethodDescriptor)methodit.next();
1363 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1364 //Need to build param structure for library code
1365 FlatMethod fm=state.getMethodFlat(md);
1366 generateTempStructs(fm, null);
1367 generateMethodParam(cn, md, null, output);
1372 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1373 MethodDescriptor md=(MethodDescriptor)methodit.next();
1374 generateMethod(cn, md, null, headersout, output);
1378 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1379 /* Output parameter structure */
1380 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1381 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1382 if ((state.DSM||state.SINGLETM)&&lb!=null)
1383 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1385 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1386 output.println(" INTPTR size;");
1387 output.println(" void * next;");
1388 for(int i=0; i<objectparams.numPointers(); i++) {
1389 TempDescriptor temp=objectparams.getPointer(i);
1390 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1392 output.println("};\n");
1396 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1397 FlatMethod fm=state.getMethodFlat(md);
1398 generateTempStructs(fm, lb);
1400 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1401 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1403 generateMethodParam(cn, md, lb, output);
1405 /* Output temp structure */
1406 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1407 if (state.DSM||state.SINGLETM)
1408 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1410 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1411 output.println(" INTPTR size;");
1412 output.println(" void * next;");
1413 for(int i=0; i<objecttemps.numPointers(); i++) {
1414 TempDescriptor temp=objecttemps.getPointer(i);
1415 if (temp.getType().isNull())
1416 output.println(" void * "+temp.getSafeSymbol()+";");
1418 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1420 output.println("};\n");
1423 /********* Output method declaration ***********/
1424 if (state.DSM||state.SINGLETM) {
1425 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1427 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1429 /* First the return type */
1430 if (md.getReturnType()!=null) {
1431 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1432 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1434 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1436 //catch the constructor case
1437 headersout.print("void ");
1439 /* Next the method name */
1440 if (state.DSM||state.SINGLETM) {
1441 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1443 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1445 boolean printcomma=false;
1446 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1447 if (state.DSM||state.SINGLETM) {
1448 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1450 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1454 /* Output parameter list*/
1455 for(int i=0; i<objectparams.numPrimitives(); i++) {
1456 TempDescriptor temp=objectparams.getPrimitive(i);
1458 headersout.print(", ");
1460 if (temp.getType().isClass()||temp.getType().isArray())
1461 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1463 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1465 headersout.println(");\n");
1469 /** This function outputs (1) structures that parameters are
1470 * passed in (when PRECISE GC is enabled) and (2) function
1471 * prototypes for the tasks */
1473 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1474 /* Cycle through tasks */
1475 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1477 while(taskit.hasNext()) {
1478 /* Classify parameters */
1479 TaskDescriptor task=(TaskDescriptor)taskit.next();
1480 FlatMethod fm=state.getMethodFlat(task);
1481 generateTempStructs(fm, null);
1483 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1484 TempObject objecttemps=(TempObject) tempstable.get(task);
1486 /* Output parameter structure */
1487 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1488 output.println("struct "+task.getSafeSymbol()+"_params {");
1490 output.println(" INTPTR size;");
1491 output.println(" void * next;");
1492 for(int i=0; i<objectparams.numPointers(); i++) {
1493 TempDescriptor temp=objectparams.getPointer(i);
1494 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1497 output.println("};\n");
1498 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1499 maxtaskparams=objectparams.numPointers()+fm.numTags();
1503 /* Output temp structure */
1504 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1505 output.println("struct "+task.getSafeSymbol()+"_locals {");
1506 output.println(" INTPTR size;");
1507 output.println(" void * next;");
1508 for(int i=0; i<objecttemps.numPointers(); i++) {
1509 TempDescriptor temp=objecttemps.getPointer(i);
1510 if (temp.getType().isNull())
1511 output.println(" void * "+temp.getSafeSymbol()+";");
1512 else if(temp.getType().isTag())
1513 output.println(" struct "+
1514 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1516 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1518 output.println("};\n");
1521 /* Output task declaration */
1522 headersout.print("void " + task.getSafeSymbol()+"(");
1524 boolean printcomma=false;
1525 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1526 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1528 headersout.print("void * parameterarray[]");
1529 headersout.println(");\n");
1533 /***** Generate code for FlatMethod fm. *****/
1535 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1536 static int atomicmethodcount=0;
1538 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1539 if (State.PRINTFLAT)
1540 System.out.println(fm.printMethod());
1541 MethodDescriptor md=fm.getMethod();
1542 TaskDescriptor task=fm.getTask();
1543 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1544 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1546 HashSet<AtomicRecord> arset=null;
1548 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1550 if (atomicmethodmap==null)
1551 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1553 //fix these so we get right strings for local variables
1554 localsprefixaddr=localsprefix;
1555 localsprefixderef=localsprefix+"->";
1556 arset=new HashSet<AtomicRecord>();
1558 //Generate commit methods here
1559 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1560 FlatNode fn=fnit.next();
1561 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1562 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0) {
1563 //We have an atomic enter
1564 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1565 Set<FlatNode> exitset=faen.getExits();
1567 String methodname=md.getSymbol()+(atomicmethodcount++);
1568 AtomicRecord ar=new AtomicRecord();
1572 atomicmethodmap.put(faen, ar);
1574 //build data structure declaration
1575 output.println("struct atomicprimitives_"+methodname+" {");
1577 Set<FlatNode> recordset=delaycomp.livecode(lb);
1578 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1579 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1580 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1582 ar.reallivein=new HashSet(liveinto);
1584 ar.liveoutvirtualread=liveoutvirtualread;
1586 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1587 TempDescriptor tmp=it.next();
1588 //remove the pointers
1589 if (tmp.getType().isPtr()) {
1592 //let's print it here
1593 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1596 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1597 TempDescriptor tmp=it.next();
1598 //remove the pointers
1599 if (tmp.getType().isPtr()) {
1601 } else if (!liveinto.contains(tmp)) {
1602 //let's print it here
1603 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1606 output.println("};");
1608 //print out method name
1609 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) {");
1610 //build code for commit method
1612 //first define local primitives
1613 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1614 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1615 TempDescriptor tmp=tmpit.next();
1616 if (!tmp.getType().isPtr()) {
1617 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1618 //read from live into set
1619 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1622 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1626 //turn off write barrier generation
1628 state.SINGLETM=false;
1629 generateCode(faen, fm, lb, exitset, output, false);
1630 state.SINGLETM=true;
1631 //turn on write barrier generation
1633 output.println("}\n\n");
1637 //redefine these back to normal
1639 localsprefixaddr="&"+localsprefix;
1640 localsprefixderef=localsprefix+".";
1642 generateHeader(fm, lb, md!=null ? md : task,output);
1643 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1645 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1646 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1647 AtomicRecord ar=arit.next();
1648 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1652 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1653 if (md!=null&&(state.DSM||state.SINGLETM))
1654 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1655 else if (md!=null&&!(state.DSM||state.SINGLETM))
1656 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1658 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1660 output.print(objecttemp.numPointers()+",");
1661 output.print(paramsprefix);
1662 for(int j=0; j<objecttemp.numPointers(); j++)
1663 output.print(", NULL");
1664 output.println("};");
1667 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1668 TempDescriptor td=objecttemp.getPrimitive(i);
1669 TypeDescriptor type=td.getType();
1671 output.println(" void * "+td.getSafeSymbol()+";");
1672 else if (type.isClass()||type.isArray())
1673 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1675 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1680 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1681 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1682 if( callerSESEplaceholder != mlpa.getMainSESE() ) {
1683 // declare variables for naming static SESE's
1684 output.println(" /* static SESE names */");
1685 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1686 while( pItr.hasNext() ) {
1687 SESEandAgePair p = pItr.next();
1688 output.println(" void* "+p+";");
1691 // declare variables for tracking dynamic sources
1692 output.println(" /* dynamic variable sources */");
1693 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1694 while( dynSrcItr.hasNext() ) {
1695 TempDescriptor dynSrcVar = dynSrcItr.next();
1696 output.println(" void* "+dynSrcVar+"_srcSESE;");
1697 output.println(" int "+dynSrcVar+"_srcOffset;");
1704 /* Check to see if we need to do a GC if this is a
1705 * multi-threaded program...*/
1707 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1708 || this.state.MULTICOREGC) {
1709 //Don't bother if we aren't in recursive methods...The loops case will catch it
1710 if (callgraph.getAllMethods(md).contains(md)) {
1711 if (state.DSM&&lb.isAtomic())
1712 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1713 else if (this.state.MULTICOREGC) {
1714 output.println("if(gcflag) gc("+localsprefixaddr+");");
1716 output.println("if (needtocollect) checkcollect("+localsprefixaddr+");");
1720 generateCode(fm.getNext(0), fm, lb, null, output, true);
1722 output.println("}\n\n");
1726 protected void initializeSESE( FlatSESEEnterNode fsen ) {
1728 FlatMethod fm = fsen.getfmEnclosing();
1729 MethodDescriptor md = fm.getMethod();
1730 ClassDescriptor cn = md.getClassDesc();
1733 // Creates bogus method descriptor to index into tables
1734 Modifiers modBogus = new Modifiers();
1735 MethodDescriptor mdBogus =
1736 new MethodDescriptor( modBogus,
1737 new TypeDescriptor( TypeDescriptor.VOID ),
1738 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1741 mdBogus.setClassDesc( fsen.getcdEnclosing() );
1742 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1743 fsen.setfmBogus( fmBogus );
1744 fsen.setmdBogus( mdBogus );
1746 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1747 inSetAndOutSet.addAll( fsen.getInVarSet() );
1748 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1750 // Build paramsobj for bogus method descriptor
1751 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
1752 paramstable.put( mdBogus, objectparams );
1754 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1755 while( itr.hasNext() ) {
1756 TempDescriptor temp = itr.next();
1757 TypeDescriptor type = temp.getType();
1758 if( type.isPtr() ) {
1759 objectparams.addPtr( temp );
1761 objectparams.addPrim( temp );
1765 // Build normal temp object for bogus method descriptor
1766 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
1767 tempstable.put( mdBogus, objecttemps );
1769 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
1770 FlatNode fn = (FlatNode)nodeit.next();
1771 TempDescriptor[] writes = fn.writesTemps();
1773 for( int i = 0; i < writes.length; i++ ) {
1774 TempDescriptor temp = writes[i];
1775 TypeDescriptor type = temp.getType();
1777 if( type.isPtr() ) {
1778 objecttemps.addPtr( temp );
1780 objecttemps.addPrim( temp );
1786 protected void generateMethodSESE(FlatSESEEnterNode fsen,
1788 PrintWriter outputStructs,
1789 PrintWriter outputMethHead,
1790 PrintWriter outputMethods
1793 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
1794 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
1796 // generate locals structure
1797 outputStructs.println("struct "+
1798 fsen.getcdEnclosing().getSafeSymbol()+
1799 fsen.getmdBogus().getSafeSymbol()+"_"+
1800 fsen.getmdBogus().getSafeMethodDescriptor()+
1802 outputStructs.println(" INTPTR size;");
1803 outputStructs.println(" void * next;");
1804 for(int i=0; i<objecttemps.numPointers(); i++) {
1805 TempDescriptor temp=objecttemps.getPointer(i);
1807 if( fsen.getPrettyIdentifier().equals( "calc" ) ) {
1808 System.out.println( " got a pointer "+temp );
1811 if (temp.getType().isNull())
1812 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1814 outputStructs.println(" struct "+
1815 temp.getType().getSafeSymbol()+" * "+
1816 temp.getSafeSymbol()+";");
1818 outputStructs.println("};\n");
1821 // generate the SESE record structure
1822 outputStructs.println(fsen.getSESErecordName()+" {");
1824 // data common to any SESE, and it must be placed first so
1825 // a module that doesn't know what kind of SESE record this
1826 // is can cast the pointer to a common struct
1827 outputStructs.println(" SESEcommon common;");
1829 // then garbage list stuff
1830 outputStructs.println(" INTPTR size;");
1831 outputStructs.println(" void * next;");
1833 // in-set source tracking
1834 // in-vars that are READY come from parent, don't need anything
1835 // stuff STATIC needs a custom SESE pointer for each age pair
1836 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
1837 while( itrStaticInVarSrcs.hasNext() ) {
1838 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
1839 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
1842 // DYNAMIC stuff needs a source SESE ptr and offset
1843 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
1844 while( itrDynInVars.hasNext() ) {
1845 TempDescriptor dynInVar = itrDynInVars.next();
1846 outputStructs.println(" void* "+dynInVar+"_srcSESE;");
1847 outputStructs.println(" int "+dynInVar+"_srcOffset;");
1850 // space for all in and out set primitives
1851 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1852 inSetAndOutSet.addAll( fsen.getInVarSet() );
1853 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1855 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
1857 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1858 while( itr.hasNext() ) {
1859 TempDescriptor temp = itr.next();
1860 TypeDescriptor type = temp.getType();
1861 if( !type.isPtr() ) {
1862 inSetAndOutSetPrims.add( temp );
1866 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
1867 while( itrPrims.hasNext() ) {
1868 TempDescriptor temp = itrPrims.next();
1869 TypeDescriptor type = temp.getType();
1870 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
1873 for(int i=0; i<objectparams.numPointers(); i++) {
1874 TempDescriptor temp=objectparams.getPointer(i);
1875 if (temp.getType().isNull())
1876 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1878 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1881 outputStructs.println("};\n");
1884 // write method declaration to header file
1885 outputMethHead.print("void ");
1886 outputMethHead.print(fsen.getSESEmethodName()+"(");
1887 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
1888 outputMethHead.println(");\n");
1891 generateFlatMethodSESE( fsen.getfmBogus(),
1892 fsen.getcdEnclosing(),
1898 private void generateFlatMethodSESE(FlatMethod fm,
1900 FlatSESEEnterNode fsen,
1901 FlatSESEExitNode seseExit,
1905 MethodDescriptor md=fm.getMethod();
1907 output.print("void ");
1908 output.print(fsen.getSESEmethodName()+"(");
1909 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
1910 output.println("){\n");
1912 TempObject objecttemp=(TempObject) tempstable.get(md);
1914 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1915 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1916 output.print(objecttemp.numPointers()+",");
1917 output.print("(void*) &("+paramsprefix+"->size)");
1918 for(int j=0; j<objecttemp.numPointers(); j++)
1919 output.print(", NULL");
1920 output.println("};");
1923 output.println(" /* regular local primitives */");
1924 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1925 TempDescriptor td=objecttemp.getPrimitive(i);
1926 TypeDescriptor type=td.getType();
1928 output.println(" void * "+td.getSafeSymbol()+";");
1929 else if (type.isClass()||type.isArray())
1930 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1932 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1936 // declare variables for naming static SESE's
1937 output.println(" /* static SESE names */");
1938 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
1939 while( pItr.hasNext() ) {
1940 SESEandAgePair p = pItr.next();
1941 output.println(" void* "+p+";");
1944 // declare variables for tracking dynamic sources
1945 output.println(" /* dynamic variable sources */");
1946 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
1947 while( dynSrcItr.hasNext() ) {
1948 TempDescriptor dynSrcVar = dynSrcItr.next();
1949 output.println(" void* "+dynSrcVar+"_srcSESE;");
1950 output.println(" int "+dynSrcVar+"_srcOffset;");
1953 // declare local temps for in-set primitives, and if it is
1954 // a ready-source variable, get the value from the record
1955 output.println(" /* local temps for in-set primitives */");
1956 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
1957 while( itrInSet.hasNext() ) {
1958 TempDescriptor temp = itrInSet.next();
1959 TypeDescriptor type = temp.getType();
1960 if( !type.isPtr() ) {
1961 if( fsen.getReadyInVarSet().contains( temp ) ) {
1962 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
1964 output.println(" "+type+" "+temp+";");
1969 // declare local temps for out-set primitives if its not already
1970 // in the in-set, and it's value will get written so no problem
1971 output.println(" /* local temp for out-set prim, not already in the in-set */");
1972 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
1973 while( itrOutSet.hasNext() ) {
1974 TempDescriptor temp = itrOutSet.next();
1975 TypeDescriptor type = temp.getType();
1976 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
1977 output.println(" "+type+" "+temp+";");
1981 // copy in-set into place, ready vars were already
1982 // copied when the SESE was issued
1983 Iterator<TempDescriptor> tempItr;
1985 // static vars are from a known SESE
1986 tempItr = fsen.getStaticInVarSet().iterator();
1987 while( tempItr.hasNext() ) {
1988 TempDescriptor temp = tempItr.next();
1989 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
1990 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
1992 // can't grab something from this source until it is done
1993 output.println(" {");
1994 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+srcPair+";" );
1995 output.println(" pthread_mutex_lock( &(com->lock) );");
1996 output.println(" while( com->doneExecuting == FALSE ) {");
1997 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
1998 output.println(" }");
1999 output.println(" pthread_mutex_unlock( &(com->lock) );");
2001 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2002 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2004 output.println(" }");
2007 // dynamic vars come from an SESE and src
2008 tempItr = fsen.getDynamicInVarSet().iterator();
2009 while( tempItr.hasNext() ) {
2010 TempDescriptor temp = tempItr.next();
2011 TypeDescriptor type = temp.getType();
2013 // go grab it from the SESE source
2014 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2016 // gotta wait until the source is done
2017 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+temp+"_srcSESE;" );
2018 output.println(" pthread_mutex_lock( &(com->lock) );");
2019 output.println(" while( com->doneExecuting == FALSE ) {");
2020 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2021 output.println(" }");
2022 output.println(" pthread_mutex_unlock( &(com->lock) );");
2025 if( type.isNull() ) {
2027 } else if( type.isClass() || type.isArray() ) {
2028 typeStr = "struct "+type.getSafeSymbol()+"*";
2030 typeStr = type.getSafeSymbol();
2033 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2034 " = *(("+typeStr+"*) ("+
2035 paramsprefix+"->"+temp+"_srcSESE + "+
2036 paramsprefix+"->"+temp+"_srcOffset));");
2038 // or if the source was our parent, its in the record to grab
2039 output.println(" } else {");
2040 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2041 " = "+paramsprefix+"->"+temp+";");
2042 output.println(" }");
2045 // Check to see if we need to do a GC if this is a
2046 // multi-threaded program...
2047 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2048 //Don't bother if we aren't in recursive methods...The loops case will catch it
2049 if (callgraph.getAllMethods(md).contains(md)) {
2050 if(this.state.MULTICOREGC) {
2051 output.println("if(gcflag) gc("+localsprefixaddr+");");
2053 output.println("if (needtocollect) checkcollect("+localsprefixaddr+");");
2058 // initialize thread-local var to a non-zero, invalid address
2059 output.println(" seseCaller = (SESEcommon*) 0x2;");
2061 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2062 exitset.add(seseExit);
2064 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2066 output.println("}\n\n");
2070 // when a new mlp thread is created for an issued SESE, it is started
2071 // by running this method which blocks on a cond variable until
2072 // it is allowed to transition to execute. Then a case statement
2073 // allows it to invoke the method with the proper SESE body, and after
2074 // exiting the SESE method, executes proper SESE exit code before the
2075 // thread can be destroyed
2076 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2077 PrintWriter outmethod
2080 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2081 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2082 outmethod.println( " int status;");
2083 outmethod.println( " char errmsg[128];");
2085 // generate a case for each SESE class that can be invoked
2086 outmethod.println( " switch( *((int*)seseRecord) ) {");
2087 outmethod.println( " ");
2088 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
2089 FlatSESEEnterNode fsen = seseit.next();
2091 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2092 outmethod.println( " case "+fsen.getIdentifier()+":");
2093 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2095 if( fsen.equals( mlpa.getMainSESE() ) ) {
2096 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2097 outmethod.println( " exit( 0 );");
2100 outmethod.println( " break;");
2101 outmethod.println( "");
2104 // default case should never be taken, error out
2105 outmethod.println( " default:");
2106 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2107 outmethod.println( " exit(-30);");
2108 outmethod.println( " break;");
2109 outmethod.println( " }");
2110 outmethod.println( " return NULL;");
2111 outmethod.println( "}\n\n");
2115 protected void generateCode(FlatNode first,
2118 Set<FlatNode> stopset,
2119 PrintWriter output, boolean firstpass) {
2121 /* Assign labels to FlatNode's if necessary.*/
2122 Hashtable<FlatNode, Integer> nodetolabel=assignLabels(first, stopset);
2124 Set<FlatNode> storeset=null;
2125 HashSet<FlatNode> genset=null;
2126 Set<FlatNode> unionset=null;
2128 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2129 storeset=delaycomp.livecode(lb);
2130 genset=new HashSet<FlatNode>();
2132 genset.addAll(delaycomp.getCannotDelay(lb));
2133 genset.addAll(delaycomp.getOther(lb));
2135 genset.addAll(delaycomp.getNotReady(lb));
2137 unionset=new HashSet<FlatNode>();
2138 unionset.addAll(storeset);
2139 unionset.addAll(genset);
2142 /* Do the actual code generation */
2143 FlatNode current_node=null;
2144 HashSet tovisit=new HashSet();
2145 HashSet visited=new HashSet();
2147 tovisit.add(first.getNext(0));
2150 while(current_node!=null||!tovisit.isEmpty()) {
2151 if (current_node==null) {
2152 current_node=(FlatNode)tovisit.iterator().next();
2153 tovisit.remove(current_node);
2154 } else if (tovisit.contains(current_node)) {
2155 tovisit.remove(current_node);
2157 visited.add(current_node);
2158 if (nodetolabel.containsKey(current_node)) {
2159 output.println("L"+nodetolabel.get(current_node)+":");
2161 if (state.INSTRUCTIONFAILURE) {
2162 if (state.THREAD||state.DSM||state.SINGLETM) {
2163 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2165 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2167 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2169 if (!state.DELAYCOMP||firstpass) {
2170 generateFlatNode(fm, lb, current_node, output);
2172 //store primitive variables in out set
2173 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2174 Set<TempDescriptor> liveout=ar.liveout;
2175 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2176 TempDescriptor tmp=tmpit.next();
2177 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2180 if (state.MLP && stopset!=null) {
2181 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2182 assert current_node instanceof FlatSESEExitNode;
2183 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2184 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2185 assert fsen.getFlatExit().equals( fsxn );
2186 assert fsxn.getFlatEnter().equals( fsen );
2188 if (current_node.kind()!=FKind.FlatReturnNode) {
2189 output.println(" return;");
2192 } else if(current_node.numNext()==1) {
2195 current_node.kind()==FKind.FlatSESEEnterNode &&
2196 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2198 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2199 generateFlatNode(fm, lb, current_node, output);
2200 nextnode=fsen.getFlatExit().getNext(0);
2201 } else if (state.DELAYCOMP) {
2202 boolean specialprimitive=false;
2203 //skip literals...no need to add extra overhead
2204 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2205 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2206 if (!typedesc.isClass()&&!typedesc.isArray()) {
2207 specialprimitive=true;
2211 if (genset==null||genset.contains(current_node)||specialprimitive)
2212 generateFlatNode(fm, lb, current_node, output);
2213 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2214 TempDescriptor wrtmp=current_node.writesTemps()[0];
2216 //need to store value written by previous node
2217 if (wrtmp.getType().isPtr()) {
2218 //only lock the objects that may actually need locking
2219 if (recorddc.getNeedTrans(lb, current_node)) {
2220 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");");
2222 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");");
2225 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");");
2228 //need to read value read by previous node
2229 if (wrtmp.getType().isPtr()) {
2230 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");");
2232 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");");
2236 nextnode=current_node.getNext(0);
2239 generateFlatNode(fm, lb, current_node, output);
2240 nextnode=current_node.getNext(0);
2242 if (visited.contains(nextnode)) {
2243 output.println("goto L"+nodetolabel.get(nextnode)+";");
2246 current_node=nextnode;
2247 } else if (current_node.numNext()==2) {
2249 if (state.DELAYCOMP) {
2250 boolean computeside=false;
2252 //need to record which way it should go
2253 if (genset==null||genset.contains(current_node)) {
2254 if (storeset!=null&&storeset.contains(current_node)) {
2255 //need to store which way branch goes
2256 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2258 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2260 //which side to execute
2264 if (genset.contains(current_node)) {
2265 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2266 } else if (storeset.contains(current_node)) {
2268 output.println("RESTOREANDBRANCH(L"+nodetolabel.get(current_node.getNext(1))+");");
2270 //which side to execute
2275 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2277 if (leftset.size()==0)
2279 if (visited.contains(current_node.getNext(branch))) {
2280 //already visited -- build jump
2281 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2284 current_node=current_node.getNext(branch);
2287 if (!visited.contains(current_node.getNext(1)))
2288 tovisit.add(current_node.getNext(1));
2289 if (visited.contains(current_node.getNext(0))) {
2290 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2293 current_node=current_node.getNext(0);
2297 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2298 if (!visited.contains(current_node.getNext(1)))
2299 tovisit.add(current_node.getNext(1));
2300 if (visited.contains(current_node.getNext(0))) {
2301 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2304 current_node=current_node.getNext(0);
2306 } else throw new Error();
2310 /** This method assigns labels to FlatNodes */
2311 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2312 return assignLabels(first, null);
2315 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2316 HashSet tovisit=new HashSet();
2317 HashSet visited=new HashSet();
2319 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2322 /*Assign labels first. A node needs a label if the previous
2323 * node has two exits or this node is a join point. */
2325 while(!tovisit.isEmpty()) {
2326 FlatNode fn=(FlatNode)tovisit.iterator().next();
2331 if(lastset!=null&&lastset.contains(fn)) {
2332 // if last is not null and matches, don't go
2333 // any further for assigning labels
2337 for(int i=0; i<fn.numNext(); i++) {
2338 FlatNode nn=fn.getNext(i);
2341 //1) Edge >1 of node
2342 nodetolabel.put(nn,new Integer(labelindex++));
2344 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2348 nodetolabel.put(nn,new Integer(labelindex++));
2356 /** Generate text string that corresponds to the TempDescriptor td. */
2357 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2358 MethodDescriptor md=fm.getMethod();
2359 TaskDescriptor task=fm.getTask();
2360 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2362 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2363 //System.out.println("generateTemp returns " + td.getSafeSymbol());
2364 return td.getSafeSymbol();
2367 if (objecttemps.isLocalPtr(td)) {
2368 return localsprefixderef+td.getSafeSymbol();
2371 if (objecttemps.isParamPtr(td)) {
2372 return paramsprefix+"->"+td.getSafeSymbol();
2378 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2380 // insert pre-node actions from the code plan
2383 CodePlan cp = mlpa.getCodePlan( fn );
2386 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2388 // for each sese and age pair that this parent statement
2389 // must stall on, take that child's stall semaphore, the
2390 // copying of values comes after the statement
2391 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2392 while( vstItr.hasNext() ) {
2393 VariableSourceToken vst = vstItr.next();
2395 SESEandAgePair p = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2397 output.println(" {");
2398 output.println(" SESEcommon* common = (SESEcommon*) "+p+";");
2400 output.println(" pthread_mutex_lock( &(common->lock) );");
2401 output.println(" while( common->doneExecuting == FALSE ) {");
2402 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2403 output.println(" }");
2404 output.println(" pthread_mutex_unlock( &(common->lock) );");
2406 //output.println(" psem_take( &(common->stallSem) );");
2408 // copy things we might have stalled for
2409 output.println(" "+p.getSESE().getSESErecordName()+"* child = ("+
2410 p.getSESE().getSESErecordName()+"*) "+p+";");
2412 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2413 while( tdItr.hasNext() ) {
2414 TempDescriptor td = tdItr.next();
2415 FlatMethod fmContext;
2416 if( currentSESE.getIsCallerSESEplaceholder() ) {
2417 fmContext = currentSESE.getfmEnclosing();
2419 fmContext = currentSESE.getfmBogus();
2421 output.println(" "+generateTemp( fmContext, td, null )+
2422 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2425 output.println(" }");
2428 // for each variable with a dynamic source, stall just for that variable
2429 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2430 while( dynItr.hasNext() ) {
2431 TempDescriptor dynVar = dynItr.next();
2433 // only stall if the dynamic source is not yourself, denoted by src==NULL
2434 // otherwise the dynamic write nodes will have the local var up-to-date
2435 output.println(" {");
2436 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2437 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2438 output.println(" psem_take( &(common->stallSem) );");
2440 FlatMethod fmContext;
2441 if( currentSESE.getIsCallerSESEplaceholder() ) {
2442 fmContext = currentSESE.getfmEnclosing();
2444 fmContext = currentSESE.getfmBogus();
2446 output.println(" "+generateTemp( fmContext, dynVar, null )+
2447 " = *(("+dynVar.getType()+"*) ("+
2448 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2450 output.println(" }");
2451 output.println(" }");
2454 // for each assignment of a variable to rhs that has a dynamic source,
2455 // copy the dynamic sources
2456 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2457 while( dynAssignItr.hasNext() ) {
2458 Map.Entry me = (Map.Entry) dynAssignItr.next();
2459 TempDescriptor lhs = (TempDescriptor) me.getKey();
2460 TempDescriptor rhs = (TempDescriptor) me.getValue();
2461 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
2462 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2465 // for each lhs that is dynamic from a non-dynamic source, set the
2466 // dynamic source vars to the current SESE
2467 dynItr = cp.getDynAssignCurr().iterator();
2468 while( dynItr.hasNext() ) {
2469 TempDescriptor dynVar = dynItr.next();
2470 output.println(" "+dynVar+"_srcSESE = NULL;");
2476 case FKind.FlatAtomicEnterNode:
2477 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
2480 case FKind.FlatAtomicExitNode:
2481 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
2484 case FKind.FlatInstanceOfNode:
2485 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
2488 case FKind.FlatSESEEnterNode:
2489 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
2492 case FKind.FlatSESEExitNode:
2493 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
2496 case FKind.FlatWriteDynamicVarNode:
2497 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
2500 case FKind.FlatGlobalConvNode:
2501 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
2504 case FKind.FlatTagDeclaration:
2505 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
2508 case FKind.FlatCall:
2509 generateFlatCall(fm, lb, (FlatCall) fn,output);
2512 case FKind.FlatFieldNode:
2513 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
2516 case FKind.FlatElementNode:
2517 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
2520 case FKind.FlatSetElementNode:
2521 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
2524 case FKind.FlatSetFieldNode:
2525 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
2529 generateFlatNew(fm, lb, (FlatNew) fn,output);
2532 case FKind.FlatOpNode:
2533 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
2536 case FKind.FlatCastNode:
2537 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
2540 case FKind.FlatLiteralNode:
2541 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
2544 case FKind.FlatReturnNode:
2545 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
2549 output.println("/* nop */");
2552 case FKind.FlatExit:
2553 output.println("/* exit */");
2556 case FKind.FlatBackEdge:
2557 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
2558 || (this.state.MULTICOREGC)) {
2559 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
2560 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
2561 } else if(this.state.MULTICOREGC) {
2562 output.println("if (gcflag) gc("+localsprefixaddr+");");
2564 output.println("if (needtocollect) checkcollect("+localsprefixaddr+");");
2566 output.println("/* nop */");
2569 case FKind.FlatCheckNode:
2570 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
2573 case FKind.FlatFlagActionNode:
2574 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
2577 case FKind.FlatPrefetchNode:
2578 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
2581 case FKind.FlatOffsetNode:
2582 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
2589 // insert post-node actions from the code-plan
2591 CodePlan cp = mlpa.getCodePlan( fn );
2598 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
2599 output.println("/* FlatOffsetNode */");
2600 FieldDescriptor fd=fofn.getField();
2601 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
2602 output.println("/* offset */");
2605 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
2606 if (state.PREFETCH) {
2607 Vector oids = new Vector();
2608 Vector fieldoffset = new Vector();
2609 Vector endoffset = new Vector();
2610 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
2611 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
2612 PrefetchPair pp = (PrefetchPair) it.next();
2613 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
2614 /* Find prefetches that can generate oid */
2615 if(statusbase == LocalityAnalysis.GLOBAL) {
2616 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
2618 } else if (statusbase == LocalityAnalysis.LOCAL) {
2619 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
2626 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
2627 output.println("{");
2628 output.println("/* prefetch */");
2629 output.println("/* prefetchid_" + fpn.siteid + " */");
2630 output.println("void * prefptr;");
2631 output.println("int tmpindex;");
2633 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
2634 /*Create C code for oid array */
2635 output.print(" unsigned int oidarray_[] = {");
2636 boolean needcomma=false;
2637 for (Iterator it = oids.iterator(); it.hasNext();) {
2640 output.print(it.next());
2643 output.println("};");
2645 /*Create C code for endoffset values */
2646 output.print(" unsigned short endoffsetarry_[] = {");
2648 for (Iterator it = endoffset.iterator(); it.hasNext();) {
2651 output.print(it.next());
2654 output.println("};");
2656 /*Create C code for Field Offset Values */
2657 output.print(" short fieldarry_[] = {");
2659 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
2662 output.print(it.next());
2665 output.println("};");
2666 /* make the prefetch call to Runtime */
2667 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
2668 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
2669 output.println(" }");
2670 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
2671 output.println(" } else {");
2672 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
2673 output.println(" }");
2674 output.println("}");
2678 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
2679 short offsetcount = 0;
2683 } else if (localbase) {
2684 for(; breakindex<pp.desc.size(); breakindex++) {
2685 Descriptor desc=pp.getDescAt(breakindex);
2686 if (desc instanceof FieldDescriptor) {
2687 FieldDescriptor fd=(FieldDescriptor)desc;
2688 if (fd.isGlobal()) {
2696 if (breakindex>pp.desc.size()) //all local
2699 TypeDescriptor lasttype=pp.base.getType();
2700 String basestr=generateTemp(fm, pp.base, lb);
2702 boolean maybenull=fm.getMethod().isStatic()||
2703 !pp.base.equals(fm.getParameter(0));
2705 for(int i=0; i<breakindex; i++) {
2706 String indexcheck="";
2708 Descriptor desc=pp.getDescAt(i);
2709 if (desc instanceof FieldDescriptor) {
2710 FieldDescriptor fd=(FieldDescriptor)desc;
2712 if (!teststr.equals(""))
2714 teststr+="((prefptr="+basestr+")!=NULL)";
2715 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
2717 basestr=basestr+"->"+fd.getSafeSymbol();
2720 lasttype=fd.getType();
2722 IndexDescriptor id=(IndexDescriptor)desc;
2723 indexcheck="((tmpindex=";
2724 for(int j=0; j<id.tddesc.size(); j++) {
2725 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
2727 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
2729 if (!teststr.equals(""))
2731 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
2732 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
2734 lasttype=lasttype.dereference();
2739 if (teststr.equals("")) {
2740 oid="((unsigned int)"+basestr+")";
2742 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
2746 for(int i = breakindex; i < pp.desc.size(); i++) {
2747 String newfieldoffset;
2748 Object desc = pp.getDescAt(i);
2749 if(desc instanceof FieldDescriptor) {
2750 FieldDescriptor fd=(FieldDescriptor)desc;
2751 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
2752 lasttype=fd.getType();
2754 newfieldoffset = "";
2755 IndexDescriptor id=(IndexDescriptor)desc;
2756 for(int j = 0; j < id.tddesc.size(); j++) {
2757 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
2759 newfieldoffset += id.offset.toString();
2760 lasttype=lasttype.dereference();
2762 fieldoffset.add(newfieldoffset);
2765 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
2766 base+=pp.desc.size()-breakindex;
2767 endoffset.add(new Short((short)base));
2772 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
2773 if (lb!=fgcn.getLocality())
2775 /* Have to generate flat globalconv */
2776 if (fgcn.getMakePtr()) {
2778 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
2780 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
2781 //need to do translation
2782 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
2783 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
2784 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
2788 /* Need to convert to OID */
2789 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
2790 if (fgcn.doConvert()||(delaycomp!=null&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
2791 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
2793 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
2799 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
2801 if (fion.getType().isArray()) {
2802 type=state.getArrayNumber(fion.getType())+state.numClasses();
2804 type=fion.getType().getClassDesc().getId();
2807 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
2808 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
2810 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
2813 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
2814 /* Check to see if we need to generate code for this atomic */
2815 if (locality==null) {
2816 output.println("pthread_mutex_lock(&atomiclock);");
2820 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
2824 if (state.DELAYCOMP) {
2825 AtomicRecord ar=atomicmethodmap.get(faen);
2827 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
2828 TempDescriptor tmp=tmpit.next();
2829 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2832 //copy outs that depend on path
2833 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
2834 TempDescriptor tmp=tmpit.next();
2835 if (!ar.livein.contains(tmp))
2836 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2840 /* Backup the temps. */
2841 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
2842 TempDescriptor tmp=tmpit.next();
2843 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
2846 output.println("goto transstart"+faen.getIdentifier()+";");
2848 /******* Print code to retry aborted transaction *******/
2849 output.println("transretry"+faen.getIdentifier()+":");
2852 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
2853 TempDescriptor tmp=tmpit.next();
2854 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
2858 /********* Need to revert local object store ********/
2859 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
2861 output.println("while ("+revertptr+") {");
2862 output.println("struct ___Object___ * tmpptr;");
2863 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
2864 output.println("REVERT_OBJ("+revertptr+");");
2865 output.println(revertptr+"=tmpptr;");
2866 output.println("}");
2868 /******* Tell the runtime to start the transaction *******/
2870 output.println("transstart"+faen.getIdentifier()+":");
2871 output.println("transStart();");
2873 if (state.ABORTREADERS) {
2874 output.println("if (_setjmp(aborttrans)) {");
2875 output.println(" goto transretry"+faen.getIdentifier()+"; }");
2879 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
2880 /* Check to see if we need to generate code for this atomic */
2881 if (locality==null) {
2882 output.println("pthread_mutex_unlock(&atomiclock);");
2885 if (locality.getAtomic(lb).get(faen).intValue()>0)
2887 //store the revert list before we lose the transaction object
2888 String revertptr=null;
2890 revertptr=generateTemp(fm, reverttable.get(lb),lb);
2891 output.println(revertptr+"=revertlist;");
2893 if (state.DELAYCOMP) {
2894 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
2897 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
2899 output.println("if (transCommit()) {");
2900 /* Transaction aborts if it returns true */
2901 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
2903 output.println("} else {");
2904 /* Need to commit local object store */
2905 output.println("while ("+revertptr+") {");
2906 output.println("struct ___Object___ * tmpptr;");
2907 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
2908 output.println("COMMIT_OBJ("+revertptr+");");
2909 output.println(revertptr+"=tmpptr;");
2910 output.println("}");
2912 output.println("}");
2913 if (state.DELAYCOMP) {
2915 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
2916 output.println("else {");
2917 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
2918 TempDescriptor tmp=tmpit.next();
2919 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
2921 output.println("}");
2925 public void generateFlatSESEEnterNode( FlatMethod fm,
2927 FlatSESEEnterNode fsen,
2931 // if MLP flag is off, okay that SESE nodes are in IR graph,
2932 // just skip over them and code generates exactly the same
2937 // there may be an SESE in an unreachable method, skip over
2938 if( !mlpa.getAllSESEs().contains( fsen ) ) {
2942 // also, if we have encountered a placeholder, just skip it
2943 if( fsen.getIsCallerSESEplaceholder() ) {
2947 output.println(" {");
2949 // set up the parent
2950 if( fsen == mlpa.getMainSESE() ) {
2951 output.println(" SESEcommon* parentCommon = NULL;");
2953 if( fsen.getParent() == null ) {
2954 System.out.println( "in "+fm+", "+fsen+" has null parent" );
2956 assert fsen.getParent() != null;
2957 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
2958 output.println(" SESEcommon* parentCommon = &("+paramsprefix+"->common);");
2960 //output.println(" SESEcommon* parentCommon = (SESEcommon*) peekItem( seseCallStack );");
2961 output.println(" SESEcommon* parentCommon = seseCaller;");
2965 // before doing anything, lock your own record and increment the running children
2966 if( fsen != mlpa.getMainSESE() ) {
2967 output.println(" pthread_mutex_lock( &(parentCommon->lock) );");
2968 output.println(" ++(parentCommon->numRunningChildren);");
2969 output.println(" pthread_mutex_unlock( &(parentCommon->lock) );");
2972 // just allocate the space for this record
2973 output.println(" "+fsen.getSESErecordName()+"* seseToIssue = ("+
2974 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
2975 fsen.getSESErecordName()+" ) );");
2977 // and keep the thread-local sese stack up to date
2978 //output.println(" addNewItem( seseCallStack, (void*) seseToIssue);");
2980 // fill in common data
2981 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
2982 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
2984 output.println(" seseToIssue->common.forwardList = createQueue();");
2985 output.println(" seseToIssue->common.unresolvedDependencies = 0;");
2986 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
2987 output.println(" seseToIssue->common.doneExecuting = FALSE;");
2988 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
2989 output.println(" seseToIssue->common.numRunningChildren = 0;");
2990 output.println(" seseToIssue->common.parent = parentCommon;");
2992 // all READY in-vars should be copied now and be done with it
2993 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
2994 while( tempItr.hasNext() ) {
2995 TempDescriptor temp = tempItr.next();
2997 // when we are issuing the main SESE or an SESE with placeholder
2998 // caller SESE as parent, generate temp child child's eclosing method,
2999 // otherwise use the parent's enclosing method as the context
3000 boolean useParentContext = false;
3002 if( fsen != mlpa.getMainSESE() ) {
3003 assert fsen.getParent() != null;
3004 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3005 useParentContext = true;
3009 if( useParentContext ) {
3010 output.println(" seseToIssue->"+temp+" = "+
3011 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3013 output.println(" seseToIssue->"+temp+" = "+
3014 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3018 // before potentially adding this SESE to other forwarding lists,
3019 // create it's lock and take it immediately
3020 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3021 output.println(" pthread_mutex_lock( &(seseToIssue->common.lock) );");
3023 if( fsen != mlpa.getMainSESE() ) {
3024 // count up outstanding dependencies, static first, then dynamic
3025 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3026 while( staticSrcsItr.hasNext() ) {
3027 SESEandAgePair srcPair = staticSrcsItr.next();
3028 output.println(" {");
3029 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3030 output.println(" pthread_mutex_lock( &(src->lock) );");
3031 output.println(" if( !isEmpty( src->forwardList ) &&");
3032 output.println(" seseToIssue == peekItem( src->forwardList ) ) {");
3033 output.println(" printf( \"This shouldnt already be here\\n\");");
3034 output.println(" exit( -1 );");
3035 output.println(" }");
3036 output.println(" if( !src->doneExecuting ) {");
3037 output.println(" addNewItem( src->forwardList, seseToIssue );");
3038 output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3039 output.println(" }");
3040 output.println(" pthread_mutex_unlock( &(src->lock) );");
3041 output.println(" }");
3043 // whether or not it is an outstanding dependency, make sure
3044 // to pass the static name to the child's record
3045 output.println(" seseToIssue->"+srcPair+" = "+srcPair+";");
3048 // dynamic sources might already be accounted for in the static list,
3049 // so only add them to forwarding lists if they're not already there
3050 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3051 while( dynVarsItr.hasNext() ) {
3052 TempDescriptor dynInVar = dynVarsItr.next();
3053 output.println(" {");
3054 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3056 // the dynamic source is NULL if it comes from your own space--you can't pass
3057 // the address off to the new child, because you're not done executing and
3058 // might change the variable, so copy it right now
3059 output.println(" if( src != NULL ) {");
3060 output.println(" pthread_mutex_lock( &(src->lock) );");
3061 output.println(" if( isEmpty( src->forwardList ) ||");
3062 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3063 output.println(" if( !src->doneExecuting ) {");
3064 output.println(" addNewItem( src->forwardList, seseToIssue );");
3065 output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3066 output.println(" }");
3067 output.println(" }");
3068 output.println(" pthread_mutex_unlock( &(src->lock) );");
3069 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3070 output.println(" } else {");
3072 boolean useParentContext = false;
3073 if( fsen != mlpa.getMainSESE() ) {
3074 assert fsen.getParent() != null;
3075 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3076 useParentContext = true;
3079 if( useParentContext ) {
3080 output.println(" seseToIssue->"+dynInVar+" = "+
3081 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3083 output.println(" seseToIssue->"+dynInVar+" = "+
3084 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3087 output.println(" }");
3088 output.println(" }");
3090 // even if the value is already copied, make sure your NULL source
3091 // gets passed so child knows it already has the dynamic value
3092 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3095 // maintain pointers for for finding dynamic SESE
3096 // instances from static names
3097 SESEandAgePair p = new SESEandAgePair( fsen, 0 );
3098 if( fsen.getParent() != null &&
3099 //!fsen.getParent().getIsCallerSESEplaceholder() &&
3100 fsen.getParent().getNeededStaticNames().contains( p )
3103 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3104 SESEandAgePair p1 = new SESEandAgePair( fsen, i );
3105 SESEandAgePair p2 = new SESEandAgePair( fsen, i-1 );
3106 output.println(" "+p1+" = "+p2+";");
3108 output.println(" "+p+" = seseToIssue;");
3112 // if there were no outstanding dependencies, issue here
3113 output.println(" if( seseToIssue->common.unresolvedDependencies == 0 ) {");
3114 output.println(" workScheduleSubmit( (void*)seseToIssue );");
3115 output.println(" }");
3117 // release this SESE for siblings to update its dependencies or,
3118 // eventually, for it to mark itself finished
3119 output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3120 output.println(" }");
3124 public void generateFlatSESEExitNode( FlatMethod fm,
3126 FlatSESEExitNode fsexn,
3130 // if MLP flag is off, okay that SESE nodes are in IR graph,
3131 // just skip over them and code generates exactly the same
3136 // get the enter node for this exit that has meta data embedded
3137 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
3139 // there may be an SESE in an unreachable method, skip over
3140 if( !mlpa.getAllSESEs().contains( fsen ) ) {
3144 // also, if we have encountered a placeholder, just jump it
3145 if( fsen.getIsCallerSESEplaceholder() ) {
3149 output.println(" /* SESE exiting */");
3151 String com = paramsprefix+"->common";
3153 // this SESE cannot be done until all of its children are done
3154 // so grab your own lock with the condition variable for watching
3155 // that the number of your running children is greater than zero
3156 output.println(" pthread_mutex_lock( &("+com+".lock) );");
3157 output.println(" while( "+com+".numRunningChildren > 0 ) {");
3158 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
3159 output.println(" }");
3161 // copy out-set from local temps into the sese record
3162 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
3163 while( itr.hasNext() ) {
3164 TempDescriptor temp = itr.next();
3166 // only have to do this for primitives
3167 if( !temp.getType().isPrimitive() ) {
3171 // have to determine the context enclosing this sese
3172 boolean useParentContext = false;
3174 if( fsen != mlpa.getMainSESE() ) {
3175 assert fsen.getParent() != null;
3176 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3177 useParentContext = true;
3182 if( useParentContext ) {
3183 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
3185 from = generateTemp( fsen.getfmEnclosing(), temp, null );
3188 output.println(" "+paramsprefix+
3189 "->"+temp.getSafeSymbol()+
3193 // mark yourself done, your SESE data is now read-only
3194 output.println(" "+com+".doneExecuting = TRUE;");
3195 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
3196 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
3198 // decrement dependency count for all SESE's on your forwarding list
3199 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
3200 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
3201 output.println(" pthread_mutex_lock( &(consumer->lock) );");
3202 output.println(" --(consumer->unresolvedDependencies);");
3203 output.println(" if( consumer->unresolvedDependencies == 0 ) {");
3204 output.println(" workScheduleSubmit( (void*)consumer );");
3205 output.println(" }");
3206 output.println(" pthread_mutex_unlock( &(consumer->lock) );");
3207 output.println(" }");
3209 // if parent is stalling on you, let them know you're done
3210 if( fsexn.getFlatEnter() != mlpa.getMainSESE() ) {
3211 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
3214 // last of all, decrement your parent's number of running children
3215 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
3216 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
3217 output.println(" --("+paramsprefix+"->common.parent->numRunningChildren);");
3218 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
3219 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
3220 output.println(" }");
3222 // this is a thread-only variable that can be handled when critical sese-to-sese
3223 // data has been taken care of--set sese pointer to remember self over method
3224 // calls to a non-zero, invalid address
3225 output.println(" seseCaller = (SESEcommon*) 0x1;");
3228 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
3230 FlatWriteDynamicVarNode fwdvn,
3234 // should node should not be in an IR graph if the
3235 // MLP flag is not set
3236 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
3239 Hashtable<TempDescriptor, VariableSourceToken> writeDynamic =
3242 assert writeDynamic != null;
3244 Iterator wdItr = writeDynamic.entrySet().iterator();
3245 while( wdItr.hasNext() ) {
3246 Map.Entry me = (Map.Entry) wdItr.next();
3247 TempDescriptor refVar = (TempDescriptor) me.getKey();
3248 VariableSourceToken vst = (VariableSourceToken) me.getValue();
3250 FlatSESEEnterNode current = fwdvn.getEnclosingSESE();
3252 // only do this if the variable in question should be tracked,
3253 // meaning that it was explicitly added to the dynamic var set
3254 if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
3258 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
3260 output.println(" {");
3262 if( current.equals( vst.getSESE() ) ) {
3263 // if the src comes from this SESE, it's a method local variable,
3264 // mark src pointer NULL to signify that the var is up-to-date
3265 output.println(" "+vst.getAddrVar()+"_srcSESE = NULL;");
3268 // otherwise we track where it will come from
3269 output.println(" "+vst.getAddrVar()+"_srcSESE = "+instance+";");
3270 output.println(" "+vst.getAddrVar()+"_srcOffset = (int) &((("+
3271 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
3274 output.println(" }");
3279 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
3280 if (state.CONSCHECK) {
3281 String specname=fcn.getSpec();
3282 String varname="repairstate___";
3283 output.println("{");
3284 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
3286 TempDescriptor[] temps=fcn.getTemps();
3287 String[] vars=fcn.getVars();
3288 for(int i=0; i<temps.length; i++) {
3289 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
3292 output.println("if (doanalysis"+specname+"("+varname+")) {");
3293 output.println("free"+specname+"_state("+varname+");");
3294 output.println("} else {");
3295 output.println("/* Bad invariant */");
3296 output.println("free"+specname+"_state("+varname+");");
3297 output.println("abort_task();");
3298 output.println("}");
3299 output.println("}");
3303 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
3305 if( state.MLP && !nonSESEpass ) {
3306 output.println(" seseCaller = (SESEcommon*)"+paramsprefix+";");
3309 MethodDescriptor md=fc.getMethod();
3310 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
3311 ClassDescriptor cn=md.getClassDesc();
3312 output.println("{");
3313 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3315 LocalityBinding fclb=locality.getBinding(lb, fc);
3316 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3318 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3320 output.print(objectparams.numPointers());
3321 output.print(", "+localsprefixaddr);
3322 if (md.getThis()!=null) {
3324 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
3326 if (fc.getThis()!=null&&md.getThis()==null) {
3327 System.out.println("WARNING!!!!!!!!!!!!");
3328 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
3332 for(int i=0; i<fc.numArgs(); i++) {
3333 Descriptor var=md.getParameter(i);
3334 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3335 if (objectparams.isParamPtr(paramtemp)) {
3336 TempDescriptor targ=fc.getArg(i);
3338 TypeDescriptor td=md.getParamType(i);
3340 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3342 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3345 output.println("};");
3350 if (fc.getReturnTemp()!=null)
3351 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
3353 /* Do we need to do virtual dispatch? */
3354 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
3357 LocalityBinding fclb=locality.getBinding(lb, fc);
3358 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3360 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3365 if (md.getReturnType().isClass()||md.getReturnType().isArray())
3366 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3368 output.print(md.getReturnType().getSafeSymbol()+" ");
3369 output.print("(*)(");
3371 boolean printcomma=false;
3372 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3374 LocalityBinding fclb=locality.getBinding(lb, fc);
3375 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3377 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3381 for(int i=0; i<objectparams.numPrimitives(); i++) {
3382 TempDescriptor temp=objectparams.getPrimitive(i);
3386 if (temp.getType().isClass()||temp.getType().isArray())
3387 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
3389 output.print(temp.getType().getSafeSymbol());
3394 LocalityBinding fclb=locality.getBinding(lb, fc);
3395 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
3397 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
3401 boolean needcomma=false;
3402 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3403 output.print("&__parameterlist__");
3407 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
3408 if (fc.getThis()!=null) {
3409 TypeDescriptor ptd=md.getThis().getType();
3412 if (ptd.isClass()&&!ptd.isArray())
3413 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3414 output.print(generateTemp(fm,fc.getThis(),lb));
3419 for(int i=0; i<fc.numArgs(); i++) {
3420 Descriptor var=md.getParameter(i);
3421 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3422 if (objectparams.isParamPrim(paramtemp)) {
3423 TempDescriptor targ=fc.getArg(i);
3427 TypeDescriptor ptd=md.getParamType(i);
3428 if (ptd.isClass()&&!ptd.isArray())
3429 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3430 output.print(generateTemp(fm, targ,lb));
3434 output.println(");");
3435 output.println(" }");
3438 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
3439 Set subclasses=typeutil.getSubClasses(thiscd);
3440 if (subclasses==null)
3442 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
3443 ClassDescriptor cd=(ClassDescriptor)classit.next();
3444 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
3445 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
3446 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
3447 if (md.matches(matchmd))
3454 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
3455 if (state.SINGLETM) {
3456 //single machine transactional memory case
3457 String field=ffn.getField().getSafeSymbol();
3458 String src=generateTemp(fm, ffn.getSrc(),lb);
3459 String dst=generateTemp(fm, ffn.getDst(),lb);
3461 output.println(dst+"="+ src +"->"+field+ ";");
3462 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
3463 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
3464 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
3465 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
3466 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
3467 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
3468 output.println("TRANSREADRD("+dst+", "+dst+");");
3471 } else if (state.DSM) {
3472 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
3473 if (status==LocalityAnalysis.GLOBAL) {
3474 String field=ffn.getField().getSafeSymbol();
3475 String src=generateTemp(fm, ffn.getSrc(),lb);
3476 String dst=generateTemp(fm, ffn.getDst(),lb);
3478 if (ffn.getField().getType().isPtr()) {
3480 //TODO: Uncomment this when we have runtime support
3481 //if (ffn.getSrc()==ffn.getDst()) {
3482 //output.println("{");
3483 //output.println("void * temp="+src+";");
3484 //output.println("if (temp&0x1) {");
3485 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
3486 //output.println(src+"->"+field+"="+temp+";");
3487 //output.println("}");
3488 //output.println(dst+"=temp;");
3489 //output.println("}");
3491 output.println(dst+"="+ src +"->"+field+ ";");
3492 //output.println("if ("+dst+"&0x1) {");
3493 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3494 //output.println(src+"->"+field+"="+src+"->"+field+";");
3495 //output.println("}");
3498 output.println(dst+"="+ src+"->"+field+";");
3500 } else if (status==LocalityAnalysis.LOCAL) {
3501 if (ffn.getField().getType().isPtr()&&
3502 ffn.getField().isGlobal()) {
3503 String field=ffn.getField().getSafeSymbol();
3504 String src=generateTemp(fm, ffn.getSrc(),lb);
3505 String dst=generateTemp(fm, ffn.getDst(),lb);
3506 output.println(dst+"="+ src +"->"+field+ ";");
3507 if (locality.getAtomic(lb).get(ffn).intValue()>0)
3508 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3510 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3511 } else if (status==LocalityAnalysis.EITHER) {
3512 //Code is reading from a null pointer
3513 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
3514 output.println("#ifndef RAW");
3515 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
3516 output.println("#endif");
3517 //This should throw a suitable null pointer error
3518 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3520 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
3522 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3526 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
3527 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
3528 throw new Error("Can't set array length");
3529 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3530 //Single Machine Transaction Case
3531 boolean srcptr=fsfn.getSrc().getType().isPtr();
3532 String src=generateTemp(fm,fsfn.getSrc(),lb);
3533 String dst=generateTemp(fm,fsfn.getDst(),lb);
3534 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
3535 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
3536 output.println("{");
3537 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
3538 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
3539 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3541 output.println("INTPTR srcoid=(INTPTR)"+src+";");
3544 if (wb.needBarrier(fsfn)&&
3545 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
3546 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
3548 if (srcptr&!fsfn.getSrc().getType().isNull()) {
3549 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
3550 output.println("}");
3552 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3554 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3555 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
3556 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
3557 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
3559 String src=generateTemp(fm,fsfn.getSrc(),lb);
3560 String dst=generateTemp(fm,fsfn.getDst(),lb);
3562 output.println("{");
3563 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3565 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
3568 if (wb.needBarrier(fsfn))
3569 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
3571 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
3573 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3574 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
3575 /** Check if we need to copy */
3576 output.println("if(!"+dst+"->"+localcopystr+") {");
3577 /* Link object into list */
3578 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3579 output.println(revertptr+"=revertlist;");
3580 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3581 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3583 output.println("COPY_OBJ("+dst+");");
3584 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3585 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3586 output.println("}");
3588 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
3590 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3591 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
3592 //writing to a null...bad
3593 output.println("if ("+dst+") {");
3594 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
3596 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
3598 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3601 output.println("}");
3604 if (state.FASTCHECK) {
3605 String dst=generateTemp(fm, fsfn.getDst(),lb);
3606 output.println("if(!"+dst+"->"+localcopystr+") {");
3607 /* Link object into list */
3608 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3609 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3611 output.println("COPY_OBJ("+dst+");");
3612 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3613 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3614 output.println("}");
3616 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
3620 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
3621 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
3624 if (elementtype.isArray()||elementtype.isClass())
3627 type=elementtype.getSafeSymbol()+" ";
3629 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
3630 output.println("if ("+generateTemp(fm, fen.getIndex(),lb)+"< 0 | "+generateTemp(fm, fen.getIndex(),lb)+" >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___)");
3631 output.println("failedboundschk();");
3633 if (state.SINGLETM) {
3634 //Single machine transaction case
3635 String dst=generateTemp(fm, fen.getDst(),lb);
3636 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3638 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
3639 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
3640 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
3641 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
3642 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
3643 output.println("TRANSREADRD("+dst+", "+dst+");");
3646 } else if (state.DSM) {
3647 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
3648 if (status==LocalityAnalysis.GLOBAL) {
3649 String dst=generateTemp(fm, fen.getDst(),lb);
3651 if (elementtype.isPtr()) {
3652 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3653 output.println("TRANSREAD("+dst+", "+dst+");");
3655 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3657 } else if (status==LocalityAnalysis.LOCAL) {
3658 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3659 } else if (status==LocalityAnalysis.EITHER) {
3660 //Code is reading from a null pointer
3661 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
3662 output.println("#ifndef RAW");
3663 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
3664 output.println("#endif");
3665 //This should throw a suitable null pointer error
3666 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3668 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
3670 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3674 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
3675 //TODO: need dynamic check to make sure this assignment is actually legal
3676 //Because Object[] could actually be something more specific...ie. Integer[]
3678 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
3681 if (elementtype.isArray()||elementtype.isClass())
3684 type=elementtype.getSafeSymbol()+" ";
3686 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
3687 output.println("if ("+generateTemp(fm, fsen.getIndex(),lb)+"< 0 | "+generateTemp(fm, fsen.getIndex(),lb)+" >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___)");
3688 output.println("failedboundschk();");
3691 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
3692 //Transaction set element case
3693 if (wb.needBarrier(fsen)&&
3694 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
3695 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
3697 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
3698 output.println("{");
3699 String src=generateTemp(fm, fsen.getSrc(), lb);
3700 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
3701 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
3702 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3704 output.println("INTPTR srcoid=(INTPTR)"+src+";");
3706 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
3707 output.println("}");
3709 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3711 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
3712 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
3713 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
3714 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
3715 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
3716 boolean dstlocal=statusdst==LocalityAnalysis.LOCAL;
3719 if (wb.needBarrier(fsen))
3720 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
3721 } else if (dstlocal) {
3722 /** Check if we need to copy */
3723 String dst=generateTemp(fm, fsen.getDst(),lb);
3724 output.println("if(!"+dst+"->"+localcopystr+") {");
3725 /* Link object into list */
3726 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3727 output.println(revertptr+"=revertlist;");
3728 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
3729 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3731 output.println("COPY_OBJ("+dst+");");
3732 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3733 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3734 output.println("}");
3735 } else throw new Error("Unknown array type");
3737 output.println("{");
3738 String src=generateTemp(fm, fsen.getSrc(), lb);
3739 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3740 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
3741 output.println("}");
3743 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3746 if (state.FASTCHECK) {
3747 String dst=generateTemp(fm, fsen.getDst(),lb);
3748 output.println("if(!"+dst+"->"+localcopystr+") {");
3749 /* Link object into list */
3750 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3751 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3753 output.println("COPY_OBJ("+dst+");");
3754 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3755 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3756 output.println("}");
3758 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3762 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
3763 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
3764 //Stash pointer in case of GC
3765 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3766 output.println(revertptr+"=revertlist;");
3768 if (state.SINGLETM) {
3769 if (fn.getType().isArray()) {
3770 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
3771 if (locality.getAtomic(lb).get(fn).intValue()>0) {
3772 //inside transaction
3773 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3775 //outside transaction
3776 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3779 if (locality.getAtomic(lb).get(fn).intValue()>0) {
3780 //inside transaction
3781 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3783 //outside transaction
3784 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3787 } else if (fn.getType().isArray()) {
3788 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
3789 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
3790 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3791 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3792 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3794 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3797 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
3798 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
3799 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3800 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3802 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
3805 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
3806 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3807 String dst=generateTemp(fm,fn.getDst(),lb);
3808 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
3809 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3810 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3812 if (state.FASTCHECK) {
3813 String dst=generateTemp(fm,fn.getDst(),lb);
3814 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
3815 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3816 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3820 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
3821 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3822 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
3824 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
3828 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
3829 if (fon.getRight()!=null) {
3830 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
3831 if (fon.getLeft().getType().isLong())
3832 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
3834 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
3836 } else if (dc!=null) {
3837 output.print(generateTemp(fm, fon.getDest(),lb)+" = ");
3838 if (dc.getNeedLeftSrcTrans(lb, fon))
3839 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
3841 output.print(generateTemp(fm, fon.getLeft(),lb));
3842 output.print(fon.getOp().toString());
3843 if (dc.getNeedRightSrcTrans(lb, fon))
3844 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL);");
3846 output.println(generateTemp(fm,fon.getRight(),lb)+";");
3848 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
3849 } else if (fon.getOp().getOp()==Operation.ASSIGN)
3850 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
3851 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
3852 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
3853 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
3854 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
3855 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
3856 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
3857 else if (fon.getOp().getOp()==Operation.COMP)
3858 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
3859 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
3860 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
3862 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
3865 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
3866 /* TODO: Do type check here */
3867 if (fcn.getType().isArray()) {
3868 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
3869 } else if (fcn.getType().isClass())
3870 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
3872 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
3875 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
3876 if (fln.getValue()==null)
3877 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
3878 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
3879 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3880 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
3881 //Stash pointer in case of GC
3882 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3883 output.println(revertptr+"=revertlist;");
3885 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
3886 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
3887 //Stash pointer in case of GC
3888 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3889 output.println("revertlist="+revertptr+";");
3892 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
3894 } else if (fln.getType().isBoolean()) {
3895 if (((Boolean)fln.getValue()).booleanValue())
3896 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
3898 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
3899 } else if (fln.getType().isChar()) {
3900 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
3901 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
3902 } else if (fln.getType().isLong()) {
3903 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
3905 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
3908 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
3909 if (frn.getReturnTemp()!=null) {
3910 if (frn.getReturnTemp().getType().isPtr())
3911 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
3913 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
3915 output.println("return;");
3919 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
3920 output.println("STOREANDBRANCH(!"+generateTemp(fm, fcb.getTest(),lb)+", "+label+");");
3923 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
3924 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
3927 /** This method generates header information for the method or
3928 * task referenced by the Descriptor des. */
3929 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
3930 generateHeader(fm, lb, des, output, false);
3933 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
3935 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
3936 MethodDescriptor md=null;
3937 TaskDescriptor task=null;
3938 if (des instanceof MethodDescriptor)
3939 md=(MethodDescriptor) des;
3941 task=(TaskDescriptor) des;
3943 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
3945 if (md!=null&&md.getReturnType()!=null) {
3946 if (md.getReturnType().isClass()||md.getReturnType().isArray())
3947 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3949 output.print(md.getReturnType().getSafeSymbol()+" ");
3951 //catch the constructor case
3952 output.print("void ");
3954 if (state.DSM||state.SINGLETM) {
3955 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
3957 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
3959 output.print(task.getSafeSymbol()+"(");
3961 boolean printcomma=false;
3962 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3964 if (state.DSM||state.SINGLETM) {
3965 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
3967 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
3969 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
3975 for(int i=0; i<objectparams.numPrimitives(); i++) {
3976 TempDescriptor temp=objectparams.getPrimitive(i);
3980 if (temp.getType().isClass()||temp.getType().isArray())
3981 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
3983 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
3985 output.println(") {");
3986 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
3987 /* Imprecise Task */
3988 output.println("void * parameterarray[]) {");
3989 /* Unpack variables */
3990 for(int i=0; i<objectparams.numPrimitives(); i++) {
3991 TempDescriptor temp=objectparams.getPrimitive(i);
3992 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
3994 for(int i=0; i<fm.numTags(); i++) {
3995 TempDescriptor temp=fm.getTag(i);
3996 int offset=i+objectparams.numPrimitives();
3997 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
4000 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
4001 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
4002 } else output.println(") {");
4005 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
4006 output.println("/* FlatFlagActionNode */");
4009 /* Process tag changes */
4010 Relation tagsettable=new Relation();
4011 Relation tagcleartable=new Relation();
4013 Iterator tagsit=ffan.getTempTagPairs();
4014 while (tagsit.hasNext()) {
4015 TempTagPair ttp=(TempTagPair) tagsit.next();
4016 TempDescriptor objtmp=ttp.getTemp();
4017 TagDescriptor tag=ttp.getTag();
4018 TempDescriptor tagtmp=ttp.getTagTemp();
4019 boolean tagstatus=ffan.getTagChange(ttp);
4021 tagsettable.put(objtmp, tagtmp);
4023 tagcleartable.put(objtmp, tagtmp);
4028 Hashtable flagandtable=new Hashtable();
4029 Hashtable flagortable=new Hashtable();
4031 /* Process flag changes */
4032 Iterator flagsit=ffan.getTempFlagPairs();
4033 while(flagsit.hasNext()) {
4034 TempFlagPair tfp=(TempFlagPair)flagsit.next();
4035 TempDescriptor temp=tfp.getTemp();
4036 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
4037 FlagDescriptor flag=tfp.getFlag();
4039 //Newly allocate objects that don't set any flags case
4040 if (flagortable.containsKey(temp)) {
4044 flagortable.put(temp,new Integer(mask));
4046 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
4047 boolean flagstatus=ffan.getFlagChange(tfp);
4050 if (flagortable.containsKey(temp)) {
4051 mask=((Integer)flagortable.get(temp)).intValue();
4054 flagortable.put(temp,new Integer(mask));
4056 int mask=0xFFFFFFFF;
4057 if (flagandtable.containsKey(temp)) {
4058 mask=((Integer)flagandtable.get(temp)).intValue();
4060 mask&=(0xFFFFFFFF^flagid);
4061 flagandtable.put(temp,new Integer(mask));
4067 HashSet flagtagset=new HashSet();
4068 flagtagset.addAll(flagortable.keySet());
4069 flagtagset.addAll(flagandtable.keySet());
4070 flagtagset.addAll(tagsettable.keySet());
4071 flagtagset.addAll(tagcleartable.keySet());
4073 Iterator ftit=flagtagset.iterator();
4074 while(ftit.hasNext()) {
4075 TempDescriptor temp=(TempDescriptor)ftit.next();
4078 Set tagtmps=tagcleartable.get(temp);
4079 if (tagtmps!=null) {
4080 Iterator tagit=tagtmps.iterator();
4081 while(tagit.hasNext()) {
4082 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4083 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4084 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4086 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4090 tagtmps=tagsettable.get(temp);
4091 if (tagtmps!=null) {
4092 Iterator tagit=tagtmps.iterator();
4093 while(tagit.hasNext()) {
4094 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4095 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4096 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4098 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
4103 int andmask=0xFFFFFFF;
4105 if (flagortable.containsKey(temp))
4106 ormask=((Integer)flagortable.get(temp)).intValue();
4107 if (flagandtable.containsKey(temp))
4108 andmask=((Integer)flagandtable.get(temp)).intValue();
4109 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
4110 generateObjectDistribute(ffan, fm, lb, temp, output);
4114 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
4115 PrintWriter output, int ormask, int andmask) {
4116 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
4117 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4119 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4123 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
4124 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
4127 void generateOptionalHeader(PrintWriter headers) {
4130 headers.println("#include \"task.h\"\n\n");
4131 headers.println("#ifndef _OPTIONAL_STRUCT_");
4132 headers.println("#define _OPTIONAL_STRUCT_");
4134 //STRUCT PREDICATEMEMBER
4135 headers.println("struct predicatemember{");
4136 headers.println("int type;");
4137 headers.println("int numdnfterms;");
4138 headers.println("int * flags;");
4139 headers.println("int numtags;");
4140 headers.println("int * tags;\n};\n\n");
4142 //STRUCT OPTIONALTASKDESCRIPTOR
4143 headers.println("struct optionaltaskdescriptor{");
4144 headers.println("struct taskdescriptor * task;");
4145 headers.println("int index;");
4146 headers.println("int numenterflags;");
4147 headers.println("int * enterflags;");
4148 headers.println("int numpredicatemembers;");
4149 headers.println("struct predicatemember ** predicatememberarray;");
4150 headers.println("};\n\n");
4152 //STRUCT TASKFAILURE
4153 headers.println("struct taskfailure {");
4154 headers.println("struct taskdescriptor * task;");
4155 headers.println("int index;");
4156 headers.println("int numoptionaltaskdescriptors;");
4157 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4159 //STRUCT FSANALYSISWRAPPER
4160 headers.println("struct fsanalysiswrapper{");
4161 headers.println("int flags;");
4162 headers.println("int numtags;");
4163 headers.println("int * tags;");
4164 headers.println("int numtaskfailures;");
4165 headers.println("struct taskfailure ** taskfailurearray;");
4166 headers.println("int numoptionaltaskdescriptors;");
4167 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4169 //STRUCT CLASSANALYSISWRAPPER
4170 headers.println("struct classanalysiswrapper{");
4171 headers.println("int type;");
4172 headers.println("int numotd;");
4173 headers.println("struct optionaltaskdescriptor ** otdarray;");
4174 headers.println("int numfsanalysiswrappers;");
4175 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
4177 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
4179 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
4180 while(taskit.hasNext()) {
4181 TaskDescriptor td=(TaskDescriptor)taskit.next();
4182 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
4187 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
4188 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
4189 int predicateindex = 0;
4190 //iterate through the classes concerned by the predicate
4191 Set c_vard = predicate.vardescriptors;
4192 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
4195 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
4196 VarDescriptor vard = (VarDescriptor)vard_it.next();
4197 TypeDescriptor typed = vard.getType();
4199 //generate for flags
4200 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
4201 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4203 if (fen_hashset!=null) {
4204 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
4205 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
4207 DNFFlag dflag=fen.getDNF();
4208 numberterms+=dflag.size();
4210 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
4212 for(int j=0; j<dflag.size(); j++) {
4214 output.println(",");
4215 Vector term=dflag.get(j);
4218 for(int k=0; k<term.size(); k++) {
4219 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
4220 FlagDescriptor fd=dfa.getFlag();
4221 boolean negated=dfa.getNegated();
4222 int flagid=1<<((Integer)flags.get(fd)).intValue();
4227 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
4232 output.println("};\n");
4235 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
4236 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4239 for(int j=0; j<tagel.numTags(); j++) {
4241 output.println(",");
4242 TempDescriptor tmp=tagel.getTemp(j);
4243 if (!slotnumber.containsKey(tmp)) {
4244 Integer slotint=new Integer(current_slot++);
4245 slotnumber.put(tmp,slotint);
4247 int slot=slotnumber.get(tmp).intValue();
4248 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
4250 numtags = tagel.numTags();
4252 output.println("};");
4254 //store the result into a predicatemember struct
4255 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4256 output.println("/*type*/"+typed.getClassDesc().getId()+",");
4257 output.println("/* number of dnf terms */"+numberterms+",");
4258 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4259 output.println("/* number of tag */"+numtags+",");
4260 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4261 output.println("};\n");
4266 //generate an array that stores the entire predicate
4267 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4268 for( int j = 0; j<predicateindex; j++) {
4269 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4270 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4272 output.println("};\n");
4273 return predicateindex;
4277 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
4278 generateOptionalHeader(headers);
4280 output.println("#include \"optionalstruct.h\"\n\n");
4281 output.println("#include \"stdlib.h\"\n");
4283 HashSet processedcd = new HashSet();
4285 Enumeration e = safeexecution.keys();
4286 while (e.hasMoreElements()) {
4289 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
4290 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
4292 //Generate the struct of optionals
4293 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4294 numotd = c_otd.size();
4295 if(maxotd<numotd) maxotd = numotd;
4296 if( !c_otd.isEmpty() ) {
4297 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4298 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4300 //generate the int arrays for the predicate
4301 Predicate predicate = otd.predicate;
4302 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
4303 TreeSet<Integer> fsset=new TreeSet<Integer>();
4304 //iterate through possible FSes corresponding to
4305 //the state when entering
4307 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
4308 FlagState fs = (FlagState)fses.next();
4310 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4311 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4312 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4315 fsset.add(new Integer(flagid));
4316 //tag information not needed because tag
4317 //changes are not tolerated.
4320 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4321 boolean needcomma=false;
4322 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
4325 output.println(it.next());
4328 output.println("};\n");
4331 //generate optionaltaskdescriptor that actually
4332 //includes exit fses, predicate and the task
4334 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4335 output.println("&task_"+otd.td.getSafeSymbol()+",");
4336 output.println("/*index*/"+otd.getIndex()+",");
4337 output.println("/*number of enter flags*/"+fsset.size()+",");
4338 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4339 output.println("/*number of members */"+predicateindex+",");
4340 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4341 output.println("};\n");
4345 // if there are no optionals, there is no need to build the rest of the struct
4347 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
4348 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4349 if( !c_otd.isEmpty() ) {
4350 boolean needcomma=false;
4351 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4352 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4354 output.println(",");
4356 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4359 output.println("};\n");
4361 //get all the possible flagstates reachable by an object
4362 Hashtable hashtbtemp = safeexecution.get(cdtemp);
4364 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
4365 fsts.addAll(hashtbtemp.keySet());
4366 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
4367 FlagState fs = (FlagState)fsit.next();
4370 //get the set of OptionalTaskDescriptors corresponding
4371 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
4372 //iterate through the OptionalTaskDescriptors and
4373 //store the pointers to the optionals struct (see on
4374 //top) into an array
4376 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
4377 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
4378 OptionalTaskDescriptor mm = mos.next();
4380 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
4382 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4385 output.println("};\n");
4387 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
4390 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4391 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4392 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4396 //process tag information
4399 boolean first = true;
4400 Enumeration tag_enum = fs.getTags();
4401 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4402 while(tag_enum.hasMoreElements()) {
4404 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
4408 output.println(", ");
4409 output.println("/*tagid*/"+state.getTagId(tagd));
4411 output.println("};");
4413 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
4414 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4415 TaskIndex ti=itti.next();
4419 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
4421 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
4422 boolean needcomma=false;
4423 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
4424 OptionalTaskDescriptor otd=otdit.next();
4428 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4430 output.println("};");
4432 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
4433 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
4434 output.print(ti.getIndex()+", ");
4435 output.print(otdset.size()+", ");
4436 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
4437 output.println("};");
4440 tiset=sa.getTaskIndex(fs);
4441 boolean needcomma=false;
4443 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4444 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4445 TaskIndex ti=itti.next();
4446 if (ti.isRuntime()) {
4453 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
4455 output.println("};\n");
4457 //Store the result in fsanalysiswrapper
4459 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
4460 output.println("/*flag*/"+flagid+",");
4461 output.println("/* number of tags*/"+tagcounter+",");
4462 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4463 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
4464 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4465 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
4466 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
4467 output.println("};\n");
4471 //Build the array of fsanalysiswrappers
4472 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
4473 boolean needcomma=false;
4474 for(int i = 0; i<fscounter; i++) {
4475 if (needcomma) output.print(",");
4476 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
4479 output.println("};");
4481 //Build the classanalysiswrapper referring to the previous array
4482 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
4483 output.println("/*type*/"+cdtemp.getId()+",");
4484 output.println("/*numotd*/"+numotd+",");
4485 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
4486 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
4487 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
4488 processedcd.add(cdtemp);
4491 //build an array containing every classes for which code has been build
4492 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
4493 for(int i=0; i<state.numClasses(); i++) {
4494 ClassDescriptor cn=cdarray[i];
4497 if ((cn != null) && (processedcd.contains(cn)))
4498 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
4500 output.print("NULL");
4502 output.println("};");
4504 output.println("#define MAXOTD "+maxotd);
4505 headers.println("#endif");
4508 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
4509 Relation r=new Relation();
4510 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
4511 OptionalTaskDescriptor otd=otdit.next();
4512 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
4516 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
4517 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
4518 Set s=r.get(it.next());
4519 for(Iterator it2=s.iterator(); it2.hasNext();) {
4520 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
4528 protected void outputTransCode(PrintWriter output) {