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
237 // first generate code for each sese's internals
238 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
239 FlatSESEEnterNode fsen = seseit.next();
240 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
243 // then write the invokeSESE switch to decouple scheduler
244 // from having to do unique details of sese invocation
245 generateSESEinvocationMethod(outmethodheader, outmethod);
249 /* Output code for tasks */
250 outputTaskCode(outtaskdefs, outmethod);
252 /* Record maximum number of task parameters */
253 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
254 } else if (state.main!=null) {
255 /* Generate main method */
256 outputMainMethod(outmethod);
259 /* Generate information for task with optional parameters */
260 if (state.TASK&&state.OPTIONAL) {
261 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
262 outoptionalarrays.close();
265 /* Output structure definitions for repair tool */
266 if (state.structfile!=null) {
267 buildRepairStructs(outrepairstructs);
268 outrepairstructs.close();
272 outmethodheader.println("#endif");
273 outmethodheader.close();
275 outstructs.println("#endif");
280 /* This code just generates the main C method for java programs.
281 * The main C method packs up the arguments into a string array
282 * and passes it to the java main method. */
284 private void outputMainMethod(PrintWriter outmethod) {
285 outmethod.println("int main(int argc, const char *argv[]) {");
286 outmethod.println(" int i;");
289 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
293 outmethod.println("#ifdef TRANSSTATS \n");
294 outmethod.println("handle();\n");
295 outmethod.println("#endif\n");
297 if (state.THREAD||state.DSM||state.SINGLETM) {
298 outmethod.println("initializethreads();");
301 outmethod.println("if (dstmStartup(argv[1])) {");
302 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
303 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
305 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
308 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
309 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
311 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
315 outmethod.println(" for(i=2;i<argc;i++) {");
317 outmethod.println(" for(i=1;i<argc;i++) {");
318 outmethod.println(" int length=strlen(argv[i]);");
319 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
320 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
322 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
325 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
327 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
328 outmethod.println(" }");
330 MethodDescriptor md=typeutil.getMain();
331 ClassDescriptor cd=typeutil.getMainClass();
333 outmethod.println(" {");
334 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
335 if (state.DSM||state.SINGLETM) {
336 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
338 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
339 outmethod.println("1, NULL,"+"stringarray};");
340 if (state.DSM||state.SINGLETM)
341 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
343 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
345 if (state.DSM||state.SINGLETM)
346 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
348 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
350 outmethod.println(" }");
353 outmethod.println("}");
356 if (state.THREAD||state.DSM||state.SINGLETM) {
357 outmethod.println("pthread_mutex_lock(&gclistlock);");
358 outmethod.println("threadcount--;");
359 outmethod.println("pthread_cond_signal(&gccond);");
360 outmethod.println("pthread_mutex_unlock(&gclistlock);");
363 if (state.DSM||state.SINGLETM) {
364 outmethod.println("#ifdef TRANSSTATS \n");
365 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
366 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
367 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
368 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
370 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
371 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
372 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
373 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
374 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
375 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
376 } else if (state.SINGLETM) {
377 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
378 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
379 outmethod.println("#ifdef STMSTATS\n");
380 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
381 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
382 outmethod.println("}\n");
383 outmethod.println("#endif\n");
384 outmethod.println("fflush(stdout);");
386 outmethod.println("#endif\n");
389 if (state.THREAD||state.SINGLETM)
390 outmethod.println("pthread_exit(NULL);");
393 outmethod.println(" workScheduleBegin();");
396 outmethod.println("}");
399 /* This method outputs code for each task. */
401 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
402 /* Compile task based program */
403 outtaskdefs.println("#include \"task.h\"");
404 outtaskdefs.println("#include \"methodheaders.h\"");
405 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
406 while(taskit.hasNext()) {
407 TaskDescriptor td=(TaskDescriptor)taskit.next();
408 FlatMethod fm=state.getMethodFlat(td);
409 generateFlatMethod(fm, null, outmethod);
410 generateTaskDescriptor(outtaskdefs, fm, td);
413 //Output task descriptors
414 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
415 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
417 while(taskit.hasNext()) {
418 TaskDescriptor td=(TaskDescriptor)taskit.next();
422 outtaskdefs.println(",");
423 outtaskdefs.print("&task_"+td.getSafeSymbol());
425 outtaskdefs.println("};");
427 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
430 /* This method outputs most of the methods.c file. This includes
431 * some standard includes and then an array with the sizes of
432 * objets and array that stores supertype and then the code for
433 * the Java methods.. */
435 protected void outputMethods(PrintWriter outmethod) {
436 outmethod.println("#include \"methodheaders.h\"");
437 outmethod.println("#include \"virtualtable.h\"");
438 outmethod.println("#include \"runtime.h\"");
440 outmethod.println("#include \"addPrefetchEnhance.h\"");
441 outmethod.println("#include \"localobjects.h\"");
443 if (state.FASTCHECK) {
444 outmethod.println("#include \"localobjects.h\"");
446 if(state.MULTICORE) {
447 outmethod.println("#include \"task.h\"");
448 outmethod.println("#include \"multicoreruntime.h\"");
449 outmethod.println("#include \"runtime_arch.h\"");
451 if (state.THREAD||state.DSM||state.SINGLETM)
452 outmethod.println("#include <thread.h>");
453 if (state.main!=null) {
454 outmethod.println("#include <string.h>");
456 if (state.CONSCHECK) {
457 outmethod.println("#include \"checkers.h\"");
460 outmethod.println("#include <stdlib.h>");
461 outmethod.println("#include <stdio.h>");
462 outmethod.println("#include \"mlp_runtime.h\"");
463 outmethod.println("#include \"psemaphore.h\"");
467 //Store the sizes of classes & array elements
468 generateSizeArray(outmethod);
470 //Store table of supertypes
471 generateSuperTypeTable(outmethod);
473 //Store the layout of classes
474 generateLayoutStructs(outmethod);
476 /* Generate code for methods */
477 if (state.DSM||state.SINGLETM) {
478 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
479 LocalityBinding lb=lbit.next();
480 MethodDescriptor md=lb.getMethod();
481 FlatMethod fm=state.getMethodFlat(md);
483 if (!md.getModifiers().isNative()) {
484 generateFlatMethod(fm, lb, outmethod);
488 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
489 while(classit.hasNext()) {
490 ClassDescriptor cn=(ClassDescriptor)classit.next();
491 Iterator methodit=cn.getMethods();
492 while(methodit.hasNext()) {
493 /* Classify parameters */
494 MethodDescriptor md=(MethodDescriptor)methodit.next();
495 FlatMethod fm=state.getMethodFlat(md);
496 if (!md.getModifiers().isNative()) {
497 generateFlatMethod(fm, null, outmethod);
504 protected void outputStructs(PrintWriter outstructs) {
505 outstructs.println("#ifndef STRUCTDEFS_H");
506 outstructs.println("#define STRUCTDEFS_H");
507 outstructs.println("#include \"classdefs.h\"");
508 outstructs.println("#ifndef INTPTR");
509 outstructs.println("#ifdef BIT64");
510 outstructs.println("#define INTPTR long");
511 outstructs.println("#else");
512 outstructs.println("#define INTPTR int");
513 outstructs.println("#endif");
514 outstructs.println("#endif");
516 outstructs.println("#include \"mlp_runtime.h\"");
517 outstructs.println("#include \"psemaphore.h\"");
520 /* Output #defines that the runtime uses to determine type
521 * numbers for various objects it needs */
522 outstructs.println("#define MAXCOUNT "+maxcount);
523 if (state.DSM||state.SINGLETM) {
524 LocalityBinding lb=new LocalityBinding(typeutil.getRun(), false);
526 lb.setGlobalThis(LocalityAnalysis.GLOBAL);
527 else if (state.SINGLETM)
528 lb.setGlobalThis(LocalityAnalysis.NORMAL);
529 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lb));
532 outstructs.println("#define STRINGARRAYTYPE "+
533 (state.getArrayNumber(
534 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
536 outstructs.println("#define OBJECTARRAYTYPE "+
537 (state.getArrayNumber(
538 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
541 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
542 outstructs.println("#define CHARARRAYTYPE "+
543 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
545 outstructs.println("#define BYTEARRAYTYPE "+
546 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
548 outstructs.println("#define BYTEARRAYARRAYTYPE "+
549 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
551 outstructs.println("#define NUMCLASSES "+state.numClasses());
552 int totalClassSize = state.numClasses() + state.numArrays();
553 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
555 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
556 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
557 outstructs.println("#define TAGARRAYTYPE "+
558 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
562 protected void outputClassDeclarations(PrintWriter outclassdefs) {
563 if (state.THREAD||state.DSM||state.SINGLETM)
564 outclassdefs.println("#include <pthread.h>");
565 outclassdefs.println("#ifndef INTPTR");
566 outclassdefs.println("#ifdef BIT64");
567 outclassdefs.println("#define INTPTR long");
568 outclassdefs.println("#else");
569 outclassdefs.println("#define INTPTR int");
570 outclassdefs.println("#endif");
571 outclassdefs.println("#endif");
573 outclassdefs.println("#include \"optionalstruct.h\"");
574 outclassdefs.println("struct "+arraytype+";");
575 /* Start by declaring all structs */
576 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
577 while(it.hasNext()) {
578 ClassDescriptor cn=(ClassDescriptor)it.next();
579 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
581 outclassdefs.println("");
582 //Print out definition for array type
583 outclassdefs.println("struct "+arraytype+" {");
584 outclassdefs.println(" int type;");
586 outclassdefs.println(" pthread_t tid;");
587 outclassdefs.println(" void * lockentry;");
588 outclassdefs.println(" int lockcount;");
591 outclassdefs.println(" int flag;");
592 if(!state.MULTICORE) {
593 outclassdefs.println(" void * flagptr;");
595 outclassdefs.println(" int version;");
596 outclassdefs.println(" int * lock;"); // lock entry for this obj
597 outclassdefs.println(" void * mutex;");
598 outclassdefs.println(" int lockcount;");
599 if(state.MULTICOREGC) {
600 outclassdefs.println(" int marked;");
604 outclassdefs.println(" int numfses;");
605 outclassdefs.println(" int * fses;");
608 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
611 outclassdefs.println(" int paddingforarray;");
613 outclassdefs.println(" int ___length___;");
614 outclassdefs.println("};\n");
615 outclassdefs.println("extern int classsize[];");
616 outclassdefs.println("extern int hasflags[];");
617 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
618 outclassdefs.println("extern int supertypes[];");
621 /** Prints out definitions for generic task structures */
623 private void outputTaskTypes(PrintWriter outtask) {
624 outtask.println("#ifndef _TASK_H");
625 outtask.println("#define _TASK_H");
626 outtask.println("struct parameterdescriptor {");
627 outtask.println("int type;");
628 outtask.println("int numberterms;");
629 outtask.println("int *intarray;");
630 outtask.println("void * queue;");
631 outtask.println("int numbertags;");
632 outtask.println("int *tagarray;");
633 outtask.println("};");
635 outtask.println("struct taskdescriptor {");
636 outtask.println("void * taskptr;");
637 outtask.println("int numParameters;");
638 outtask.println(" int numTotal;");
639 outtask.println("struct parameterdescriptor **descriptorarray;");
640 outtask.println("char * name;");
641 outtask.println("};");
642 outtask.println("extern struct taskdescriptor * taskarray[];");
643 outtask.println("extern numtasks;");
644 outtask.println("#endif");
648 private void buildRepairStructs(PrintWriter outrepairstructs) {
649 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
650 while(classit.hasNext()) {
651 ClassDescriptor cn=(ClassDescriptor)classit.next();
652 outrepairstructs.println("structure "+cn.getSymbol()+" {");
653 outrepairstructs.println(" int __type__;");
655 outrepairstructs.println(" int __flag__;");
656 if(!state.MULTICORE) {
657 outrepairstructs.println(" int __flagptr__;");
660 printRepairStruct(cn, outrepairstructs);
661 outrepairstructs.println("}\n");
664 for(int i=0; i<state.numArrays(); i++) {
665 TypeDescriptor tdarray=arraytable[i];
666 TypeDescriptor tdelement=tdarray.dereference();
667 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
668 outrepairstructs.println(" int __type__;");
669 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
670 outrepairstructs.println(" int length;");
672 // Need to add support to repair tool for this
673 if (tdelement.isClass()||tdelement.isArray())
674 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
676 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
678 outrepairstructs.println("}\n");
682 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
683 ClassDescriptor sp=cn.getSuperDesc();
685 printRepairStruct(sp, output);
687 Vector fields=(Vector)fieldorder.get(cn);
689 for(int i=0; i<fields.size(); i++) {
690 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
691 if (fd.getType().isArray()) {
692 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
693 } else if (fd.getType().isClass())
694 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
695 else if (fd.getType().isFloat())
696 output.println(" int "+fd.getSymbol()+"; /* really float */");
698 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
702 /** This method outputs TaskDescriptor information */
703 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
704 for (int i=0; i<task.numParameters(); i++) {
705 VarDescriptor param_var=task.getParameter(i);
706 TypeDescriptor param_type=task.getParamType(i);
707 FlagExpressionNode param_flag=task.getFlag(param_var);
708 TagExpressionList param_tag=task.getTag(param_var);
711 if (param_flag==null) {
712 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
713 output.println("0x0, 0x0 };");
716 DNFFlag dflag=param_flag.getDNF();
717 dnfterms=dflag.size();
719 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
720 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
721 for(int j=0; j<dflag.size(); j++) {
724 Vector term=dflag.get(j);
727 for(int k=0; k<term.size(); k++) {
728 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
729 FlagDescriptor fd=dfa.getFlag();
730 boolean negated=dfa.getNegated();
731 int flagid=1<<((Integer)flags.get(fd)).intValue();
736 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
738 output.println("};");
741 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
742 //BUG...added next line to fix, test with any task program
744 for(int j=0; j<param_tag.numTags(); j++) {
747 /* for each tag we need */
748 /* which slot it is */
749 /* what type it is */
750 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
751 TempDescriptor tmp=param_tag.getTemp(j);
752 int slot=fm.getTagInt(tmp);
753 output.println(slot+", "+state.getTagId(tvd.getTag()));
755 output.println("};");
757 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
758 output.println("/* type */"+param_type.getClassDesc().getId()+",");
759 output.println("/* number of DNF terms */"+dnfterms+",");
760 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
761 output.println("0,");
762 //BUG, added next line to fix and else statement...test
763 //with any task program
765 output.println("/* number of tags */"+param_tag.numTags()+",");
767 output.println("/* number of tags */ 0,");
768 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
769 output.println("};");
773 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
774 for (int i=0; i<task.numParameters(); i++) {
777 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
779 output.println("};");
781 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
782 output.println("&"+task.getSafeSymbol()+",");
783 output.println("/* number of parameters */" +task.numParameters() + ",");
784 int numtotal=task.numParameters()+fm.numTags();
785 output.println("/* number total parameters */" +numtotal + ",");
786 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
787 output.println("\""+task.getSymbol()+"\"");
788 output.println("};");
792 /** The buildVirtualTables method outputs the virtual dispatch
793 * tables for methods. */
795 protected void buildVirtualTables(PrintWriter outvirtual) {
796 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
797 while(classit.hasNext()) {
798 ClassDescriptor cd=(ClassDescriptor)classit.next();
799 if (virtualcalls.getMethodCount(cd)>maxcount)
800 maxcount=virtualcalls.getMethodCount(cd);
802 MethodDescriptor[][] virtualtable=null;
803 LocalityBinding[][] lbvirtualtable=null;
804 if (state.DSM||state.SINGLETM)
805 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
807 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
809 /* Fill in virtual table */
810 classit=state.getClassSymbolTable().getDescriptorsIterator();
811 while(classit.hasNext()) {
812 ClassDescriptor cd=(ClassDescriptor)classit.next();
813 if (state.DSM||state.SINGLETM)
814 fillinRow(cd, lbvirtualtable, cd.getId());
816 fillinRow(cd, virtualtable, cd.getId());
819 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
820 Iterator arrayit=state.getArrayIterator();
821 while(arrayit.hasNext()) {
822 TypeDescriptor td=(TypeDescriptor)arrayit.next();
823 int id=state.getArrayNumber(td);
824 if (state.DSM||state.SINGLETM)
825 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
827 fillinRow(objectcd, virtualtable, id+state.numClasses());
830 outvirtual.print("void * virtualtable[]={");
831 boolean needcomma=false;
832 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
833 for(int j=0; j<maxcount; j++) {
835 outvirtual.print(", ");
836 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
837 LocalityBinding lb=lbvirtualtable[i][j];
838 MethodDescriptor md=lb.getMethod();
839 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
840 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
841 MethodDescriptor md=virtualtable[i][j];
842 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
844 outvirtual.print("0");
848 outvirtual.println("");
850 outvirtual.println("};");
854 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
855 /* Get inherited methods */
856 if (cd.getSuperDesc()!=null)
857 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
858 /* Override them with our methods */
859 for(Iterator it=cd.getMethods(); it.hasNext();) {
860 MethodDescriptor md=(MethodDescriptor)it.next();
861 if (md.isStatic()||md.getReturnType()==null)
863 int methodnum=virtualcalls.getMethodNumber(md);
864 virtualtable[rownum][methodnum]=md;
868 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
869 /* Get inherited methods */
870 if (cd.getSuperDesc()!=null)
871 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
872 /* Override them with our methods */
873 if (locality.getClassBindings(cd)!=null)
874 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
875 LocalityBinding lb=lbit.next();
876 MethodDescriptor md=lb.getMethod();
877 //Is the method static or a constructor
878 if (md.isStatic()||md.getReturnType()==null)
880 int methodnum=virtualcalls.getLocalityNumber(lb);
881 virtualtable[rownum][methodnum]=lb;
885 /** Generate array that contains the sizes of class objects. The
886 * object allocation functions in the runtime use this
889 private void generateSizeArray(PrintWriter outclassdefs) {
890 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
891 outclassdefs.print("#ifdef TRANSSTATS \n");
892 outclassdefs.print("extern int numTransAbort;\n");
893 outclassdefs.print("extern int numTransCommit;\n");
894 outclassdefs.print("extern int nSoftAbort;\n");
896 outclassdefs.print("extern int nchashSearch;\n");
897 outclassdefs.print("extern int nmhashSearch;\n");
898 outclassdefs.print("extern int nprehashSearch;\n");
899 outclassdefs.print("extern int nRemoteSend;\n");
900 outclassdefs.print("extern int bytesSent;\n");
901 outclassdefs.print("extern int bytesRecv;\n");
902 outclassdefs.print("extern void handle();\n");
903 } else if (state.SINGLETM) {
904 outclassdefs.println("extern int nSoftAbortAbort;");
905 outclassdefs.println("extern int nSoftAbortCommit;");
906 outclassdefs.println("#ifdef STMSTATS\n");
907 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
908 outclassdefs.println("#endif\n");
910 outclassdefs.print("#endif\n");
911 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
913 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
914 cdarray=new ClassDescriptor[state.numClasses()];
915 while(it.hasNext()) {
916 ClassDescriptor cd=(ClassDescriptor)it.next();
917 cdarray[cd.getId()]=cd;
920 arraytable=new TypeDescriptor[state.numArrays()];
922 Iterator arrayit=state.getArrayIterator();
923 while(arrayit.hasNext()) {
924 TypeDescriptor td=(TypeDescriptor)arrayit.next();
925 int id=state.getArrayNumber(td);
931 /* Print out types */
932 outclassdefs.println("/* ");
933 for(int i=0; i<state.numClasses(); i++) {
934 ClassDescriptor cd=cdarray[i];
935 outclassdefs.println(cd +" "+i);
938 for(int i=0; i<state.numArrays(); i++) {
939 TypeDescriptor arraytd=arraytable[i];
940 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
943 outclassdefs.println("*/");
946 outclassdefs.print("int classsize[]={");
948 boolean needcomma=false;
949 for(int i=0; i<state.numClasses(); i++) {
951 outclassdefs.print(", ");
952 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
957 for(int i=0; i<state.numArrays(); i++) {
959 outclassdefs.print(", ");
960 TypeDescriptor tdelement=arraytable[i].dereference();
961 if (tdelement.isArray()||tdelement.isClass())
962 outclassdefs.print("sizeof(void *)");
964 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
968 outclassdefs.println("};");
970 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
972 outclassdefs.print("int typearray[]={");
973 for(int i=0; i<state.numClasses(); i++) {
974 ClassDescriptor cd=cdarray[i];
975 ClassDescriptor supercd=cd.getSuperDesc();
977 outclassdefs.print(", ");
979 outclassdefs.print("-1");
981 outclassdefs.print(supercd.getId());
985 for(int i=0; i<state.numArrays(); i++) {
986 TypeDescriptor arraytd=arraytable[i];
987 ClassDescriptor arraycd=arraytd.getClassDesc();
990 outclassdefs.print(", ");
991 outclassdefs.print(objectclass.getId());
995 ClassDescriptor cd=arraycd.getSuperDesc();
998 TypeDescriptor supertd=new TypeDescriptor(cd);
999 supertd.setArrayCount(arraytd.getArrayCount());
1000 type=state.getArrayNumber(supertd);
1002 type+=state.numClasses();
1005 cd=cd.getSuperDesc();
1008 outclassdefs.print(", ");
1009 outclassdefs.print(type);
1013 outclassdefs.println("};");
1018 outclassdefs.print("int typearray2[]={");
1019 for(int i=0; i<state.numArrays(); i++) {
1020 TypeDescriptor arraytd=arraytable[i];
1021 ClassDescriptor arraycd=arraytd.getClassDesc();
1022 if (arraycd==null) {
1024 outclassdefs.print(", ");
1025 outclassdefs.print("-1");
1029 ClassDescriptor cd=arraycd.getSuperDesc();
1030 int level=arraytd.getArrayCount()-1;
1032 for(; level>0; level--) {
1033 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1034 supertd.setArrayCount(level);
1035 type=state.getArrayNumber(supertd);
1037 type+=state.numClasses();
1042 outclassdefs.print(", ");
1043 outclassdefs.print(type);
1047 outclassdefs.println("};");
1050 /** Constructs params and temp objects for each method or task.
1051 * These objects tell the compiler which temps need to be
1054 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1055 MethodDescriptor md=fm.getMethod();
1056 TaskDescriptor task=fm.getTask();
1057 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1058 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1060 paramstable.put(lb, objectparams);
1061 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1062 } else if (md!=null)
1063 paramstable.put(md, objectparams);
1065 paramstable.put(task, objectparams);
1067 for(int i=0; i<fm.numParameters(); i++) {
1068 TempDescriptor temp=fm.getParameter(i);
1069 TypeDescriptor type=temp.getType();
1070 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1071 objectparams.addPtr(temp);
1073 objectparams.addPrim(temp);
1074 if(lb!=null&&saveset.contains(temp)) {
1075 backuptable.get(lb).put(temp, temp.createNew());
1079 for(int i=0; i<fm.numTags(); i++) {
1080 TempDescriptor temp=fm.getTag(i);
1081 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1082 objectparams.addPtr(temp);
1084 objectparams.addPrim(temp);
1087 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1089 tempstable.put(lb, objecttemps);
1091 tempstable.put(md, objecttemps);
1093 tempstable.put(task, objecttemps);
1095 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1096 FlatNode fn=(FlatNode)nodeit.next();
1097 TempDescriptor[] writes=fn.writesTemps();
1098 for(int i=0; i<writes.length; i++) {
1099 TempDescriptor temp=writes[i];
1100 TypeDescriptor type=temp.getType();
1101 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1102 objecttemps.addPtr(temp);
1104 objecttemps.addPrim(temp);
1105 if(lb!=null&&saveset.contains(temp)&&
1106 !backuptable.get(lb).containsKey(temp))
1107 backuptable.get(lb).put(temp, temp.createNew());
1111 /* Create backup temps */
1113 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1114 TempDescriptor tmp=tmpit.next();
1115 TypeDescriptor type=tmp.getType();
1116 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1117 objecttemps.addPtr(tmp);
1119 objecttemps.addPrim(tmp);
1121 /* Create temp to hold revert table */
1122 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1123 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1124 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1125 objecttemps.addPtr(reverttmp);
1127 objecttemps.addPrim(reverttmp);
1128 reverttable.put(lb, reverttmp);
1133 /** This method outputs the following information about classes
1135 * (1) For classes, what are the locations of pointers.
1136 * (2) For arrays, does the array contain pointers or primitives.
1137 * (3) For classes, does the class contain flags.
1140 private void generateLayoutStructs(PrintWriter output) {
1141 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1142 while(it.hasNext()) {
1143 ClassDescriptor cn=(ClassDescriptor)it.next();
1144 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1145 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1147 while(allit.hasNext()) {
1148 FieldDescriptor fd=(FieldDescriptor)allit.next();
1149 TypeDescriptor type=fd.getType();
1150 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1155 output.print(count);
1156 allit=cn.getFieldTable().getAllDescriptorsIterator();
1157 while(allit.hasNext()) {
1158 FieldDescriptor fd=(FieldDescriptor)allit.next();
1159 TypeDescriptor type=fd.getType();
1160 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1163 output.println(",");
1164 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1167 output.println("};");
1169 output.println("unsigned INTPTR * pointerarray[]={");
1170 boolean needcomma=false;
1171 for(int i=0; i<state.numClasses(); i++) {
1172 ClassDescriptor cn=cdarray[i];
1174 output.println(",");
1176 output.print(cn.getSafeSymbol()+"_pointers");
1179 for(int i=0; i<state.numArrays(); i++) {
1181 output.println(", ");
1182 TypeDescriptor tdelement=arraytable[i].dereference();
1183 if (tdelement.isArray()||tdelement.isClass())
1184 output.print("((unsigned INTPTR *)1)");
1190 output.println("};");
1192 output.println("int hasflags[]={");
1193 for(int i=0; i<state.numClasses(); i++) {
1194 ClassDescriptor cn=cdarray[i];
1196 output.println(", ");
1203 output.println("};");
1206 /** Print out table to give us supertypes */
1207 private void generateSuperTypeTable(PrintWriter output) {
1208 output.println("int supertypes[]={");
1209 boolean needcomma=false;
1210 for(int i=0; i<state.numClasses(); i++) {
1211 ClassDescriptor cn=cdarray[i];
1213 output.println(",");
1215 if (cn.getSuperDesc()!=null) {
1216 ClassDescriptor cdsuper=cn.getSuperDesc();
1217 output.print(cdsuper.getId());
1221 output.println("};");
1224 /** Force consistent field ordering between inherited classes. */
1226 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1228 ClassDescriptor sp=cn.getSuperDesc();
1230 printClassStruct(sp, classdefout);
1232 if (!fieldorder.containsKey(cn)) {
1233 Vector fields=new Vector();
1234 fieldorder.put(cn,fields);
1235 Vector fieldvec=cn.getFieldVec();
1236 for(int i=0;i<fieldvec.size();i++) {
1237 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1238 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1242 Vector fields=(Vector)fieldorder.get(cn);
1244 for(int i=0; i<fields.size(); i++) {
1245 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1246 if (fd.getType().isClass()||fd.getType().isArray())
1247 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1249 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1254 /* Map flags to integers consistently between inherited
1257 protected void mapFlags(ClassDescriptor cn) {
1258 ClassDescriptor sp=cn.getSuperDesc();
1262 if (!flagorder.containsKey(cn)) {
1263 Hashtable flags=new Hashtable();
1264 flagorder.put(cn,flags);
1266 Hashtable superflags=(Hashtable)flagorder.get(sp);
1267 Iterator superflagit=superflags.keySet().iterator();
1268 while(superflagit.hasNext()) {
1269 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1270 Integer number=(Integer)superflags.get(fd);
1271 flags.put(fd, number);
1272 if ((number.intValue()+1)>max)
1273 max=number.intValue()+1;
1277 Iterator flagit=cn.getFlags();
1278 while(flagit.hasNext()) {
1279 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1280 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1281 flags.put(fd, new Integer(max++));
1287 /** This function outputs (1) structures that parameters are
1288 * passed in (when PRECISE GC is enabled) and (2) function
1289 * prototypes for the methods */
1291 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1292 /* Output class structure */
1293 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1294 classdefout.println(" int type;");
1296 classdefout.println(" pthread_t tid;");
1297 classdefout.println(" void * lockentry;");
1298 classdefout.println(" int lockcount;");
1302 classdefout.println(" int flag;");
1303 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1304 classdefout.println(" void * flagptr;");
1305 } else if (state.MULTICORE) {
1306 if(state.MULTICOREGC) {
1307 classdefout.println(" int marked;");
1309 classdefout.println(" int version;");
1310 classdefout.println(" int * lock;"); // lock entry for this obj
1311 classdefout.println(" void * mutex;");
1312 classdefout.println(" int lockcount;");
1314 if (state.OPTIONAL) {
1315 classdefout.println(" int numfses;");
1316 classdefout.println(" int * fses;");
1319 printClassStruct(cn, classdefout);
1320 classdefout.println("};\n");
1322 if (state.DSM||state.SINGLETM) {
1323 /* Cycle through LocalityBindings */
1324 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1325 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1327 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1328 LocalityBinding lb=lbit.next();
1329 MethodDescriptor md=lb.getMethod();
1330 if (md.getModifiers().isNative()) {
1331 //make sure we only print a native method once
1332 if (nativemethods.contains(md)) {
1333 FlatMethod fm=state.getMethodFlat(md);
1334 generateTempStructs(fm, lb);
1337 nativemethods.add(md);
1339 generateMethod(cn, md, lb, headersout, output);
1342 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1343 MethodDescriptor md=(MethodDescriptor)methodit.next();
1344 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1345 //Need to build param structure for library code
1346 FlatMethod fm=state.getMethodFlat(md);
1347 generateTempStructs(fm, null);
1348 generateMethodParam(cn, md, null, output);
1353 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1354 MethodDescriptor md=(MethodDescriptor)methodit.next();
1355 generateMethod(cn, md, null, headersout, output);
1359 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1360 /* Output parameter structure */
1361 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1362 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1363 if ((state.DSM||state.SINGLETM)&&lb!=null)
1364 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1366 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1367 output.println(" INTPTR size;");
1368 output.println(" void * next;");
1369 for(int i=0; i<objectparams.numPointers(); i++) {
1370 TempDescriptor temp=objectparams.getPointer(i);
1371 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1373 output.println("};\n");
1377 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1378 FlatMethod fm=state.getMethodFlat(md);
1379 generateTempStructs(fm, lb);
1381 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1382 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1384 generateMethodParam(cn, md, lb, output);
1386 /* Output temp structure */
1387 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1388 if (state.DSM||state.SINGLETM)
1389 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1391 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1392 output.println(" INTPTR size;");
1393 output.println(" void * next;");
1394 for(int i=0; i<objecttemps.numPointers(); i++) {
1395 TempDescriptor temp=objecttemps.getPointer(i);
1396 if (temp.getType().isNull())
1397 output.println(" void * "+temp.getSafeSymbol()+";");
1399 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1401 output.println("};\n");
1404 /********* Output method declaration ***********/
1405 if (state.DSM||state.SINGLETM) {
1406 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1408 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1410 /* First the return type */
1411 if (md.getReturnType()!=null) {
1412 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1413 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1415 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1417 //catch the constructor case
1418 headersout.print("void ");
1420 /* Next the method name */
1421 if (state.DSM||state.SINGLETM) {
1422 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1424 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1426 boolean printcomma=false;
1427 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1428 if (state.DSM||state.SINGLETM) {
1429 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1431 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1435 /* Output parameter list*/
1436 for(int i=0; i<objectparams.numPrimitives(); i++) {
1437 TempDescriptor temp=objectparams.getPrimitive(i);
1439 headersout.print(", ");
1441 if (temp.getType().isClass()||temp.getType().isArray())
1442 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1444 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1446 headersout.println(");\n");
1450 /** This function outputs (1) structures that parameters are
1451 * passed in (when PRECISE GC is enabled) and (2) function
1452 * prototypes for the tasks */
1454 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1455 /* Cycle through tasks */
1456 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1458 while(taskit.hasNext()) {
1459 /* Classify parameters */
1460 TaskDescriptor task=(TaskDescriptor)taskit.next();
1461 FlatMethod fm=state.getMethodFlat(task);
1462 generateTempStructs(fm, null);
1464 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1465 TempObject objecttemps=(TempObject) tempstable.get(task);
1467 /* Output parameter structure */
1468 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1469 output.println("struct "+task.getSafeSymbol()+"_params {");
1471 output.println(" INTPTR size;");
1472 output.println(" void * next;");
1473 for(int i=0; i<objectparams.numPointers(); i++) {
1474 TempDescriptor temp=objectparams.getPointer(i);
1475 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1478 output.println("};\n");
1479 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1480 maxtaskparams=objectparams.numPointers()+fm.numTags();
1484 /* Output temp structure */
1485 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1486 output.println("struct "+task.getSafeSymbol()+"_locals {");
1487 output.println(" INTPTR size;");
1488 output.println(" void * next;");
1489 for(int i=0; i<objecttemps.numPointers(); i++) {
1490 TempDescriptor temp=objecttemps.getPointer(i);
1491 if (temp.getType().isNull())
1492 output.println(" void * "+temp.getSafeSymbol()+";");
1493 else if(temp.getType().isTag())
1494 output.println(" struct "+
1495 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1497 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1499 output.println("};\n");
1502 /* Output task declaration */
1503 headersout.print("void " + task.getSafeSymbol()+"(");
1505 boolean printcomma=false;
1506 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1507 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1509 headersout.print("void * parameterarray[]");
1510 headersout.println(");\n");
1514 /***** Generate code for FlatMethod fm. *****/
1516 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1517 static int atomicmethodcount=0;
1519 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1520 if (State.PRINTFLAT)
1521 System.out.println(fm.printMethod());
1522 MethodDescriptor md=fm.getMethod();
1523 TaskDescriptor task=fm.getTask();
1524 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1525 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1527 HashSet<AtomicRecord> arset=null;
1529 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1531 if (atomicmethodmap==null)
1532 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1534 //fix these so we get right strings for local variables
1535 localsprefixaddr=localsprefix;
1536 localsprefixderef=localsprefix+"->";
1537 arset=new HashSet<AtomicRecord>();
1539 //Generate commit methods here
1540 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1541 FlatNode fn=fnit.next();
1542 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1543 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0) {
1544 //We have an atomic enter
1545 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1546 Set<FlatNode> exitset=faen.getExits();
1548 String methodname=md.getSymbol()+(atomicmethodcount++);
1549 AtomicRecord ar=new AtomicRecord();
1553 atomicmethodmap.put(faen, ar);
1555 //build data structure declaration
1556 output.println("struct atomicprimitives_"+methodname+" {");
1558 Set<FlatNode> recordset=delaycomp.livecode(lb);
1559 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1560 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1561 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1563 ar.reallivein=new HashSet(liveinto);
1565 ar.liveoutvirtualread=liveoutvirtualread;
1567 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1568 TempDescriptor tmp=it.next();
1569 //remove the pointers
1570 if (tmp.getType().isPtr()) {
1573 //let's print it here
1574 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1577 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1578 TempDescriptor tmp=it.next();
1579 //remove the pointers
1580 if (tmp.getType().isPtr()) {
1582 } else if (!liveinto.contains(tmp)) {
1583 //let's print it here
1584 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1587 output.println("};");
1589 //print out method name
1590 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) {");
1591 //build code for commit method
1593 //first define local primitives
1594 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1595 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1596 TempDescriptor tmp=tmpit.next();
1597 if (!tmp.getType().isPtr()) {
1598 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1599 //read from live into set
1600 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1603 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1607 //turn off write barrier generation
1609 state.SINGLETM=false;
1610 generateCode(faen, fm, lb, exitset, output, false);
1611 state.SINGLETM=true;
1612 //turn on write barrier generation
1614 output.println("}\n\n");
1618 //redefine these back to normal
1620 localsprefixaddr="&"+localsprefix;
1621 localsprefixderef=localsprefix+".";
1623 generateHeader(fm, lb, md!=null ? md : task,output);
1624 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1626 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1627 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1628 AtomicRecord ar=arit.next();
1629 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1633 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1634 if (md!=null&&(state.DSM||state.SINGLETM))
1635 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1636 else if (md!=null&&!(state.DSM||state.SINGLETM))
1637 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1639 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1641 output.print(objecttemp.numPointers()+",");
1642 output.print(paramsprefix);
1643 for(int j=0; j<objecttemp.numPointers(); j++)
1644 output.print(", NULL");
1645 output.println("};");
1648 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1649 TempDescriptor td=objecttemp.getPrimitive(i);
1650 TypeDescriptor type=td.getType();
1652 output.println(" void * "+td.getSafeSymbol()+";");
1653 else if (type.isClass()||type.isArray())
1654 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1656 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1659 /* Check to see if we need to do a GC if this is a
1660 * multi-threaded program...*/
1662 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1663 || this.state.MULTICOREGC) {
1664 //Don't bother if we aren't in recursive methods...The loops case will catch it
1665 if (callgraph.getAllMethods(md).contains(md)) {
1666 if (state.DSM&&lb.isAtomic())
1667 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1668 else if (this.state.MULTICOREGC) {
1669 output.println("if(gcflag) gc("+localsprefixaddr+");");
1671 output.println("if (needtocollect) checkcollect("+localsprefixaddr+");");
1675 generateCode(fm.getNext(0), fm, lb, null, output, true);
1677 output.println("}\n\n");
1681 protected void initializeSESE( FlatSESEEnterNode fsen ) {
1683 FlatMethod fm = fsen.getfmEnclosing();
1684 MethodDescriptor md = fm.getMethod();
1685 ClassDescriptor cn = md.getClassDesc();
1688 // Creates bogus method descriptor to index into tables
1689 Modifiers modBogus = new Modifiers();
1690 MethodDescriptor mdBogus =
1691 new MethodDescriptor( modBogus,
1692 new TypeDescriptor( TypeDescriptor.VOID ),
1693 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1696 mdBogus.setClassDesc( fsen.getcdEnclosing() );
1697 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1698 fsen.setfmBogus( fmBogus );
1699 fsen.setmdBogus( mdBogus );
1701 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1702 inSetAndOutSet.addAll( fsen.getInVarSet() );
1703 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1705 // Build paramsobj for bogus method descriptor
1706 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
1707 paramstable.put( mdBogus, objectparams );
1709 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1710 while( itr.hasNext() ) {
1711 TempDescriptor temp = itr.next();
1712 TypeDescriptor type = temp.getType();
1713 if( type.isPtr() ) {
1714 objectparams.addPtr( temp );
1716 objectparams.addPrim( temp );
1720 // Build normal temp object for bogus method descriptor
1721 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
1722 tempstable.put( mdBogus, objecttemps );
1724 for(Iterator nodeit=fsen.getNodeSet().iterator(); nodeit.hasNext();) {
1725 FlatNode fn=(FlatNode)nodeit.next();
1726 TempDescriptor[] writes=fn.writesTemps();
1727 for(int i=0; i<writes.length; i++) {
1728 TempDescriptor temp=writes[i];
1729 TypeDescriptor type=temp.getType();
1730 if (type.isPtr()&&GENERATEPRECISEGC) {
1731 objecttemps.addPtr(temp);
1733 objecttemps.addPrim(temp);
1739 protected void generateMethodSESE(FlatSESEEnterNode fsen,
1741 PrintWriter outputStructs,
1742 PrintWriter outputMethHead,
1743 PrintWriter outputMethods
1746 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
1748 TempObject objecttemps = (TempObject) tempstable.get( fsen.getmdBogus() );
1750 // generate locals structure
1751 outputStructs.println("struct "+fsen.getcdEnclosing().getSafeSymbol()+fsen.getmdBogus().getSafeSymbol()+"_"+fsen.getmdBogus().getSafeMethodDescriptor()+"_locals {");
1752 outputStructs.println(" INTPTR size;");
1753 outputStructs.println(" void * next;");
1754 for(int i=0; i<objecttemps.numPointers(); i++) {
1755 TempDescriptor temp=objecttemps.getPointer(i);
1756 if (temp.getType().isNull())
1757 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1759 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1761 outputStructs.println("};\n");
1764 // generate the SESE record structure
1765 outputStructs.println(fsen.getSESErecordName()+" {");
1767 // data common to any SESE, and it must be placed first so
1768 // a module that doesn't know what kind of SESE record this
1769 // is can cast the pointer to a common struct
1770 outputStructs.println(" SESEcommon common;");
1772 // then garbage list stuff
1773 outputStructs.println(" INTPTR size;");
1774 outputStructs.println(" void * next;");
1776 // in-set source tracking
1777 // in-vars that are READY come from parent, don't need anything
1778 // stuff STATIC needs a custom SESE pointer for each age pair
1779 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
1780 while( itrStaticInVarSrcs.hasNext() ) {
1781 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
1782 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
1785 // DYNAMIC stuff needs a source SESE ptr and offset
1786 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
1787 while( itrDynInVars.hasNext() ) {
1788 TempDescriptor dynInVar = itrDynInVars.next();
1789 outputStructs.println(" void* "+dynInVar+"_srcSESE;");
1790 outputStructs.println(" int "+dynInVar+"_srcOffset;");
1793 // space for all in and out set primitives
1794 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1795 inSetAndOutSet.addAll( fsen.getInVarSet() );
1796 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1798 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
1800 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1801 while( itr.hasNext() ) {
1802 TempDescriptor temp = itr.next();
1803 TypeDescriptor type = temp.getType();
1804 if( !type.isPtr() ) {
1805 inSetAndOutSetPrims.add( temp );
1809 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
1810 while( itrPrims.hasNext() ) {
1811 TempDescriptor temp = itrPrims.next();
1812 TypeDescriptor type = temp.getType();
1813 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
1816 for(int i=0; i<objectparams.numPointers(); i++) {
1817 TempDescriptor temp=objectparams.getPointer(i);
1818 if (temp.getType().isNull())
1819 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1821 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1824 outputStructs.println("};\n");
1827 // write method declaration to header file
1828 outputMethHead.print("void ");
1829 outputMethHead.print(fsen.getSESEmethodName()+"(");
1830 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
1831 outputMethHead.println(");\n");
1834 generateFlatMethodSESE( fsen.getfmBogus(),
1835 fsen.getcdEnclosing(),
1841 private void generateFlatMethodSESE(FlatMethod fm,
1843 FlatSESEEnterNode fsen,
1844 FlatSESEExitNode seseExit,
1848 MethodDescriptor md=fm.getMethod();
1850 output.print("void ");
1851 output.print(fsen.getSESEmethodName()+"(");
1852 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
1853 output.println("){\n");
1855 TempObject objecttemp=(TempObject) tempstable.get(md);
1857 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1858 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1859 output.print(objecttemp.numPointers()+",");
1860 output.print("(void*) &("+paramsprefix+"->size)");
1861 for(int j=0; j<objecttemp.numPointers(); j++)
1862 output.print(", NULL");
1863 output.println("};");
1866 output.println(" /* regular local primitives */");
1867 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1868 TempDescriptor td=objecttemp.getPrimitive(i);
1869 TypeDescriptor type=td.getType();
1871 output.println(" void * "+td.getSafeSymbol()+";");
1872 else if (type.isClass()||type.isArray())
1873 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1875 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1879 // declare variables for naming static SESE's
1880 output.println(" /* static SESE names */");
1881 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
1882 while( pItr.hasNext() ) {
1883 SESEandAgePair p = pItr.next();
1884 output.println(" void* "+p+";");
1887 // declare variables for tracking dynamic sources
1888 output.println(" /* dynamic variable sources */");
1889 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
1890 while( dynSrcItr.hasNext() ) {
1891 TempDescriptor dynSrcVar = dynSrcItr.next();
1892 output.println(" void* "+dynSrcVar+"_srcSESE;");
1893 output.println(" int "+dynSrcVar+"_srcOffset;");
1896 // declare local temps for in-set primitives, and if it is
1897 // a ready-source variable, get the value from the record
1898 output.println(" /* local temps for in-set primitives */");
1899 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
1900 while( itrInSet.hasNext() ) {
1901 TempDescriptor temp = itrInSet.next();
1902 TypeDescriptor type = temp.getType();
1903 if( !type.isPtr() ) {
1904 if( fsen.getReadyInVarSet().contains( temp ) ) {
1905 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
1907 output.println(" "+type+" "+temp+";");
1912 // declare local temps for out-set primitives if its not already
1913 // in the in-set, and it's value will get written so no problem
1914 output.println(" /* local temp for out-set prim, not already in the in-set */");
1915 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
1916 while( itrOutSet.hasNext() ) {
1917 TempDescriptor temp = itrOutSet.next();
1918 TypeDescriptor type = temp.getType();
1919 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
1920 output.println(" "+type+" "+temp+";");
1924 // copy in-set into place, ready vars were already
1925 // copied when the SESE was issued
1926 Iterator<TempDescriptor> tempItr;
1928 // static vars are from a known SESE
1929 tempItr = fsen.getStaticInVarSet().iterator();
1930 while( tempItr.hasNext() ) {
1931 TempDescriptor temp = tempItr.next();
1932 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
1933 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
1935 // can't grab something from this source until it is done
1936 output.println(" {");
1937 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+srcPair+";" );
1938 output.println(" pthread_mutex_lock( &(com->lock) );");
1939 output.println(" while( com->doneExecuting == FALSE ) {");
1940 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
1941 output.println(" }");
1942 output.println(" pthread_mutex_unlock( &(com->lock) );");
1944 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
1945 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
1947 output.println(" }");
1950 // dynamic vars come from an SESE and src
1951 tempItr = fsen.getDynamicInVarSet().iterator();
1952 while( tempItr.hasNext() ) {
1953 TempDescriptor temp = tempItr.next();
1955 // go grab it from the SESE source
1956 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
1958 // gotta wait until the source is done
1959 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+temp+"_srcSESE;" );
1960 output.println(" pthread_mutex_lock( &(com->lock) );");
1961 output.println(" while( com->doneExecuting == FALSE ) {");
1962 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
1963 output.println(" }");
1964 output.println(" pthread_mutex_unlock( &(com->lock) );");
1966 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
1967 " = *(("+temp.getType().toPrettyString()+"*) ("+
1968 paramsprefix+"->"+temp+"_srcSESE + "+
1969 paramsprefix+"->"+temp+"_srcOffset));");
1971 // or if the source was our parent, its in the record to grab
1972 output.println(" } else {");
1973 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
1974 " = "+paramsprefix+"->"+temp+";");
1975 output.println(" }");
1978 // Check to see if we need to do a GC if this is a
1979 // multi-threaded program...
1980 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1981 //Don't bother if we aren't in recursive methods...The loops case will catch it
1982 if (callgraph.getAllMethods(md).contains(md)) {
1983 if(this.state.MULTICOREGC) {
1984 output.println("if(gcflag) gc("+localsprefixaddr+");");
1986 output.println("if (needtocollect) checkcollect("+localsprefixaddr+");");
1991 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
1992 exitset.add(seseExit);
1995 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
1997 output.println("}\n\n");
2001 // when a new mlp thread is created for an issued SESE, it is started
2002 // by running this method which blocks on a cond variable until
2003 // it is allowed to transition to execute. Then a case statement
2004 // allows it to invoke the method with the proper SESE body, and after
2005 // exiting the SESE method, executes proper SESE exit code before the
2006 // thread can be destroyed
2007 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2008 PrintWriter outmethod
2011 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2012 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2013 outmethod.println( " int status;");
2014 outmethod.println( " char errmsg[128];");
2016 // generate a case for each SESE class that can be invoked
2017 outmethod.println( " switch( *((int*)seseRecord) ) {");
2018 outmethod.println( " ");
2019 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
2020 FlatSESEEnterNode fsen = seseit.next();
2022 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2023 outmethod.println( " case "+fsen.getIdentifier()+":");
2024 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2025 outmethod.println( " break;");
2026 outmethod.println( "");
2029 // default case should never be taken, error out
2030 outmethod.println( " default:");
2031 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2032 outmethod.println( " exit(-30);");
2033 outmethod.println( " break;");
2034 outmethod.println( " }");
2035 outmethod.println( " return NULL;");
2036 outmethod.println( "}\n\n");
2040 protected void generateCode(FlatNode first,
2043 Set<FlatNode> stopset,
2044 PrintWriter output, boolean firstpass) {
2046 /* Assign labels to FlatNode's if necessary.*/
2047 Hashtable<FlatNode, Integer> nodetolabel=assignLabels(first, stopset);
2049 Set<FlatNode> storeset=null;
2050 HashSet<FlatNode> genset=null;
2051 Set<FlatNode> unionset=null;
2053 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2054 storeset=delaycomp.livecode(lb);
2055 genset=new HashSet<FlatNode>();
2057 genset.addAll(delaycomp.getCannotDelay(lb));
2058 genset.addAll(delaycomp.getOther(lb));
2060 genset.addAll(delaycomp.getNotReady(lb));
2062 unionset=new HashSet<FlatNode>();
2063 unionset.addAll(storeset);
2064 unionset.addAll(genset);
2067 /* Do the actual code generation */
2068 FlatNode current_node=null;
2069 HashSet tovisit=new HashSet();
2070 HashSet visited=new HashSet();
2072 tovisit.add(first.getNext(0));
2075 while(current_node!=null||!tovisit.isEmpty()) {
2076 if (current_node==null) {
2077 current_node=(FlatNode)tovisit.iterator().next();
2078 tovisit.remove(current_node);
2079 } else if (tovisit.contains(current_node)) {
2080 tovisit.remove(current_node);
2082 visited.add(current_node);
2083 if (nodetolabel.containsKey(current_node)) {
2084 output.println("L"+nodetolabel.get(current_node)+":");
2086 if (state.INSTRUCTIONFAILURE) {
2087 if (state.THREAD||state.DSM||state.SINGLETM) {
2088 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2090 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2092 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2094 if (!state.DELAYCOMP||firstpass) {
2095 generateFlatNode(fm, lb, current_node, output);
2097 //store primitive variables in out set
2098 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2099 Set<TempDescriptor> liveout=ar.liveout;
2100 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2101 TempDescriptor tmp=tmpit.next();
2102 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2105 if (current_node.kind()!=FKind.FlatReturnNode) {
2106 output.println(" return;");
2109 } else if(current_node.numNext()==1) {
2111 if (state.MLP && current_node.kind()==FKind.FlatSESEEnterNode) {
2112 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2113 generateFlatNode(fm, lb, current_node, output);
2114 nextnode=fsen.getFlatExit().getNext(0);
2115 } else if (state.DELAYCOMP) {
2116 boolean specialprimitive=false;
2117 //skip literals...no need to add extra overhead
2118 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2119 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2120 if (!typedesc.isClass()&&!typedesc.isArray()) {
2121 specialprimitive=true;
2125 if (genset==null||genset.contains(current_node)||specialprimitive)
2126 generateFlatNode(fm, lb, current_node, output);
2127 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2128 TempDescriptor wrtmp=current_node.writesTemps()[0];
2130 //need to store value written by previous node
2131 if (wrtmp.getType().isPtr()) {
2132 //only lock the objects that may actually need locking
2133 if (recorddc.getNeedTrans(lb, current_node)) {
2134 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");");
2136 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");");
2139 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");");
2142 //need to read value read by previous node
2143 if (wrtmp.getType().isPtr()) {
2144 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");");
2146 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");");
2150 nextnode=current_node.getNext(0);
2153 generateFlatNode(fm, lb, current_node, output);
2154 nextnode=current_node.getNext(0);
2156 if (visited.contains(nextnode)) {
2157 output.println("goto L"+nodetolabel.get(nextnode)+";");
2160 current_node=nextnode;
2161 } else if (current_node.numNext()==2) {
2163 if (state.DELAYCOMP) {
2164 boolean computeside=false;
2166 //need to record which way it should go
2167 if (genset==null||genset.contains(current_node)) {
2168 if (storeset!=null&&storeset.contains(current_node)) {
2169 //need to store which way branch goes
2170 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2172 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2174 //which side to execute
2178 if (genset.contains(current_node)) {
2179 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2180 } else if (storeset.contains(current_node)) {
2182 output.println("RESTOREANDBRANCH(L"+nodetolabel.get(current_node.getNext(1))+");");
2184 //which side to execute
2189 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2191 if (leftset.size()==0)
2193 if (visited.contains(current_node.getNext(branch))) {
2194 //already visited -- build jump
2195 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2198 current_node=current_node.getNext(branch);
2201 if (!visited.contains(current_node.getNext(1)))
2202 tovisit.add(current_node.getNext(1));
2203 if (visited.contains(current_node.getNext(0))) {
2204 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2207 current_node=current_node.getNext(0);
2211 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2212 if (!visited.contains(current_node.getNext(1)))
2213 tovisit.add(current_node.getNext(1));
2214 if (visited.contains(current_node.getNext(0))) {
2215 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2218 current_node=current_node.getNext(0);
2220 } else throw new Error();
2224 /** This method assigns labels to FlatNodes */
2225 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2226 return assignLabels(first, null);
2229 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2230 HashSet tovisit=new HashSet();
2231 HashSet visited=new HashSet();
2233 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2236 /*Assign labels first. A node needs a label if the previous
2237 * node has two exits or this node is a join point. */
2239 while(!tovisit.isEmpty()) {
2240 FlatNode fn=(FlatNode)tovisit.iterator().next();
2245 if(lastset!=null&&lastset.contains(fn)) {
2246 // if last is not null and matches, don't go
2247 // any further for assigning labels
2251 for(int i=0; i<fn.numNext(); i++) {
2252 FlatNode nn=fn.getNext(i);
2255 //1) Edge >1 of node
2256 nodetolabel.put(nn,new Integer(labelindex++));
2258 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2262 nodetolabel.put(nn,new Integer(labelindex++));
2270 /** Generate text string that corresponds to the TempDescriptor td. */
2271 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2272 MethodDescriptor md=fm.getMethod();
2273 TaskDescriptor task=fm.getTask();
2274 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2276 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2277 //System.out.println("generateTemp returns " + td.getSafeSymbol());
2278 return td.getSafeSymbol();
2281 if (objecttemps.isLocalPtr(td)) {
2282 return localsprefixderef+td.getSafeSymbol();
2285 if (objecttemps.isParamPtr(td)) {
2286 return paramsprefix+"->"+td.getSafeSymbol();
2292 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2294 // insert pre-node actions from the code plan
2297 CodePlan cp = mlpa.getCodePlan( fn );
2300 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2302 // for each sese and age pair that this parent statement
2303 // must stall on, take that child's stall semaphore, the
2304 // copying of values comes after the statement
2305 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2306 while( vstItr.hasNext() ) {
2307 VariableSourceToken vst = vstItr.next();
2309 SESEandAgePair p = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2311 output.println(" {");
2312 output.println(" SESEcommon* common = (SESEcommon*) "+p+";");
2314 output.println(" pthread_mutex_lock( &(common->lock) );");
2315 output.println(" while( common->doneExecuting == FALSE ) {");
2316 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2317 output.println(" }");
2318 output.println(" pthread_mutex_unlock( &(common->lock) );");
2320 //output.println(" psem_take( &(common->stallSem) );");
2322 // copy things we might have stalled for
2323 output.println(" "+p.getSESE().getSESErecordName()+"* child = ("+
2324 p.getSESE().getSESErecordName()+"*) "+p+";");
2326 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2327 while( tdItr.hasNext() ) {
2328 TempDescriptor td = tdItr.next();
2329 output.println(" "+generateTemp( currentSESE.getfmBogus(), td, null )+
2330 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2333 output.println(" }");
2336 // for each variable with a dynamic source, stall just for that variable
2337 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2338 while( dynItr.hasNext() ) {
2339 TempDescriptor dynVar = dynItr.next();
2341 // only stall if the dynamic source is not yourself, denoted by src==NULL
2342 // otherwise the dynamic write nodes will have the local var up-to-date
2343 output.println(" {");
2344 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2345 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2346 output.println(" psem_take( &(common->stallSem) );");
2347 output.println(" "+generateTemp( currentSESE.getfmBogus(), dynVar, null )+
2348 " = *(("+dynVar.getType()+"*) ("+
2349 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2350 output.println(" }");
2351 output.println(" }");
2354 // for each assignment of a variable to rhs that has a dynamic source,
2355 // copy the dynamic sources
2356 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2357 while( dynAssignItr.hasNext() ) {
2358 Map.Entry me = (Map.Entry) dynAssignItr.next();
2359 TempDescriptor lhs = (TempDescriptor) me.getKey();
2360 TempDescriptor rhs = (TempDescriptor) me.getValue();
2361 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
2362 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2368 case FKind.FlatAtomicEnterNode:
2369 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
2372 case FKind.FlatAtomicExitNode:
2373 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
2376 case FKind.FlatInstanceOfNode:
2377 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
2380 case FKind.FlatSESEEnterNode:
2381 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
2384 case FKind.FlatSESEExitNode:
2385 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
2388 case FKind.FlatWriteDynamicVarNode:
2389 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
2392 case FKind.FlatGlobalConvNode:
2393 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
2396 case FKind.FlatTagDeclaration:
2397 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
2400 case FKind.FlatCall:
2401 generateFlatCall(fm, lb, (FlatCall) fn,output);
2404 case FKind.FlatFieldNode:
2405 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
2408 case FKind.FlatElementNode:
2409 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
2412 case FKind.FlatSetElementNode:
2413 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
2416 case FKind.FlatSetFieldNode:
2417 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
2421 generateFlatNew(fm, lb, (FlatNew) fn,output);
2424 case FKind.FlatOpNode:
2425 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
2428 case FKind.FlatCastNode:
2429 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
2432 case FKind.FlatLiteralNode:
2433 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
2436 case FKind.FlatReturnNode:
2437 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
2441 output.println("/* nop */");
2444 case FKind.FlatExit:
2445 output.println("/* exit */");
2448 case FKind.FlatBackEdge:
2449 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
2450 || (this.state.MULTICOREGC)) {
2451 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
2452 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
2453 } else if(this.state.MULTICOREGC) {
2454 output.println("if (gcflag) gc("+localsprefixaddr+");");
2456 output.println("if (needtocollect) checkcollect("+localsprefixaddr+");");
2458 output.println("/* nop */");
2461 case FKind.FlatCheckNode:
2462 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
2465 case FKind.FlatFlagActionNode:
2466 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
2469 case FKind.FlatPrefetchNode:
2470 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
2473 case FKind.FlatOffsetNode:
2474 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
2481 // insert post-node actions from the code-plan
2483 CodePlan cp = mlpa.getCodePlan( fn );
2490 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
2491 output.println("/* FlatOffsetNode */");
2492 FieldDescriptor fd=fofn.getField();
2493 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
2494 output.println("/* offset */");
2497 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
2498 if (state.PREFETCH) {
2499 Vector oids = new Vector();
2500 Vector fieldoffset = new Vector();
2501 Vector endoffset = new Vector();
2502 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
2503 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
2504 PrefetchPair pp = (PrefetchPair) it.next();
2505 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
2506 /* Find prefetches that can generate oid */
2507 if(statusbase == LocalityAnalysis.GLOBAL) {
2508 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
2510 } else if (statusbase == LocalityAnalysis.LOCAL) {
2511 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
2518 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
2519 output.println("{");
2520 output.println("/* prefetch */");
2521 output.println("/* prefetchid_" + fpn.siteid + " */");
2522 output.println("void * prefptr;");
2523 output.println("int tmpindex;");
2525 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
2526 /*Create C code for oid array */
2527 output.print(" unsigned int oidarray_[] = {");
2528 boolean needcomma=false;
2529 for (Iterator it = oids.iterator(); it.hasNext();) {
2532 output.print(it.next());
2535 output.println("};");
2537 /*Create C code for endoffset values */
2538 output.print(" unsigned short endoffsetarry_[] = {");
2540 for (Iterator it = endoffset.iterator(); it.hasNext();) {
2543 output.print(it.next());
2546 output.println("};");
2548 /*Create C code for Field Offset Values */
2549 output.print(" short fieldarry_[] = {");
2551 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
2554 output.print(it.next());
2557 output.println("};");
2558 /* make the prefetch call to Runtime */
2559 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
2560 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
2561 output.println(" }");
2562 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
2563 output.println(" } else {");
2564 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
2565 output.println(" }");
2566 output.println("}");
2570 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
2571 short offsetcount = 0;
2575 } else if (localbase) {
2576 for(; breakindex<pp.desc.size(); breakindex++) {
2577 Descriptor desc=pp.getDescAt(breakindex);
2578 if (desc instanceof FieldDescriptor) {
2579 FieldDescriptor fd=(FieldDescriptor)desc;
2580 if (fd.isGlobal()) {
2588 if (breakindex>pp.desc.size()) //all local
2591 TypeDescriptor lasttype=pp.base.getType();
2592 String basestr=generateTemp(fm, pp.base, lb);
2594 boolean maybenull=fm.getMethod().isStatic()||
2595 !pp.base.equals(fm.getParameter(0));
2597 for(int i=0; i<breakindex; i++) {
2598 String indexcheck="";
2600 Descriptor desc=pp.getDescAt(i);
2601 if (desc instanceof FieldDescriptor) {
2602 FieldDescriptor fd=(FieldDescriptor)desc;
2604 if (!teststr.equals(""))
2606 teststr+="((prefptr="+basestr+")!=NULL)";
2607 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
2609 basestr=basestr+"->"+fd.getSafeSymbol();
2612 lasttype=fd.getType();
2614 IndexDescriptor id=(IndexDescriptor)desc;
2615 indexcheck="((tmpindex=";
2616 for(int j=0; j<id.tddesc.size(); j++) {
2617 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
2619 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
2621 if (!teststr.equals(""))
2623 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
2624 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
2626 lasttype=lasttype.dereference();
2631 if (teststr.equals("")) {
2632 oid="((unsigned int)"+basestr+")";
2634 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
2638 for(int i = breakindex; i < pp.desc.size(); i++) {
2639 String newfieldoffset;
2640 Object desc = pp.getDescAt(i);
2641 if(desc instanceof FieldDescriptor) {
2642 FieldDescriptor fd=(FieldDescriptor)desc;
2643 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
2644 lasttype=fd.getType();
2646 newfieldoffset = "";
2647 IndexDescriptor id=(IndexDescriptor)desc;
2648 for(int j = 0; j < id.tddesc.size(); j++) {
2649 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
2651 newfieldoffset += id.offset.toString();
2652 lasttype=lasttype.dereference();
2654 fieldoffset.add(newfieldoffset);
2657 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
2658 base+=pp.desc.size()-breakindex;
2659 endoffset.add(new Short((short)base));
2664 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
2665 if (lb!=fgcn.getLocality())
2667 /* Have to generate flat globalconv */
2668 if (fgcn.getMakePtr()) {
2670 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
2672 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
2673 //need to do translation
2674 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
2675 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
2676 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
2680 /* Need to convert to OID */
2681 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
2682 if (fgcn.doConvert()||(delaycomp!=null&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
2683 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
2685 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
2691 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
2693 if (fion.getType().isArray()) {
2694 type=state.getArrayNumber(fion.getType())+state.numClasses();
2696 type=fion.getType().getClassDesc().getId();
2699 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
2700 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
2702 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
2705 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
2706 /* Check to see if we need to generate code for this atomic */
2707 if (locality==null) {
2708 output.println("pthread_mutex_lock(&atomiclock);");
2712 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
2716 if (state.DELAYCOMP) {
2717 AtomicRecord ar=atomicmethodmap.get(faen);
2719 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
2720 TempDescriptor tmp=tmpit.next();
2721 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2724 //copy outs that depend on path
2725 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
2726 TempDescriptor tmp=tmpit.next();
2727 if (!ar.livein.contains(tmp))
2728 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2732 /* Backup the temps. */
2733 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
2734 TempDescriptor tmp=tmpit.next();
2735 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
2738 output.println("goto transstart"+faen.getIdentifier()+";");
2740 /******* Print code to retry aborted transaction *******/
2741 output.println("transretry"+faen.getIdentifier()+":");
2744 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
2745 TempDescriptor tmp=tmpit.next();
2746 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
2750 /********* Need to revert local object store ********/
2751 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
2753 output.println("while ("+revertptr+") {");
2754 output.println("struct ___Object___ * tmpptr;");
2755 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
2756 output.println("REVERT_OBJ("+revertptr+");");
2757 output.println(revertptr+"=tmpptr;");
2758 output.println("}");
2760 /******* Tell the runtime to start the transaction *******/
2762 output.println("transstart"+faen.getIdentifier()+":");
2763 output.println("transStart();");
2765 if (state.ABORTREADERS) {
2766 output.println("if (_setjmp(aborttrans)) {");
2767 output.println(" goto transretry"+faen.getIdentifier()+"; }");
2771 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
2772 /* Check to see if we need to generate code for this atomic */
2773 if (locality==null) {
2774 output.println("pthread_mutex_unlock(&atomiclock);");
2777 if (locality.getAtomic(lb).get(faen).intValue()>0)
2779 //store the revert list before we lose the transaction object
2780 String revertptr=null;
2782 revertptr=generateTemp(fm, reverttable.get(lb),lb);
2783 output.println(revertptr+"=revertlist;");
2785 if (state.DELAYCOMP) {
2786 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
2789 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
2791 output.println("if (transCommit()) {");
2792 /* Transaction aborts if it returns true */
2793 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
2795 output.println("} else {");
2796 /* Need to commit local object store */
2797 output.println("while ("+revertptr+") {");
2798 output.println("struct ___Object___ * tmpptr;");
2799 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
2800 output.println("COMMIT_OBJ("+revertptr+");");
2801 output.println(revertptr+"=tmpptr;");
2802 output.println("}");
2804 output.println("}");
2805 if (state.DELAYCOMP) {
2807 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
2808 output.println("else {");
2809 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
2810 TempDescriptor tmp=tmpit.next();
2811 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
2813 output.println("}");
2817 public void generateFlatSESEEnterNode( FlatMethod fm,
2819 FlatSESEEnterNode fsen,
2823 // SESE nodes can be parsed for normal compilation, just skip over them
2827 output.println(" {");
2829 // before doing anything, lock your own record and increment the running children
2830 if( fsen != mlpa.getRootSESE() ) {
2831 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.lock) );");
2832 output.println(" ++("+paramsprefix+"->common.numRunningChildren);");
2833 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.lock) );");
2836 // just allocate the space for this record
2837 output.println(" "+fsen.getSESErecordName()+"* seseToIssue = ("+
2838 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
2839 fsen.getSESErecordName()+" ) );");
2841 // fill in common data
2842 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
2843 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
2845 output.println(" seseToIssue->common.forwardList = createQueue();");
2846 output.println(" seseToIssue->common.unresolvedDependencies = 0;");
2847 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
2848 output.println(" seseToIssue->common.doneExecuting = FALSE;");
2849 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
2850 output.println(" seseToIssue->common.numRunningChildren = 0;");
2852 if( fsen != mlpa.getRootSESE() ) {
2853 output.println(" seseToIssue->common.parent = (SESEcommon*) "+paramsprefix+";");
2855 output.println(" seseToIssue->common.parent = NULL;");
2858 // all READY in-vars should be copied now and be done with it
2859 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
2860 while( tempItr.hasNext() ) {
2861 TempDescriptor temp = tempItr.next();
2862 if( fsen != mlpa.getRootSESE() ) {
2863 output.println(" seseToIssue->"+temp+" = "+
2864 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
2866 output.println(" seseToIssue->"+temp+" = "+
2867 paramsprefix+"->"+temp+";");
2871 // before potentially adding this SESE to other forwarding lists,
2872 // create it's lock and take it immediately
2873 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
2874 output.println(" pthread_mutex_lock( &(seseToIssue->common.lock) );");
2876 if( fsen != mlpa.getRootSESE() ) {
2877 // count up outstanding dependencies, static first, then dynamic
2878 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
2879 while( staticSrcsItr.hasNext() ) {
2880 SESEandAgePair srcPair = staticSrcsItr.next();
2881 output.println(" {");
2882 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
2883 output.println(" pthread_mutex_lock( &(src->lock) );");
2884 output.println(" if( !isEmpty( src->forwardList ) &&");
2885 output.println(" seseToIssue == peekItem( src->forwardList ) ) {");
2886 output.println(" printf( \"This shouldnt already be here\\n\");");
2887 output.println(" exit( -1 );");
2888 output.println(" }");
2889 output.println(" if( !src->doneExecuting ) {");
2890 output.println(" addNewItem( src->forwardList, seseToIssue );");
2891 output.println(" ++(seseToIssue->common.unresolvedDependencies);");
2892 output.println(" }");
2893 output.println(" pthread_mutex_unlock( &(src->lock) );");
2894 output.println(" }");
2896 // whether or not it is an outstanding dependency, make sure
2897 // to pass the static name to the child's record
2898 output.println(" seseToIssue->"+srcPair+" = "+srcPair+";");
2901 // dynamic sources might already be accounted for in the static list,
2902 // so only add them to forwarding lists if they're not already there
2903 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
2904 while( dynVarsItr.hasNext() ) {
2905 TempDescriptor dynInVar = dynVarsItr.next();
2906 output.println(" {");
2907 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
2909 // the dynamic source is NULL if it comes from your own space--you can't pass
2910 // the address off to the new child, because you're not done executing and
2911 // might change the variable, so copy it right now
2912 output.println(" if( src != NULL ) {");
2913 output.println(" pthread_mutex_lock( &(src->lock) );");
2914 output.println(" if( isEmpty( src->forwardList ) ||");
2915 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
2916 output.println(" if( !src->doneExecuting ) {");
2917 output.println(" addNewItem( src->forwardList, seseToIssue );");
2918 output.println(" ++(seseToIssue->common.unresolvedDependencies);");
2919 output.println(" }");
2920 output.println(" }");
2921 output.println(" pthread_mutex_unlock( &(src->lock) );");
2922 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
2923 output.println(" } else {");
2924 output.println(" seseToIssue->"+dynInVar+" = "+dynInVar+";");
2925 output.println(" }");
2926 output.println(" }");
2928 // even if the value is already copied, make sure your NULL source
2929 // gets passed so child knows it already has the dynamic value
2930 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
2933 // maintain pointers for for finding dynamic SESE
2934 // instances from static names
2935 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
2936 SESEandAgePair p1 = new SESEandAgePair( fsen, i );
2937 SESEandAgePair p2 = new SESEandAgePair( fsen, i-1 );
2938 output.println(" "+p1+" = "+p2+";");
2940 SESEandAgePair p = new SESEandAgePair( fsen, 0 );
2941 output.println(" "+p+" = seseToIssue;");
2944 // if there were no outstanding dependencies, issue here
2945 output.println(" if( seseToIssue->common.unresolvedDependencies == 0 ) {");
2946 output.println(" workScheduleSubmit( (void*)seseToIssue );");
2947 output.println(" }");
2949 // release this SESE for siblings to update its dependencies or,
2950 // eventually, for it to mark itself finished
2951 output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
2952 output.println(" }");
2956 public void generateFlatSESEExitNode( FlatMethod fm,
2958 FlatSESEExitNode fsexn,
2962 // SESE nodes can be parsed for normal compilation, just skip over them
2966 String com = paramsprefix+"->common";
2968 // this SESE cannot be done until all of its children are done
2969 // so grab your own lock with the condition variable for watching
2970 // that the number of your running children is greater than zero
2971 output.println(" pthread_mutex_lock( &("+com+".lock) );");
2972 output.println(" while( "+com+".numRunningChildren > 0 ) {");
2973 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
2974 output.println(" }");
2975 //output.println(" pthread_mutex_unlock( &("+com+".lock) );");
2977 // copy out-set from local temps into the sese record
2978 Iterator<TempDescriptor> itr = fsexn.getFlatEnter().getOutVarSet().iterator();
2979 while( itr.hasNext() ) {
2980 TempDescriptor temp = itr.next();
2981 output.println(" "+paramsprefix+
2982 "->"+temp.getSafeSymbol()+
2983 " = "+temp.getSafeSymbol()+";" );
2986 // mark yourself done, your SESE data is now read-only
2987 //output.println(" pthread_mutex_lock( &("+com+".lock) );");
2988 output.println(" "+com+".doneExecuting = TRUE;");
2989 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
2990 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
2992 // decrement dependency count for all SESE's on your forwarding list
2993 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
2994 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
2995 output.println(" pthread_mutex_lock( &(consumer->lock) );");
2996 output.println(" --(consumer->unresolvedDependencies);");
2997 output.println(" if( consumer->unresolvedDependencies == 0 ) {");
2998 output.println(" workScheduleSubmit( (void*)consumer );");
2999 output.println(" }");
3000 output.println(" pthread_mutex_unlock( &(consumer->lock) );");
3001 output.println(" }");
3003 // if parent is stalling on you, let them know you're done
3004 if( fsexn.getFlatEnter() != mlpa.getRootSESE() ) {
3005 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
3008 // last of all, decrement your parent's number of running children
3009 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
3010 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
3011 output.println(" --("+paramsprefix+"->common.parent->numRunningChildren);");
3012 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
3013 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
3014 output.println(" }");
3017 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
3019 FlatWriteDynamicVarNode fwdvn,
3023 // should node should not be in an IR graph if the
3024 // MLP flag is not set
3025 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
3028 Hashtable<TempDescriptor, VariableSourceToken> writeDynamic =
3031 assert writeDynamic != null;
3033 Iterator wdItr = writeDynamic.entrySet().iterator();
3034 while( wdItr.hasNext() ) {
3035 Map.Entry me = (Map.Entry) wdItr.next();
3036 TempDescriptor refVar = (TempDescriptor) me.getKey();
3037 VariableSourceToken vst = (VariableSourceToken) me.getValue();
3039 FlatSESEEnterNode current = fwdvn.getEnclosingSESE();
3041 // only do this if the variable in question should be tracked,
3042 // meaning that it was explicitly added to the dynamic var set
3043 if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
3047 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
3049 output.println(" {");
3051 if( current.equals( vst.getSESE() ) ) {
3052 // if the src comes from this SESE, it's a method local variable,
3053 // mark src pointer NULL to signify that the var is up-to-date
3054 output.println(" "+vst.getAddrVar()+"_srcSESE = NULL;");
3057 // otherwise we track where it will come from
3058 output.println(" "+vst.getAddrVar()+"_srcSESE = "+instance+";");
3059 output.println(" "+vst.getAddrVar()+"_srcOffset = (int) &((("+
3060 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
3063 output.println(" }");
3068 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
3069 if (state.CONSCHECK) {
3070 String specname=fcn.getSpec();
3071 String varname="repairstate___";
3072 output.println("{");
3073 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
3075 TempDescriptor[] temps=fcn.getTemps();
3076 String[] vars=fcn.getVars();
3077 for(int i=0; i<temps.length; i++) {
3078 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
3081 output.println("if (doanalysis"+specname+"("+varname+")) {");
3082 output.println("free"+specname+"_state("+varname+");");
3083 output.println("} else {");
3084 output.println("/* Bad invariant */");
3085 output.println("free"+specname+"_state("+varname+");");
3086 output.println("abort_task();");
3087 output.println("}");
3088 output.println("}");
3092 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
3093 MethodDescriptor md=fc.getMethod();
3094 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
3095 ClassDescriptor cn=md.getClassDesc();
3096 output.println("{");
3097 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3099 LocalityBinding fclb=locality.getBinding(lb, fc);
3100 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3102 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3104 output.print(objectparams.numPointers());
3105 output.print(", "+localsprefixaddr);
3106 if (md.getThis()!=null) {
3108 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
3110 if (fc.getThis()!=null&&md.getThis()==null) {
3111 System.out.println("WARNING!!!!!!!!!!!!");
3112 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
3116 for(int i=0; i<fc.numArgs(); i++) {
3117 Descriptor var=md.getParameter(i);
3118 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3119 if (objectparams.isParamPtr(paramtemp)) {
3120 TempDescriptor targ=fc.getArg(i);
3122 TypeDescriptor td=md.getParamType(i);
3124 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3126 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3129 output.println("};");
3134 if (fc.getReturnTemp()!=null)
3135 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
3137 /* Do we need to do virtual dispatch? */
3138 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
3141 LocalityBinding fclb=locality.getBinding(lb, fc);
3142 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3144 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3149 if (md.getReturnType().isClass()||md.getReturnType().isArray())
3150 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3152 output.print(md.getReturnType().getSafeSymbol()+" ");
3153 output.print("(*)(");
3155 boolean printcomma=false;
3156 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3158 LocalityBinding fclb=locality.getBinding(lb, fc);
3159 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3161 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3165 for(int i=0; i<objectparams.numPrimitives(); i++) {
3166 TempDescriptor temp=objectparams.getPrimitive(i);
3170 if (temp.getType().isClass()||temp.getType().isArray())
3171 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
3173 output.print(temp.getType().getSafeSymbol());
3178 LocalityBinding fclb=locality.getBinding(lb, fc);
3179 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
3181 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
3185 boolean needcomma=false;
3186 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3187 output.print("&__parameterlist__");
3191 if (!GENERATEPRECISEGC) {
3192 if (fc.getThis()!=null) {
3193 TypeDescriptor ptd=md.getThis().getType();
3196 if (ptd.isClass()&&!ptd.isArray())
3197 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3198 output.print(generateTemp(fm,fc.getThis(),lb));
3203 for(int i=0; i<fc.numArgs(); i++) {
3204 Descriptor var=md.getParameter(i);
3205 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3206 if (objectparams.isParamPrim(paramtemp)) {
3207 TempDescriptor targ=fc.getArg(i);
3211 TypeDescriptor ptd=md.getParamType(i);
3212 if (ptd.isClass()&&!ptd.isArray())
3213 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3214 output.print(generateTemp(fm, targ,lb));
3218 output.println(");");
3219 output.println(" }");
3222 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
3223 Set subclasses=typeutil.getSubClasses(thiscd);
3224 if (subclasses==null)
3226 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
3227 ClassDescriptor cd=(ClassDescriptor)classit.next();
3228 Set possiblematches=cd.getMethodTable().getSet(md.getSymbol());
3229 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
3230 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
3231 if (md.matches(matchmd))
3238 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
3239 if (state.SINGLETM) {
3240 //single machine transactional memory case
3241 String field=ffn.getField().getSafeSymbol();
3242 String src=generateTemp(fm, ffn.getSrc(),lb);
3243 String dst=generateTemp(fm, ffn.getDst(),lb);
3245 output.println(dst+"="+ src +"->"+field+ ";");
3246 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
3247 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
3248 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
3249 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
3250 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
3251 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
3252 output.println("TRANSREADRD("+dst+", "+dst+");");
3255 } else if (state.DSM) {
3256 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
3257 if (status==LocalityAnalysis.GLOBAL) {
3258 String field=ffn.getField().getSafeSymbol();
3259 String src=generateTemp(fm, ffn.getSrc(),lb);
3260 String dst=generateTemp(fm, ffn.getDst(),lb);
3262 if (ffn.getField().getType().isPtr()) {
3264 //TODO: Uncomment this when we have runtime support
3265 //if (ffn.getSrc()==ffn.getDst()) {
3266 //output.println("{");
3267 //output.println("void * temp="+src+";");
3268 //output.println("if (temp&0x1) {");
3269 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
3270 //output.println(src+"->"+field+"="+temp+";");
3271 //output.println("}");
3272 //output.println(dst+"=temp;");
3273 //output.println("}");
3275 output.println(dst+"="+ src +"->"+field+ ";");
3276 //output.println("if ("+dst+"&0x1) {");
3277 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3278 //output.println(src+"->"+field+"="+src+"->"+field+";");
3279 //output.println("}");
3282 output.println(dst+"="+ src+"->"+field+";");
3284 } else if (status==LocalityAnalysis.LOCAL) {
3285 if (ffn.getField().getType().isPtr()&&
3286 ffn.getField().isGlobal()) {
3287 String field=ffn.getField().getSafeSymbol();
3288 String src=generateTemp(fm, ffn.getSrc(),lb);
3289 String dst=generateTemp(fm, ffn.getDst(),lb);
3290 output.println(dst+"="+ src +"->"+field+ ";");
3291 if (locality.getAtomic(lb).get(ffn).intValue()>0)
3292 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3294 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3295 } else if (status==LocalityAnalysis.EITHER) {
3296 //Code is reading from a null pointer
3297 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
3298 output.println("#ifndef RAW");
3299 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
3300 output.println("#endif");
3301 //This should throw a suitable null pointer error
3302 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3304 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
3306 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3310 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
3311 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
3312 throw new Error("Can't set array length");
3313 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3314 //Single Machine Transaction Case
3315 boolean srcptr=fsfn.getSrc().getType().isPtr();
3316 String src=generateTemp(fm,fsfn.getSrc(),lb);
3317 String dst=generateTemp(fm,fsfn.getDst(),lb);
3318 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
3319 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
3320 output.println("{");
3321 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
3322 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
3323 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3325 output.println("INTPTR srcoid=(INTPTR)"+src+";");
3328 if (wb.needBarrier(fsfn)&&
3329 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
3330 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
3332 if (srcptr&!fsfn.getSrc().getType().isNull()) {
3333 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
3334 output.println("}");
3336 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3338 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3339 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
3340 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
3341 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
3343 String src=generateTemp(fm,fsfn.getSrc(),lb);
3344 String dst=generateTemp(fm,fsfn.getDst(),lb);
3346 output.println("{");
3347 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3349 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
3352 if (wb.needBarrier(fsfn))
3353 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
3355 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
3357 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3358 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
3359 /** Check if we need to copy */
3360 output.println("if(!"+dst+"->"+localcopystr+") {");
3361 /* Link object into list */
3362 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3363 output.println(revertptr+"=revertlist;");
3364 if (GENERATEPRECISEGC)
3365 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3367 output.println("COPY_OBJ("+dst+");");
3368 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3369 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3370 output.println("}");
3372 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
3374 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3375 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
3376 //writing to a null...bad
3377 output.println("if ("+dst+") {");
3378 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
3380 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
3382 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3385 output.println("}");
3388 if (state.FASTCHECK) {
3389 String dst=generateTemp(fm, fsfn.getDst(),lb);
3390 output.println("if(!"+dst+"->"+localcopystr+") {");
3391 /* Link object into list */
3392 if (GENERATEPRECISEGC)
3393 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3395 output.println("COPY_OBJ("+dst+");");
3396 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3397 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3398 output.println("}");
3400 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
3404 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
3405 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
3408 if (elementtype.isArray()||elementtype.isClass())
3411 type=elementtype.getSafeSymbol()+" ";
3413 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
3414 output.println("if ("+generateTemp(fm, fen.getIndex(),lb)+"< 0 | "+generateTemp(fm, fen.getIndex(),lb)+" >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___)");
3415 output.println("failedboundschk();");
3417 if (state.SINGLETM) {
3418 //Single machine transaction case
3419 String dst=generateTemp(fm, fen.getDst(),lb);
3420 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3422 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
3423 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
3424 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
3425 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
3426 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
3427 output.println("TRANSREADRD("+dst+", "+dst+");");
3430 } else if (state.DSM) {
3431 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
3432 if (status==LocalityAnalysis.GLOBAL) {
3433 String dst=generateTemp(fm, fen.getDst(),lb);
3435 if (elementtype.isPtr()) {
3436 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3437 output.println("TRANSREAD("+dst+", "+dst+");");
3439 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3441 } else if (status==LocalityAnalysis.LOCAL) {
3442 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3443 } else if (status==LocalityAnalysis.EITHER) {
3444 //Code is reading from a null pointer
3445 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
3446 output.println("#ifndef RAW");
3447 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
3448 output.println("#endif");
3449 //This should throw a suitable null pointer error
3450 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3452 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
3454 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3458 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
3459 //TODO: need dynamic check to make sure this assignment is actually legal
3460 //Because Object[] could actually be something more specific...ie. Integer[]
3462 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
3465 if (elementtype.isArray()||elementtype.isClass())
3468 type=elementtype.getSafeSymbol()+" ";
3470 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
3471 output.println("if ("+generateTemp(fm, fsen.getIndex(),lb)+"< 0 | "+generateTemp(fm, fsen.getIndex(),lb)+" >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___)");
3472 output.println("failedboundschk();");
3475 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
3476 //Transaction set element case
3477 if (wb.needBarrier(fsen)&&
3478 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
3479 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
3481 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
3482 output.println("{");
3483 String src=generateTemp(fm, fsen.getSrc(), lb);
3484 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
3485 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
3486 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3488 output.println("INTPTR srcoid=(INTPTR)"+src+";");
3490 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
3491 output.println("}");
3493 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3495 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
3496 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
3497 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
3498 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
3499 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
3500 boolean dstlocal=statusdst==LocalityAnalysis.LOCAL;
3503 if (wb.needBarrier(fsen))
3504 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
3505 } else if (dstlocal) {
3506 /** Check if we need to copy */
3507 String dst=generateTemp(fm, fsen.getDst(),lb);
3508 output.println("if(!"+dst+"->"+localcopystr+") {");
3509 /* Link object into list */
3510 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3511 output.println(revertptr+"=revertlist;");
3512 if ((GENERATEPRECISEGC))
3513 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3515 output.println("COPY_OBJ("+dst+");");
3516 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3517 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3518 output.println("}");
3519 } else throw new Error("Unknown array type");
3521 output.println("{");
3522 String src=generateTemp(fm, fsen.getSrc(), lb);
3523 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3524 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
3525 output.println("}");
3527 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3530 if (state.FASTCHECK) {
3531 String dst=generateTemp(fm, fsen.getDst(),lb);
3532 output.println("if(!"+dst+"->"+localcopystr+") {");
3533 /* Link object into list */
3534 if (GENERATEPRECISEGC)
3535 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3537 output.println("COPY_OBJ("+dst+");");
3538 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3539 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3540 output.println("}");
3542 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3546 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
3547 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
3548 //Stash pointer in case of GC
3549 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3550 output.println(revertptr+"=revertlist;");
3552 if (state.SINGLETM) {
3553 if (fn.getType().isArray()) {
3554 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
3555 if (locality.getAtomic(lb).get(fn).intValue()>0) {
3556 //inside transaction
3557 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3559 //outside transaction
3560 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3563 if (locality.getAtomic(lb).get(fn).intValue()>0) {
3564 //inside transaction
3565 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3567 //outside transaction
3568 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3571 } else if (fn.getType().isArray()) {
3572 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
3573 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
3574 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3575 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3576 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3578 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3581 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
3582 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
3583 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3584 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3586 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
3589 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
3590 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3591 String dst=generateTemp(fm,fn.getDst(),lb);
3592 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
3593 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3594 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3596 if (state.FASTCHECK) {
3597 String dst=generateTemp(fm,fn.getDst(),lb);
3598 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
3599 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3600 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3604 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
3605 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3606 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
3608 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
3612 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
3613 if (fon.getRight()!=null) {
3614 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
3615 if (fon.getLeft().getType().isLong())
3616 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
3618 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
3620 } else if (dc!=null) {
3621 output.print(generateTemp(fm, fon.getDest(),lb)+" = ");
3622 if (dc.getNeedLeftSrcTrans(lb, fon))
3623 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
3625 output.print(generateTemp(fm, fon.getLeft(),lb));
3626 output.print(fon.getOp().toString());
3627 if (dc.getNeedRightSrcTrans(lb, fon))
3628 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL);");
3630 output.println(generateTemp(fm,fon.getRight(),lb)+";");
3632 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
3633 } else if (fon.getOp().getOp()==Operation.ASSIGN)
3634 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
3635 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
3636 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
3637 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
3638 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
3639 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
3640 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
3641 else if (fon.getOp().getOp()==Operation.COMP)
3642 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
3643 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
3644 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
3646 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
3649 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
3650 /* TODO: Do type check here */
3651 if (fcn.getType().isArray()) {
3652 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
3653 } else if (fcn.getType().isClass())
3654 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
3656 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
3659 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
3660 if (fln.getValue()==null)
3661 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
3662 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
3663 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3664 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
3665 //Stash pointer in case of GC
3666 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3667 output.println(revertptr+"=revertlist;");
3669 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
3670 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
3671 //Stash pointer in case of GC
3672 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3673 output.println("revertlist="+revertptr+";");
3676 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
3678 } else if (fln.getType().isBoolean()) {
3679 if (((Boolean)fln.getValue()).booleanValue())
3680 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
3682 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
3683 } else if (fln.getType().isChar()) {
3684 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
3685 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
3686 } else if (fln.getType().isLong()) {
3687 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
3689 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
3692 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
3693 if (frn.getReturnTemp()!=null) {
3694 if (frn.getReturnTemp().getType().isPtr())
3695 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
3697 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
3699 output.println("return;");
3703 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
3704 output.println("STOREANDBRANCH(!"+generateTemp(fm, fcb.getTest(),lb)+", "+label+");");
3707 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
3708 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
3711 /** This method generates header information for the method or
3712 * task referenced by the Descriptor des. */
3713 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
3714 generateHeader(fm, lb, des, output, false);
3717 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
3719 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
3720 MethodDescriptor md=null;
3721 TaskDescriptor task=null;
3722 if (des instanceof MethodDescriptor)
3723 md=(MethodDescriptor) des;
3725 task=(TaskDescriptor) des;
3727 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
3729 if (md!=null&&md.getReturnType()!=null) {
3730 if (md.getReturnType().isClass()||md.getReturnType().isArray())
3731 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3733 output.print(md.getReturnType().getSafeSymbol()+" ");
3735 //catch the constructor case
3736 output.print("void ");
3738 if (state.DSM||state.SINGLETM) {
3739 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
3741 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
3743 output.print(task.getSafeSymbol()+"(");
3746 if (addSESErecord) {
3747 output.print("SESErecord* currentSESE, ");
3751 boolean printcomma=false;
3752 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3754 if (state.DSM||state.SINGLETM) {
3755 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
3757 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
3759 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
3765 for(int i=0; i<objectparams.numPrimitives(); i++) {
3766 TempDescriptor temp=objectparams.getPrimitive(i);
3770 if (temp.getType().isClass()||temp.getType().isArray())
3771 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
3773 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
3775 output.println(") {");
3776 } else if (!GENERATEPRECISEGC) {
3777 /* Imprecise Task */
3778 output.println("void * parameterarray[]) {");
3779 /* Unpack variables */
3780 for(int i=0; i<objectparams.numPrimitives(); i++) {
3781 TempDescriptor temp=objectparams.getPrimitive(i);
3782 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
3784 for(int i=0; i<fm.numTags(); i++) {
3785 TempDescriptor temp=fm.getTag(i);
3786 int offset=i+objectparams.numPrimitives();
3787 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
3790 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
3791 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
3792 } else output.println(") {");
3795 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
3796 output.println("/* FlatFlagActionNode */");
3799 /* Process tag changes */
3800 Relation tagsettable=new Relation();
3801 Relation tagcleartable=new Relation();
3803 Iterator tagsit=ffan.getTempTagPairs();
3804 while (tagsit.hasNext()) {
3805 TempTagPair ttp=(TempTagPair) tagsit.next();
3806 TempDescriptor objtmp=ttp.getTemp();
3807 TagDescriptor tag=ttp.getTag();
3808 TempDescriptor tagtmp=ttp.getTagTemp();
3809 boolean tagstatus=ffan.getTagChange(ttp);
3811 tagsettable.put(objtmp, tagtmp);
3813 tagcleartable.put(objtmp, tagtmp);
3818 Hashtable flagandtable=new Hashtable();
3819 Hashtable flagortable=new Hashtable();
3821 /* Process flag changes */
3822 Iterator flagsit=ffan.getTempFlagPairs();
3823 while(flagsit.hasNext()) {
3824 TempFlagPair tfp=(TempFlagPair)flagsit.next();
3825 TempDescriptor temp=tfp.getTemp();
3826 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
3827 FlagDescriptor flag=tfp.getFlag();
3829 //Newly allocate objects that don't set any flags case
3830 if (flagortable.containsKey(temp)) {
3834 flagortable.put(temp,new Integer(mask));
3836 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
3837 boolean flagstatus=ffan.getFlagChange(tfp);
3840 if (flagortable.containsKey(temp)) {
3841 mask=((Integer)flagortable.get(temp)).intValue();
3844 flagortable.put(temp,new Integer(mask));
3846 int mask=0xFFFFFFFF;
3847 if (flagandtable.containsKey(temp)) {
3848 mask=((Integer)flagandtable.get(temp)).intValue();
3850 mask&=(0xFFFFFFFF^flagid);
3851 flagandtable.put(temp,new Integer(mask));
3857 HashSet flagtagset=new HashSet();
3858 flagtagset.addAll(flagortable.keySet());
3859 flagtagset.addAll(flagandtable.keySet());
3860 flagtagset.addAll(tagsettable.keySet());
3861 flagtagset.addAll(tagcleartable.keySet());
3863 Iterator ftit=flagtagset.iterator();
3864 while(ftit.hasNext()) {
3865 TempDescriptor temp=(TempDescriptor)ftit.next();
3868 Set tagtmps=tagcleartable.get(temp);
3869 if (tagtmps!=null) {
3870 Iterator tagit=tagtmps.iterator();
3871 while(tagit.hasNext()) {
3872 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
3873 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
3874 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
3876 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
3880 tagtmps=tagsettable.get(temp);
3881 if (tagtmps!=null) {
3882 Iterator tagit=tagtmps.iterator();
3883 while(tagit.hasNext()) {
3884 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
3885 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
3886 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
3888 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
3893 int andmask=0xFFFFFFF;
3895 if (flagortable.containsKey(temp))
3896 ormask=((Integer)flagortable.get(temp)).intValue();
3897 if (flagandtable.containsKey(temp))
3898 andmask=((Integer)flagandtable.get(temp)).intValue();
3899 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
3900 generateObjectDistribute(ffan, fm, lb, temp, output);
3904 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
3905 PrintWriter output, int ormask, int andmask) {
3906 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
3907 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
3909 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
3913 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
3914 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
3917 void generateOptionalHeader(PrintWriter headers) {
3920 headers.println("#include \"task.h\"\n\n");
3921 headers.println("#ifndef _OPTIONAL_STRUCT_");
3922 headers.println("#define _OPTIONAL_STRUCT_");
3924 //STRUCT PREDICATEMEMBER
3925 headers.println("struct predicatemember{");
3926 headers.println("int type;");
3927 headers.println("int numdnfterms;");
3928 headers.println("int * flags;");
3929 headers.println("int numtags;");
3930 headers.println("int * tags;\n};\n\n");
3932 //STRUCT OPTIONALTASKDESCRIPTOR
3933 headers.println("struct optionaltaskdescriptor{");
3934 headers.println("struct taskdescriptor * task;");
3935 headers.println("int index;");
3936 headers.println("int numenterflags;");
3937 headers.println("int * enterflags;");
3938 headers.println("int numpredicatemembers;");
3939 headers.println("struct predicatemember ** predicatememberarray;");
3940 headers.println("};\n\n");
3942 //STRUCT TASKFAILURE
3943 headers.println("struct taskfailure {");
3944 headers.println("struct taskdescriptor * task;");
3945 headers.println("int index;");
3946 headers.println("int numoptionaltaskdescriptors;");
3947 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
3949 //STRUCT FSANALYSISWRAPPER
3950 headers.println("struct fsanalysiswrapper{");
3951 headers.println("int flags;");
3952 headers.println("int numtags;");
3953 headers.println("int * tags;");
3954 headers.println("int numtaskfailures;");
3955 headers.println("struct taskfailure ** taskfailurearray;");
3956 headers.println("int numoptionaltaskdescriptors;");
3957 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
3959 //STRUCT CLASSANALYSISWRAPPER
3960 headers.println("struct classanalysiswrapper{");
3961 headers.println("int type;");
3962 headers.println("int numotd;");
3963 headers.println("struct optionaltaskdescriptor ** otdarray;");
3964 headers.println("int numfsanalysiswrappers;");
3965 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
3967 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
3969 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
3970 while(taskit.hasNext()) {
3971 TaskDescriptor td=(TaskDescriptor)taskit.next();
3972 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
3977 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
3978 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
3979 int predicateindex = 0;
3980 //iterate through the classes concerned by the predicate
3981 Set c_vard = predicate.vardescriptors;
3982 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
3985 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
3986 VarDescriptor vard = (VarDescriptor)vard_it.next();
3987 TypeDescriptor typed = vard.getType();
3989 //generate for flags
3990 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
3991 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3993 if (fen_hashset!=null) {
3994 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
3995 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
3997 DNFFlag dflag=fen.getDNF();
3998 numberterms+=dflag.size();
4000 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
4002 for(int j=0; j<dflag.size(); j++) {
4004 output.println(",");
4005 Vector term=dflag.get(j);
4008 for(int k=0; k<term.size(); k++) {
4009 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
4010 FlagDescriptor fd=dfa.getFlag();
4011 boolean negated=dfa.getNegated();
4012 int flagid=1<<((Integer)flags.get(fd)).intValue();
4017 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
4022 output.println("};\n");
4025 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
4026 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4029 for(int j=0; j<tagel.numTags(); j++) {
4031 output.println(",");
4032 TempDescriptor tmp=tagel.getTemp(j);
4033 if (!slotnumber.containsKey(tmp)) {
4034 Integer slotint=new Integer(current_slot++);
4035 slotnumber.put(tmp,slotint);
4037 int slot=slotnumber.get(tmp).intValue();
4038 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
4040 numtags = tagel.numTags();
4042 output.println("};");
4044 //store the result into a predicatemember struct
4045 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4046 output.println("/*type*/"+typed.getClassDesc().getId()+",");
4047 output.println("/* number of dnf terms */"+numberterms+",");
4048 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4049 output.println("/* number of tag */"+numtags+",");
4050 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4051 output.println("};\n");
4056 //generate an array that stores the entire predicate
4057 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4058 for( int j = 0; j<predicateindex; j++) {
4059 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4060 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4062 output.println("};\n");
4063 return predicateindex;
4067 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
4068 generateOptionalHeader(headers);
4070 output.println("#include \"optionalstruct.h\"\n\n");
4071 output.println("#include \"stdlib.h\"\n");
4073 HashSet processedcd = new HashSet();
4075 Enumeration e = safeexecution.keys();
4076 while (e.hasMoreElements()) {
4079 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
4080 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
4082 //Generate the struct of optionals
4083 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4084 numotd = c_otd.size();
4085 if(maxotd<numotd) maxotd = numotd;
4086 if( !c_otd.isEmpty() ) {
4087 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4088 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4090 //generate the int arrays for the predicate
4091 Predicate predicate = otd.predicate;
4092 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
4093 TreeSet<Integer> fsset=new TreeSet<Integer>();
4094 //iterate through possible FSes corresponding to
4095 //the state when entering
4097 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
4098 FlagState fs = (FlagState)fses.next();
4100 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4101 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4102 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4105 fsset.add(new Integer(flagid));
4106 //tag information not needed because tag
4107 //changes are not tolerated.
4110 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4111 boolean needcomma=false;
4112 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
4115 output.println(it.next());
4118 output.println("};\n");
4121 //generate optionaltaskdescriptor that actually
4122 //includes exit fses, predicate and the task
4124 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4125 output.println("&task_"+otd.td.getSafeSymbol()+",");
4126 output.println("/*index*/"+otd.getIndex()+",");
4127 output.println("/*number of enter flags*/"+fsset.size()+",");
4128 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4129 output.println("/*number of members */"+predicateindex+",");
4130 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4131 output.println("};\n");
4135 // if there are no optionals, there is no need to build the rest of the struct
4137 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
4138 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4139 if( !c_otd.isEmpty() ) {
4140 boolean needcomma=false;
4141 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4142 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4144 output.println(",");
4146 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4149 output.println("};\n");
4151 //get all the possible flagstates reachable by an object
4152 Hashtable hashtbtemp = safeexecution.get(cdtemp);
4154 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
4155 fsts.addAll(hashtbtemp.keySet());
4156 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
4157 FlagState fs = (FlagState)fsit.next();
4160 //get the set of OptionalTaskDescriptors corresponding
4161 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
4162 //iterate through the OptionalTaskDescriptors and
4163 //store the pointers to the optionals struct (see on
4164 //top) into an array
4166 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
4167 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
4168 OptionalTaskDescriptor mm = mos.next();
4170 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
4172 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4175 output.println("};\n");
4177 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
4180 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4181 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4182 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4186 //process tag information
4189 boolean first = true;
4190 Enumeration tag_enum = fs.getTags();
4191 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4192 while(tag_enum.hasMoreElements()) {
4194 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
4198 output.println(", ");
4199 output.println("/*tagid*/"+state.getTagId(tagd));
4201 output.println("};");
4203 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
4204 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4205 TaskIndex ti=itti.next();
4209 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
4211 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
4212 boolean needcomma=false;
4213 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
4214 OptionalTaskDescriptor otd=otdit.next();
4218 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4220 output.println("};");
4222 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
4223 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
4224 output.print(ti.getIndex()+", ");
4225 output.print(otdset.size()+", ");
4226 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
4227 output.println("};");
4230 tiset=sa.getTaskIndex(fs);
4231 boolean needcomma=false;
4233 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4234 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4235 TaskIndex ti=itti.next();
4236 if (ti.isRuntime()) {
4243 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
4245 output.println("};\n");
4247 //Store the result in fsanalysiswrapper
4249 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
4250 output.println("/*flag*/"+flagid+",");
4251 output.println("/* number of tags*/"+tagcounter+",");
4252 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4253 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
4254 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4255 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
4256 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
4257 output.println("};\n");
4261 //Build the array of fsanalysiswrappers
4262 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
4263 boolean needcomma=false;
4264 for(int i = 0; i<fscounter; i++) {
4265 if (needcomma) output.print(",");
4266 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
4269 output.println("};");
4271 //Build the classanalysiswrapper referring to the previous array
4272 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
4273 output.println("/*type*/"+cdtemp.getId()+",");
4274 output.println("/*numotd*/"+numotd+",");
4275 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
4276 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
4277 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
4278 processedcd.add(cdtemp);
4281 //build an array containing every classes for which code has been build
4282 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
4283 for(int i=0; i<state.numClasses(); i++) {
4284 ClassDescriptor cn=cdarray[i];
4287 if (processedcd.contains(cn))
4288 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
4290 output.print("NULL");
4292 output.println("};");
4294 output.println("#define MAXOTD "+maxotd);
4295 headers.println("#endif");
4298 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
4299 Relation r=new Relation();
4300 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
4301 OptionalTaskDescriptor otd=otdit.next();
4302 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
4306 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
4307 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
4308 Set s=r.get(it.next());
4309 for(Iterator it2=s.iterator(); it2.hasNext();) {
4310 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
4318 protected void outputTransCode(PrintWriter output) {