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 lbrun=new LocalityBinding(typeutil.getRun(), false);
531 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
533 else if (state.SINGLETM) {
534 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
536 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
540 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
542 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
543 else if( state.SINGLETM)
544 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
545 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
548 outstructs.println("#define STRINGARRAYTYPE "+
549 (state.getArrayNumber(
550 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
552 outstructs.println("#define OBJECTARRAYTYPE "+
553 (state.getArrayNumber(
554 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
557 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
558 outstructs.println("#define CHARARRAYTYPE "+
559 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
561 outstructs.println("#define BYTEARRAYTYPE "+
562 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
564 outstructs.println("#define BYTEARRAYARRAYTYPE "+
565 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
567 outstructs.println("#define NUMCLASSES "+state.numClasses());
568 int totalClassSize = state.numClasses() + state.numArrays();
569 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
571 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
572 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
573 outstructs.println("#define TAGARRAYTYPE "+
574 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
578 protected void outputClassDeclarations(PrintWriter outclassdefs) {
579 if (state.THREAD||state.DSM||state.SINGLETM)
580 outclassdefs.println("#include <pthread.h>");
581 outclassdefs.println("#ifndef INTPTR");
582 outclassdefs.println("#ifdef BIT64");
583 outclassdefs.println("#define INTPTR long");
584 outclassdefs.println("#else");
585 outclassdefs.println("#define INTPTR int");
586 outclassdefs.println("#endif");
587 outclassdefs.println("#endif");
589 outclassdefs.println("#include \"optionalstruct.h\"");
590 outclassdefs.println("struct "+arraytype+";");
591 /* Start by declaring all structs */
592 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
593 while(it.hasNext()) {
594 ClassDescriptor cn=(ClassDescriptor)it.next();
595 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
597 outclassdefs.println("");
598 //Print out definition for array type
599 outclassdefs.println("struct "+arraytype+" {");
600 outclassdefs.println(" int type;");
602 outclassdefs.println(" pthread_t tid;");
603 outclassdefs.println(" void * lockentry;");
604 outclassdefs.println(" int lockcount;");
607 outclassdefs.println(" int flag;");
608 if(!state.MULTICORE) {
609 outclassdefs.println(" void * flagptr;");
611 outclassdefs.println(" int version;");
612 outclassdefs.println(" int * lock;"); // lock entry for this obj
613 outclassdefs.println(" int mutex;");
614 outclassdefs.println(" int lockcount;");
615 if(state.MULTICOREGC) {
616 outclassdefs.println(" int marked;");
620 outclassdefs.println(" int numfses;");
621 outclassdefs.println(" int * fses;");
624 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
627 outclassdefs.println(" int paddingforarray;");
629 outclassdefs.println(" int ___length___;");
630 outclassdefs.println("};\n");
631 outclassdefs.println("extern int classsize[];");
632 outclassdefs.println("extern int hasflags[];");
633 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
634 outclassdefs.println("extern int supertypes[];");
637 /** Prints out definitions for generic task structures */
639 private void outputTaskTypes(PrintWriter outtask) {
640 outtask.println("#ifndef _TASK_H");
641 outtask.println("#define _TASK_H");
642 outtask.println("struct parameterdescriptor {");
643 outtask.println("int type;");
644 outtask.println("int numberterms;");
645 outtask.println("int *intarray;");
646 outtask.println("void * queue;");
647 outtask.println("int numbertags;");
648 outtask.println("int *tagarray;");
649 outtask.println("};");
651 outtask.println("struct taskdescriptor {");
652 outtask.println("void * taskptr;");
653 outtask.println("int numParameters;");
654 outtask.println(" int numTotal;");
655 outtask.println("struct parameterdescriptor **descriptorarray;");
656 outtask.println("char * name;");
657 outtask.println("};");
658 outtask.println("extern struct taskdescriptor * taskarray[];");
659 outtask.println("extern numtasks;");
660 outtask.println("#endif");
664 private void buildRepairStructs(PrintWriter outrepairstructs) {
665 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
666 while(classit.hasNext()) {
667 ClassDescriptor cn=(ClassDescriptor)classit.next();
668 outrepairstructs.println("structure "+cn.getSymbol()+" {");
669 outrepairstructs.println(" int __type__;");
671 outrepairstructs.println(" int __flag__;");
672 if(!state.MULTICORE) {
673 outrepairstructs.println(" int __flagptr__;");
676 printRepairStruct(cn, outrepairstructs);
677 outrepairstructs.println("}\n");
680 for(int i=0; i<state.numArrays(); i++) {
681 TypeDescriptor tdarray=arraytable[i];
682 TypeDescriptor tdelement=tdarray.dereference();
683 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
684 outrepairstructs.println(" int __type__;");
685 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
686 outrepairstructs.println(" int length;");
688 // Need to add support to repair tool for this
689 if (tdelement.isClass()||tdelement.isArray())
690 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
692 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
694 outrepairstructs.println("}\n");
698 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
699 ClassDescriptor sp=cn.getSuperDesc();
701 printRepairStruct(sp, output);
703 Vector fields=(Vector)fieldorder.get(cn);
705 for(int i=0; i<fields.size(); i++) {
706 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
707 if (fd.getType().isArray()) {
708 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
709 } else if (fd.getType().isClass())
710 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
711 else if (fd.getType().isFloat())
712 output.println(" int "+fd.getSymbol()+"; /* really float */");
714 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
718 /** This method outputs TaskDescriptor information */
719 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
720 for (int i=0; i<task.numParameters(); i++) {
721 VarDescriptor param_var=task.getParameter(i);
722 TypeDescriptor param_type=task.getParamType(i);
723 FlagExpressionNode param_flag=task.getFlag(param_var);
724 TagExpressionList param_tag=task.getTag(param_var);
727 if (param_flag==null) {
728 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
729 output.println("0x0, 0x0 };");
732 DNFFlag dflag=param_flag.getDNF();
733 dnfterms=dflag.size();
735 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
736 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
737 for(int j=0; j<dflag.size(); j++) {
740 Vector term=dflag.get(j);
743 for(int k=0; k<term.size(); k++) {
744 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
745 FlagDescriptor fd=dfa.getFlag();
746 boolean negated=dfa.getNegated();
747 int flagid=1<<((Integer)flags.get(fd)).intValue();
752 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
754 output.println("};");
757 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
758 //BUG...added next line to fix, test with any task program
760 for(int j=0; j<param_tag.numTags(); j++) {
763 /* for each tag we need */
764 /* which slot it is */
765 /* what type it is */
766 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
767 TempDescriptor tmp=param_tag.getTemp(j);
768 int slot=fm.getTagInt(tmp);
769 output.println(slot+", "+state.getTagId(tvd.getTag()));
771 output.println("};");
773 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
774 output.println("/* type */"+param_type.getClassDesc().getId()+",");
775 output.println("/* number of DNF terms */"+dnfterms+",");
776 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
777 output.println("0,");
778 //BUG, added next line to fix and else statement...test
779 //with any task program
781 output.println("/* number of tags */"+param_tag.numTags()+",");
783 output.println("/* number of tags */ 0,");
784 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
785 output.println("};");
789 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
790 for (int i=0; i<task.numParameters(); i++) {
793 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
795 output.println("};");
797 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
798 output.println("&"+task.getSafeSymbol()+",");
799 output.println("/* number of parameters */" +task.numParameters() + ",");
800 int numtotal=task.numParameters()+fm.numTags();
801 output.println("/* number total parameters */" +numtotal + ",");
802 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
803 output.println("\""+task.getSymbol()+"\"");
804 output.println("};");
808 /** The buildVirtualTables method outputs the virtual dispatch
809 * tables for methods. */
811 protected void buildVirtualTables(PrintWriter outvirtual) {
812 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
813 while(classit.hasNext()) {
814 ClassDescriptor cd=(ClassDescriptor)classit.next();
815 if (virtualcalls.getMethodCount(cd)>maxcount)
816 maxcount=virtualcalls.getMethodCount(cd);
818 MethodDescriptor[][] virtualtable=null;
819 LocalityBinding[][] lbvirtualtable=null;
820 if (state.DSM||state.SINGLETM)
821 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
823 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
825 /* Fill in virtual table */
826 classit=state.getClassSymbolTable().getDescriptorsIterator();
827 while(classit.hasNext()) {
828 ClassDescriptor cd=(ClassDescriptor)classit.next();
829 if (state.DSM||state.SINGLETM)
830 fillinRow(cd, lbvirtualtable, cd.getId());
832 fillinRow(cd, virtualtable, cd.getId());
835 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
836 Iterator arrayit=state.getArrayIterator();
837 while(arrayit.hasNext()) {
838 TypeDescriptor td=(TypeDescriptor)arrayit.next();
839 int id=state.getArrayNumber(td);
840 if (state.DSM||state.SINGLETM)
841 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
843 fillinRow(objectcd, virtualtable, id+state.numClasses());
846 outvirtual.print("void * virtualtable[]={");
847 boolean needcomma=false;
848 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
849 for(int j=0; j<maxcount; j++) {
851 outvirtual.print(", ");
852 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
853 LocalityBinding lb=lbvirtualtable[i][j];
854 MethodDescriptor md=lb.getMethod();
855 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
856 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
857 MethodDescriptor md=virtualtable[i][j];
858 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
860 outvirtual.print("0");
864 outvirtual.println("");
866 outvirtual.println("};");
870 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
871 /* Get inherited methods */
872 if (cd.getSuperDesc()!=null)
873 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
874 /* Override them with our methods */
875 for(Iterator it=cd.getMethods(); it.hasNext();) {
876 MethodDescriptor md=(MethodDescriptor)it.next();
877 if (md.isStatic()||md.getReturnType()==null)
879 int methodnum=virtualcalls.getMethodNumber(md);
880 virtualtable[rownum][methodnum]=md;
884 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
885 /* Get inherited methods */
886 if (cd.getSuperDesc()!=null)
887 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
888 /* Override them with our methods */
889 if (locality.getClassBindings(cd)!=null)
890 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
891 LocalityBinding lb=lbit.next();
892 MethodDescriptor md=lb.getMethod();
893 //Is the method static or a constructor
894 if (md.isStatic()||md.getReturnType()==null)
896 int methodnum=virtualcalls.getLocalityNumber(lb);
897 virtualtable[rownum][methodnum]=lb;
901 /** Generate array that contains the sizes of class objects. The
902 * object allocation functions in the runtime use this
905 private void generateSizeArray(PrintWriter outclassdefs) {
906 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
907 outclassdefs.print("#ifdef TRANSSTATS \n");
908 outclassdefs.print("extern int numTransAbort;\n");
909 outclassdefs.print("extern int numTransCommit;\n");
910 outclassdefs.print("extern int nSoftAbort;\n");
912 outclassdefs.print("extern int nchashSearch;\n");
913 outclassdefs.print("extern int nmhashSearch;\n");
914 outclassdefs.print("extern int nprehashSearch;\n");
915 outclassdefs.print("extern int nRemoteSend;\n");
916 outclassdefs.print("extern int getResponse;\n");
917 outclassdefs.print("extern int bytesSent;\n");
918 outclassdefs.print("extern int bytesRecv;\n");
919 outclassdefs.print("extern void handle();\n");
920 } else if (state.SINGLETM) {
921 outclassdefs.println("extern int nSoftAbortAbort;");
922 outclassdefs.println("extern int nSoftAbortCommit;");
923 outclassdefs.println("#ifdef STMSTATS\n");
924 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
925 outclassdefs.println("#endif\n");
927 outclassdefs.print("#endif\n");
928 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
930 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
931 cdarray=new ClassDescriptor[state.numClasses()];
933 while(it.hasNext()) {
934 ClassDescriptor cd=(ClassDescriptor)it.next();
935 cdarray[cd.getId()]=cd;
938 arraytable=new TypeDescriptor[state.numArrays()];
940 Iterator arrayit=state.getArrayIterator();
941 while(arrayit.hasNext()) {
942 TypeDescriptor td=(TypeDescriptor)arrayit.next();
943 int id=state.getArrayNumber(td);
949 /* Print out types */
950 outclassdefs.println("/* ");
951 for(int i=0; i<state.numClasses(); i++) {
952 ClassDescriptor cd=cdarray[i];
954 outclassdefs.println("NULL " + i);
956 outclassdefs.println(cd +" "+i);
960 for(int i=0; i<state.numArrays(); i++) {
961 TypeDescriptor arraytd=arraytable[i];
962 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
965 outclassdefs.println("*/");
968 outclassdefs.print("int classsize[]={");
970 boolean needcomma=false;
971 for(int i=0; i<state.numClasses(); i++) {
973 outclassdefs.print(", ");
975 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
977 outclassdefs.print("0");
983 for(int i=0; i<state.numArrays(); i++) {
985 outclassdefs.print(", ");
986 TypeDescriptor tdelement=arraytable[i].dereference();
987 if (tdelement.isArray()||tdelement.isClass())
988 outclassdefs.print("sizeof(void *)");
990 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
994 outclassdefs.println("};");
996 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
998 outclassdefs.print("int typearray[]={");
999 for(int i=0; i<state.numClasses(); i++) {
1000 ClassDescriptor cd=cdarray[i];
1001 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1003 outclassdefs.print(", ");
1005 outclassdefs.print("-1");
1007 outclassdefs.print(supercd.getId());
1011 for(int i=0; i<state.numArrays(); i++) {
1012 TypeDescriptor arraytd=arraytable[i];
1013 ClassDescriptor arraycd=arraytd.getClassDesc();
1014 if (arraycd==null) {
1016 outclassdefs.print(", ");
1017 outclassdefs.print(objectclass.getId());
1021 ClassDescriptor cd=arraycd.getSuperDesc();
1024 TypeDescriptor supertd=new TypeDescriptor(cd);
1025 supertd.setArrayCount(arraytd.getArrayCount());
1026 type=state.getArrayNumber(supertd);
1028 type+=state.numClasses();
1031 cd=cd.getSuperDesc();
1034 outclassdefs.print(", ");
1035 outclassdefs.print(type);
1039 outclassdefs.println("};");
1044 outclassdefs.print("int typearray2[]={");
1045 for(int i=0; i<state.numArrays(); i++) {
1046 TypeDescriptor arraytd=arraytable[i];
1047 ClassDescriptor arraycd=arraytd.getClassDesc();
1048 if (arraycd==null) {
1050 outclassdefs.print(", ");
1051 outclassdefs.print("-1");
1055 ClassDescriptor cd=arraycd.getSuperDesc();
1056 int level=arraytd.getArrayCount()-1;
1058 for(; level>0; level--) {
1059 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1060 supertd.setArrayCount(level);
1061 type=state.getArrayNumber(supertd);
1063 type+=state.numClasses();
1068 outclassdefs.print(", ");
1069 outclassdefs.print(type);
1073 outclassdefs.println("};");
1076 /** Constructs params and temp objects for each method or task.
1077 * These objects tell the compiler which temps need to be
1080 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1081 MethodDescriptor md=fm.getMethod();
1082 TaskDescriptor task=fm.getTask();
1083 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1084 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1086 paramstable.put(lb, objectparams);
1087 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1088 } else if (md!=null)
1089 paramstable.put(md, objectparams);
1091 paramstable.put(task, objectparams);
1093 for(int i=0; i<fm.numParameters(); i++) {
1094 TempDescriptor temp=fm.getParameter(i);
1095 TypeDescriptor type=temp.getType();
1096 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1097 objectparams.addPtr(temp);
1099 objectparams.addPrim(temp);
1100 if(lb!=null&&saveset.contains(temp)) {
1101 backuptable.get(lb).put(temp, temp.createNew());
1105 for(int i=0; i<fm.numTags(); i++) {
1106 TempDescriptor temp=fm.getTag(i);
1107 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1108 objectparams.addPtr(temp);
1110 objectparams.addPrim(temp);
1113 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1115 tempstable.put(lb, objecttemps);
1117 tempstable.put(md, objecttemps);
1119 tempstable.put(task, objecttemps);
1121 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1122 FlatNode fn=(FlatNode)nodeit.next();
1123 TempDescriptor[] writes=fn.writesTemps();
1124 for(int i=0; i<writes.length; i++) {
1125 TempDescriptor temp=writes[i];
1126 TypeDescriptor type=temp.getType();
1127 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1128 objecttemps.addPtr(temp);
1130 objecttemps.addPrim(temp);
1131 if(lb!=null&&saveset.contains(temp)&&
1132 !backuptable.get(lb).containsKey(temp))
1133 backuptable.get(lb).put(temp, temp.createNew());
1137 /* Create backup temps */
1139 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1140 TempDescriptor tmp=tmpit.next();
1141 TypeDescriptor type=tmp.getType();
1142 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1143 objecttemps.addPtr(tmp);
1145 objecttemps.addPrim(tmp);
1147 /* Create temp to hold revert table */
1148 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1149 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1150 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1151 objecttemps.addPtr(reverttmp);
1153 objecttemps.addPrim(reverttmp);
1154 reverttable.put(lb, reverttmp);
1159 /** This method outputs the following information about classes
1161 * (1) For classes, what are the locations of pointers.
1162 * (2) For arrays, does the array contain pointers or primitives.
1163 * (3) For classes, does the class contain flags.
1166 private void generateLayoutStructs(PrintWriter output) {
1167 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1168 while(it.hasNext()) {
1169 ClassDescriptor cn=(ClassDescriptor)it.next();
1170 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1171 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1173 while(allit.hasNext()) {
1174 FieldDescriptor fd=(FieldDescriptor)allit.next();
1175 TypeDescriptor type=fd.getType();
1176 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1181 output.print(count);
1182 allit=cn.getFieldTable().getAllDescriptorsIterator();
1183 while(allit.hasNext()) {
1184 FieldDescriptor fd=(FieldDescriptor)allit.next();
1185 TypeDescriptor type=fd.getType();
1186 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1189 output.println(",");
1190 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1193 output.println("};");
1195 output.println("unsigned INTPTR * pointerarray[]={");
1196 boolean needcomma=false;
1197 for(int i=0; i<state.numClasses(); i++) {
1198 ClassDescriptor cn=cdarray[i];
1200 output.println(",");
1203 output.print(cn.getSafeSymbol()+"_pointers");
1205 output.print("NULL");
1209 for(int i=0; i<state.numArrays(); i++) {
1211 output.println(", ");
1212 TypeDescriptor tdelement=arraytable[i].dereference();
1213 if (tdelement.isArray()||tdelement.isClass())
1214 output.print("((unsigned INTPTR *)1)");
1220 output.println("};");
1222 output.println("int hasflags[]={");
1223 for(int i=0; i<state.numClasses(); i++) {
1224 ClassDescriptor cn=cdarray[i];
1226 output.println(", ");
1228 if ((cn != null) && (cn.hasFlags()))
1233 output.println("};");
1236 /** Print out table to give us supertypes */
1237 private void generateSuperTypeTable(PrintWriter output) {
1238 output.println("int supertypes[]={");
1239 boolean needcomma=false;
1240 for(int i=0; i<state.numClasses(); i++) {
1241 ClassDescriptor cn=cdarray[i];
1243 output.println(",");
1245 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1246 ClassDescriptor cdsuper=cn.getSuperDesc();
1247 output.print(cdsuper.getId());
1251 output.println("};");
1254 /** Force consistent field ordering between inherited classes. */
1256 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1258 ClassDescriptor sp=cn.getSuperDesc();
1260 printClassStruct(sp, classdefout);
1262 if (!fieldorder.containsKey(cn)) {
1263 Vector fields=new Vector();
1264 fieldorder.put(cn,fields);
1265 Vector fieldvec=cn.getFieldVec();
1266 for(int i=0;i<fieldvec.size();i++) {
1267 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1268 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1272 Vector fields=(Vector)fieldorder.get(cn);
1274 for(int i=0; i<fields.size(); i++) {
1275 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1276 if (fd.getType().isClass()||fd.getType().isArray())
1277 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1279 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1284 /* Map flags to integers consistently between inherited
1287 protected void mapFlags(ClassDescriptor cn) {
1288 ClassDescriptor sp=cn.getSuperDesc();
1292 if (!flagorder.containsKey(cn)) {
1293 Hashtable flags=new Hashtable();
1294 flagorder.put(cn,flags);
1296 Hashtable superflags=(Hashtable)flagorder.get(sp);
1297 Iterator superflagit=superflags.keySet().iterator();
1298 while(superflagit.hasNext()) {
1299 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1300 Integer number=(Integer)superflags.get(fd);
1301 flags.put(fd, number);
1302 if ((number.intValue()+1)>max)
1303 max=number.intValue()+1;
1307 Iterator flagit=cn.getFlags();
1308 while(flagit.hasNext()) {
1309 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1310 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1311 flags.put(fd, new Integer(max++));
1317 /** This function outputs (1) structures that parameters are
1318 * passed in (when PRECISE GC is enabled) and (2) function
1319 * prototypes for the methods */
1321 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1322 /* Output class structure */
1323 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1324 classdefout.println(" int type;");
1326 classdefout.println(" pthread_t tid;");
1327 classdefout.println(" void * lockentry;");
1328 classdefout.println(" int lockcount;");
1332 classdefout.println(" int flag;");
1333 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1334 classdefout.println(" void * flagptr;");
1335 } else if (state.MULTICORE) {
1336 classdefout.println(" int version;");
1337 classdefout.println(" int * lock;"); // lock entry for this obj
1338 classdefout.println(" int mutex;");
1339 classdefout.println(" int lockcount;");
1340 if(state.MULTICOREGC) {
1341 classdefout.println(" int marked;");
1344 if (state.OPTIONAL) {
1345 classdefout.println(" int numfses;");
1346 classdefout.println(" int * fses;");
1349 printClassStruct(cn, classdefout);
1350 classdefout.println("};\n");
1352 if (state.DSM||state.SINGLETM) {
1353 /* Cycle through LocalityBindings */
1354 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1355 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1357 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1358 LocalityBinding lb=lbit.next();
1359 MethodDescriptor md=lb.getMethod();
1360 if (md.getModifiers().isNative()) {
1361 //make sure we only print a native method once
1362 if (nativemethods.contains(md)) {
1363 FlatMethod fm=state.getMethodFlat(md);
1364 generateTempStructs(fm, lb);
1367 nativemethods.add(md);
1369 generateMethod(cn, md, lb, headersout, output);
1372 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1373 MethodDescriptor md=(MethodDescriptor)methodit.next();
1374 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1375 //Need to build param structure for library code
1376 FlatMethod fm=state.getMethodFlat(md);
1377 generateTempStructs(fm, null);
1378 generateMethodParam(cn, md, null, output);
1383 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1384 MethodDescriptor md=(MethodDescriptor)methodit.next();
1385 generateMethod(cn, md, null, headersout, output);
1389 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1390 /* Output parameter structure */
1391 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1392 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1393 if ((state.DSM||state.SINGLETM)&&lb!=null)
1394 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1396 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1397 output.println(" INTPTR size;");
1398 output.println(" void * next;");
1399 for(int i=0; i<objectparams.numPointers(); i++) {
1400 TempDescriptor temp=objectparams.getPointer(i);
1401 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1403 output.println("};\n");
1407 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1408 FlatMethod fm=state.getMethodFlat(md);
1409 generateTempStructs(fm, lb);
1411 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1412 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1414 generateMethodParam(cn, md, lb, output);
1416 /* Output temp structure */
1417 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1418 if (state.DSM||state.SINGLETM)
1419 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1421 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1422 output.println(" INTPTR size;");
1423 output.println(" void * next;");
1424 for(int i=0; i<objecttemps.numPointers(); i++) {
1425 TempDescriptor temp=objecttemps.getPointer(i);
1426 if (temp.getType().isNull())
1427 output.println(" void * "+temp.getSafeSymbol()+";");
1429 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1431 output.println("};\n");
1434 /********* Output method declaration ***********/
1435 if (state.DSM||state.SINGLETM) {
1436 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1438 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1440 /* First the return type */
1441 if (md.getReturnType()!=null) {
1442 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1443 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1445 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1447 //catch the constructor case
1448 headersout.print("void ");
1450 /* Next the method name */
1451 if (state.DSM||state.SINGLETM) {
1452 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1454 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1456 boolean printcomma=false;
1457 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1458 if (state.DSM||state.SINGLETM) {
1459 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1461 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1465 /* Output parameter list*/
1466 for(int i=0; i<objectparams.numPrimitives(); i++) {
1467 TempDescriptor temp=objectparams.getPrimitive(i);
1469 headersout.print(", ");
1471 if (temp.getType().isClass()||temp.getType().isArray())
1472 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1474 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1476 headersout.println(");\n");
1480 /** This function outputs (1) structures that parameters are
1481 * passed in (when PRECISE GC is enabled) and (2) function
1482 * prototypes for the tasks */
1484 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1485 /* Cycle through tasks */
1486 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1488 while(taskit.hasNext()) {
1489 /* Classify parameters */
1490 TaskDescriptor task=(TaskDescriptor)taskit.next();
1491 FlatMethod fm=state.getMethodFlat(task);
1492 generateTempStructs(fm, null);
1494 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1495 TempObject objecttemps=(TempObject) tempstable.get(task);
1497 /* Output parameter structure */
1498 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1499 output.println("struct "+task.getSafeSymbol()+"_params {");
1501 output.println(" INTPTR size;");
1502 output.println(" void * next;");
1503 for(int i=0; i<objectparams.numPointers(); i++) {
1504 TempDescriptor temp=objectparams.getPointer(i);
1505 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1508 output.println("};\n");
1509 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1510 maxtaskparams=objectparams.numPointers()+fm.numTags();
1514 /* Output temp structure */
1515 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1516 output.println("struct "+task.getSafeSymbol()+"_locals {");
1517 output.println(" INTPTR size;");
1518 output.println(" void * next;");
1519 for(int i=0; i<objecttemps.numPointers(); i++) {
1520 TempDescriptor temp=objecttemps.getPointer(i);
1521 if (temp.getType().isNull())
1522 output.println(" void * "+temp.getSafeSymbol()+";");
1523 else if(temp.getType().isTag())
1524 output.println(" struct "+
1525 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1527 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1529 output.println("};\n");
1532 /* Output task declaration */
1533 headersout.print("void " + task.getSafeSymbol()+"(");
1535 boolean printcomma=false;
1536 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1537 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1539 headersout.print("void * parameterarray[]");
1540 headersout.println(");\n");
1544 /***** Generate code for FlatMethod fm. *****/
1546 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1547 static int atomicmethodcount=0;
1549 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1550 if (State.PRINTFLAT)
1551 System.out.println(fm.printMethod());
1552 MethodDescriptor md=fm.getMethod();
1553 TaskDescriptor task=fm.getTask();
1554 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1555 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1557 HashSet<AtomicRecord> arset=null;
1559 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1561 if (atomicmethodmap==null)
1562 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1564 //fix these so we get right strings for local variables
1565 localsprefixaddr=localsprefix;
1566 localsprefixderef=localsprefix+"->";
1567 arset=new HashSet<AtomicRecord>();
1569 //Generate commit methods here
1570 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1571 FlatNode fn=fnit.next();
1572 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1573 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0) {
1574 //We have an atomic enter
1575 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1576 Set<FlatNode> exitset=faen.getExits();
1578 String methodname=md.getSymbol()+(atomicmethodcount++);
1579 AtomicRecord ar=new AtomicRecord();
1583 atomicmethodmap.put(faen, ar);
1585 //build data structure declaration
1586 output.println("struct atomicprimitives_"+methodname+" {");
1588 Set<FlatNode> recordset=delaycomp.livecode(lb);
1589 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1590 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1591 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1593 ar.reallivein=new HashSet(liveinto);
1595 ar.liveoutvirtualread=liveoutvirtualread;
1597 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1598 TempDescriptor tmp=it.next();
1599 //remove the pointers
1600 if (tmp.getType().isPtr()) {
1603 //let's print it here
1604 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1607 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1608 TempDescriptor tmp=it.next();
1609 //remove the pointers
1610 if (tmp.getType().isPtr()) {
1612 } else if (!liveinto.contains(tmp)) {
1613 //let's print it here
1614 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1617 output.println("};");
1619 //print out method name
1620 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) {");
1621 //build code for commit method
1623 //first define local primitives
1624 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1625 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1626 TempDescriptor tmp=tmpit.next();
1627 if (!tmp.getType().isPtr()) {
1628 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1629 //read from live into set
1630 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1633 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1637 //turn off write barrier generation
1639 state.SINGLETM=false;
1640 generateCode(faen, fm, lb, exitset, output, false);
1641 state.SINGLETM=true;
1642 //turn on write barrier generation
1644 output.println("}\n\n");
1648 //redefine these back to normal
1650 localsprefixaddr="&"+localsprefix;
1651 localsprefixderef=localsprefix+".";
1653 generateHeader(fm, lb, md!=null ? md : task,output);
1654 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1656 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1657 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1658 AtomicRecord ar=arit.next();
1659 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1663 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1664 if (md!=null&&(state.DSM||state.SINGLETM))
1665 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1666 else if (md!=null&&!(state.DSM||state.SINGLETM))
1667 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1669 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1671 output.print(objecttemp.numPointers()+",");
1672 output.print(paramsprefix);
1673 for(int j=0; j<objecttemp.numPointers(); j++)
1674 output.print(", NULL");
1675 output.println("};");
1678 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1679 TempDescriptor td=objecttemp.getPrimitive(i);
1680 TypeDescriptor type=td.getType();
1682 output.println(" void * "+td.getSafeSymbol()+";");
1683 else if (type.isClass()||type.isArray())
1684 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1686 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1691 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1692 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1693 if( callerSESEplaceholder != mlpa.getMainSESE() ) {
1694 // declare variables for naming static SESE's
1695 output.println(" /* static SESE names */");
1696 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1697 while( pItr.hasNext() ) {
1698 SESEandAgePair p = pItr.next();
1699 output.println(" void* "+p+";");
1702 // declare variables for tracking dynamic sources
1703 output.println(" /* dynamic variable sources */");
1704 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1705 while( dynSrcItr.hasNext() ) {
1706 TempDescriptor dynSrcVar = dynSrcItr.next();
1707 output.println(" void* "+dynSrcVar+"_srcSESE;");
1708 output.println(" int "+dynSrcVar+"_srcOffset;");
1715 /* Check to see if we need to do a GC if this is a
1716 * multi-threaded program...*/
1718 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1719 || this.state.MULTICOREGC) {
1720 //Don't bother if we aren't in recursive methods...The loops case will catch it
1721 if (callgraph.getAllMethods(md).contains(md)) {
1722 if (state.DSM&&lb.isAtomic())
1723 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1724 else if (this.state.MULTICOREGC) {
1725 output.println("if(gcflag) gc("+localsprefixaddr+");");
1727 output.println("if (needtocollect) checkcollect("+localsprefixaddr+");");
1731 generateCode(fm.getNext(0), fm, lb, null, output, true);
1733 output.println("}\n\n");
1737 protected void initializeSESE( FlatSESEEnterNode fsen ) {
1739 FlatMethod fm = fsen.getfmEnclosing();
1740 MethodDescriptor md = fm.getMethod();
1741 ClassDescriptor cn = md.getClassDesc();
1744 // Creates bogus method descriptor to index into tables
1745 Modifiers modBogus = new Modifiers();
1746 MethodDescriptor mdBogus =
1747 new MethodDescriptor( modBogus,
1748 new TypeDescriptor( TypeDescriptor.VOID ),
1749 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1752 mdBogus.setClassDesc( fsen.getcdEnclosing() );
1753 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1754 fsen.setfmBogus( fmBogus );
1755 fsen.setmdBogus( mdBogus );
1757 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1758 inSetAndOutSet.addAll( fsen.getInVarSet() );
1759 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1761 // Build paramsobj for bogus method descriptor
1762 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
1763 paramstable.put( mdBogus, objectparams );
1765 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1766 while( itr.hasNext() ) {
1767 TempDescriptor temp = itr.next();
1768 TypeDescriptor type = temp.getType();
1769 if( type.isPtr() ) {
1770 objectparams.addPtr( temp );
1772 objectparams.addPrim( temp );
1776 // Build normal temp object for bogus method descriptor
1777 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
1778 tempstable.put( mdBogus, objecttemps );
1780 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
1781 FlatNode fn = (FlatNode)nodeit.next();
1782 TempDescriptor[] writes = fn.writesTemps();
1784 for( int i = 0; i < writes.length; i++ ) {
1785 TempDescriptor temp = writes[i];
1786 TypeDescriptor type = temp.getType();
1788 if( type.isPtr() ) {
1789 objecttemps.addPtr( temp );
1791 objecttemps.addPrim( temp );
1797 protected void generateMethodSESE(FlatSESEEnterNode fsen,
1799 PrintWriter outputStructs,
1800 PrintWriter outputMethHead,
1801 PrintWriter outputMethods
1804 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
1805 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
1807 // generate locals structure
1808 outputStructs.println("struct "+
1809 fsen.getcdEnclosing().getSafeSymbol()+
1810 fsen.getmdBogus().getSafeSymbol()+"_"+
1811 fsen.getmdBogus().getSafeMethodDescriptor()+
1813 outputStructs.println(" INTPTR size;");
1814 outputStructs.println(" void * next;");
1815 for(int i=0; i<objecttemps.numPointers(); i++) {
1816 TempDescriptor temp=objecttemps.getPointer(i);
1818 if( fsen.getPrettyIdentifier().equals( "calc" ) ) {
1819 System.out.println( " got a pointer "+temp );
1822 if (temp.getType().isNull())
1823 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1825 outputStructs.println(" struct "+
1826 temp.getType().getSafeSymbol()+" * "+
1827 temp.getSafeSymbol()+";");
1829 outputStructs.println("};\n");
1832 // generate the SESE record structure
1833 outputStructs.println(fsen.getSESErecordName()+" {");
1835 // data common to any SESE, and it must be placed first so
1836 // a module that doesn't know what kind of SESE record this
1837 // is can cast the pointer to a common struct
1838 outputStructs.println(" SESEcommon common;");
1840 // then garbage list stuff
1841 outputStructs.println(" INTPTR size;");
1842 outputStructs.println(" void * next;");
1844 // in-set source tracking
1845 // in-vars that are READY come from parent, don't need anything
1846 // stuff STATIC needs a custom SESE pointer for each age pair
1847 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
1848 while( itrStaticInVarSrcs.hasNext() ) {
1849 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
1850 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
1853 // DYNAMIC stuff needs a source SESE ptr and offset
1854 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
1855 while( itrDynInVars.hasNext() ) {
1856 TempDescriptor dynInVar = itrDynInVars.next();
1857 outputStructs.println(" void* "+dynInVar+"_srcSESE;");
1858 outputStructs.println(" int "+dynInVar+"_srcOffset;");
1861 // space for all in and out set primitives
1862 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1863 inSetAndOutSet.addAll( fsen.getInVarSet() );
1864 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1866 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
1868 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1869 while( itr.hasNext() ) {
1870 TempDescriptor temp = itr.next();
1871 TypeDescriptor type = temp.getType();
1872 if( !type.isPtr() ) {
1873 inSetAndOutSetPrims.add( temp );
1877 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
1878 while( itrPrims.hasNext() ) {
1879 TempDescriptor temp = itrPrims.next();
1880 TypeDescriptor type = temp.getType();
1881 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
1884 for(int i=0; i<objectparams.numPointers(); i++) {
1885 TempDescriptor temp=objectparams.getPointer(i);
1886 if (temp.getType().isNull())
1887 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1889 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1892 outputStructs.println("};\n");
1895 // write method declaration to header file
1896 outputMethHead.print("void ");
1897 outputMethHead.print(fsen.getSESEmethodName()+"(");
1898 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
1899 outputMethHead.println(");\n");
1902 generateFlatMethodSESE( fsen.getfmBogus(),
1903 fsen.getcdEnclosing(),
1909 private void generateFlatMethodSESE(FlatMethod fm,
1911 FlatSESEEnterNode fsen,
1912 FlatSESEExitNode seseExit,
1916 MethodDescriptor md=fm.getMethod();
1918 output.print("void ");
1919 output.print(fsen.getSESEmethodName()+"(");
1920 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
1921 output.println("){\n");
1923 TempObject objecttemp=(TempObject) tempstable.get(md);
1925 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1926 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1927 output.print(objecttemp.numPointers()+",");
1928 output.print("(void*) &("+paramsprefix+"->size)");
1929 for(int j=0; j<objecttemp.numPointers(); j++)
1930 output.print(", NULL");
1931 output.println("};");
1934 output.println(" /* regular local primitives */");
1935 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1936 TempDescriptor td=objecttemp.getPrimitive(i);
1937 TypeDescriptor type=td.getType();
1939 output.println(" void * "+td.getSafeSymbol()+";");
1940 else if (type.isClass()||type.isArray())
1941 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1943 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1947 // declare variables for naming static SESE's
1948 output.println(" /* static SESE names */");
1949 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
1950 while( pItr.hasNext() ) {
1951 SESEandAgePair p = pItr.next();
1952 output.println(" void* "+p+";");
1955 // declare variables for tracking dynamic sources
1956 output.println(" /* dynamic variable sources */");
1957 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
1958 while( dynSrcItr.hasNext() ) {
1959 TempDescriptor dynSrcVar = dynSrcItr.next();
1960 output.println(" void* "+dynSrcVar+"_srcSESE;");
1961 output.println(" int "+dynSrcVar+"_srcOffset;");
1964 // declare local temps for in-set primitives, and if it is
1965 // a ready-source variable, get the value from the record
1966 output.println(" /* local temps for in-set primitives */");
1967 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
1968 while( itrInSet.hasNext() ) {
1969 TempDescriptor temp = itrInSet.next();
1970 TypeDescriptor type = temp.getType();
1971 if( !type.isPtr() ) {
1972 if( fsen.getReadyInVarSet().contains( temp ) ) {
1973 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
1975 output.println(" "+type+" "+temp+";");
1980 // declare local temps for out-set primitives if its not already
1981 // in the in-set, and it's value will get written so no problem
1982 output.println(" /* local temp for out-set prim, not already in the in-set */");
1983 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
1984 while( itrOutSet.hasNext() ) {
1985 TempDescriptor temp = itrOutSet.next();
1986 TypeDescriptor type = temp.getType();
1987 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
1988 output.println(" "+type+" "+temp+";");
1992 // copy in-set into place, ready vars were already
1993 // copied when the SESE was issued
1994 Iterator<TempDescriptor> tempItr;
1996 // static vars are from a known SESE
1997 tempItr = fsen.getStaticInVarSet().iterator();
1998 while( tempItr.hasNext() ) {
1999 TempDescriptor temp = tempItr.next();
2000 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2001 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2003 // can't grab something from this source until it is done
2004 output.println(" {");
2005 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+srcPair+";" );
2006 output.println(" pthread_mutex_lock( &(com->lock) );");
2007 output.println(" while( com->doneExecuting == FALSE ) {");
2008 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2009 output.println(" }");
2010 output.println(" pthread_mutex_unlock( &(com->lock) );");
2012 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2013 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2015 output.println(" }");
2018 // dynamic vars come from an SESE and src
2019 tempItr = fsen.getDynamicInVarSet().iterator();
2020 while( tempItr.hasNext() ) {
2021 TempDescriptor temp = tempItr.next();
2022 TypeDescriptor type = temp.getType();
2024 // go grab it from the SESE source
2025 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2027 // gotta wait until the source is done
2028 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+temp+"_srcSESE;" );
2029 output.println(" pthread_mutex_lock( &(com->lock) );");
2030 output.println(" while( com->doneExecuting == FALSE ) {");
2031 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2032 output.println(" }");
2033 output.println(" pthread_mutex_unlock( &(com->lock) );");
2036 if( type.isNull() ) {
2038 } else if( type.isClass() || type.isArray() ) {
2039 typeStr = "struct "+type.getSafeSymbol()+"*";
2041 typeStr = type.getSafeSymbol();
2044 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2045 " = *(("+typeStr+"*) ("+
2046 paramsprefix+"->"+temp+"_srcSESE + "+
2047 paramsprefix+"->"+temp+"_srcOffset));");
2049 // or if the source was our parent, its in the record to grab
2050 output.println(" } else {");
2051 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2052 " = "+paramsprefix+"->"+temp+";");
2053 output.println(" }");
2056 // Check to see if we need to do a GC if this is a
2057 // multi-threaded program...
2058 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2059 //Don't bother if we aren't in recursive methods...The loops case will catch it
2060 if (callgraph.getAllMethods(md).contains(md)) {
2061 if(this.state.MULTICOREGC) {
2062 output.println("if(gcflag) gc("+localsprefixaddr+");");
2064 output.println("if (needtocollect) checkcollect("+localsprefixaddr+");");
2069 // initialize thread-local var to a non-zero, invalid address
2070 output.println(" seseCaller = (SESEcommon*) 0x2;");
2072 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2073 exitset.add(seseExit);
2075 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2077 output.println("}\n\n");
2081 // when a new mlp thread is created for an issued SESE, it is started
2082 // by running this method which blocks on a cond variable until
2083 // it is allowed to transition to execute. Then a case statement
2084 // allows it to invoke the method with the proper SESE body, and after
2085 // exiting the SESE method, executes proper SESE exit code before the
2086 // thread can be destroyed
2087 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2088 PrintWriter outmethod
2091 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2092 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2093 outmethod.println( " int status;");
2094 outmethod.println( " char errmsg[128];");
2096 // generate a case for each SESE class that can be invoked
2097 outmethod.println( " switch( *((int*)seseRecord) ) {");
2098 outmethod.println( " ");
2099 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
2100 FlatSESEEnterNode fsen = seseit.next();
2102 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2103 outmethod.println( " case "+fsen.getIdentifier()+":");
2104 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2106 if( fsen.equals( mlpa.getMainSESE() ) ) {
2107 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2108 outmethod.println( " exit( 0 );");
2111 outmethod.println( " break;");
2112 outmethod.println( "");
2115 // default case should never be taken, error out
2116 outmethod.println( " default:");
2117 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2118 outmethod.println( " exit(-30);");
2119 outmethod.println( " break;");
2120 outmethod.println( " }");
2121 outmethod.println( " return NULL;");
2122 outmethod.println( "}\n\n");
2126 protected void generateCode(FlatNode first,
2129 Set<FlatNode> stopset,
2130 PrintWriter output, boolean firstpass) {
2132 /* Assign labels to FlatNode's if necessary.*/
2133 Hashtable<FlatNode, Integer> nodetolabel=assignLabels(first, stopset);
2135 Set<FlatNode> storeset=null;
2136 HashSet<FlatNode> genset=null;
2137 Set<FlatNode> unionset=null;
2139 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2140 storeset=delaycomp.livecode(lb);
2141 genset=new HashSet<FlatNode>();
2143 genset.addAll(delaycomp.getCannotDelay(lb));
2144 genset.addAll(delaycomp.getOther(lb));
2146 genset.addAll(delaycomp.getNotReady(lb));
2148 unionset=new HashSet<FlatNode>();
2149 unionset.addAll(storeset);
2150 unionset.addAll(genset);
2153 /* Do the actual code generation */
2154 FlatNode current_node=null;
2155 HashSet tovisit=new HashSet();
2156 HashSet visited=new HashSet();
2158 tovisit.add(first.getNext(0));
2161 while(current_node!=null||!tovisit.isEmpty()) {
2162 if (current_node==null) {
2163 current_node=(FlatNode)tovisit.iterator().next();
2164 tovisit.remove(current_node);
2165 } else if (tovisit.contains(current_node)) {
2166 tovisit.remove(current_node);
2168 visited.add(current_node);
2169 if (nodetolabel.containsKey(current_node)) {
2170 output.println("L"+nodetolabel.get(current_node)+":");
2172 if (state.INSTRUCTIONFAILURE) {
2173 if (state.THREAD||state.DSM||state.SINGLETM) {
2174 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2176 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2178 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2180 if (!state.DELAYCOMP||firstpass) {
2181 generateFlatNode(fm, lb, current_node, output);
2183 //store primitive variables in out set
2184 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2185 Set<TempDescriptor> liveout=ar.liveout;
2186 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2187 TempDescriptor tmp=tmpit.next();
2188 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2191 if (state.MLP && stopset!=null) {
2192 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2193 assert current_node instanceof FlatSESEExitNode;
2194 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2195 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2196 assert fsen.getFlatExit().equals( fsxn );
2197 assert fsxn.getFlatEnter().equals( fsen );
2199 if (current_node.kind()!=FKind.FlatReturnNode) {
2200 output.println(" return;");
2203 } else if(current_node.numNext()==1) {
2206 current_node.kind()==FKind.FlatSESEEnterNode &&
2207 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2209 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2210 generateFlatNode(fm, lb, current_node, output);
2211 nextnode=fsen.getFlatExit().getNext(0);
2212 } else if (state.DELAYCOMP) {
2213 boolean specialprimitive=false;
2214 //skip literals...no need to add extra overhead
2215 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2216 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2217 if (!typedesc.isClass()&&!typedesc.isArray()) {
2218 specialprimitive=true;
2222 if (genset==null||genset.contains(current_node)||specialprimitive)
2223 generateFlatNode(fm, lb, current_node, output);
2224 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2225 TempDescriptor wrtmp=current_node.writesTemps()[0];
2227 //need to store value written by previous node
2228 if (wrtmp.getType().isPtr()) {
2229 //only lock the objects that may actually need locking
2230 if (recorddc.getNeedTrans(lb, current_node)) {
2231 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");");
2233 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");");
2236 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");");
2239 //need to read value read by previous node
2240 if (wrtmp.getType().isPtr()) {
2241 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");");
2243 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");");
2247 nextnode=current_node.getNext(0);
2250 generateFlatNode(fm, lb, current_node, output);
2251 nextnode=current_node.getNext(0);
2253 if (visited.contains(nextnode)) {
2254 output.println("goto L"+nodetolabel.get(nextnode)+";");
2257 current_node=nextnode;
2258 } else if (current_node.numNext()==2) {
2260 if (state.DELAYCOMP) {
2261 boolean computeside=false;
2263 //need to record which way it should go
2264 if (genset==null||genset.contains(current_node)) {
2265 if (storeset!=null&&storeset.contains(current_node)) {
2266 //need to store which way branch goes
2267 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2269 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2271 //which side to execute
2275 if (genset.contains(current_node)) {
2276 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2277 } else if (storeset.contains(current_node)) {
2279 output.println("RESTOREANDBRANCH(L"+nodetolabel.get(current_node.getNext(1))+");");
2281 //which side to execute
2286 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2288 if (leftset.size()==0)
2290 if (visited.contains(current_node.getNext(branch))) {
2291 //already visited -- build jump
2292 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2295 current_node=current_node.getNext(branch);
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);
2308 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2309 if (!visited.contains(current_node.getNext(1)))
2310 tovisit.add(current_node.getNext(1));
2311 if (visited.contains(current_node.getNext(0))) {
2312 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2315 current_node=current_node.getNext(0);
2317 } else throw new Error();
2321 /** This method assigns labels to FlatNodes */
2322 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2323 return assignLabels(first, null);
2326 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2327 HashSet tovisit=new HashSet();
2328 HashSet visited=new HashSet();
2330 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2333 /*Assign labels first. A node needs a label if the previous
2334 * node has two exits or this node is a join point. */
2336 while(!tovisit.isEmpty()) {
2337 FlatNode fn=(FlatNode)tovisit.iterator().next();
2342 if(lastset!=null&&lastset.contains(fn)) {
2343 // if last is not null and matches, don't go
2344 // any further for assigning labels
2348 for(int i=0; i<fn.numNext(); i++) {
2349 FlatNode nn=fn.getNext(i);
2352 //1) Edge >1 of node
2353 nodetolabel.put(nn,new Integer(labelindex++));
2355 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2359 nodetolabel.put(nn,new Integer(labelindex++));
2367 /** Generate text string that corresponds to the TempDescriptor td. */
2368 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2369 MethodDescriptor md=fm.getMethod();
2370 TaskDescriptor task=fm.getTask();
2371 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2373 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2374 //System.out.println("generateTemp returns " + td.getSafeSymbol());
2375 return td.getSafeSymbol();
2378 if (objecttemps.isLocalPtr(td)) {
2379 return localsprefixderef+td.getSafeSymbol();
2382 if (objecttemps.isParamPtr(td)) {
2383 return paramsprefix+"->"+td.getSafeSymbol();
2389 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2391 // insert pre-node actions from the code plan
2394 CodePlan cp = mlpa.getCodePlan( fn );
2397 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2399 // for each sese and age pair that this parent statement
2400 // must stall on, take that child's stall semaphore, the
2401 // copying of values comes after the statement
2402 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2403 while( vstItr.hasNext() ) {
2404 VariableSourceToken vst = vstItr.next();
2406 SESEandAgePair p = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2408 output.println(" {");
2409 output.println(" SESEcommon* common = (SESEcommon*) "+p+";");
2411 output.println(" pthread_mutex_lock( &(common->lock) );");
2412 output.println(" while( common->doneExecuting == FALSE ) {");
2413 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2414 output.println(" }");
2415 output.println(" pthread_mutex_unlock( &(common->lock) );");
2417 //output.println(" psem_take( &(common->stallSem) );");
2419 // copy things we might have stalled for
2420 output.println(" "+p.getSESE().getSESErecordName()+"* child = ("+
2421 p.getSESE().getSESErecordName()+"*) "+p+";");
2423 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2424 while( tdItr.hasNext() ) {
2425 TempDescriptor td = tdItr.next();
2426 FlatMethod fmContext;
2427 if( currentSESE.getIsCallerSESEplaceholder() ) {
2428 fmContext = currentSESE.getfmEnclosing();
2430 fmContext = currentSESE.getfmBogus();
2432 output.println(" "+generateTemp( fmContext, td, null )+
2433 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2436 output.println(" }");
2439 // for each variable with a dynamic source, stall just for that variable
2440 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2441 while( dynItr.hasNext() ) {
2442 TempDescriptor dynVar = dynItr.next();
2444 // only stall if the dynamic source is not yourself, denoted by src==NULL
2445 // otherwise the dynamic write nodes will have the local var up-to-date
2446 output.println(" {");
2447 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2448 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2449 output.println(" psem_take( &(common->stallSem) );");
2451 FlatMethod fmContext;
2452 if( currentSESE.getIsCallerSESEplaceholder() ) {
2453 fmContext = currentSESE.getfmEnclosing();
2455 fmContext = currentSESE.getfmBogus();
2457 output.println(" "+generateTemp( fmContext, dynVar, null )+
2458 " = *(("+dynVar.getType()+"*) ("+
2459 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2461 output.println(" }");
2462 output.println(" }");
2465 // for each assignment of a variable to rhs that has a dynamic source,
2466 // copy the dynamic sources
2467 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2468 while( dynAssignItr.hasNext() ) {
2469 Map.Entry me = (Map.Entry) dynAssignItr.next();
2470 TempDescriptor lhs = (TempDescriptor) me.getKey();
2471 TempDescriptor rhs = (TempDescriptor) me.getValue();
2472 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
2473 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2476 // for each lhs that is dynamic from a non-dynamic source, set the
2477 // dynamic source vars to the current SESE
2478 dynItr = cp.getDynAssignCurr().iterator();
2479 while( dynItr.hasNext() ) {
2480 TempDescriptor dynVar = dynItr.next();
2481 output.println(" "+dynVar+"_srcSESE = NULL;");
2487 case FKind.FlatAtomicEnterNode:
2488 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
2491 case FKind.FlatAtomicExitNode:
2492 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
2495 case FKind.FlatInstanceOfNode:
2496 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
2499 case FKind.FlatSESEEnterNode:
2500 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
2503 case FKind.FlatSESEExitNode:
2504 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
2507 case FKind.FlatWriteDynamicVarNode:
2508 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
2511 case FKind.FlatGlobalConvNode:
2512 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
2515 case FKind.FlatTagDeclaration:
2516 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
2519 case FKind.FlatCall:
2520 generateFlatCall(fm, lb, (FlatCall) fn,output);
2523 case FKind.FlatFieldNode:
2524 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
2527 case FKind.FlatElementNode:
2528 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
2531 case FKind.FlatSetElementNode:
2532 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
2535 case FKind.FlatSetFieldNode:
2536 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
2540 generateFlatNew(fm, lb, (FlatNew) fn,output);
2543 case FKind.FlatOpNode:
2544 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
2547 case FKind.FlatCastNode:
2548 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
2551 case FKind.FlatLiteralNode:
2552 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
2555 case FKind.FlatReturnNode:
2556 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
2560 output.println("/* nop */");
2563 case FKind.FlatExit:
2564 output.println("/* exit */");
2567 case FKind.FlatBackEdge:
2568 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
2569 || (this.state.MULTICOREGC)) {
2570 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
2571 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
2572 } else if(this.state.MULTICOREGC) {
2573 output.println("if (gcflag) gc("+localsprefixaddr+");");
2575 output.println("if (needtocollect) checkcollect("+localsprefixaddr+");");
2577 output.println("/* nop */");
2580 case FKind.FlatCheckNode:
2581 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
2584 case FKind.FlatFlagActionNode:
2585 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
2588 case FKind.FlatPrefetchNode:
2589 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
2592 case FKind.FlatOffsetNode:
2593 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
2600 // insert post-node actions from the code-plan
2602 CodePlan cp = mlpa.getCodePlan( fn );
2609 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
2610 output.println("/* FlatOffsetNode */");
2611 FieldDescriptor fd=fofn.getField();
2612 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
2613 output.println("/* offset */");
2616 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
2617 if (state.PREFETCH) {
2618 Vector oids = new Vector();
2619 Vector fieldoffset = new Vector();
2620 Vector endoffset = new Vector();
2621 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
2622 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
2623 PrefetchPair pp = (PrefetchPair) it.next();
2624 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
2625 /* Find prefetches that can generate oid */
2626 if(statusbase == LocalityAnalysis.GLOBAL) {
2627 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
2629 } else if (statusbase == LocalityAnalysis.LOCAL) {
2630 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
2637 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
2638 output.println("{");
2639 output.println("/* prefetch */");
2640 output.println("/* prefetchid_" + fpn.siteid + " */");
2641 output.println("void * prefptr;");
2642 output.println("int tmpindex;");
2644 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
2645 /*Create C code for oid array */
2646 output.print(" unsigned int oidarray_[] = {");
2647 boolean needcomma=false;
2648 for (Iterator it = oids.iterator(); it.hasNext();) {
2651 output.print(it.next());
2654 output.println("};");
2656 /*Create C code for endoffset values */
2657 output.print(" unsigned short endoffsetarry_[] = {");
2659 for (Iterator it = endoffset.iterator(); it.hasNext();) {
2662 output.print(it.next());
2665 output.println("};");
2667 /*Create C code for Field Offset Values */
2668 output.print(" short fieldarry_[] = {");
2670 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
2673 output.print(it.next());
2676 output.println("};");
2677 /* make the prefetch call to Runtime */
2678 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
2679 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
2680 output.println(" }");
2681 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
2682 output.println(" } else {");
2683 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
2684 output.println(" }");
2685 output.println("}");
2689 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
2690 short offsetcount = 0;
2694 } else if (localbase) {
2695 for(; breakindex<pp.desc.size(); breakindex++) {
2696 Descriptor desc=pp.getDescAt(breakindex);
2697 if (desc instanceof FieldDescriptor) {
2698 FieldDescriptor fd=(FieldDescriptor)desc;
2699 if (fd.isGlobal()) {
2707 if (breakindex>pp.desc.size()) //all local
2710 TypeDescriptor lasttype=pp.base.getType();
2711 String basestr=generateTemp(fm, pp.base, lb);
2713 boolean maybenull=fm.getMethod().isStatic()||
2714 !pp.base.equals(fm.getParameter(0));
2716 for(int i=0; i<breakindex; i++) {
2717 String indexcheck="";
2719 Descriptor desc=pp.getDescAt(i);
2720 if (desc instanceof FieldDescriptor) {
2721 FieldDescriptor fd=(FieldDescriptor)desc;
2723 if (!teststr.equals(""))
2725 teststr+="((prefptr="+basestr+")!=NULL)";
2726 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
2728 basestr=basestr+"->"+fd.getSafeSymbol();
2731 lasttype=fd.getType();
2733 IndexDescriptor id=(IndexDescriptor)desc;
2734 indexcheck="((tmpindex=";
2735 for(int j=0; j<id.tddesc.size(); j++) {
2736 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
2738 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
2740 if (!teststr.equals(""))
2742 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
2743 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
2745 lasttype=lasttype.dereference();
2750 if (teststr.equals("")) {
2751 oid="((unsigned int)"+basestr+")";
2753 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
2757 for(int i = breakindex; i < pp.desc.size(); i++) {
2758 String newfieldoffset;
2759 Object desc = pp.getDescAt(i);
2760 if(desc instanceof FieldDescriptor) {
2761 FieldDescriptor fd=(FieldDescriptor)desc;
2762 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
2763 lasttype=fd.getType();
2765 newfieldoffset = "";
2766 IndexDescriptor id=(IndexDescriptor)desc;
2767 for(int j = 0; j < id.tddesc.size(); j++) {
2768 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
2770 newfieldoffset += id.offset.toString();
2771 lasttype=lasttype.dereference();
2773 fieldoffset.add(newfieldoffset);
2776 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
2777 base+=pp.desc.size()-breakindex;
2778 endoffset.add(new Short((short)base));
2783 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
2784 if (lb!=fgcn.getLocality())
2786 /* Have to generate flat globalconv */
2787 if (fgcn.getMakePtr()) {
2789 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
2791 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
2792 //need to do translation
2793 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
2794 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
2795 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
2799 /* Need to convert to OID */
2800 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
2801 if (fgcn.doConvert()||(delaycomp!=null&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
2802 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
2804 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
2810 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
2812 if (fion.getType().isArray()) {
2813 type=state.getArrayNumber(fion.getType())+state.numClasses();
2815 type=fion.getType().getClassDesc().getId();
2818 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
2819 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
2821 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
2824 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
2825 /* Check to see if we need to generate code for this atomic */
2826 if (locality==null) {
2827 output.println("pthread_mutex_lock(&atomiclock);");
2831 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
2835 if (state.DELAYCOMP) {
2836 AtomicRecord ar=atomicmethodmap.get(faen);
2838 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
2839 TempDescriptor tmp=tmpit.next();
2840 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2843 //copy outs that depend on path
2844 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
2845 TempDescriptor tmp=tmpit.next();
2846 if (!ar.livein.contains(tmp))
2847 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2851 /* Backup the temps. */
2852 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
2853 TempDescriptor tmp=tmpit.next();
2854 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
2857 output.println("goto transstart"+faen.getIdentifier()+";");
2859 /******* Print code to retry aborted transaction *******/
2860 output.println("transretry"+faen.getIdentifier()+":");
2863 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
2864 TempDescriptor tmp=tmpit.next();
2865 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
2869 /********* Need to revert local object store ********/
2870 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
2872 output.println("while ("+revertptr+") {");
2873 output.println("struct ___Object___ * tmpptr;");
2874 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
2875 output.println("REVERT_OBJ("+revertptr+");");
2876 output.println(revertptr+"=tmpptr;");
2877 output.println("}");
2879 /******* Tell the runtime to start the transaction *******/
2881 output.println("transstart"+faen.getIdentifier()+":");
2882 output.println("transStart();");
2884 if (state.ABORTREADERS||state.SANDBOX) {
2886 output.println("abortenabled=1;");
2887 output.println("if (_setjmp(aborttrans)) {");
2888 output.println(" goto transretry"+faen.getIdentifier()+"; }");
2892 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
2893 /* Check to see if we need to generate code for this atomic */
2894 if (locality==null) {
2895 output.println("pthread_mutex_unlock(&atomiclock);");
2898 if (locality.getAtomic(lb).get(faen).intValue()>0)
2900 //store the revert list before we lose the transaction object
2901 String revertptr=null;
2903 revertptr=generateTemp(fm, reverttable.get(lb),lb);
2904 output.println(revertptr+"=revertlist;");
2906 if (state.DELAYCOMP) {
2907 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
2910 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
2912 output.println("if (transCommit()) {");
2913 /* Transaction aborts if it returns true */
2914 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
2916 output.println("} else {");
2917 /* Need to commit local object store */
2918 output.println("while ("+revertptr+") {");
2919 output.println("struct ___Object___ * tmpptr;");
2920 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
2921 output.println("COMMIT_OBJ("+revertptr+");");
2922 output.println(revertptr+"=tmpptr;");
2923 output.println("}");
2925 output.println("}");
2926 if (state.DELAYCOMP) {
2928 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
2929 output.println("else {");
2930 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
2931 TempDescriptor tmp=tmpit.next();
2932 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
2934 output.println("}");
2938 public void generateFlatSESEEnterNode( FlatMethod fm,
2940 FlatSESEEnterNode fsen,
2944 // if MLP flag is off, okay that SESE nodes are in IR graph,
2945 // just skip over them and code generates exactly the same
2950 // there may be an SESE in an unreachable method, skip over
2951 if( !mlpa.getAllSESEs().contains( fsen ) ) {
2955 // also, if we have encountered a placeholder, just skip it
2956 if( fsen.getIsCallerSESEplaceholder() ) {
2960 output.println(" {");
2962 // set up the parent
2963 if( fsen == mlpa.getMainSESE() ) {
2964 output.println(" SESEcommon* parentCommon = NULL;");
2966 if( fsen.getParent() == null ) {
2967 System.out.println( "in "+fm+", "+fsen+" has null parent" );
2969 assert fsen.getParent() != null;
2970 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
2971 output.println(" SESEcommon* parentCommon = &("+paramsprefix+"->common);");
2973 //output.println(" SESEcommon* parentCommon = (SESEcommon*) peekItem( seseCallStack );");
2974 output.println(" SESEcommon* parentCommon = seseCaller;");
2978 // before doing anything, lock your own record and increment the running children
2979 if( fsen != mlpa.getMainSESE() ) {
2980 output.println(" pthread_mutex_lock( &(parentCommon->lock) );");
2981 output.println(" ++(parentCommon->numRunningChildren);");
2982 output.println(" pthread_mutex_unlock( &(parentCommon->lock) );");
2985 // just allocate the space for this record
2986 output.println(" "+fsen.getSESErecordName()+"* seseToIssue = ("+
2987 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
2988 fsen.getSESErecordName()+" ) );");
2990 // and keep the thread-local sese stack up to date
2991 //output.println(" addNewItem( seseCallStack, (void*) seseToIssue);");
2993 // fill in common data
2994 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
2995 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
2997 output.println(" seseToIssue->common.forwardList = createQueue();");
2998 output.println(" seseToIssue->common.unresolvedDependencies = 0;");
2999 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3000 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3001 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3002 output.println(" seseToIssue->common.numRunningChildren = 0;");
3003 output.println(" seseToIssue->common.parent = parentCommon;");
3005 // all READY in-vars should be copied now and be done with it
3006 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3007 while( tempItr.hasNext() ) {
3008 TempDescriptor temp = tempItr.next();
3010 // when we are issuing the main SESE or an SESE with placeholder
3011 // caller SESE as parent, generate temp child child's eclosing method,
3012 // otherwise use the parent's enclosing method as the context
3013 boolean useParentContext = false;
3015 if( fsen != mlpa.getMainSESE() ) {
3016 assert fsen.getParent() != null;
3017 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3018 useParentContext = true;
3022 if( useParentContext ) {
3023 output.println(" seseToIssue->"+temp+" = "+
3024 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3026 output.println(" seseToIssue->"+temp+" = "+
3027 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3031 // before potentially adding this SESE to other forwarding lists,
3032 // create it's lock and take it immediately
3033 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3034 output.println(" pthread_mutex_lock( &(seseToIssue->common.lock) );");
3036 if( fsen != mlpa.getMainSESE() ) {
3037 // count up outstanding dependencies, static first, then dynamic
3038 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3039 while( staticSrcsItr.hasNext() ) {
3040 SESEandAgePair srcPair = staticSrcsItr.next();
3041 output.println(" {");
3042 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3043 output.println(" pthread_mutex_lock( &(src->lock) );");
3044 output.println(" if( !isEmpty( src->forwardList ) &&");
3045 output.println(" seseToIssue == peekItem( src->forwardList ) ) {");
3046 output.println(" printf( \"This shouldnt already be here\\n\");");
3047 output.println(" exit( -1 );");
3048 output.println(" }");
3049 output.println(" if( !src->doneExecuting ) {");
3050 output.println(" addNewItem( src->forwardList, seseToIssue );");
3051 output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3052 output.println(" }");
3053 output.println(" pthread_mutex_unlock( &(src->lock) );");
3054 output.println(" }");
3056 // whether or not it is an outstanding dependency, make sure
3057 // to pass the static name to the child's record
3058 output.println(" seseToIssue->"+srcPair+" = "+srcPair+";");
3061 // dynamic sources might already be accounted for in the static list,
3062 // so only add them to forwarding lists if they're not already there
3063 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3064 while( dynVarsItr.hasNext() ) {
3065 TempDescriptor dynInVar = dynVarsItr.next();
3066 output.println(" {");
3067 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3069 // the dynamic source is NULL if it comes from your own space--you can't pass
3070 // the address off to the new child, because you're not done executing and
3071 // might change the variable, so copy it right now
3072 output.println(" if( src != NULL ) {");
3073 output.println(" pthread_mutex_lock( &(src->lock) );");
3074 output.println(" if( isEmpty( src->forwardList ) ||");
3075 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3076 output.println(" if( !src->doneExecuting ) {");
3077 output.println(" addNewItem( src->forwardList, seseToIssue );");
3078 output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3079 output.println(" }");
3080 output.println(" }");
3081 output.println(" pthread_mutex_unlock( &(src->lock) );");
3082 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3083 output.println(" } else {");
3085 boolean useParentContext = false;
3086 if( fsen != mlpa.getMainSESE() ) {
3087 assert fsen.getParent() != null;
3088 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3089 useParentContext = true;
3092 if( useParentContext ) {
3093 output.println(" seseToIssue->"+dynInVar+" = "+
3094 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3096 output.println(" seseToIssue->"+dynInVar+" = "+
3097 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3100 output.println(" }");
3101 output.println(" }");
3103 // even if the value is already copied, make sure your NULL source
3104 // gets passed so child knows it already has the dynamic value
3105 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3108 // maintain pointers for for finding dynamic SESE
3109 // instances from static names
3110 SESEandAgePair p = new SESEandAgePair( fsen, 0 );
3111 if( fsen.getParent() != null &&
3112 //!fsen.getParent().getIsCallerSESEplaceholder() &&
3113 fsen.getParent().getNeededStaticNames().contains( p )
3116 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3117 SESEandAgePair p1 = new SESEandAgePair( fsen, i );
3118 SESEandAgePair p2 = new SESEandAgePair( fsen, i-1 );
3119 output.println(" "+p1+" = "+p2+";");
3121 output.println(" "+p+" = seseToIssue;");
3125 // if there were no outstanding dependencies, issue here
3126 output.println(" if( seseToIssue->common.unresolvedDependencies == 0 ) {");
3127 output.println(" workScheduleSubmit( (void*)seseToIssue );");
3128 output.println(" }");
3130 // release this SESE for siblings to update its dependencies or,
3131 // eventually, for it to mark itself finished
3132 output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3133 output.println(" }");
3137 public void generateFlatSESEExitNode( FlatMethod fm,
3139 FlatSESEExitNode fsexn,
3143 // if MLP flag is off, okay that SESE nodes are in IR graph,
3144 // just skip over them and code generates exactly the same
3149 // get the enter node for this exit that has meta data embedded
3150 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
3152 // there may be an SESE in an unreachable method, skip over
3153 if( !mlpa.getAllSESEs().contains( fsen ) ) {
3157 // also, if we have encountered a placeholder, just jump it
3158 if( fsen.getIsCallerSESEplaceholder() ) {
3162 output.println(" /* SESE exiting */");
3164 String com = paramsprefix+"->common";
3166 // this SESE cannot be done until all of its children are done
3167 // so grab your own lock with the condition variable for watching
3168 // that the number of your running children is greater than zero
3169 output.println(" pthread_mutex_lock( &("+com+".lock) );");
3170 output.println(" while( "+com+".numRunningChildren > 0 ) {");
3171 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
3172 output.println(" }");
3174 // copy out-set from local temps into the sese record
3175 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
3176 while( itr.hasNext() ) {
3177 TempDescriptor temp = itr.next();
3179 // only have to do this for primitives
3180 if( !temp.getType().isPrimitive() ) {
3184 // have to determine the context enclosing this sese
3185 boolean useParentContext = false;
3187 if( fsen != mlpa.getMainSESE() ) {
3188 assert fsen.getParent() != null;
3189 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3190 useParentContext = true;
3195 if( useParentContext ) {
3196 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
3198 from = generateTemp( fsen.getfmEnclosing(), temp, null );
3201 output.println(" "+paramsprefix+
3202 "->"+temp.getSafeSymbol()+
3206 // mark yourself done, your SESE data is now read-only
3207 output.println(" "+com+".doneExecuting = TRUE;");
3208 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
3209 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
3211 // decrement dependency count for all SESE's on your forwarding list
3212 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
3213 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
3214 output.println(" pthread_mutex_lock( &(consumer->lock) );");
3215 output.println(" --(consumer->unresolvedDependencies);");
3216 output.println(" if( consumer->unresolvedDependencies == 0 ) {");
3217 output.println(" workScheduleSubmit( (void*)consumer );");
3218 output.println(" }");
3219 output.println(" pthread_mutex_unlock( &(consumer->lock) );");
3220 output.println(" }");
3222 // if parent is stalling on you, let them know you're done
3223 if( fsexn.getFlatEnter() != mlpa.getMainSESE() ) {
3224 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
3227 // last of all, decrement your parent's number of running children
3228 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
3229 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
3230 output.println(" --("+paramsprefix+"->common.parent->numRunningChildren);");
3231 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
3232 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
3233 output.println(" }");
3235 // this is a thread-only variable that can be handled when critical sese-to-sese
3236 // data has been taken care of--set sese pointer to remember self over method
3237 // calls to a non-zero, invalid address
3238 output.println(" seseCaller = (SESEcommon*) 0x1;");
3241 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
3243 FlatWriteDynamicVarNode fwdvn,
3247 // should node should not be in an IR graph if the
3248 // MLP flag is not set
3249 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
3252 Hashtable<TempDescriptor, VariableSourceToken> writeDynamic =
3255 assert writeDynamic != null;
3257 Iterator wdItr = writeDynamic.entrySet().iterator();
3258 while( wdItr.hasNext() ) {
3259 Map.Entry me = (Map.Entry) wdItr.next();
3260 TempDescriptor refVar = (TempDescriptor) me.getKey();
3261 VariableSourceToken vst = (VariableSourceToken) me.getValue();
3263 FlatSESEEnterNode current = fwdvn.getEnclosingSESE();
3265 // only do this if the variable in question should be tracked,
3266 // meaning that it was explicitly added to the dynamic var set
3267 if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
3271 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
3273 output.println(" {");
3275 if( current.equals( vst.getSESE() ) ) {
3276 // if the src comes from this SESE, it's a method local variable,
3277 // mark src pointer NULL to signify that the var is up-to-date
3278 output.println(" "+vst.getAddrVar()+"_srcSESE = NULL;");
3281 // otherwise we track where it will come from
3282 output.println(" "+vst.getAddrVar()+"_srcSESE = "+instance+";");
3283 output.println(" "+vst.getAddrVar()+"_srcOffset = (int) &((("+
3284 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
3287 output.println(" }");
3292 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
3293 if (state.CONSCHECK) {
3294 String specname=fcn.getSpec();
3295 String varname="repairstate___";
3296 output.println("{");
3297 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
3299 TempDescriptor[] temps=fcn.getTemps();
3300 String[] vars=fcn.getVars();
3301 for(int i=0; i<temps.length; i++) {
3302 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
3305 output.println("if (doanalysis"+specname+"("+varname+")) {");
3306 output.println("free"+specname+"_state("+varname+");");
3307 output.println("} else {");
3308 output.println("/* Bad invariant */");
3309 output.println("free"+specname+"_state("+varname+");");
3310 output.println("abort_task();");
3311 output.println("}");
3312 output.println("}");
3316 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
3318 if( state.MLP && !nonSESEpass ) {
3319 output.println(" seseCaller = (SESEcommon*)"+paramsprefix+";");
3322 MethodDescriptor md=fc.getMethod();
3323 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
3324 ClassDescriptor cn=md.getClassDesc();
3325 output.println("{");
3326 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3328 LocalityBinding fclb=locality.getBinding(lb, fc);
3329 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3331 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3333 output.print(objectparams.numPointers());
3334 output.print(", "+localsprefixaddr);
3335 if (md.getThis()!=null) {
3337 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
3339 if (fc.getThis()!=null&&md.getThis()==null) {
3340 System.out.println("WARNING!!!!!!!!!!!!");
3341 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
3345 for(int i=0; i<fc.numArgs(); i++) {
3346 Descriptor var=md.getParameter(i);
3347 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3348 if (objectparams.isParamPtr(paramtemp)) {
3349 TempDescriptor targ=fc.getArg(i);
3351 TypeDescriptor td=md.getParamType(i);
3353 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3355 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3358 output.println("};");
3363 if (fc.getReturnTemp()!=null)
3364 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
3366 /* Do we need to do virtual dispatch? */
3367 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
3370 LocalityBinding fclb=locality.getBinding(lb, fc);
3371 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3373 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3378 if (md.getReturnType().isClass()||md.getReturnType().isArray())
3379 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3381 output.print(md.getReturnType().getSafeSymbol()+" ");
3382 output.print("(*)(");
3384 boolean printcomma=false;
3385 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3387 LocalityBinding fclb=locality.getBinding(lb, fc);
3388 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3390 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3394 for(int i=0; i<objectparams.numPrimitives(); i++) {
3395 TempDescriptor temp=objectparams.getPrimitive(i);
3399 if (temp.getType().isClass()||temp.getType().isArray())
3400 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
3402 output.print(temp.getType().getSafeSymbol());
3407 LocalityBinding fclb=locality.getBinding(lb, fc);
3408 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
3410 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
3414 boolean needcomma=false;
3415 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3416 output.print("&__parameterlist__");
3420 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
3421 if (fc.getThis()!=null) {
3422 TypeDescriptor ptd=md.getThis().getType();
3425 if (ptd.isClass()&&!ptd.isArray())
3426 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3427 output.print(generateTemp(fm,fc.getThis(),lb));
3432 for(int i=0; i<fc.numArgs(); i++) {
3433 Descriptor var=md.getParameter(i);
3434 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3435 if (objectparams.isParamPrim(paramtemp)) {
3436 TempDescriptor targ=fc.getArg(i);
3440 TypeDescriptor ptd=md.getParamType(i);
3441 if (ptd.isClass()&&!ptd.isArray())
3442 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3443 output.print(generateTemp(fm, targ,lb));
3447 output.println(");");
3448 output.println(" }");
3451 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
3452 Set subclasses=typeutil.getSubClasses(thiscd);
3453 if (subclasses==null)
3455 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
3456 ClassDescriptor cd=(ClassDescriptor)classit.next();
3457 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
3458 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
3459 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
3460 if (md.matches(matchmd))
3467 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
3468 if (state.SINGLETM) {
3469 //single machine transactional memory case
3470 String field=ffn.getField().getSafeSymbol();
3471 String src=generateTemp(fm, ffn.getSrc(),lb);
3472 String dst=generateTemp(fm, ffn.getDst(),lb);
3474 output.println(dst+"="+ src +"->"+field+ ";");
3475 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
3476 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
3477 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
3478 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
3479 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
3480 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
3481 output.println("TRANSREADRD("+dst+", "+dst+");");
3484 } else if (state.DSM) {
3485 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
3486 if (status==LocalityAnalysis.GLOBAL) {
3487 String field=ffn.getField().getSafeSymbol();
3488 String src=generateTemp(fm, ffn.getSrc(),lb);
3489 String dst=generateTemp(fm, ffn.getDst(),lb);
3491 if (ffn.getField().getType().isPtr()) {
3493 //TODO: Uncomment this when we have runtime support
3494 //if (ffn.getSrc()==ffn.getDst()) {
3495 //output.println("{");
3496 //output.println("void * temp="+src+";");
3497 //output.println("if (temp&0x1) {");
3498 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
3499 //output.println(src+"->"+field+"="+temp+";");
3500 //output.println("}");
3501 //output.println(dst+"=temp;");
3502 //output.println("}");
3504 output.println(dst+"="+ src +"->"+field+ ";");
3505 //output.println("if ("+dst+"&0x1) {");
3506 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3507 //output.println(src+"->"+field+"="+src+"->"+field+";");
3508 //output.println("}");
3511 output.println(dst+"="+ src+"->"+field+";");
3513 } else if (status==LocalityAnalysis.LOCAL) {
3514 if (ffn.getField().getType().isPtr()&&
3515 ffn.getField().isGlobal()) {
3516 String field=ffn.getField().getSafeSymbol();
3517 String src=generateTemp(fm, ffn.getSrc(),lb);
3518 String dst=generateTemp(fm, ffn.getDst(),lb);
3519 output.println(dst+"="+ src +"->"+field+ ";");
3520 if (locality.getAtomic(lb).get(ffn).intValue()>0)
3521 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3523 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3524 } else if (status==LocalityAnalysis.EITHER) {
3525 //Code is reading from a null pointer
3526 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
3527 output.println("#ifndef RAW");
3528 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
3529 output.println("#endif");
3530 //This should throw a suitable null pointer error
3531 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3533 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
3535 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3539 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
3540 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
3541 throw new Error("Can't set array length");
3542 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3543 //Single Machine Transaction Case
3544 boolean srcptr=fsfn.getSrc().getType().isPtr();
3545 String src=generateTemp(fm,fsfn.getSrc(),lb);
3546 String dst=generateTemp(fm,fsfn.getDst(),lb);
3547 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
3548 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
3549 output.println("{");
3550 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
3551 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
3552 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3554 output.println("INTPTR srcoid=(INTPTR)"+src+";");
3557 if (wb.needBarrier(fsfn)&&
3558 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
3559 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
3561 if (srcptr&!fsfn.getSrc().getType().isNull()) {
3562 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
3563 output.println("}");
3565 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3567 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3568 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
3569 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
3570 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
3572 String src=generateTemp(fm,fsfn.getSrc(),lb);
3573 String dst=generateTemp(fm,fsfn.getDst(),lb);
3575 output.println("{");
3576 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3578 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
3581 if (wb.needBarrier(fsfn))
3582 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
3584 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
3586 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3587 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
3588 /** Check if we need to copy */
3589 output.println("if(!"+dst+"->"+localcopystr+") {");
3590 /* Link object into list */
3591 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3592 output.println(revertptr+"=revertlist;");
3593 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3594 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3596 output.println("COPY_OBJ("+dst+");");
3597 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3598 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3599 output.println("}");
3601 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
3603 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3604 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
3605 //writing to a null...bad
3606 output.println("if ("+dst+") {");
3607 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
3609 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
3611 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3614 output.println("}");
3617 if (state.FASTCHECK) {
3618 String dst=generateTemp(fm, fsfn.getDst(),lb);
3619 output.println("if(!"+dst+"->"+localcopystr+") {");
3620 /* Link object into list */
3621 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3622 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3624 output.println("COPY_OBJ("+dst+");");
3625 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3626 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3627 output.println("}");
3629 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
3633 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
3634 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
3637 if (elementtype.isArray()||elementtype.isClass())
3640 type=elementtype.getSafeSymbol()+" ";
3642 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
3643 output.println("if ("+generateTemp(fm, fen.getIndex(),lb)+"< 0 | "+generateTemp(fm, fen.getIndex(),lb)+" >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___)");
3644 output.println("failedboundschk();");
3646 if (state.SINGLETM) {
3647 //Single machine transaction case
3648 String dst=generateTemp(fm, fen.getDst(),lb);
3649 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3651 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
3652 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
3653 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
3654 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
3655 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
3656 output.println("TRANSREADRD("+dst+", "+dst+");");
3659 } else if (state.DSM) {
3660 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
3661 if (status==LocalityAnalysis.GLOBAL) {
3662 String dst=generateTemp(fm, fen.getDst(),lb);
3664 if (elementtype.isPtr()) {
3665 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3666 output.println("TRANSREAD("+dst+", "+dst+");");
3668 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3670 } else if (status==LocalityAnalysis.LOCAL) {
3671 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3672 } else if (status==LocalityAnalysis.EITHER) {
3673 //Code is reading from a null pointer
3674 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
3675 output.println("#ifndef RAW");
3676 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
3677 output.println("#endif");
3678 //This should throw a suitable null pointer error
3679 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3681 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
3683 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3687 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
3688 //TODO: need dynamic check to make sure this assignment is actually legal
3689 //Because Object[] could actually be something more specific...ie. Integer[]
3691 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
3694 if (elementtype.isArray()||elementtype.isClass())
3697 type=elementtype.getSafeSymbol()+" ";
3699 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
3700 output.println("if ("+generateTemp(fm, fsen.getIndex(),lb)+"< 0 | "+generateTemp(fm, fsen.getIndex(),lb)+" >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___)");
3701 output.println("failedboundschk();");
3704 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
3705 //Transaction set element case
3706 if (wb.needBarrier(fsen)&&
3707 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
3708 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
3710 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
3711 output.println("{");
3712 String src=generateTemp(fm, fsen.getSrc(), lb);
3713 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
3714 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
3715 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3717 output.println("INTPTR srcoid=(INTPTR)"+src+";");
3719 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
3720 output.println("}");
3722 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3724 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
3725 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
3726 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
3727 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
3728 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
3729 boolean dstlocal=statusdst==LocalityAnalysis.LOCAL;
3732 if (wb.needBarrier(fsen))
3733 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
3734 } else if (dstlocal) {
3735 /** Check if we need to copy */
3736 String dst=generateTemp(fm, fsen.getDst(),lb);
3737 output.println("if(!"+dst+"->"+localcopystr+") {");
3738 /* Link object into list */
3739 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3740 output.println(revertptr+"=revertlist;");
3741 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
3742 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3744 output.println("COPY_OBJ("+dst+");");
3745 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3746 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3747 output.println("}");
3748 } else throw new Error("Unknown array type");
3750 output.println("{");
3751 String src=generateTemp(fm, fsen.getSrc(), lb);
3752 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3753 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
3754 output.println("}");
3756 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3759 if (state.FASTCHECK) {
3760 String dst=generateTemp(fm, fsen.getDst(),lb);
3761 output.println("if(!"+dst+"->"+localcopystr+") {");
3762 /* Link object into list */
3763 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3764 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3766 output.println("COPY_OBJ("+dst+");");
3767 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3768 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3769 output.println("}");
3771 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3775 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
3776 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
3777 //Stash pointer in case of GC
3778 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3779 output.println(revertptr+"=revertlist;");
3781 if (state.SINGLETM) {
3782 if (fn.getType().isArray()) {
3783 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
3784 if (locality.getAtomic(lb).get(fn).intValue()>0) {
3785 //inside transaction
3786 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3788 //outside transaction
3789 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3792 if (locality.getAtomic(lb).get(fn).intValue()>0) {
3793 //inside transaction
3794 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3796 //outside transaction
3797 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3800 } else if (fn.getType().isArray()) {
3801 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
3802 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
3803 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3804 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3805 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3807 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3810 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
3811 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
3812 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3813 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3815 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
3818 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
3819 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3820 String dst=generateTemp(fm,fn.getDst(),lb);
3821 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
3822 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3823 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3825 if (state.FASTCHECK) {
3826 String dst=generateTemp(fm,fn.getDst(),lb);
3827 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
3828 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3829 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3833 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
3834 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3835 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
3837 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
3841 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
3842 if (fon.getRight()!=null) {
3843 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
3844 if (fon.getLeft().getType().isLong())
3845 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
3847 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
3849 } else if (dc!=null) {
3850 output.print(generateTemp(fm, fon.getDest(),lb)+" = ");
3851 if (dc.getNeedLeftSrcTrans(lb, fon))
3852 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
3854 output.print(generateTemp(fm, fon.getLeft(),lb));
3855 output.print(fon.getOp().toString());
3856 if (dc.getNeedRightSrcTrans(lb, fon))
3857 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL);");
3859 output.println(generateTemp(fm,fon.getRight(),lb)+";");
3861 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
3862 } else if (fon.getOp().getOp()==Operation.ASSIGN)
3863 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
3864 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
3865 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
3866 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
3867 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
3868 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
3869 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
3870 else if (fon.getOp().getOp()==Operation.COMP)
3871 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
3872 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
3873 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
3875 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
3878 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
3879 /* TODO: Do type check here */
3880 if (fcn.getType().isArray()) {
3881 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
3882 } else if (fcn.getType().isClass())
3883 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
3885 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
3888 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
3889 if (fln.getValue()==null)
3890 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
3891 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
3892 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3893 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
3894 //Stash pointer in case of GC
3895 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3896 output.println(revertptr+"=revertlist;");
3898 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
3899 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
3900 //Stash pointer in case of GC
3901 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3902 output.println("revertlist="+revertptr+";");
3905 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
3907 } else if (fln.getType().isBoolean()) {
3908 if (((Boolean)fln.getValue()).booleanValue())
3909 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
3911 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
3912 } else if (fln.getType().isChar()) {
3913 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
3914 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
3915 } else if (fln.getType().isLong()) {
3916 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
3918 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
3921 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
3922 if (frn.getReturnTemp()!=null) {
3923 if (frn.getReturnTemp().getType().isPtr())
3924 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
3926 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
3928 output.println("return;");
3932 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
3933 output.println("STOREANDBRANCH(!"+generateTemp(fm, fcb.getTest(),lb)+", "+label+");");
3936 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
3937 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
3940 /** This method generates header information for the method or
3941 * task referenced by the Descriptor des. */
3942 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
3943 generateHeader(fm, lb, des, output, false);
3946 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
3948 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
3949 MethodDescriptor md=null;
3950 TaskDescriptor task=null;
3951 if (des instanceof MethodDescriptor)
3952 md=(MethodDescriptor) des;
3954 task=(TaskDescriptor) des;
3956 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
3958 if (md!=null&&md.getReturnType()!=null) {
3959 if (md.getReturnType().isClass()||md.getReturnType().isArray())
3960 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3962 output.print(md.getReturnType().getSafeSymbol()+" ");
3964 //catch the constructor case
3965 output.print("void ");
3967 if (state.DSM||state.SINGLETM) {
3968 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
3970 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
3972 output.print(task.getSafeSymbol()+"(");
3974 boolean printcomma=false;
3975 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3977 if (state.DSM||state.SINGLETM) {
3978 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
3980 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
3982 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
3988 for(int i=0; i<objectparams.numPrimitives(); i++) {
3989 TempDescriptor temp=objectparams.getPrimitive(i);
3993 if (temp.getType().isClass()||temp.getType().isArray())
3994 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
3996 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
3998 output.println(") {");
3999 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4000 /* Imprecise Task */
4001 output.println("void * parameterarray[]) {");
4002 /* Unpack variables */
4003 for(int i=0; i<objectparams.numPrimitives(); i++) {
4004 TempDescriptor temp=objectparams.getPrimitive(i);
4005 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
4007 for(int i=0; i<fm.numTags(); i++) {
4008 TempDescriptor temp=fm.getTag(i);
4009 int offset=i+objectparams.numPrimitives();
4010 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
4013 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
4014 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
4015 } else output.println(") {");
4018 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
4019 output.println("/* FlatFlagActionNode */");
4022 /* Process tag changes */
4023 Relation tagsettable=new Relation();
4024 Relation tagcleartable=new Relation();
4026 Iterator tagsit=ffan.getTempTagPairs();
4027 while (tagsit.hasNext()) {
4028 TempTagPair ttp=(TempTagPair) tagsit.next();
4029 TempDescriptor objtmp=ttp.getTemp();
4030 TagDescriptor tag=ttp.getTag();
4031 TempDescriptor tagtmp=ttp.getTagTemp();
4032 boolean tagstatus=ffan.getTagChange(ttp);
4034 tagsettable.put(objtmp, tagtmp);
4036 tagcleartable.put(objtmp, tagtmp);
4041 Hashtable flagandtable=new Hashtable();
4042 Hashtable flagortable=new Hashtable();
4044 /* Process flag changes */
4045 Iterator flagsit=ffan.getTempFlagPairs();
4046 while(flagsit.hasNext()) {
4047 TempFlagPair tfp=(TempFlagPair)flagsit.next();
4048 TempDescriptor temp=tfp.getTemp();
4049 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
4050 FlagDescriptor flag=tfp.getFlag();
4052 //Newly allocate objects that don't set any flags case
4053 if (flagortable.containsKey(temp)) {
4057 flagortable.put(temp,new Integer(mask));
4059 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
4060 boolean flagstatus=ffan.getFlagChange(tfp);
4063 if (flagortable.containsKey(temp)) {
4064 mask=((Integer)flagortable.get(temp)).intValue();
4067 flagortable.put(temp,new Integer(mask));
4069 int mask=0xFFFFFFFF;
4070 if (flagandtable.containsKey(temp)) {
4071 mask=((Integer)flagandtable.get(temp)).intValue();
4073 mask&=(0xFFFFFFFF^flagid);
4074 flagandtable.put(temp,new Integer(mask));
4080 HashSet flagtagset=new HashSet();
4081 flagtagset.addAll(flagortable.keySet());
4082 flagtagset.addAll(flagandtable.keySet());
4083 flagtagset.addAll(tagsettable.keySet());
4084 flagtagset.addAll(tagcleartable.keySet());
4086 Iterator ftit=flagtagset.iterator();
4087 while(ftit.hasNext()) {
4088 TempDescriptor temp=(TempDescriptor)ftit.next();
4091 Set tagtmps=tagcleartable.get(temp);
4092 if (tagtmps!=null) {
4093 Iterator tagit=tagtmps.iterator();
4094 while(tagit.hasNext()) {
4095 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4096 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4097 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4099 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4103 tagtmps=tagsettable.get(temp);
4104 if (tagtmps!=null) {
4105 Iterator tagit=tagtmps.iterator();
4106 while(tagit.hasNext()) {
4107 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4108 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4109 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4111 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
4116 int andmask=0xFFFFFFF;
4118 if (flagortable.containsKey(temp))
4119 ormask=((Integer)flagortable.get(temp)).intValue();
4120 if (flagandtable.containsKey(temp))
4121 andmask=((Integer)flagandtable.get(temp)).intValue();
4122 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
4123 generateObjectDistribute(ffan, fm, lb, temp, output);
4127 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
4128 PrintWriter output, int ormask, int andmask) {
4129 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
4130 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4132 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4136 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
4137 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
4140 void generateOptionalHeader(PrintWriter headers) {
4143 headers.println("#include \"task.h\"\n\n");
4144 headers.println("#ifndef _OPTIONAL_STRUCT_");
4145 headers.println("#define _OPTIONAL_STRUCT_");
4147 //STRUCT PREDICATEMEMBER
4148 headers.println("struct predicatemember{");
4149 headers.println("int type;");
4150 headers.println("int numdnfterms;");
4151 headers.println("int * flags;");
4152 headers.println("int numtags;");
4153 headers.println("int * tags;\n};\n\n");
4155 //STRUCT OPTIONALTASKDESCRIPTOR
4156 headers.println("struct optionaltaskdescriptor{");
4157 headers.println("struct taskdescriptor * task;");
4158 headers.println("int index;");
4159 headers.println("int numenterflags;");
4160 headers.println("int * enterflags;");
4161 headers.println("int numpredicatemembers;");
4162 headers.println("struct predicatemember ** predicatememberarray;");
4163 headers.println("};\n\n");
4165 //STRUCT TASKFAILURE
4166 headers.println("struct taskfailure {");
4167 headers.println("struct taskdescriptor * task;");
4168 headers.println("int index;");
4169 headers.println("int numoptionaltaskdescriptors;");
4170 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4172 //STRUCT FSANALYSISWRAPPER
4173 headers.println("struct fsanalysiswrapper{");
4174 headers.println("int flags;");
4175 headers.println("int numtags;");
4176 headers.println("int * tags;");
4177 headers.println("int numtaskfailures;");
4178 headers.println("struct taskfailure ** taskfailurearray;");
4179 headers.println("int numoptionaltaskdescriptors;");
4180 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4182 //STRUCT CLASSANALYSISWRAPPER
4183 headers.println("struct classanalysiswrapper{");
4184 headers.println("int type;");
4185 headers.println("int numotd;");
4186 headers.println("struct optionaltaskdescriptor ** otdarray;");
4187 headers.println("int numfsanalysiswrappers;");
4188 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
4190 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
4192 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
4193 while(taskit.hasNext()) {
4194 TaskDescriptor td=(TaskDescriptor)taskit.next();
4195 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
4200 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
4201 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
4202 int predicateindex = 0;
4203 //iterate through the classes concerned by the predicate
4204 Set c_vard = predicate.vardescriptors;
4205 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
4208 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
4209 VarDescriptor vard = (VarDescriptor)vard_it.next();
4210 TypeDescriptor typed = vard.getType();
4212 //generate for flags
4213 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
4214 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4216 if (fen_hashset!=null) {
4217 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
4218 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
4220 DNFFlag dflag=fen.getDNF();
4221 numberterms+=dflag.size();
4223 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
4225 for(int j=0; j<dflag.size(); j++) {
4227 output.println(",");
4228 Vector term=dflag.get(j);
4231 for(int k=0; k<term.size(); k++) {
4232 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
4233 FlagDescriptor fd=dfa.getFlag();
4234 boolean negated=dfa.getNegated();
4235 int flagid=1<<((Integer)flags.get(fd)).intValue();
4240 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
4245 output.println("};\n");
4248 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
4249 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4252 for(int j=0; j<tagel.numTags(); j++) {
4254 output.println(",");
4255 TempDescriptor tmp=tagel.getTemp(j);
4256 if (!slotnumber.containsKey(tmp)) {
4257 Integer slotint=new Integer(current_slot++);
4258 slotnumber.put(tmp,slotint);
4260 int slot=slotnumber.get(tmp).intValue();
4261 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
4263 numtags = tagel.numTags();
4265 output.println("};");
4267 //store the result into a predicatemember struct
4268 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4269 output.println("/*type*/"+typed.getClassDesc().getId()+",");
4270 output.println("/* number of dnf terms */"+numberterms+",");
4271 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4272 output.println("/* number of tag */"+numtags+",");
4273 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4274 output.println("};\n");
4279 //generate an array that stores the entire predicate
4280 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4281 for( int j = 0; j<predicateindex; j++) {
4282 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4283 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4285 output.println("};\n");
4286 return predicateindex;
4290 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
4291 generateOptionalHeader(headers);
4293 output.println("#include \"optionalstruct.h\"\n\n");
4294 output.println("#include \"stdlib.h\"\n");
4296 HashSet processedcd = new HashSet();
4298 Enumeration e = safeexecution.keys();
4299 while (e.hasMoreElements()) {
4302 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
4303 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
4305 //Generate the struct of optionals
4306 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4307 numotd = c_otd.size();
4308 if(maxotd<numotd) maxotd = numotd;
4309 if( !c_otd.isEmpty() ) {
4310 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4311 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4313 //generate the int arrays for the predicate
4314 Predicate predicate = otd.predicate;
4315 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
4316 TreeSet<Integer> fsset=new TreeSet<Integer>();
4317 //iterate through possible FSes corresponding to
4318 //the state when entering
4320 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
4321 FlagState fs = (FlagState)fses.next();
4323 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4324 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4325 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4328 fsset.add(new Integer(flagid));
4329 //tag information not needed because tag
4330 //changes are not tolerated.
4333 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4334 boolean needcomma=false;
4335 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
4338 output.println(it.next());
4341 output.println("};\n");
4344 //generate optionaltaskdescriptor that actually
4345 //includes exit fses, predicate and the task
4347 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4348 output.println("&task_"+otd.td.getSafeSymbol()+",");
4349 output.println("/*index*/"+otd.getIndex()+",");
4350 output.println("/*number of enter flags*/"+fsset.size()+",");
4351 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4352 output.println("/*number of members */"+predicateindex+",");
4353 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4354 output.println("};\n");
4358 // if there are no optionals, there is no need to build the rest of the struct
4360 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
4361 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4362 if( !c_otd.isEmpty() ) {
4363 boolean needcomma=false;
4364 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4365 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4367 output.println(",");
4369 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4372 output.println("};\n");
4374 //get all the possible flagstates reachable by an object
4375 Hashtable hashtbtemp = safeexecution.get(cdtemp);
4377 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
4378 fsts.addAll(hashtbtemp.keySet());
4379 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
4380 FlagState fs = (FlagState)fsit.next();
4383 //get the set of OptionalTaskDescriptors corresponding
4384 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
4385 //iterate through the OptionalTaskDescriptors and
4386 //store the pointers to the optionals struct (see on
4387 //top) into an array
4389 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
4390 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
4391 OptionalTaskDescriptor mm = mos.next();
4393 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
4395 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4398 output.println("};\n");
4400 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
4403 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4404 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4405 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4409 //process tag information
4412 boolean first = true;
4413 Enumeration tag_enum = fs.getTags();
4414 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4415 while(tag_enum.hasMoreElements()) {
4417 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
4421 output.println(", ");
4422 output.println("/*tagid*/"+state.getTagId(tagd));
4424 output.println("};");
4426 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
4427 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4428 TaskIndex ti=itti.next();
4432 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
4434 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
4435 boolean needcomma=false;
4436 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
4437 OptionalTaskDescriptor otd=otdit.next();
4441 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4443 output.println("};");
4445 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
4446 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
4447 output.print(ti.getIndex()+", ");
4448 output.print(otdset.size()+", ");
4449 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
4450 output.println("};");
4453 tiset=sa.getTaskIndex(fs);
4454 boolean needcomma=false;
4456 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4457 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4458 TaskIndex ti=itti.next();
4459 if (ti.isRuntime()) {
4466 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
4468 output.println("};\n");
4470 //Store the result in fsanalysiswrapper
4472 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
4473 output.println("/*flag*/"+flagid+",");
4474 output.println("/* number of tags*/"+tagcounter+",");
4475 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4476 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
4477 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4478 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
4479 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
4480 output.println("};\n");
4484 //Build the array of fsanalysiswrappers
4485 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
4486 boolean needcomma=false;
4487 for(int i = 0; i<fscounter; i++) {
4488 if (needcomma) output.print(",");
4489 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
4492 output.println("};");
4494 //Build the classanalysiswrapper referring to the previous array
4495 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
4496 output.println("/*type*/"+cdtemp.getId()+",");
4497 output.println("/*numotd*/"+numotd+",");
4498 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
4499 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
4500 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
4501 processedcd.add(cdtemp);
4504 //build an array containing every classes for which code has been build
4505 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
4506 for(int i=0; i<state.numClasses(); i++) {
4507 ClassDescriptor cn=cdarray[i];
4510 if ((cn != null) && (processedcd.contains(cn)))
4511 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
4513 output.print("NULL");
4515 output.println("};");
4517 output.println("#define MAXOTD "+maxotd);
4518 headers.println("#endif");
4521 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
4522 Relation r=new Relation();
4523 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
4524 OptionalTaskDescriptor otd=otdit.next();
4525 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
4529 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
4530 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
4531 Set s=r.get(it.next());
4532 for(Iterator it2=s.iterator(); it2.hasNext();) {
4533 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
4541 protected void outputTransCode(PrintWriter output) {