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(\"bytesSent= %d\\n\", bytesSent);");
379 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
380 } else if (state.SINGLETM) {
381 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
382 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
383 outmethod.println("#ifdef STMSTATS\n");
384 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
385 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
386 outmethod.println("}\n");
387 outmethod.println("#endif\n");
388 outmethod.println("fflush(stdout);");
390 outmethod.println("#endif\n");
393 if (state.THREAD||state.SINGLETM)
394 outmethod.println("pthread_exit(NULL);");
397 outmethod.println(" workScheduleBegin();");
400 outmethod.println("}");
403 /* This method outputs code for each task. */
405 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
406 /* Compile task based program */
407 outtaskdefs.println("#include \"task.h\"");
408 outtaskdefs.println("#include \"methodheaders.h\"");
409 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
410 while(taskit.hasNext()) {
411 TaskDescriptor td=(TaskDescriptor)taskit.next();
412 FlatMethod fm=state.getMethodFlat(td);
413 generateFlatMethod(fm, null, outmethod);
414 generateTaskDescriptor(outtaskdefs, fm, td);
417 //Output task descriptors
418 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
419 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
421 while(taskit.hasNext()) {
422 TaskDescriptor td=(TaskDescriptor)taskit.next();
426 outtaskdefs.println(",");
427 outtaskdefs.print("&task_"+td.getSafeSymbol());
429 outtaskdefs.println("};");
431 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
434 /* This method outputs most of the methods.c file. This includes
435 * some standard includes and then an array with the sizes of
436 * objets and array that stores supertype and then the code for
437 * the Java methods.. */
439 protected void outputMethods(PrintWriter outmethod) {
440 outmethod.println("#include \"methodheaders.h\"");
441 outmethod.println("#include \"virtualtable.h\"");
442 outmethod.println("#include \"runtime.h\"");
444 outmethod.println("#include \"addPrefetchEnhance.h\"");
445 outmethod.println("#include \"localobjects.h\"");
447 if (state.FASTCHECK) {
448 outmethod.println("#include \"localobjects.h\"");
450 if(state.MULTICORE) {
451 outmethod.println("#include \"task.h\"");
452 outmethod.println("#include \"multicoreruntime.h\"");
453 outmethod.println("#include \"runtime_arch.h\"");
455 if (state.THREAD||state.DSM||state.SINGLETM)
456 outmethod.println("#include <thread.h>");
457 if (state.main!=null) {
458 outmethod.println("#include <string.h>");
460 if (state.CONSCHECK) {
461 outmethod.println("#include \"checkers.h\"");
464 outmethod.println("#include <stdlib.h>");
465 outmethod.println("#include <stdio.h>");
466 outmethod.println("#include \"mlp_runtime.h\"");
467 outmethod.println("#include \"psemaphore.h\"");
471 //Store the sizes of classes & array elements
472 generateSizeArray(outmethod);
474 //Store table of supertypes
475 generateSuperTypeTable(outmethod);
477 //Store the layout of classes
478 generateLayoutStructs(outmethod);
480 /* Generate code for methods */
481 if (state.DSM||state.SINGLETM) {
482 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
483 LocalityBinding lb=lbit.next();
484 MethodDescriptor md=lb.getMethod();
485 FlatMethod fm=state.getMethodFlat(md);
487 if (!md.getModifiers().isNative()) {
488 generateFlatMethod(fm, lb, outmethod);
492 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
493 while(classit.hasNext()) {
494 ClassDescriptor cn=(ClassDescriptor)classit.next();
495 Iterator methodit=cn.getMethods();
496 while(methodit.hasNext()) {
497 /* Classify parameters */
498 MethodDescriptor md=(MethodDescriptor)methodit.next();
499 FlatMethod fm=state.getMethodFlat(md);
500 if (!md.getModifiers().isNative()) {
501 generateFlatMethod(fm, null, outmethod);
508 protected void outputStructs(PrintWriter outstructs) {
509 outstructs.println("#ifndef STRUCTDEFS_H");
510 outstructs.println("#define STRUCTDEFS_H");
511 outstructs.println("#include \"classdefs.h\"");
512 outstructs.println("#ifndef INTPTR");
513 outstructs.println("#ifdef BIT64");
514 outstructs.println("#define INTPTR long");
515 outstructs.println("#else");
516 outstructs.println("#define INTPTR int");
517 outstructs.println("#endif");
518 outstructs.println("#endif");
520 outstructs.println("#include \"mlp_runtime.h\"");
521 outstructs.println("#include \"psemaphore.h\"");
524 /* Output #defines that the runtime uses to determine type
525 * numbers for various objects it needs */
526 outstructs.println("#define MAXCOUNT "+maxcount);
527 if (state.DSM||state.SINGLETM) {
528 LocalityBinding lb=new LocalityBinding(typeutil.getRun(), false);
530 lb.setGlobalThis(LocalityAnalysis.GLOBAL);
531 else if (state.SINGLETM)
532 lb.setGlobalThis(LocalityAnalysis.NORMAL);
533 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lb));
536 outstructs.println("#define STRINGARRAYTYPE "+
537 (state.getArrayNumber(
538 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
540 outstructs.println("#define OBJECTARRAYTYPE "+
541 (state.getArrayNumber(
542 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
545 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
546 outstructs.println("#define CHARARRAYTYPE "+
547 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
549 outstructs.println("#define BYTEARRAYTYPE "+
550 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
552 outstructs.println("#define BYTEARRAYARRAYTYPE "+
553 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
555 outstructs.println("#define NUMCLASSES "+state.numClasses());
556 int totalClassSize = state.numClasses() + state.numArrays();
557 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
559 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
560 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
561 outstructs.println("#define TAGARRAYTYPE "+
562 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
566 protected void outputClassDeclarations(PrintWriter outclassdefs) {
567 if (state.THREAD||state.DSM||state.SINGLETM)
568 outclassdefs.println("#include <pthread.h>");
569 outclassdefs.println("#ifndef INTPTR");
570 outclassdefs.println("#ifdef BIT64");
571 outclassdefs.println("#define INTPTR long");
572 outclassdefs.println("#else");
573 outclassdefs.println("#define INTPTR int");
574 outclassdefs.println("#endif");
575 outclassdefs.println("#endif");
577 outclassdefs.println("#include \"optionalstruct.h\"");
578 outclassdefs.println("struct "+arraytype+";");
579 /* Start by declaring all structs */
580 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
581 while(it.hasNext()) {
582 ClassDescriptor cn=(ClassDescriptor)it.next();
583 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
585 outclassdefs.println("");
586 //Print out definition for array type
587 outclassdefs.println("struct "+arraytype+" {");
588 outclassdefs.println(" int type;");
590 outclassdefs.println(" pthread_t tid;");
591 outclassdefs.println(" void * lockentry;");
592 outclassdefs.println(" int lockcount;");
595 outclassdefs.println(" int flag;");
596 if(!state.MULTICORE) {
597 outclassdefs.println(" void * flagptr;");
599 outclassdefs.println(" int version;");
600 outclassdefs.println(" int * lock;"); // lock entry for this obj
601 outclassdefs.println(" int mutex;");
602 outclassdefs.println(" int lockcount;");
603 if(state.MULTICOREGC) {
604 outclassdefs.println(" int marked;");
608 outclassdefs.println(" int numfses;");
609 outclassdefs.println(" int * fses;");
612 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
615 outclassdefs.println(" int paddingforarray;");
617 outclassdefs.println(" int ___length___;");
618 outclassdefs.println("};\n");
619 outclassdefs.println("extern int classsize[];");
620 outclassdefs.println("extern int hasflags[];");
621 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
622 outclassdefs.println("extern int supertypes[];");
625 /** Prints out definitions for generic task structures */
627 private void outputTaskTypes(PrintWriter outtask) {
628 outtask.println("#ifndef _TASK_H");
629 outtask.println("#define _TASK_H");
630 outtask.println("struct parameterdescriptor {");
631 outtask.println("int type;");
632 outtask.println("int numberterms;");
633 outtask.println("int *intarray;");
634 outtask.println("void * queue;");
635 outtask.println("int numbertags;");
636 outtask.println("int *tagarray;");
637 outtask.println("};");
639 outtask.println("struct taskdescriptor {");
640 outtask.println("void * taskptr;");
641 outtask.println("int numParameters;");
642 outtask.println(" int numTotal;");
643 outtask.println("struct parameterdescriptor **descriptorarray;");
644 outtask.println("char * name;");
645 outtask.println("};");
646 outtask.println("extern struct taskdescriptor * taskarray[];");
647 outtask.println("extern numtasks;");
648 outtask.println("#endif");
652 private void buildRepairStructs(PrintWriter outrepairstructs) {
653 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
654 while(classit.hasNext()) {
655 ClassDescriptor cn=(ClassDescriptor)classit.next();
656 outrepairstructs.println("structure "+cn.getSymbol()+" {");
657 outrepairstructs.println(" int __type__;");
659 outrepairstructs.println(" int __flag__;");
660 if(!state.MULTICORE) {
661 outrepairstructs.println(" int __flagptr__;");
664 printRepairStruct(cn, outrepairstructs);
665 outrepairstructs.println("}\n");
668 for(int i=0; i<state.numArrays(); i++) {
669 TypeDescriptor tdarray=arraytable[i];
670 TypeDescriptor tdelement=tdarray.dereference();
671 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
672 outrepairstructs.println(" int __type__;");
673 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
674 outrepairstructs.println(" int length;");
676 // Need to add support to repair tool for this
677 if (tdelement.isClass()||tdelement.isArray())
678 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
680 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
682 outrepairstructs.println("}\n");
686 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
687 ClassDescriptor sp=cn.getSuperDesc();
689 printRepairStruct(sp, output);
691 Vector fields=(Vector)fieldorder.get(cn);
693 for(int i=0; i<fields.size(); i++) {
694 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
695 if (fd.getType().isArray()) {
696 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
697 } else if (fd.getType().isClass())
698 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
699 else if (fd.getType().isFloat())
700 output.println(" int "+fd.getSymbol()+"; /* really float */");
702 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
706 /** This method outputs TaskDescriptor information */
707 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
708 for (int i=0; i<task.numParameters(); i++) {
709 VarDescriptor param_var=task.getParameter(i);
710 TypeDescriptor param_type=task.getParamType(i);
711 FlagExpressionNode param_flag=task.getFlag(param_var);
712 TagExpressionList param_tag=task.getTag(param_var);
715 if (param_flag==null) {
716 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
717 output.println("0x0, 0x0 };");
720 DNFFlag dflag=param_flag.getDNF();
721 dnfterms=dflag.size();
723 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
724 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
725 for(int j=0; j<dflag.size(); j++) {
728 Vector term=dflag.get(j);
731 for(int k=0; k<term.size(); k++) {
732 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
733 FlagDescriptor fd=dfa.getFlag();
734 boolean negated=dfa.getNegated();
735 int flagid=1<<((Integer)flags.get(fd)).intValue();
740 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
742 output.println("};");
745 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
746 //BUG...added next line to fix, test with any task program
748 for(int j=0; j<param_tag.numTags(); j++) {
751 /* for each tag we need */
752 /* which slot it is */
753 /* what type it is */
754 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
755 TempDescriptor tmp=param_tag.getTemp(j);
756 int slot=fm.getTagInt(tmp);
757 output.println(slot+", "+state.getTagId(tvd.getTag()));
759 output.println("};");
761 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
762 output.println("/* type */"+param_type.getClassDesc().getId()+",");
763 output.println("/* number of DNF terms */"+dnfterms+",");
764 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
765 output.println("0,");
766 //BUG, added next line to fix and else statement...test
767 //with any task program
769 output.println("/* number of tags */"+param_tag.numTags()+",");
771 output.println("/* number of tags */ 0,");
772 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
773 output.println("};");
777 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
778 for (int i=0; i<task.numParameters(); i++) {
781 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
783 output.println("};");
785 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
786 output.println("&"+task.getSafeSymbol()+",");
787 output.println("/* number of parameters */" +task.numParameters() + ",");
788 int numtotal=task.numParameters()+fm.numTags();
789 output.println("/* number total parameters */" +numtotal + ",");
790 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
791 output.println("\""+task.getSymbol()+"\"");
792 output.println("};");
796 /** The buildVirtualTables method outputs the virtual dispatch
797 * tables for methods. */
799 protected void buildVirtualTables(PrintWriter outvirtual) {
800 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
801 while(classit.hasNext()) {
802 ClassDescriptor cd=(ClassDescriptor)classit.next();
803 if (virtualcalls.getMethodCount(cd)>maxcount)
804 maxcount=virtualcalls.getMethodCount(cd);
806 MethodDescriptor[][] virtualtable=null;
807 LocalityBinding[][] lbvirtualtable=null;
808 if (state.DSM||state.SINGLETM)
809 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
811 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
813 /* Fill in virtual table */
814 classit=state.getClassSymbolTable().getDescriptorsIterator();
815 while(classit.hasNext()) {
816 ClassDescriptor cd=(ClassDescriptor)classit.next();
817 if (state.DSM||state.SINGLETM)
818 fillinRow(cd, lbvirtualtable, cd.getId());
820 fillinRow(cd, virtualtable, cd.getId());
823 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
824 Iterator arrayit=state.getArrayIterator();
825 while(arrayit.hasNext()) {
826 TypeDescriptor td=(TypeDescriptor)arrayit.next();
827 int id=state.getArrayNumber(td);
828 if (state.DSM||state.SINGLETM)
829 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
831 fillinRow(objectcd, virtualtable, id+state.numClasses());
834 outvirtual.print("void * virtualtable[]={");
835 boolean needcomma=false;
836 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
837 for(int j=0; j<maxcount; j++) {
839 outvirtual.print(", ");
840 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
841 LocalityBinding lb=lbvirtualtable[i][j];
842 MethodDescriptor md=lb.getMethod();
843 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
844 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
845 MethodDescriptor md=virtualtable[i][j];
846 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
848 outvirtual.print("0");
852 outvirtual.println("");
854 outvirtual.println("};");
858 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
859 /* Get inherited methods */
860 if (cd.getSuperDesc()!=null)
861 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
862 /* Override them with our methods */
863 for(Iterator it=cd.getMethods(); it.hasNext();) {
864 MethodDescriptor md=(MethodDescriptor)it.next();
865 if (md.isStatic()||md.getReturnType()==null)
867 int methodnum=virtualcalls.getMethodNumber(md);
868 virtualtable[rownum][methodnum]=md;
872 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
873 /* Get inherited methods */
874 if (cd.getSuperDesc()!=null)
875 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
876 /* Override them with our methods */
877 if (locality.getClassBindings(cd)!=null)
878 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
879 LocalityBinding lb=lbit.next();
880 MethodDescriptor md=lb.getMethod();
881 //Is the method static or a constructor
882 if (md.isStatic()||md.getReturnType()==null)
884 int methodnum=virtualcalls.getLocalityNumber(lb);
885 virtualtable[rownum][methodnum]=lb;
889 /** Generate array that contains the sizes of class objects. The
890 * object allocation functions in the runtime use this
893 private void generateSizeArray(PrintWriter outclassdefs) {
894 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
895 outclassdefs.print("#ifdef TRANSSTATS \n");
896 outclassdefs.print("extern int numTransAbort;\n");
897 outclassdefs.print("extern int numTransCommit;\n");
898 outclassdefs.print("extern int nSoftAbort;\n");
900 outclassdefs.print("extern int nchashSearch;\n");
901 outclassdefs.print("extern int nmhashSearch;\n");
902 outclassdefs.print("extern int nprehashSearch;\n");
903 outclassdefs.print("extern int nRemoteSend;\n");
904 outclassdefs.print("extern int bytesSent;\n");
905 outclassdefs.print("extern int bytesRecv;\n");
906 outclassdefs.print("extern void handle();\n");
907 } else if (state.SINGLETM) {
908 outclassdefs.println("extern int nSoftAbortAbort;");
909 outclassdefs.println("extern int nSoftAbortCommit;");
910 outclassdefs.println("#ifdef STMSTATS\n");
911 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
912 outclassdefs.println("#endif\n");
914 outclassdefs.print("#endif\n");
915 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
917 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
918 cdarray=new ClassDescriptor[state.numClasses()];
920 while(it.hasNext()) {
921 ClassDescriptor cd=(ClassDescriptor)it.next();
922 cdarray[cd.getId()]=cd;
925 arraytable=new TypeDescriptor[state.numArrays()];
927 Iterator arrayit=state.getArrayIterator();
928 while(arrayit.hasNext()) {
929 TypeDescriptor td=(TypeDescriptor)arrayit.next();
930 int id=state.getArrayNumber(td);
936 /* Print out types */
937 outclassdefs.println("/* ");
938 for(int i=0; i<state.numClasses(); i++) {
939 ClassDescriptor cd=cdarray[i];
941 outclassdefs.println("NULL " + i);
943 outclassdefs.println(cd +" "+i);
947 for(int i=0; i<state.numArrays(); i++) {
948 TypeDescriptor arraytd=arraytable[i];
949 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
952 outclassdefs.println("*/");
955 outclassdefs.print("int classsize[]={");
957 boolean needcomma=false;
958 for(int i=0; i<state.numClasses(); i++) {
960 outclassdefs.print(", ");
962 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
964 outclassdefs.print("0");
970 for(int i=0; i<state.numArrays(); i++) {
972 outclassdefs.print(", ");
973 TypeDescriptor tdelement=arraytable[i].dereference();
974 if (tdelement.isArray()||tdelement.isClass())
975 outclassdefs.print("sizeof(void *)");
977 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
981 outclassdefs.println("};");
983 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
985 outclassdefs.print("int typearray[]={");
986 for(int i=0; i<state.numClasses(); i++) {
987 ClassDescriptor cd=cdarray[i];
988 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
990 outclassdefs.print(", ");
992 outclassdefs.print("-1");
994 outclassdefs.print(supercd.getId());
998 for(int i=0; i<state.numArrays(); i++) {
999 TypeDescriptor arraytd=arraytable[i];
1000 ClassDescriptor arraycd=arraytd.getClassDesc();
1001 if (arraycd==null) {
1003 outclassdefs.print(", ");
1004 outclassdefs.print(objectclass.getId());
1008 ClassDescriptor cd=arraycd.getSuperDesc();
1011 TypeDescriptor supertd=new TypeDescriptor(cd);
1012 supertd.setArrayCount(arraytd.getArrayCount());
1013 type=state.getArrayNumber(supertd);
1015 type+=state.numClasses();
1018 cd=cd.getSuperDesc();
1021 outclassdefs.print(", ");
1022 outclassdefs.print(type);
1026 outclassdefs.println("};");
1031 outclassdefs.print("int typearray2[]={");
1032 for(int i=0; i<state.numArrays(); i++) {
1033 TypeDescriptor arraytd=arraytable[i];
1034 ClassDescriptor arraycd=arraytd.getClassDesc();
1035 if (arraycd==null) {
1037 outclassdefs.print(", ");
1038 outclassdefs.print("-1");
1042 ClassDescriptor cd=arraycd.getSuperDesc();
1043 int level=arraytd.getArrayCount()-1;
1045 for(; level>0; level--) {
1046 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1047 supertd.setArrayCount(level);
1048 type=state.getArrayNumber(supertd);
1050 type+=state.numClasses();
1055 outclassdefs.print(", ");
1056 outclassdefs.print(type);
1060 outclassdefs.println("};");
1063 /** Constructs params and temp objects for each method or task.
1064 * These objects tell the compiler which temps need to be
1067 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1068 MethodDescriptor md=fm.getMethod();
1069 TaskDescriptor task=fm.getTask();
1070 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1071 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1073 paramstable.put(lb, objectparams);
1074 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1075 } else if (md!=null)
1076 paramstable.put(md, objectparams);
1078 paramstable.put(task, objectparams);
1080 for(int i=0; i<fm.numParameters(); i++) {
1081 TempDescriptor temp=fm.getParameter(i);
1082 TypeDescriptor type=temp.getType();
1083 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1084 objectparams.addPtr(temp);
1086 objectparams.addPrim(temp);
1087 if(lb!=null&&saveset.contains(temp)) {
1088 backuptable.get(lb).put(temp, temp.createNew());
1092 for(int i=0; i<fm.numTags(); i++) {
1093 TempDescriptor temp=fm.getTag(i);
1094 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1095 objectparams.addPtr(temp);
1097 objectparams.addPrim(temp);
1100 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1102 tempstable.put(lb, objecttemps);
1104 tempstable.put(md, objecttemps);
1106 tempstable.put(task, objecttemps);
1108 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1109 FlatNode fn=(FlatNode)nodeit.next();
1110 TempDescriptor[] writes=fn.writesTemps();
1111 for(int i=0; i<writes.length; i++) {
1112 TempDescriptor temp=writes[i];
1113 TypeDescriptor type=temp.getType();
1114 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1115 objecttemps.addPtr(temp);
1117 objecttemps.addPrim(temp);
1118 if(lb!=null&&saveset.contains(temp)&&
1119 !backuptable.get(lb).containsKey(temp))
1120 backuptable.get(lb).put(temp, temp.createNew());
1124 /* Create backup temps */
1126 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1127 TempDescriptor tmp=tmpit.next();
1128 TypeDescriptor type=tmp.getType();
1129 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1130 objecttemps.addPtr(tmp);
1132 objecttemps.addPrim(tmp);
1134 /* Create temp to hold revert table */
1135 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1136 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1137 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1138 objecttemps.addPtr(reverttmp);
1140 objecttemps.addPrim(reverttmp);
1141 reverttable.put(lb, reverttmp);
1146 /** This method outputs the following information about classes
1148 * (1) For classes, what are the locations of pointers.
1149 * (2) For arrays, does the array contain pointers or primitives.
1150 * (3) For classes, does the class contain flags.
1153 private void generateLayoutStructs(PrintWriter output) {
1154 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1155 while(it.hasNext()) {
1156 ClassDescriptor cn=(ClassDescriptor)it.next();
1157 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1158 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1160 while(allit.hasNext()) {
1161 FieldDescriptor fd=(FieldDescriptor)allit.next();
1162 TypeDescriptor type=fd.getType();
1163 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1168 output.print(count);
1169 allit=cn.getFieldTable().getAllDescriptorsIterator();
1170 while(allit.hasNext()) {
1171 FieldDescriptor fd=(FieldDescriptor)allit.next();
1172 TypeDescriptor type=fd.getType();
1173 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1176 output.println(",");
1177 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1180 output.println("};");
1182 output.println("unsigned INTPTR * pointerarray[]={");
1183 boolean needcomma=false;
1184 for(int i=0; i<state.numClasses(); i++) {
1185 ClassDescriptor cn=cdarray[i];
1187 output.println(",");
1190 output.print(cn.getSafeSymbol()+"_pointers");
1192 output.print("NULL");
1196 for(int i=0; i<state.numArrays(); i++) {
1198 output.println(", ");
1199 TypeDescriptor tdelement=arraytable[i].dereference();
1200 if (tdelement.isArray()||tdelement.isClass())
1201 output.print("((unsigned INTPTR *)1)");
1207 output.println("};");
1209 output.println("int hasflags[]={");
1210 for(int i=0; i<state.numClasses(); i++) {
1211 ClassDescriptor cn=cdarray[i];
1213 output.println(", ");
1215 if ((cn != null) && (cn.hasFlags()))
1220 output.println("};");
1223 /** Print out table to give us supertypes */
1224 private void generateSuperTypeTable(PrintWriter output) {
1225 output.println("int supertypes[]={");
1226 boolean needcomma=false;
1227 for(int i=0; i<state.numClasses(); i++) {
1228 ClassDescriptor cn=cdarray[i];
1230 output.println(",");
1232 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1233 ClassDescriptor cdsuper=cn.getSuperDesc();
1234 output.print(cdsuper.getId());
1238 output.println("};");
1241 /** Force consistent field ordering between inherited classes. */
1243 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1245 ClassDescriptor sp=cn.getSuperDesc();
1247 printClassStruct(sp, classdefout);
1249 if (!fieldorder.containsKey(cn)) {
1250 Vector fields=new Vector();
1251 fieldorder.put(cn,fields);
1252 Vector fieldvec=cn.getFieldVec();
1253 for(int i=0;i<fieldvec.size();i++) {
1254 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1255 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1259 Vector fields=(Vector)fieldorder.get(cn);
1261 for(int i=0; i<fields.size(); i++) {
1262 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1263 if (fd.getType().isClass()||fd.getType().isArray())
1264 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1266 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1271 /* Map flags to integers consistently between inherited
1274 protected void mapFlags(ClassDescriptor cn) {
1275 ClassDescriptor sp=cn.getSuperDesc();
1279 if (!flagorder.containsKey(cn)) {
1280 Hashtable flags=new Hashtable();
1281 flagorder.put(cn,flags);
1283 Hashtable superflags=(Hashtable)flagorder.get(sp);
1284 Iterator superflagit=superflags.keySet().iterator();
1285 while(superflagit.hasNext()) {
1286 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1287 Integer number=(Integer)superflags.get(fd);
1288 flags.put(fd, number);
1289 if ((number.intValue()+1)>max)
1290 max=number.intValue()+1;
1294 Iterator flagit=cn.getFlags();
1295 while(flagit.hasNext()) {
1296 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1297 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1298 flags.put(fd, new Integer(max++));
1304 /** This function outputs (1) structures that parameters are
1305 * passed in (when PRECISE GC is enabled) and (2) function
1306 * prototypes for the methods */
1308 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1309 /* Output class structure */
1310 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1311 classdefout.println(" int type;");
1313 classdefout.println(" pthread_t tid;");
1314 classdefout.println(" void * lockentry;");
1315 classdefout.println(" int lockcount;");
1319 classdefout.println(" int flag;");
1320 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1321 classdefout.println(" void * flagptr;");
1322 } else if (state.MULTICORE) {
1323 classdefout.println(" int version;");
1324 classdefout.println(" int * lock;"); // lock entry for this obj
1325 classdefout.println(" int mutex;");
1326 classdefout.println(" int lockcount;");
1327 if(state.MULTICOREGC) {
1328 classdefout.println(" int marked;");
1331 if (state.OPTIONAL) {
1332 classdefout.println(" int numfses;");
1333 classdefout.println(" int * fses;");
1336 printClassStruct(cn, classdefout);
1337 classdefout.println("};\n");
1339 if (state.DSM||state.SINGLETM) {
1340 /* Cycle through LocalityBindings */
1341 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1342 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1344 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1345 LocalityBinding lb=lbit.next();
1346 MethodDescriptor md=lb.getMethod();
1347 if (md.getModifiers().isNative()) {
1348 //make sure we only print a native method once
1349 if (nativemethods.contains(md)) {
1350 FlatMethod fm=state.getMethodFlat(md);
1351 generateTempStructs(fm, lb);
1354 nativemethods.add(md);
1356 generateMethod(cn, md, lb, headersout, output);
1359 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1360 MethodDescriptor md=(MethodDescriptor)methodit.next();
1361 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1362 //Need to build param structure for library code
1363 FlatMethod fm=state.getMethodFlat(md);
1364 generateTempStructs(fm, null);
1365 generateMethodParam(cn, md, null, output);
1370 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1371 MethodDescriptor md=(MethodDescriptor)methodit.next();
1372 generateMethod(cn, md, null, headersout, output);
1376 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1377 /* Output parameter structure */
1378 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1379 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1380 if ((state.DSM||state.SINGLETM)&&lb!=null)
1381 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1383 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1384 output.println(" INTPTR size;");
1385 output.println(" void * next;");
1386 for(int i=0; i<objectparams.numPointers(); i++) {
1387 TempDescriptor temp=objectparams.getPointer(i);
1388 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1390 output.println("};\n");
1394 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1395 FlatMethod fm=state.getMethodFlat(md);
1396 generateTempStructs(fm, lb);
1398 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1399 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1401 generateMethodParam(cn, md, lb, output);
1403 /* Output temp structure */
1404 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1405 if (state.DSM||state.SINGLETM)
1406 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1408 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1409 output.println(" INTPTR size;");
1410 output.println(" void * next;");
1411 for(int i=0; i<objecttemps.numPointers(); i++) {
1412 TempDescriptor temp=objecttemps.getPointer(i);
1413 if (temp.getType().isNull())
1414 output.println(" void * "+temp.getSafeSymbol()+";");
1416 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1418 output.println("};\n");
1421 /********* Output method declaration ***********/
1422 if (state.DSM||state.SINGLETM) {
1423 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1425 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1427 /* First the return type */
1428 if (md.getReturnType()!=null) {
1429 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1430 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1432 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1434 //catch the constructor case
1435 headersout.print("void ");
1437 /* Next the method name */
1438 if (state.DSM||state.SINGLETM) {
1439 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1441 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1443 boolean printcomma=false;
1444 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1445 if (state.DSM||state.SINGLETM) {
1446 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1448 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1452 /* Output parameter list*/
1453 for(int i=0; i<objectparams.numPrimitives(); i++) {
1454 TempDescriptor temp=objectparams.getPrimitive(i);
1456 headersout.print(", ");
1458 if (temp.getType().isClass()||temp.getType().isArray())
1459 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1461 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1463 headersout.println(");\n");
1467 /** This function outputs (1) structures that parameters are
1468 * passed in (when PRECISE GC is enabled) and (2) function
1469 * prototypes for the tasks */
1471 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1472 /* Cycle through tasks */
1473 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1475 while(taskit.hasNext()) {
1476 /* Classify parameters */
1477 TaskDescriptor task=(TaskDescriptor)taskit.next();
1478 FlatMethod fm=state.getMethodFlat(task);
1479 generateTempStructs(fm, null);
1481 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1482 TempObject objecttemps=(TempObject) tempstable.get(task);
1484 /* Output parameter structure */
1485 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1486 output.println("struct "+task.getSafeSymbol()+"_params {");
1488 output.println(" INTPTR size;");
1489 output.println(" void * next;");
1490 for(int i=0; i<objectparams.numPointers(); i++) {
1491 TempDescriptor temp=objectparams.getPointer(i);
1492 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1495 output.println("};\n");
1496 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1497 maxtaskparams=objectparams.numPointers()+fm.numTags();
1501 /* Output temp structure */
1502 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1503 output.println("struct "+task.getSafeSymbol()+"_locals {");
1504 output.println(" INTPTR size;");
1505 output.println(" void * next;");
1506 for(int i=0; i<objecttemps.numPointers(); i++) {
1507 TempDescriptor temp=objecttemps.getPointer(i);
1508 if (temp.getType().isNull())
1509 output.println(" void * "+temp.getSafeSymbol()+";");
1510 else if(temp.getType().isTag())
1511 output.println(" struct "+
1512 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1514 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1516 output.println("};\n");
1519 /* Output task declaration */
1520 headersout.print("void " + task.getSafeSymbol()+"(");
1522 boolean printcomma=false;
1523 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1524 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1526 headersout.print("void * parameterarray[]");
1527 headersout.println(");\n");
1531 /***** Generate code for FlatMethod fm. *****/
1533 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1534 static int atomicmethodcount=0;
1536 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1537 if (State.PRINTFLAT)
1538 System.out.println(fm.printMethod());
1539 MethodDescriptor md=fm.getMethod();
1540 TaskDescriptor task=fm.getTask();
1541 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1542 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1544 HashSet<AtomicRecord> arset=null;
1546 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1548 if (atomicmethodmap==null)
1549 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1551 //fix these so we get right strings for local variables
1552 localsprefixaddr=localsprefix;
1553 localsprefixderef=localsprefix+"->";
1554 arset=new HashSet<AtomicRecord>();
1556 //Generate commit methods here
1557 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1558 FlatNode fn=fnit.next();
1559 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1560 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0) {
1561 //We have an atomic enter
1562 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1563 Set<FlatNode> exitset=faen.getExits();
1565 String methodname=md.getSymbol()+(atomicmethodcount++);
1566 AtomicRecord ar=new AtomicRecord();
1570 atomicmethodmap.put(faen, ar);
1572 //build data structure declaration
1573 output.println("struct atomicprimitives_"+methodname+" {");
1575 Set<FlatNode> recordset=delaycomp.livecode(lb);
1576 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1577 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1578 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1580 ar.reallivein=new HashSet(liveinto);
1582 ar.liveoutvirtualread=liveoutvirtualread;
1584 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1585 TempDescriptor tmp=it.next();
1586 //remove the pointers
1587 if (tmp.getType().isPtr()) {
1590 //let's print it here
1591 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1594 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1595 TempDescriptor tmp=it.next();
1596 //remove the pointers
1597 if (tmp.getType().isPtr()) {
1599 } else if (!liveinto.contains(tmp)) {
1600 //let's print it here
1601 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1604 output.println("};");
1606 //print out method name
1607 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) {");
1608 //build code for commit method
1610 //first define local primitives
1611 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1612 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1613 TempDescriptor tmp=tmpit.next();
1614 if (!tmp.getType().isPtr()) {
1615 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1616 //read from live into set
1617 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1620 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1624 //turn off write barrier generation
1626 state.SINGLETM=false;
1627 generateCode(faen, fm, lb, exitset, output, false);
1628 state.SINGLETM=true;
1629 //turn on write barrier generation
1631 output.println("}\n\n");
1635 //redefine these back to normal
1637 localsprefixaddr="&"+localsprefix;
1638 localsprefixderef=localsprefix+".";
1640 generateHeader(fm, lb, md!=null ? md : task,output);
1641 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1643 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1644 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1645 AtomicRecord ar=arit.next();
1646 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1650 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1651 if (md!=null&&(state.DSM||state.SINGLETM))
1652 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1653 else if (md!=null&&!(state.DSM||state.SINGLETM))
1654 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1656 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1658 output.print(objecttemp.numPointers()+",");
1659 output.print(paramsprefix);
1660 for(int j=0; j<objecttemp.numPointers(); j++)
1661 output.print(", NULL");
1662 output.println("};");
1665 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1666 TempDescriptor td=objecttemp.getPrimitive(i);
1667 TypeDescriptor type=td.getType();
1669 output.println(" void * "+td.getSafeSymbol()+";");
1670 else if (type.isClass()||type.isArray())
1671 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1673 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1678 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1679 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1680 if( callerSESEplaceholder != mlpa.getMainSESE() ) {
1681 // declare variables for naming static SESE's
1682 output.println(" /* static SESE names */");
1683 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1684 while( pItr.hasNext() ) {
1685 SESEandAgePair p = pItr.next();
1686 output.println(" void* "+p+";");
1689 // declare variables for tracking dynamic sources
1690 output.println(" /* dynamic variable sources */");
1691 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1692 while( dynSrcItr.hasNext() ) {
1693 TempDescriptor dynSrcVar = dynSrcItr.next();
1694 output.println(" void* "+dynSrcVar+"_srcSESE;");
1695 output.println(" int "+dynSrcVar+"_srcOffset;");
1702 /* Check to see if we need to do a GC if this is a
1703 * multi-threaded program...*/
1705 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1706 || this.state.MULTICOREGC) {
1707 //Don't bother if we aren't in recursive methods...The loops case will catch it
1708 if (callgraph.getAllMethods(md).contains(md)) {
1709 if (state.DSM&&lb.isAtomic())
1710 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1711 else if (this.state.MULTICOREGC) {
1712 output.println("if(gcflag) gc("+localsprefixaddr+");");
1714 output.println("if (needtocollect) checkcollect("+localsprefixaddr+");");
1718 generateCode(fm.getNext(0), fm, lb, null, output, true);
1720 output.println("}\n\n");
1724 protected void initializeSESE( FlatSESEEnterNode fsen ) {
1726 FlatMethod fm = fsen.getfmEnclosing();
1727 MethodDescriptor md = fm.getMethod();
1728 ClassDescriptor cn = md.getClassDesc();
1731 // Creates bogus method descriptor to index into tables
1732 Modifiers modBogus = new Modifiers();
1733 MethodDescriptor mdBogus =
1734 new MethodDescriptor( modBogus,
1735 new TypeDescriptor( TypeDescriptor.VOID ),
1736 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1739 mdBogus.setClassDesc( fsen.getcdEnclosing() );
1740 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1741 fsen.setfmBogus( fmBogus );
1742 fsen.setmdBogus( mdBogus );
1744 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1745 inSetAndOutSet.addAll( fsen.getInVarSet() );
1746 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1748 // Build paramsobj for bogus method descriptor
1749 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
1750 paramstable.put( mdBogus, objectparams );
1752 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1753 while( itr.hasNext() ) {
1754 TempDescriptor temp = itr.next();
1755 TypeDescriptor type = temp.getType();
1756 if( type.isPtr() ) {
1757 objectparams.addPtr( temp );
1759 objectparams.addPrim( temp );
1763 // Build normal temp object for bogus method descriptor
1764 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
1765 tempstable.put( mdBogus, objecttemps );
1767 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
1768 FlatNode fn = (FlatNode)nodeit.next();
1769 TempDescriptor[] writes = fn.writesTemps();
1771 for( int i = 0; i < writes.length; i++ ) {
1772 TempDescriptor temp = writes[i];
1773 TypeDescriptor type = temp.getType();
1775 if( type.isPtr() ) {
1776 objecttemps.addPtr( temp );
1778 objecttemps.addPrim( temp );
1784 protected void generateMethodSESE(FlatSESEEnterNode fsen,
1786 PrintWriter outputStructs,
1787 PrintWriter outputMethHead,
1788 PrintWriter outputMethods
1791 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
1792 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
1794 // generate locals structure
1795 outputStructs.println("struct "+
1796 fsen.getcdEnclosing().getSafeSymbol()+
1797 fsen.getmdBogus().getSafeSymbol()+"_"+
1798 fsen.getmdBogus().getSafeMethodDescriptor()+
1800 outputStructs.println(" INTPTR size;");
1801 outputStructs.println(" void * next;");
1802 for(int i=0; i<objecttemps.numPointers(); i++) {
1803 TempDescriptor temp=objecttemps.getPointer(i);
1805 if( fsen.getPrettyIdentifier().equals( "calc" ) ) {
1806 System.out.println( " got a pointer "+temp );
1809 if (temp.getType().isNull())
1810 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1812 outputStructs.println(" struct "+
1813 temp.getType().getSafeSymbol()+" * "+
1814 temp.getSafeSymbol()+";");
1816 outputStructs.println("};\n");
1819 // generate the SESE record structure
1820 outputStructs.println(fsen.getSESErecordName()+" {");
1822 // data common to any SESE, and it must be placed first so
1823 // a module that doesn't know what kind of SESE record this
1824 // is can cast the pointer to a common struct
1825 outputStructs.println(" SESEcommon common;");
1827 // then garbage list stuff
1828 outputStructs.println(" INTPTR size;");
1829 outputStructs.println(" void * next;");
1831 // in-set source tracking
1832 // in-vars that are READY come from parent, don't need anything
1833 // stuff STATIC needs a custom SESE pointer for each age pair
1834 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
1835 while( itrStaticInVarSrcs.hasNext() ) {
1836 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
1837 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
1840 // DYNAMIC stuff needs a source SESE ptr and offset
1841 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
1842 while( itrDynInVars.hasNext() ) {
1843 TempDescriptor dynInVar = itrDynInVars.next();
1844 outputStructs.println(" void* "+dynInVar+"_srcSESE;");
1845 outputStructs.println(" int "+dynInVar+"_srcOffset;");
1848 // space for all in and out set primitives
1849 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1850 inSetAndOutSet.addAll( fsen.getInVarSet() );
1851 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1853 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
1855 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1856 while( itr.hasNext() ) {
1857 TempDescriptor temp = itr.next();
1858 TypeDescriptor type = temp.getType();
1859 if( !type.isPtr() ) {
1860 inSetAndOutSetPrims.add( temp );
1864 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
1865 while( itrPrims.hasNext() ) {
1866 TempDescriptor temp = itrPrims.next();
1867 TypeDescriptor type = temp.getType();
1868 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
1871 for(int i=0; i<objectparams.numPointers(); i++) {
1872 TempDescriptor temp=objectparams.getPointer(i);
1873 if (temp.getType().isNull())
1874 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1876 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1879 outputStructs.println("};\n");
1882 // write method declaration to header file
1883 outputMethHead.print("void ");
1884 outputMethHead.print(fsen.getSESEmethodName()+"(");
1885 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
1886 outputMethHead.println(");\n");
1889 generateFlatMethodSESE( fsen.getfmBogus(),
1890 fsen.getcdEnclosing(),
1896 private void generateFlatMethodSESE(FlatMethod fm,
1898 FlatSESEEnterNode fsen,
1899 FlatSESEExitNode seseExit,
1903 MethodDescriptor md=fm.getMethod();
1905 output.print("void ");
1906 output.print(fsen.getSESEmethodName()+"(");
1907 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
1908 output.println("){\n");
1910 TempObject objecttemp=(TempObject) tempstable.get(md);
1912 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1913 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1914 output.print(objecttemp.numPointers()+",");
1915 output.print("(void*) &("+paramsprefix+"->size)");
1916 for(int j=0; j<objecttemp.numPointers(); j++)
1917 output.print(", NULL");
1918 output.println("};");
1921 output.println(" /* regular local primitives */");
1922 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1923 TempDescriptor td=objecttemp.getPrimitive(i);
1924 TypeDescriptor type=td.getType();
1926 output.println(" void * "+td.getSafeSymbol()+";");
1927 else if (type.isClass()||type.isArray())
1928 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1930 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1934 // declare variables for naming static SESE's
1935 output.println(" /* static SESE names */");
1936 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
1937 while( pItr.hasNext() ) {
1938 SESEandAgePair p = pItr.next();
1939 output.println(" void* "+p+";");
1942 // declare variables for tracking dynamic sources
1943 output.println(" /* dynamic variable sources */");
1944 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
1945 while( dynSrcItr.hasNext() ) {
1946 TempDescriptor dynSrcVar = dynSrcItr.next();
1947 output.println(" void* "+dynSrcVar+"_srcSESE;");
1948 output.println(" int "+dynSrcVar+"_srcOffset;");
1951 // declare local temps for in-set primitives, and if it is
1952 // a ready-source variable, get the value from the record
1953 output.println(" /* local temps for in-set primitives */");
1954 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
1955 while( itrInSet.hasNext() ) {
1956 TempDescriptor temp = itrInSet.next();
1957 TypeDescriptor type = temp.getType();
1958 if( !type.isPtr() ) {
1959 if( fsen.getReadyInVarSet().contains( temp ) ) {
1960 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
1962 output.println(" "+type+" "+temp+";");
1967 // declare local temps for out-set primitives if its not already
1968 // in the in-set, and it's value will get written so no problem
1969 output.println(" /* local temp for out-set prim, not already in the in-set */");
1970 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
1971 while( itrOutSet.hasNext() ) {
1972 TempDescriptor temp = itrOutSet.next();
1973 TypeDescriptor type = temp.getType();
1974 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
1975 output.println(" "+type+" "+temp+";");
1979 // copy in-set into place, ready vars were already
1980 // copied when the SESE was issued
1981 Iterator<TempDescriptor> tempItr;
1983 // static vars are from a known SESE
1984 tempItr = fsen.getStaticInVarSet().iterator();
1985 while( tempItr.hasNext() ) {
1986 TempDescriptor temp = tempItr.next();
1987 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
1988 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
1990 // can't grab something from this source until it is done
1991 output.println(" {");
1992 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+srcPair+";" );
1993 output.println(" pthread_mutex_lock( &(com->lock) );");
1994 output.println(" while( com->doneExecuting == FALSE ) {");
1995 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
1996 output.println(" }");
1997 output.println(" pthread_mutex_unlock( &(com->lock) );");
1999 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2000 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2002 output.println(" }");
2005 // dynamic vars come from an SESE and src
2006 tempItr = fsen.getDynamicInVarSet().iterator();
2007 while( tempItr.hasNext() ) {
2008 TempDescriptor temp = tempItr.next();
2009 TypeDescriptor type = temp.getType();
2011 // go grab it from the SESE source
2012 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2014 // gotta wait until the source is done
2015 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+temp+"_srcSESE;" );
2016 output.println(" pthread_mutex_lock( &(com->lock) );");
2017 output.println(" while( com->doneExecuting == FALSE ) {");
2018 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2019 output.println(" }");
2020 output.println(" pthread_mutex_unlock( &(com->lock) );");
2023 if( type.isNull() ) {
2025 } else if( type.isClass() || type.isArray() ) {
2026 typeStr = "struct "+type.getSafeSymbol()+"*";
2028 typeStr = type.getSafeSymbol();
2031 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2032 " = *(("+typeStr+"*) ("+
2033 paramsprefix+"->"+temp+"_srcSESE + "+
2034 paramsprefix+"->"+temp+"_srcOffset));");
2036 // or if the source was our parent, its in the record to grab
2037 output.println(" } else {");
2038 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2039 " = "+paramsprefix+"->"+temp+";");
2040 output.println(" }");
2043 // Check to see if we need to do a GC if this is a
2044 // multi-threaded program...
2045 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2046 //Don't bother if we aren't in recursive methods...The loops case will catch it
2047 if (callgraph.getAllMethods(md).contains(md)) {
2048 if(this.state.MULTICOREGC) {
2049 output.println("if(gcflag) gc("+localsprefixaddr+");");
2051 output.println("if (needtocollect) checkcollect("+localsprefixaddr+");");
2056 // initialize thread-local var to a non-zero, invalid address
2057 output.println(" seseCaller = (SESEcommon*) 0x2;");
2059 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2060 exitset.add(seseExit);
2062 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2064 output.println("}\n\n");
2068 // when a new mlp thread is created for an issued SESE, it is started
2069 // by running this method which blocks on a cond variable until
2070 // it is allowed to transition to execute. Then a case statement
2071 // allows it to invoke the method with the proper SESE body, and after
2072 // exiting the SESE method, executes proper SESE exit code before the
2073 // thread can be destroyed
2074 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2075 PrintWriter outmethod
2078 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2079 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2080 outmethod.println( " int status;");
2081 outmethod.println( " char errmsg[128];");
2083 // generate a case for each SESE class that can be invoked
2084 outmethod.println( " switch( *((int*)seseRecord) ) {");
2085 outmethod.println( " ");
2086 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
2087 FlatSESEEnterNode fsen = seseit.next();
2089 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2090 outmethod.println( " case "+fsen.getIdentifier()+":");
2091 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2093 if( fsen.equals( mlpa.getMainSESE() ) ) {
2094 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2095 outmethod.println( " exit( 0 );");
2098 outmethod.println( " break;");
2099 outmethod.println( "");
2102 // default case should never be taken, error out
2103 outmethod.println( " default:");
2104 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2105 outmethod.println( " exit(-30);");
2106 outmethod.println( " break;");
2107 outmethod.println( " }");
2108 outmethod.println( " return NULL;");
2109 outmethod.println( "}\n\n");
2113 protected void generateCode(FlatNode first,
2116 Set<FlatNode> stopset,
2117 PrintWriter output, boolean firstpass) {
2119 /* Assign labels to FlatNode's if necessary.*/
2120 Hashtable<FlatNode, Integer> nodetolabel=assignLabels(first, stopset);
2122 Set<FlatNode> storeset=null;
2123 HashSet<FlatNode> genset=null;
2124 Set<FlatNode> unionset=null;
2126 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2127 storeset=delaycomp.livecode(lb);
2128 genset=new HashSet<FlatNode>();
2130 genset.addAll(delaycomp.getCannotDelay(lb));
2131 genset.addAll(delaycomp.getOther(lb));
2133 genset.addAll(delaycomp.getNotReady(lb));
2135 unionset=new HashSet<FlatNode>();
2136 unionset.addAll(storeset);
2137 unionset.addAll(genset);
2140 /* Do the actual code generation */
2141 FlatNode current_node=null;
2142 HashSet tovisit=new HashSet();
2143 HashSet visited=new HashSet();
2145 tovisit.add(first.getNext(0));
2148 while(current_node!=null||!tovisit.isEmpty()) {
2149 if (current_node==null) {
2150 current_node=(FlatNode)tovisit.iterator().next();
2151 tovisit.remove(current_node);
2152 } else if (tovisit.contains(current_node)) {
2153 tovisit.remove(current_node);
2155 visited.add(current_node);
2156 if (nodetolabel.containsKey(current_node)) {
2157 output.println("L"+nodetolabel.get(current_node)+":");
2159 if (state.INSTRUCTIONFAILURE) {
2160 if (state.THREAD||state.DSM||state.SINGLETM) {
2161 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2163 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2165 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2167 if (!state.DELAYCOMP||firstpass) {
2168 generateFlatNode(fm, lb, current_node, output);
2170 //store primitive variables in out set
2171 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2172 Set<TempDescriptor> liveout=ar.liveout;
2173 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2174 TempDescriptor tmp=tmpit.next();
2175 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2178 if (state.MLP && stopset!=null) {
2179 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2180 assert current_node instanceof FlatSESEExitNode;
2181 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2182 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2183 assert fsen.getFlatExit().equals( fsxn );
2184 assert fsxn.getFlatEnter().equals( fsen );
2186 if (current_node.kind()!=FKind.FlatReturnNode) {
2187 output.println(" return;");
2190 } else if(current_node.numNext()==1) {
2193 current_node.kind()==FKind.FlatSESEEnterNode &&
2194 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2196 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2197 generateFlatNode(fm, lb, current_node, output);
2198 nextnode=fsen.getFlatExit().getNext(0);
2199 } else if (state.DELAYCOMP) {
2200 boolean specialprimitive=false;
2201 //skip literals...no need to add extra overhead
2202 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2203 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2204 if (!typedesc.isClass()&&!typedesc.isArray()) {
2205 specialprimitive=true;
2209 if (genset==null||genset.contains(current_node)||specialprimitive)
2210 generateFlatNode(fm, lb, current_node, output);
2211 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2212 TempDescriptor wrtmp=current_node.writesTemps()[0];
2214 //need to store value written by previous node
2215 if (wrtmp.getType().isPtr()) {
2216 //only lock the objects that may actually need locking
2217 if (recorddc.getNeedTrans(lb, current_node)) {
2218 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");");
2220 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");");
2223 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");");
2226 //need to read value read by previous node
2227 if (wrtmp.getType().isPtr()) {
2228 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");");
2230 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");");
2234 nextnode=current_node.getNext(0);
2237 generateFlatNode(fm, lb, current_node, output);
2238 nextnode=current_node.getNext(0);
2240 if (visited.contains(nextnode)) {
2241 output.println("goto L"+nodetolabel.get(nextnode)+";");
2244 current_node=nextnode;
2245 } else if (current_node.numNext()==2) {
2247 if (state.DELAYCOMP) {
2248 boolean computeside=false;
2250 //need to record which way it should go
2251 if (genset==null||genset.contains(current_node)) {
2252 if (storeset!=null&&storeset.contains(current_node)) {
2253 //need to store which way branch goes
2254 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2256 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2258 //which side to execute
2262 if (genset.contains(current_node)) {
2263 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2264 } else if (storeset.contains(current_node)) {
2266 output.println("RESTOREANDBRANCH(L"+nodetolabel.get(current_node.getNext(1))+");");
2268 //which side to execute
2273 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2275 if (leftset.size()==0)
2277 if (visited.contains(current_node.getNext(branch))) {
2278 //already visited -- build jump
2279 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2282 current_node=current_node.getNext(branch);
2285 if (!visited.contains(current_node.getNext(1)))
2286 tovisit.add(current_node.getNext(1));
2287 if (visited.contains(current_node.getNext(0))) {
2288 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2291 current_node=current_node.getNext(0);
2295 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2296 if (!visited.contains(current_node.getNext(1)))
2297 tovisit.add(current_node.getNext(1));
2298 if (visited.contains(current_node.getNext(0))) {
2299 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2302 current_node=current_node.getNext(0);
2304 } else throw new Error();
2308 /** This method assigns labels to FlatNodes */
2309 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2310 return assignLabels(first, null);
2313 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2314 HashSet tovisit=new HashSet();
2315 HashSet visited=new HashSet();
2317 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2320 /*Assign labels first. A node needs a label if the previous
2321 * node has two exits or this node is a join point. */
2323 while(!tovisit.isEmpty()) {
2324 FlatNode fn=(FlatNode)tovisit.iterator().next();
2329 if(lastset!=null&&lastset.contains(fn)) {
2330 // if last is not null and matches, don't go
2331 // any further for assigning labels
2335 for(int i=0; i<fn.numNext(); i++) {
2336 FlatNode nn=fn.getNext(i);
2339 //1) Edge >1 of node
2340 nodetolabel.put(nn,new Integer(labelindex++));
2342 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2346 nodetolabel.put(nn,new Integer(labelindex++));
2354 /** Generate text string that corresponds to the TempDescriptor td. */
2355 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2356 MethodDescriptor md=fm.getMethod();
2357 TaskDescriptor task=fm.getTask();
2358 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2360 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2361 //System.out.println("generateTemp returns " + td.getSafeSymbol());
2362 return td.getSafeSymbol();
2365 if (objecttemps.isLocalPtr(td)) {
2366 return localsprefixderef+td.getSafeSymbol();
2369 if (objecttemps.isParamPtr(td)) {
2370 return paramsprefix+"->"+td.getSafeSymbol();
2376 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2378 // insert pre-node actions from the code plan
2381 CodePlan cp = mlpa.getCodePlan( fn );
2384 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2386 // for each sese and age pair that this parent statement
2387 // must stall on, take that child's stall semaphore, the
2388 // copying of values comes after the statement
2389 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2390 while( vstItr.hasNext() ) {
2391 VariableSourceToken vst = vstItr.next();
2393 SESEandAgePair p = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2395 output.println(" {");
2396 output.println(" SESEcommon* common = (SESEcommon*) "+p+";");
2398 output.println(" pthread_mutex_lock( &(common->lock) );");
2399 output.println(" while( common->doneExecuting == FALSE ) {");
2400 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2401 output.println(" }");
2402 output.println(" pthread_mutex_unlock( &(common->lock) );");
2404 //output.println(" psem_take( &(common->stallSem) );");
2406 // copy things we might have stalled for
2407 output.println(" "+p.getSESE().getSESErecordName()+"* child = ("+
2408 p.getSESE().getSESErecordName()+"*) "+p+";");
2410 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2411 while( tdItr.hasNext() ) {
2412 TempDescriptor td = tdItr.next();
2413 FlatMethod fmContext;
2414 if( currentSESE.getIsCallerSESEplaceholder() ) {
2415 fmContext = currentSESE.getfmEnclosing();
2417 fmContext = currentSESE.getfmBogus();
2419 output.println(" "+generateTemp( fmContext, td, null )+
2420 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2423 output.println(" }");
2426 // for each variable with a dynamic source, stall just for that variable
2427 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2428 while( dynItr.hasNext() ) {
2429 TempDescriptor dynVar = dynItr.next();
2431 // only stall if the dynamic source is not yourself, denoted by src==NULL
2432 // otherwise the dynamic write nodes will have the local var up-to-date
2433 output.println(" {");
2434 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2435 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2436 output.println(" psem_take( &(common->stallSem) );");
2438 FlatMethod fmContext;
2439 if( currentSESE.getIsCallerSESEplaceholder() ) {
2440 fmContext = currentSESE.getfmEnclosing();
2442 fmContext = currentSESE.getfmBogus();
2444 output.println(" "+generateTemp( fmContext, dynVar, null )+
2445 " = *(("+dynVar.getType()+"*) ("+
2446 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2448 output.println(" }");
2449 output.println(" }");
2452 // for each assignment of a variable to rhs that has a dynamic source,
2453 // copy the dynamic sources
2454 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2455 while( dynAssignItr.hasNext() ) {
2456 Map.Entry me = (Map.Entry) dynAssignItr.next();
2457 TempDescriptor lhs = (TempDescriptor) me.getKey();
2458 TempDescriptor rhs = (TempDescriptor) me.getValue();
2459 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
2460 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2463 // for each lhs that is dynamic from a non-dynamic source, set the
2464 // dynamic source vars to the current SESE
2465 dynItr = cp.getDynAssignCurr().iterator();
2466 while( dynItr.hasNext() ) {
2467 TempDescriptor dynVar = dynItr.next();
2468 output.println(" "+dynVar+"_srcSESE = NULL;");
2474 case FKind.FlatAtomicEnterNode:
2475 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
2478 case FKind.FlatAtomicExitNode:
2479 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
2482 case FKind.FlatInstanceOfNode:
2483 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
2486 case FKind.FlatSESEEnterNode:
2487 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
2490 case FKind.FlatSESEExitNode:
2491 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
2494 case FKind.FlatWriteDynamicVarNode:
2495 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
2498 case FKind.FlatGlobalConvNode:
2499 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
2502 case FKind.FlatTagDeclaration:
2503 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
2506 case FKind.FlatCall:
2507 generateFlatCall(fm, lb, (FlatCall) fn,output);
2510 case FKind.FlatFieldNode:
2511 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
2514 case FKind.FlatElementNode:
2515 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
2518 case FKind.FlatSetElementNode:
2519 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
2522 case FKind.FlatSetFieldNode:
2523 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
2527 generateFlatNew(fm, lb, (FlatNew) fn,output);
2530 case FKind.FlatOpNode:
2531 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
2534 case FKind.FlatCastNode:
2535 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
2538 case FKind.FlatLiteralNode:
2539 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
2542 case FKind.FlatReturnNode:
2543 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
2547 output.println("/* nop */");
2550 case FKind.FlatExit:
2551 output.println("/* exit */");
2554 case FKind.FlatBackEdge:
2555 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
2556 || (this.state.MULTICOREGC)) {
2557 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
2558 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
2559 } else if(this.state.MULTICOREGC) {
2560 output.println("if (gcflag) gc("+localsprefixaddr+");");
2562 output.println("if (needtocollect) checkcollect("+localsprefixaddr+");");
2564 output.println("/* nop */");
2567 case FKind.FlatCheckNode:
2568 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
2571 case FKind.FlatFlagActionNode:
2572 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
2575 case FKind.FlatPrefetchNode:
2576 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
2579 case FKind.FlatOffsetNode:
2580 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
2587 // insert post-node actions from the code-plan
2589 CodePlan cp = mlpa.getCodePlan( fn );
2596 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
2597 output.println("/* FlatOffsetNode */");
2598 FieldDescriptor fd=fofn.getField();
2599 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
2600 output.println("/* offset */");
2603 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
2604 if (state.PREFETCH) {
2605 Vector oids = new Vector();
2606 Vector fieldoffset = new Vector();
2607 Vector endoffset = new Vector();
2608 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
2609 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
2610 PrefetchPair pp = (PrefetchPair) it.next();
2611 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
2612 /* Find prefetches that can generate oid */
2613 if(statusbase == LocalityAnalysis.GLOBAL) {
2614 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
2616 } else if (statusbase == LocalityAnalysis.LOCAL) {
2617 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
2624 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
2625 output.println("{");
2626 output.println("/* prefetch */");
2627 output.println("/* prefetchid_" + fpn.siteid + " */");
2628 output.println("void * prefptr;");
2629 output.println("int tmpindex;");
2631 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
2632 /*Create C code for oid array */
2633 output.print(" unsigned int oidarray_[] = {");
2634 boolean needcomma=false;
2635 for (Iterator it = oids.iterator(); it.hasNext();) {
2638 output.print(it.next());
2641 output.println("};");
2643 /*Create C code for endoffset values */
2644 output.print(" unsigned short endoffsetarry_[] = {");
2646 for (Iterator it = endoffset.iterator(); it.hasNext();) {
2649 output.print(it.next());
2652 output.println("};");
2654 /*Create C code for Field Offset Values */
2655 output.print(" short fieldarry_[] = {");
2657 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
2660 output.print(it.next());
2663 output.println("};");
2664 /* make the prefetch call to Runtime */
2665 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
2666 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
2667 output.println(" }");
2668 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
2669 output.println(" } else {");
2670 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
2671 output.println(" }");
2672 output.println("}");
2676 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
2677 short offsetcount = 0;
2681 } else if (localbase) {
2682 for(; breakindex<pp.desc.size(); breakindex++) {
2683 Descriptor desc=pp.getDescAt(breakindex);
2684 if (desc instanceof FieldDescriptor) {
2685 FieldDescriptor fd=(FieldDescriptor)desc;
2686 if (fd.isGlobal()) {
2694 if (breakindex>pp.desc.size()) //all local
2697 TypeDescriptor lasttype=pp.base.getType();
2698 String basestr=generateTemp(fm, pp.base, lb);
2700 boolean maybenull=fm.getMethod().isStatic()||
2701 !pp.base.equals(fm.getParameter(0));
2703 for(int i=0; i<breakindex; i++) {
2704 String indexcheck="";
2706 Descriptor desc=pp.getDescAt(i);
2707 if (desc instanceof FieldDescriptor) {
2708 FieldDescriptor fd=(FieldDescriptor)desc;
2710 if (!teststr.equals(""))
2712 teststr+="((prefptr="+basestr+")!=NULL)";
2713 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
2715 basestr=basestr+"->"+fd.getSafeSymbol();
2718 lasttype=fd.getType();
2720 IndexDescriptor id=(IndexDescriptor)desc;
2721 indexcheck="((tmpindex=";
2722 for(int j=0; j<id.tddesc.size(); j++) {
2723 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
2725 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
2727 if (!teststr.equals(""))
2729 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
2730 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
2732 lasttype=lasttype.dereference();
2737 if (teststr.equals("")) {
2738 oid="((unsigned int)"+basestr+")";
2740 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
2744 for(int i = breakindex; i < pp.desc.size(); i++) {
2745 String newfieldoffset;
2746 Object desc = pp.getDescAt(i);
2747 if(desc instanceof FieldDescriptor) {
2748 FieldDescriptor fd=(FieldDescriptor)desc;
2749 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
2750 lasttype=fd.getType();
2752 newfieldoffset = "";
2753 IndexDescriptor id=(IndexDescriptor)desc;
2754 for(int j = 0; j < id.tddesc.size(); j++) {
2755 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
2757 newfieldoffset += id.offset.toString();
2758 lasttype=lasttype.dereference();
2760 fieldoffset.add(newfieldoffset);
2763 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
2764 base+=pp.desc.size()-breakindex;
2765 endoffset.add(new Short((short)base));
2770 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
2771 if (lb!=fgcn.getLocality())
2773 /* Have to generate flat globalconv */
2774 if (fgcn.getMakePtr()) {
2776 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
2778 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
2779 //need to do translation
2780 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
2781 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
2782 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
2786 /* Need to convert to OID */
2787 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
2788 if (fgcn.doConvert()||(delaycomp!=null&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
2789 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
2791 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
2797 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
2799 if (fion.getType().isArray()) {
2800 type=state.getArrayNumber(fion.getType())+state.numClasses();
2802 type=fion.getType().getClassDesc().getId();
2805 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
2806 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
2808 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
2811 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
2812 /* Check to see if we need to generate code for this atomic */
2813 if (locality==null) {
2814 output.println("pthread_mutex_lock(&atomiclock);");
2818 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
2822 if (state.DELAYCOMP) {
2823 AtomicRecord ar=atomicmethodmap.get(faen);
2825 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
2826 TempDescriptor tmp=tmpit.next();
2827 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2830 //copy outs that depend on path
2831 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
2832 TempDescriptor tmp=tmpit.next();
2833 if (!ar.livein.contains(tmp))
2834 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2838 /* Backup the temps. */
2839 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
2840 TempDescriptor tmp=tmpit.next();
2841 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
2844 output.println("goto transstart"+faen.getIdentifier()+";");
2846 /******* Print code to retry aborted transaction *******/
2847 output.println("transretry"+faen.getIdentifier()+":");
2850 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
2851 TempDescriptor tmp=tmpit.next();
2852 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
2856 /********* Need to revert local object store ********/
2857 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
2859 output.println("while ("+revertptr+") {");
2860 output.println("struct ___Object___ * tmpptr;");
2861 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
2862 output.println("REVERT_OBJ("+revertptr+");");
2863 output.println(revertptr+"=tmpptr;");
2864 output.println("}");
2866 /******* Tell the runtime to start the transaction *******/
2868 output.println("transstart"+faen.getIdentifier()+":");
2869 output.println("transStart();");
2871 if (state.ABORTREADERS) {
2872 output.println("if (_setjmp(aborttrans)) {");
2873 output.println(" goto transretry"+faen.getIdentifier()+"; }");
2877 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
2878 /* Check to see if we need to generate code for this atomic */
2879 if (locality==null) {
2880 output.println("pthread_mutex_unlock(&atomiclock);");
2883 if (locality.getAtomic(lb).get(faen).intValue()>0)
2885 //store the revert list before we lose the transaction object
2886 String revertptr=null;
2888 revertptr=generateTemp(fm, reverttable.get(lb),lb);
2889 output.println(revertptr+"=revertlist;");
2891 if (state.DELAYCOMP) {
2892 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
2895 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
2897 output.println("if (transCommit()) {");
2898 /* Transaction aborts if it returns true */
2899 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
2901 output.println("} else {");
2902 /* Need to commit local object store */
2903 output.println("while ("+revertptr+") {");
2904 output.println("struct ___Object___ * tmpptr;");
2905 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
2906 output.println("COMMIT_OBJ("+revertptr+");");
2907 output.println(revertptr+"=tmpptr;");
2908 output.println("}");
2910 output.println("}");
2911 if (state.DELAYCOMP) {
2913 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
2914 output.println("else {");
2915 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
2916 TempDescriptor tmp=tmpit.next();
2917 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
2919 output.println("}");
2923 public void generateFlatSESEEnterNode( FlatMethod fm,
2925 FlatSESEEnterNode fsen,
2929 // if MLP flag is off, okay that SESE nodes are in IR graph,
2930 // just skip over them and code generates exactly the same
2935 // there may be an SESE in an unreachable method, skip over
2936 if( !mlpa.getAllSESEs().contains( fsen ) ) {
2940 // also, if we have encountered a placeholder, just skip it
2941 if( fsen.getIsCallerSESEplaceholder() ) {
2945 output.println(" {");
2947 // set up the parent
2948 if( fsen == mlpa.getMainSESE() ) {
2949 output.println(" SESEcommon* parentCommon = NULL;");
2951 if( fsen.getParent() == null ) {
2952 System.out.println( "in "+fm+", "+fsen+" has null parent" );
2954 assert fsen.getParent() != null;
2955 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
2956 output.println(" SESEcommon* parentCommon = &("+paramsprefix+"->common);");
2958 //output.println(" SESEcommon* parentCommon = (SESEcommon*) peekItem( seseCallStack );");
2959 output.println(" SESEcommon* parentCommon = seseCaller;");
2963 // before doing anything, lock your own record and increment the running children
2964 if( fsen != mlpa.getMainSESE() ) {
2965 output.println(" pthread_mutex_lock( &(parentCommon->lock) );");
2966 output.println(" ++(parentCommon->numRunningChildren);");
2967 output.println(" pthread_mutex_unlock( &(parentCommon->lock) );");
2970 // just allocate the space for this record
2971 output.println(" "+fsen.getSESErecordName()+"* seseToIssue = ("+
2972 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
2973 fsen.getSESErecordName()+" ) );");
2975 // and keep the thread-local sese stack up to date
2976 //output.println(" addNewItem( seseCallStack, (void*) seseToIssue);");
2978 // fill in common data
2979 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
2980 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
2982 output.println(" seseToIssue->common.forwardList = createQueue();");
2983 output.println(" seseToIssue->common.unresolvedDependencies = 0;");
2984 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
2985 output.println(" seseToIssue->common.doneExecuting = FALSE;");
2986 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
2987 output.println(" seseToIssue->common.numRunningChildren = 0;");
2988 output.println(" seseToIssue->common.parent = parentCommon;");
2990 // all READY in-vars should be copied now and be done with it
2991 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
2992 while( tempItr.hasNext() ) {
2993 TempDescriptor temp = tempItr.next();
2995 // when we are issuing the main SESE or an SESE with placeholder
2996 // caller SESE as parent, generate temp child child's eclosing method,
2997 // otherwise use the parent's enclosing method as the context
2998 boolean useParentContext = false;
3000 if( fsen != mlpa.getMainSESE() ) {
3001 assert fsen.getParent() != null;
3002 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3003 useParentContext = true;
3007 if( useParentContext ) {
3008 output.println(" seseToIssue->"+temp+" = "+
3009 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3011 output.println(" seseToIssue->"+temp+" = "+
3012 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3016 // before potentially adding this SESE to other forwarding lists,
3017 // create it's lock and take it immediately
3018 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3019 output.println(" pthread_mutex_lock( &(seseToIssue->common.lock) );");
3021 if( fsen != mlpa.getMainSESE() ) {
3022 // count up outstanding dependencies, static first, then dynamic
3023 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3024 while( staticSrcsItr.hasNext() ) {
3025 SESEandAgePair srcPair = staticSrcsItr.next();
3026 output.println(" {");
3027 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3028 output.println(" pthread_mutex_lock( &(src->lock) );");
3029 output.println(" if( !isEmpty( src->forwardList ) &&");
3030 output.println(" seseToIssue == peekItem( src->forwardList ) ) {");
3031 output.println(" printf( \"This shouldnt already be here\\n\");");
3032 output.println(" exit( -1 );");
3033 output.println(" }");
3034 output.println(" if( !src->doneExecuting ) {");
3035 output.println(" addNewItem( src->forwardList, seseToIssue );");
3036 output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3037 output.println(" }");
3038 output.println(" pthread_mutex_unlock( &(src->lock) );");
3039 output.println(" }");
3041 // whether or not it is an outstanding dependency, make sure
3042 // to pass the static name to the child's record
3043 output.println(" seseToIssue->"+srcPair+" = "+srcPair+";");
3046 // dynamic sources might already be accounted for in the static list,
3047 // so only add them to forwarding lists if they're not already there
3048 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3049 while( dynVarsItr.hasNext() ) {
3050 TempDescriptor dynInVar = dynVarsItr.next();
3051 output.println(" {");
3052 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3054 // the dynamic source is NULL if it comes from your own space--you can't pass
3055 // the address off to the new child, because you're not done executing and
3056 // might change the variable, so copy it right now
3057 output.println(" if( src != NULL ) {");
3058 output.println(" pthread_mutex_lock( &(src->lock) );");
3059 output.println(" if( isEmpty( src->forwardList ) ||");
3060 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3061 output.println(" if( !src->doneExecuting ) {");
3062 output.println(" addNewItem( src->forwardList, seseToIssue );");
3063 output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3064 output.println(" }");
3065 output.println(" }");
3066 output.println(" pthread_mutex_unlock( &(src->lock) );");
3067 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3068 output.println(" } else {");
3070 boolean useParentContext = false;
3071 if( fsen != mlpa.getMainSESE() ) {
3072 assert fsen.getParent() != null;
3073 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3074 useParentContext = true;
3077 if( useParentContext ) {
3078 output.println(" seseToIssue->"+dynInVar+" = "+
3079 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3081 output.println(" seseToIssue->"+dynInVar+" = "+
3082 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3085 output.println(" }");
3086 output.println(" }");
3088 // even if the value is already copied, make sure your NULL source
3089 // gets passed so child knows it already has the dynamic value
3090 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3093 // maintain pointers for for finding dynamic SESE
3094 // instances from static names
3095 SESEandAgePair p = new SESEandAgePair( fsen, 0 );
3096 if( fsen.getParent() != null &&
3097 //!fsen.getParent().getIsCallerSESEplaceholder() &&
3098 fsen.getParent().getNeededStaticNames().contains( p )
3101 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3102 SESEandAgePair p1 = new SESEandAgePair( fsen, i );
3103 SESEandAgePair p2 = new SESEandAgePair( fsen, i-1 );
3104 output.println(" "+p1+" = "+p2+";");
3106 output.println(" "+p+" = seseToIssue;");
3110 // if there were no outstanding dependencies, issue here
3111 output.println(" if( seseToIssue->common.unresolvedDependencies == 0 ) {");
3112 output.println(" workScheduleSubmit( (void*)seseToIssue );");
3113 output.println(" }");
3115 // release this SESE for siblings to update its dependencies or,
3116 // eventually, for it to mark itself finished
3117 output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3118 output.println(" }");
3122 public void generateFlatSESEExitNode( FlatMethod fm,
3124 FlatSESEExitNode fsexn,
3128 // if MLP flag is off, okay that SESE nodes are in IR graph,
3129 // just skip over them and code generates exactly the same
3134 // get the enter node for this exit that has meta data embedded
3135 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
3137 // there may be an SESE in an unreachable method, skip over
3138 if( !mlpa.getAllSESEs().contains( fsen ) ) {
3142 // also, if we have encountered a placeholder, just jump it
3143 if( fsen.getIsCallerSESEplaceholder() ) {
3147 output.println(" /* SESE exiting */");
3149 String com = paramsprefix+"->common";
3151 // this SESE cannot be done until all of its children are done
3152 // so grab your own lock with the condition variable for watching
3153 // that the number of your running children is greater than zero
3154 output.println(" pthread_mutex_lock( &("+com+".lock) );");
3155 output.println(" while( "+com+".numRunningChildren > 0 ) {");
3156 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
3157 output.println(" }");
3159 // copy out-set from local temps into the sese record
3160 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
3161 while( itr.hasNext() ) {
3162 TempDescriptor temp = itr.next();
3164 // only have to do this for primitives
3165 if( !temp.getType().isPrimitive() ) {
3169 // have to determine the context enclosing this sese
3170 boolean useParentContext = false;
3172 if( fsen != mlpa.getMainSESE() ) {
3173 assert fsen.getParent() != null;
3174 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3175 useParentContext = true;
3180 if( useParentContext ) {
3181 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
3183 from = generateTemp( fsen.getfmEnclosing(), temp, null );
3186 output.println(" "+paramsprefix+
3187 "->"+temp.getSafeSymbol()+
3191 // mark yourself done, your SESE data is now read-only
3192 output.println(" "+com+".doneExecuting = TRUE;");
3193 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
3194 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
3196 // decrement dependency count for all SESE's on your forwarding list
3197 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
3198 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
3199 output.println(" pthread_mutex_lock( &(consumer->lock) );");
3200 output.println(" --(consumer->unresolvedDependencies);");
3201 output.println(" if( consumer->unresolvedDependencies == 0 ) {");
3202 output.println(" workScheduleSubmit( (void*)consumer );");
3203 output.println(" }");
3204 output.println(" pthread_mutex_unlock( &(consumer->lock) );");
3205 output.println(" }");
3207 // if parent is stalling on you, let them know you're done
3208 if( fsexn.getFlatEnter() != mlpa.getMainSESE() ) {
3209 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
3212 // last of all, decrement your parent's number of running children
3213 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
3214 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
3215 output.println(" --("+paramsprefix+"->common.parent->numRunningChildren);");
3216 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
3217 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
3218 output.println(" }");
3220 // this is a thread-only variable that can be handled when critical sese-to-sese
3221 // data has been taken care of--set sese pointer to remember self over method
3222 // calls to a non-zero, invalid address
3223 output.println(" seseCaller = (SESEcommon*) 0x1;");
3226 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
3228 FlatWriteDynamicVarNode fwdvn,
3232 // should node should not be in an IR graph if the
3233 // MLP flag is not set
3234 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
3237 Hashtable<TempDescriptor, VariableSourceToken> writeDynamic =
3240 assert writeDynamic != null;
3242 Iterator wdItr = writeDynamic.entrySet().iterator();
3243 while( wdItr.hasNext() ) {
3244 Map.Entry me = (Map.Entry) wdItr.next();
3245 TempDescriptor refVar = (TempDescriptor) me.getKey();
3246 VariableSourceToken vst = (VariableSourceToken) me.getValue();
3248 FlatSESEEnterNode current = fwdvn.getEnclosingSESE();
3250 // only do this if the variable in question should be tracked,
3251 // meaning that it was explicitly added to the dynamic var set
3252 if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
3256 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
3258 output.println(" {");
3260 if( current.equals( vst.getSESE() ) ) {
3261 // if the src comes from this SESE, it's a method local variable,
3262 // mark src pointer NULL to signify that the var is up-to-date
3263 output.println(" "+vst.getAddrVar()+"_srcSESE = NULL;");
3266 // otherwise we track where it will come from
3267 output.println(" "+vst.getAddrVar()+"_srcSESE = "+instance+";");
3268 output.println(" "+vst.getAddrVar()+"_srcOffset = (int) &((("+
3269 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
3272 output.println(" }");
3277 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
3278 if (state.CONSCHECK) {
3279 String specname=fcn.getSpec();
3280 String varname="repairstate___";
3281 output.println("{");
3282 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
3284 TempDescriptor[] temps=fcn.getTemps();
3285 String[] vars=fcn.getVars();
3286 for(int i=0; i<temps.length; i++) {
3287 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
3290 output.println("if (doanalysis"+specname+"("+varname+")) {");
3291 output.println("free"+specname+"_state("+varname+");");
3292 output.println("} else {");
3293 output.println("/* Bad invariant */");
3294 output.println("free"+specname+"_state("+varname+");");
3295 output.println("abort_task();");
3296 output.println("}");
3297 output.println("}");
3301 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
3303 if( state.MLP && !nonSESEpass ) {
3304 output.println(" seseCaller = (SESEcommon*)"+paramsprefix+";");
3307 MethodDescriptor md=fc.getMethod();
3308 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
3309 ClassDescriptor cn=md.getClassDesc();
3310 output.println("{");
3311 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3313 LocalityBinding fclb=locality.getBinding(lb, fc);
3314 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3316 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3318 output.print(objectparams.numPointers());
3319 output.print(", "+localsprefixaddr);
3320 if (md.getThis()!=null) {
3322 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
3324 if (fc.getThis()!=null&&md.getThis()==null) {
3325 System.out.println("WARNING!!!!!!!!!!!!");
3326 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
3330 for(int i=0; i<fc.numArgs(); i++) {
3331 Descriptor var=md.getParameter(i);
3332 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3333 if (objectparams.isParamPtr(paramtemp)) {
3334 TempDescriptor targ=fc.getArg(i);
3336 TypeDescriptor td=md.getParamType(i);
3338 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3340 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3343 output.println("};");
3348 if (fc.getReturnTemp()!=null)
3349 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
3351 /* Do we need to do virtual dispatch? */
3352 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
3355 LocalityBinding fclb=locality.getBinding(lb, fc);
3356 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3358 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3363 if (md.getReturnType().isClass()||md.getReturnType().isArray())
3364 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3366 output.print(md.getReturnType().getSafeSymbol()+" ");
3367 output.print("(*)(");
3369 boolean printcomma=false;
3370 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3372 LocalityBinding fclb=locality.getBinding(lb, fc);
3373 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3375 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3379 for(int i=0; i<objectparams.numPrimitives(); i++) {
3380 TempDescriptor temp=objectparams.getPrimitive(i);
3384 if (temp.getType().isClass()||temp.getType().isArray())
3385 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
3387 output.print(temp.getType().getSafeSymbol());
3392 LocalityBinding fclb=locality.getBinding(lb, fc);
3393 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
3395 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
3399 boolean needcomma=false;
3400 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3401 output.print("&__parameterlist__");
3405 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
3406 if (fc.getThis()!=null) {
3407 TypeDescriptor ptd=md.getThis().getType();
3410 if (ptd.isClass()&&!ptd.isArray())
3411 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3412 output.print(generateTemp(fm,fc.getThis(),lb));
3417 for(int i=0; i<fc.numArgs(); i++) {
3418 Descriptor var=md.getParameter(i);
3419 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3420 if (objectparams.isParamPrim(paramtemp)) {
3421 TempDescriptor targ=fc.getArg(i);
3425 TypeDescriptor ptd=md.getParamType(i);
3426 if (ptd.isClass()&&!ptd.isArray())
3427 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3428 output.print(generateTemp(fm, targ,lb));
3432 output.println(");");
3433 output.println(" }");
3436 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
3437 Set subclasses=typeutil.getSubClasses(thiscd);
3438 if (subclasses==null)
3440 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
3441 ClassDescriptor cd=(ClassDescriptor)classit.next();
3442 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
3443 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
3444 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
3445 if (md.matches(matchmd))
3452 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
3453 if (state.SINGLETM) {
3454 //single machine transactional memory case
3455 String field=ffn.getField().getSafeSymbol();
3456 String src=generateTemp(fm, ffn.getSrc(),lb);
3457 String dst=generateTemp(fm, ffn.getDst(),lb);
3459 output.println(dst+"="+ src +"->"+field+ ";");
3460 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
3461 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
3462 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
3463 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
3464 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
3465 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
3466 output.println("TRANSREADRD("+dst+", "+dst+");");
3469 } else if (state.DSM) {
3470 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
3471 if (status==LocalityAnalysis.GLOBAL) {
3472 String field=ffn.getField().getSafeSymbol();
3473 String src=generateTemp(fm, ffn.getSrc(),lb);
3474 String dst=generateTemp(fm, ffn.getDst(),lb);
3476 if (ffn.getField().getType().isPtr()) {
3478 //TODO: Uncomment this when we have runtime support
3479 //if (ffn.getSrc()==ffn.getDst()) {
3480 //output.println("{");
3481 //output.println("void * temp="+src+";");
3482 //output.println("if (temp&0x1) {");
3483 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
3484 //output.println(src+"->"+field+"="+temp+";");
3485 //output.println("}");
3486 //output.println(dst+"=temp;");
3487 //output.println("}");
3489 output.println(dst+"="+ src +"->"+field+ ";");
3490 //output.println("if ("+dst+"&0x1) {");
3491 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3492 //output.println(src+"->"+field+"="+src+"->"+field+";");
3493 //output.println("}");
3496 output.println(dst+"="+ src+"->"+field+";");
3498 } else if (status==LocalityAnalysis.LOCAL) {
3499 if (ffn.getField().getType().isPtr()&&
3500 ffn.getField().isGlobal()) {
3501 String field=ffn.getField().getSafeSymbol();
3502 String src=generateTemp(fm, ffn.getSrc(),lb);
3503 String dst=generateTemp(fm, ffn.getDst(),lb);
3504 output.println(dst+"="+ src +"->"+field+ ";");
3505 if (locality.getAtomic(lb).get(ffn).intValue()>0)
3506 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3508 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3509 } else if (status==LocalityAnalysis.EITHER) {
3510 //Code is reading from a null pointer
3511 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
3512 output.println("#ifndef RAW");
3513 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
3514 output.println("#endif");
3515 //This should throw a suitable null pointer error
3516 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3518 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
3520 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3524 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
3525 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
3526 throw new Error("Can't set array length");
3527 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3528 //Single Machine Transaction Case
3529 boolean srcptr=fsfn.getSrc().getType().isPtr();
3530 String src=generateTemp(fm,fsfn.getSrc(),lb);
3531 String dst=generateTemp(fm,fsfn.getDst(),lb);
3532 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
3533 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
3534 output.println("{");
3535 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
3536 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
3537 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3539 output.println("INTPTR srcoid=(INTPTR)"+src+";");
3542 if (wb.needBarrier(fsfn)&&
3543 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
3544 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
3546 if (srcptr&!fsfn.getSrc().getType().isNull()) {
3547 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
3548 output.println("}");
3550 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3552 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3553 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
3554 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
3555 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
3557 String src=generateTemp(fm,fsfn.getSrc(),lb);
3558 String dst=generateTemp(fm,fsfn.getDst(),lb);
3560 output.println("{");
3561 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3563 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
3566 if (wb.needBarrier(fsfn))
3567 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
3569 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
3571 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3572 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
3573 /** Check if we need to copy */
3574 output.println("if(!"+dst+"->"+localcopystr+") {");
3575 /* Link object into list */
3576 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3577 output.println(revertptr+"=revertlist;");
3578 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3579 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3581 output.println("COPY_OBJ("+dst+");");
3582 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3583 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3584 output.println("}");
3586 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
3588 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3589 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
3590 //writing to a null...bad
3591 output.println("if ("+dst+") {");
3592 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
3594 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
3596 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3599 output.println("}");
3602 if (state.FASTCHECK) {
3603 String dst=generateTemp(fm, fsfn.getDst(),lb);
3604 output.println("if(!"+dst+"->"+localcopystr+") {");
3605 /* Link object into list */
3606 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3607 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3609 output.println("COPY_OBJ("+dst+");");
3610 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3611 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3612 output.println("}");
3614 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
3618 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
3619 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
3622 if (elementtype.isArray()||elementtype.isClass())
3625 type=elementtype.getSafeSymbol()+" ";
3627 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
3628 output.println("if ("+generateTemp(fm, fen.getIndex(),lb)+"< 0 | "+generateTemp(fm, fen.getIndex(),lb)+" >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___)");
3629 output.println("failedboundschk();");
3631 if (state.SINGLETM) {
3632 //Single machine transaction case
3633 String dst=generateTemp(fm, fen.getDst(),lb);
3634 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3636 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
3637 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
3638 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
3639 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
3640 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
3641 output.println("TRANSREADRD("+dst+", "+dst+");");
3644 } else if (state.DSM) {
3645 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
3646 if (status==LocalityAnalysis.GLOBAL) {
3647 String dst=generateTemp(fm, fen.getDst(),lb);
3649 if (elementtype.isPtr()) {
3650 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3651 output.println("TRANSREAD("+dst+", "+dst+");");
3653 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3655 } else if (status==LocalityAnalysis.LOCAL) {
3656 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3657 } else if (status==LocalityAnalysis.EITHER) {
3658 //Code is reading from a null pointer
3659 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
3660 output.println("#ifndef RAW");
3661 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
3662 output.println("#endif");
3663 //This should throw a suitable null pointer error
3664 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3666 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
3668 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3672 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
3673 //TODO: need dynamic check to make sure this assignment is actually legal
3674 //Because Object[] could actually be something more specific...ie. Integer[]
3676 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
3679 if (elementtype.isArray()||elementtype.isClass())
3682 type=elementtype.getSafeSymbol()+" ";
3684 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
3685 output.println("if ("+generateTemp(fm, fsen.getIndex(),lb)+"< 0 | "+generateTemp(fm, fsen.getIndex(),lb)+" >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___)");
3686 output.println("failedboundschk();");
3689 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
3690 //Transaction set element case
3691 if (wb.needBarrier(fsen)&&
3692 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
3693 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
3695 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
3696 output.println("{");
3697 String src=generateTemp(fm, fsen.getSrc(), lb);
3698 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
3699 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
3700 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3702 output.println("INTPTR srcoid=(INTPTR)"+src+";");
3704 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
3705 output.println("}");
3707 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3709 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
3710 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
3711 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
3712 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
3713 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
3714 boolean dstlocal=statusdst==LocalityAnalysis.LOCAL;
3717 if (wb.needBarrier(fsen))
3718 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
3719 } else if (dstlocal) {
3720 /** Check if we need to copy */
3721 String dst=generateTemp(fm, fsen.getDst(),lb);
3722 output.println("if(!"+dst+"->"+localcopystr+") {");
3723 /* Link object into list */
3724 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3725 output.println(revertptr+"=revertlist;");
3726 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
3727 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3729 output.println("COPY_OBJ("+dst+");");
3730 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3731 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3732 output.println("}");
3733 } else throw new Error("Unknown array type");
3735 output.println("{");
3736 String src=generateTemp(fm, fsen.getSrc(), lb);
3737 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3738 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
3739 output.println("}");
3741 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3744 if (state.FASTCHECK) {
3745 String dst=generateTemp(fm, fsen.getDst(),lb);
3746 output.println("if(!"+dst+"->"+localcopystr+") {");
3747 /* Link object into list */
3748 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3749 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3751 output.println("COPY_OBJ("+dst+");");
3752 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3753 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
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)+";");
3760 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
3761 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
3762 //Stash pointer in case of GC
3763 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3764 output.println(revertptr+"=revertlist;");
3766 if (state.SINGLETM) {
3767 if (fn.getType().isArray()) {
3768 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
3769 if (locality.getAtomic(lb).get(fn).intValue()>0) {
3770 //inside transaction
3771 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3773 //outside transaction
3774 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3777 if (locality.getAtomic(lb).get(fn).intValue()>0) {
3778 //inside transaction
3779 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3781 //outside transaction
3782 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3785 } else if (fn.getType().isArray()) {
3786 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
3787 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
3788 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3789 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3790 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3792 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3795 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
3796 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
3797 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3798 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3800 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
3803 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
3804 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3805 String dst=generateTemp(fm,fn.getDst(),lb);
3806 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
3807 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3808 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3810 if (state.FASTCHECK) {
3811 String dst=generateTemp(fm,fn.getDst(),lb);
3812 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
3813 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3814 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3818 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
3819 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3820 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
3822 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
3826 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
3827 if (fon.getRight()!=null) {
3828 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
3829 if (fon.getLeft().getType().isLong())
3830 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
3832 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
3834 } else if (dc!=null) {
3835 output.print(generateTemp(fm, fon.getDest(),lb)+" = ");
3836 if (dc.getNeedLeftSrcTrans(lb, fon))
3837 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
3839 output.print(generateTemp(fm, fon.getLeft(),lb));
3840 output.print(fon.getOp().toString());
3841 if (dc.getNeedRightSrcTrans(lb, fon))
3842 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL);");
3844 output.println(generateTemp(fm,fon.getRight(),lb)+";");
3846 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
3847 } else if (fon.getOp().getOp()==Operation.ASSIGN)
3848 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
3849 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
3850 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
3851 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
3852 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
3853 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
3854 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
3855 else if (fon.getOp().getOp()==Operation.COMP)
3856 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
3857 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
3858 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
3860 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
3863 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
3864 /* TODO: Do type check here */
3865 if (fcn.getType().isArray()) {
3866 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
3867 } else if (fcn.getType().isClass())
3868 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
3870 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
3873 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
3874 if (fln.getValue()==null)
3875 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
3876 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
3877 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3878 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
3879 //Stash pointer in case of GC
3880 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3881 output.println(revertptr+"=revertlist;");
3883 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
3884 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
3885 //Stash pointer in case of GC
3886 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3887 output.println("revertlist="+revertptr+";");
3890 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
3892 } else if (fln.getType().isBoolean()) {
3893 if (((Boolean)fln.getValue()).booleanValue())
3894 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
3896 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
3897 } else if (fln.getType().isChar()) {
3898 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
3899 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
3900 } else if (fln.getType().isLong()) {
3901 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
3903 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
3906 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
3907 if (frn.getReturnTemp()!=null) {
3908 if (frn.getReturnTemp().getType().isPtr())
3909 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
3911 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
3913 output.println("return;");
3917 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
3918 output.println("STOREANDBRANCH(!"+generateTemp(fm, fcb.getTest(),lb)+", "+label+");");
3921 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
3922 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
3925 /** This method generates header information for the method or
3926 * task referenced by the Descriptor des. */
3927 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
3928 generateHeader(fm, lb, des, output, false);
3931 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
3933 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
3934 MethodDescriptor md=null;
3935 TaskDescriptor task=null;
3936 if (des instanceof MethodDescriptor)
3937 md=(MethodDescriptor) des;
3939 task=(TaskDescriptor) des;
3941 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
3943 if (md!=null&&md.getReturnType()!=null) {
3944 if (md.getReturnType().isClass()||md.getReturnType().isArray())
3945 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3947 output.print(md.getReturnType().getSafeSymbol()+" ");
3949 //catch the constructor case
3950 output.print("void ");
3952 if (state.DSM||state.SINGLETM) {
3953 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
3955 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
3957 output.print(task.getSafeSymbol()+"(");
3959 boolean printcomma=false;
3960 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3962 if (state.DSM||state.SINGLETM) {
3963 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
3965 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
3967 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
3973 for(int i=0; i<objectparams.numPrimitives(); i++) {
3974 TempDescriptor temp=objectparams.getPrimitive(i);
3978 if (temp.getType().isClass()||temp.getType().isArray())
3979 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
3981 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
3983 output.println(") {");
3984 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
3985 /* Imprecise Task */
3986 output.println("void * parameterarray[]) {");
3987 /* Unpack variables */
3988 for(int i=0; i<objectparams.numPrimitives(); i++) {
3989 TempDescriptor temp=objectparams.getPrimitive(i);
3990 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
3992 for(int i=0; i<fm.numTags(); i++) {
3993 TempDescriptor temp=fm.getTag(i);
3994 int offset=i+objectparams.numPrimitives();
3995 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
3998 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
3999 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
4000 } else output.println(") {");
4003 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
4004 output.println("/* FlatFlagActionNode */");
4007 /* Process tag changes */
4008 Relation tagsettable=new Relation();
4009 Relation tagcleartable=new Relation();
4011 Iterator tagsit=ffan.getTempTagPairs();
4012 while (tagsit.hasNext()) {
4013 TempTagPair ttp=(TempTagPair) tagsit.next();
4014 TempDescriptor objtmp=ttp.getTemp();
4015 TagDescriptor tag=ttp.getTag();
4016 TempDescriptor tagtmp=ttp.getTagTemp();
4017 boolean tagstatus=ffan.getTagChange(ttp);
4019 tagsettable.put(objtmp, tagtmp);
4021 tagcleartable.put(objtmp, tagtmp);
4026 Hashtable flagandtable=new Hashtable();
4027 Hashtable flagortable=new Hashtable();
4029 /* Process flag changes */
4030 Iterator flagsit=ffan.getTempFlagPairs();
4031 while(flagsit.hasNext()) {
4032 TempFlagPair tfp=(TempFlagPair)flagsit.next();
4033 TempDescriptor temp=tfp.getTemp();
4034 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
4035 FlagDescriptor flag=tfp.getFlag();
4037 //Newly allocate objects that don't set any flags case
4038 if (flagortable.containsKey(temp)) {
4042 flagortable.put(temp,new Integer(mask));
4044 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
4045 boolean flagstatus=ffan.getFlagChange(tfp);
4048 if (flagortable.containsKey(temp)) {
4049 mask=((Integer)flagortable.get(temp)).intValue();
4052 flagortable.put(temp,new Integer(mask));
4054 int mask=0xFFFFFFFF;
4055 if (flagandtable.containsKey(temp)) {
4056 mask=((Integer)flagandtable.get(temp)).intValue();
4058 mask&=(0xFFFFFFFF^flagid);
4059 flagandtable.put(temp,new Integer(mask));
4065 HashSet flagtagset=new HashSet();
4066 flagtagset.addAll(flagortable.keySet());
4067 flagtagset.addAll(flagandtable.keySet());
4068 flagtagset.addAll(tagsettable.keySet());
4069 flagtagset.addAll(tagcleartable.keySet());
4071 Iterator ftit=flagtagset.iterator();
4072 while(ftit.hasNext()) {
4073 TempDescriptor temp=(TempDescriptor)ftit.next();
4076 Set tagtmps=tagcleartable.get(temp);
4077 if (tagtmps!=null) {
4078 Iterator tagit=tagtmps.iterator();
4079 while(tagit.hasNext()) {
4080 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4081 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4082 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4084 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4088 tagtmps=tagsettable.get(temp);
4089 if (tagtmps!=null) {
4090 Iterator tagit=tagtmps.iterator();
4091 while(tagit.hasNext()) {
4092 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4093 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4094 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4096 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
4101 int andmask=0xFFFFFFF;
4103 if (flagortable.containsKey(temp))
4104 ormask=((Integer)flagortable.get(temp)).intValue();
4105 if (flagandtable.containsKey(temp))
4106 andmask=((Integer)flagandtable.get(temp)).intValue();
4107 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
4108 generateObjectDistribute(ffan, fm, lb, temp, output);
4112 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
4113 PrintWriter output, int ormask, int andmask) {
4114 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
4115 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4117 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4121 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
4122 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
4125 void generateOptionalHeader(PrintWriter headers) {
4128 headers.println("#include \"task.h\"\n\n");
4129 headers.println("#ifndef _OPTIONAL_STRUCT_");
4130 headers.println("#define _OPTIONAL_STRUCT_");
4132 //STRUCT PREDICATEMEMBER
4133 headers.println("struct predicatemember{");
4134 headers.println("int type;");
4135 headers.println("int numdnfterms;");
4136 headers.println("int * flags;");
4137 headers.println("int numtags;");
4138 headers.println("int * tags;\n};\n\n");
4140 //STRUCT OPTIONALTASKDESCRIPTOR
4141 headers.println("struct optionaltaskdescriptor{");
4142 headers.println("struct taskdescriptor * task;");
4143 headers.println("int index;");
4144 headers.println("int numenterflags;");
4145 headers.println("int * enterflags;");
4146 headers.println("int numpredicatemembers;");
4147 headers.println("struct predicatemember ** predicatememberarray;");
4148 headers.println("};\n\n");
4150 //STRUCT TASKFAILURE
4151 headers.println("struct taskfailure {");
4152 headers.println("struct taskdescriptor * task;");
4153 headers.println("int index;");
4154 headers.println("int numoptionaltaskdescriptors;");
4155 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4157 //STRUCT FSANALYSISWRAPPER
4158 headers.println("struct fsanalysiswrapper{");
4159 headers.println("int flags;");
4160 headers.println("int numtags;");
4161 headers.println("int * tags;");
4162 headers.println("int numtaskfailures;");
4163 headers.println("struct taskfailure ** taskfailurearray;");
4164 headers.println("int numoptionaltaskdescriptors;");
4165 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4167 //STRUCT CLASSANALYSISWRAPPER
4168 headers.println("struct classanalysiswrapper{");
4169 headers.println("int type;");
4170 headers.println("int numotd;");
4171 headers.println("struct optionaltaskdescriptor ** otdarray;");
4172 headers.println("int numfsanalysiswrappers;");
4173 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
4175 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
4177 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
4178 while(taskit.hasNext()) {
4179 TaskDescriptor td=(TaskDescriptor)taskit.next();
4180 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
4185 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
4186 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
4187 int predicateindex = 0;
4188 //iterate through the classes concerned by the predicate
4189 Set c_vard = predicate.vardescriptors;
4190 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
4193 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
4194 VarDescriptor vard = (VarDescriptor)vard_it.next();
4195 TypeDescriptor typed = vard.getType();
4197 //generate for flags
4198 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
4199 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4201 if (fen_hashset!=null) {
4202 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
4203 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
4205 DNFFlag dflag=fen.getDNF();
4206 numberterms+=dflag.size();
4208 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
4210 for(int j=0; j<dflag.size(); j++) {
4212 output.println(",");
4213 Vector term=dflag.get(j);
4216 for(int k=0; k<term.size(); k++) {
4217 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
4218 FlagDescriptor fd=dfa.getFlag();
4219 boolean negated=dfa.getNegated();
4220 int flagid=1<<((Integer)flags.get(fd)).intValue();
4225 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
4230 output.println("};\n");
4233 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
4234 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4237 for(int j=0; j<tagel.numTags(); j++) {
4239 output.println(",");
4240 TempDescriptor tmp=tagel.getTemp(j);
4241 if (!slotnumber.containsKey(tmp)) {
4242 Integer slotint=new Integer(current_slot++);
4243 slotnumber.put(tmp,slotint);
4245 int slot=slotnumber.get(tmp).intValue();
4246 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
4248 numtags = tagel.numTags();
4250 output.println("};");
4252 //store the result into a predicatemember struct
4253 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4254 output.println("/*type*/"+typed.getClassDesc().getId()+",");
4255 output.println("/* number of dnf terms */"+numberterms+",");
4256 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4257 output.println("/* number of tag */"+numtags+",");
4258 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4259 output.println("};\n");
4264 //generate an array that stores the entire predicate
4265 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4266 for( int j = 0; j<predicateindex; j++) {
4267 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4268 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4270 output.println("};\n");
4271 return predicateindex;
4275 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
4276 generateOptionalHeader(headers);
4278 output.println("#include \"optionalstruct.h\"\n\n");
4279 output.println("#include \"stdlib.h\"\n");
4281 HashSet processedcd = new HashSet();
4283 Enumeration e = safeexecution.keys();
4284 while (e.hasMoreElements()) {
4287 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
4288 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
4290 //Generate the struct of optionals
4291 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4292 numotd = c_otd.size();
4293 if(maxotd<numotd) maxotd = numotd;
4294 if( !c_otd.isEmpty() ) {
4295 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4296 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4298 //generate the int arrays for the predicate
4299 Predicate predicate = otd.predicate;
4300 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
4301 TreeSet<Integer> fsset=new TreeSet<Integer>();
4302 //iterate through possible FSes corresponding to
4303 //the state when entering
4305 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
4306 FlagState fs = (FlagState)fses.next();
4308 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4309 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4310 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4313 fsset.add(new Integer(flagid));
4314 //tag information not needed because tag
4315 //changes are not tolerated.
4318 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4319 boolean needcomma=false;
4320 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
4323 output.println(it.next());
4326 output.println("};\n");
4329 //generate optionaltaskdescriptor that actually
4330 //includes exit fses, predicate and the task
4332 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4333 output.println("&task_"+otd.td.getSafeSymbol()+",");
4334 output.println("/*index*/"+otd.getIndex()+",");
4335 output.println("/*number of enter flags*/"+fsset.size()+",");
4336 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4337 output.println("/*number of members */"+predicateindex+",");
4338 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4339 output.println("};\n");
4343 // if there are no optionals, there is no need to build the rest of the struct
4345 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
4346 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4347 if( !c_otd.isEmpty() ) {
4348 boolean needcomma=false;
4349 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4350 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4352 output.println(",");
4354 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4357 output.println("};\n");
4359 //get all the possible flagstates reachable by an object
4360 Hashtable hashtbtemp = safeexecution.get(cdtemp);
4362 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
4363 fsts.addAll(hashtbtemp.keySet());
4364 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
4365 FlagState fs = (FlagState)fsit.next();
4368 //get the set of OptionalTaskDescriptors corresponding
4369 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
4370 //iterate through the OptionalTaskDescriptors and
4371 //store the pointers to the optionals struct (see on
4372 //top) into an array
4374 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
4375 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
4376 OptionalTaskDescriptor mm = mos.next();
4378 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
4380 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4383 output.println("};\n");
4385 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
4388 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4389 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4390 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4394 //process tag information
4397 boolean first = true;
4398 Enumeration tag_enum = fs.getTags();
4399 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4400 while(tag_enum.hasMoreElements()) {
4402 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
4406 output.println(", ");
4407 output.println("/*tagid*/"+state.getTagId(tagd));
4409 output.println("};");
4411 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
4412 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4413 TaskIndex ti=itti.next();
4417 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
4419 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
4420 boolean needcomma=false;
4421 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
4422 OptionalTaskDescriptor otd=otdit.next();
4426 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4428 output.println("};");
4430 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
4431 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
4432 output.print(ti.getIndex()+", ");
4433 output.print(otdset.size()+", ");
4434 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
4435 output.println("};");
4438 tiset=sa.getTaskIndex(fs);
4439 boolean needcomma=false;
4441 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4442 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4443 TaskIndex ti=itti.next();
4444 if (ti.isRuntime()) {
4451 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
4453 output.println("};\n");
4455 //Store the result in fsanalysiswrapper
4457 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
4458 output.println("/*flag*/"+flagid+",");
4459 output.println("/* number of tags*/"+tagcounter+",");
4460 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4461 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
4462 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4463 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
4464 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
4465 output.println("};\n");
4469 //Build the array of fsanalysiswrappers
4470 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
4471 boolean needcomma=false;
4472 for(int i = 0; i<fscounter; i++) {
4473 if (needcomma) output.print(",");
4474 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
4477 output.println("};");
4479 //Build the classanalysiswrapper referring to the previous array
4480 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
4481 output.println("/*type*/"+cdtemp.getId()+",");
4482 output.println("/*numotd*/"+numotd+",");
4483 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
4484 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
4485 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
4486 processedcd.add(cdtemp);
4489 //build an array containing every classes for which code has been build
4490 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
4491 for(int i=0; i<state.numClasses(); i++) {
4492 ClassDescriptor cn=cdarray[i];
4495 if ((cn != null) && (processedcd.contains(cn)))
4496 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
4498 output.print("NULL");
4500 output.println("};");
4502 output.println("#define MAXOTD "+maxotd);
4503 headers.println("#endif");
4506 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
4507 Relation r=new Relation();
4508 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
4509 OptionalTaskDescriptor otd=otdit.next();
4510 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
4514 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
4515 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
4516 Set s=r.get(it.next());
4517 for(Iterator it2=s.iterator(); it2.hasNext();) {
4518 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
4526 protected void outputTransCode(PrintWriter output) {