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.DCWrapper;
23 import Analysis.Locality.DelayComputation;
24 import Analysis.Locality.BranchAnalysis;
25 import Analysis.CallGraph.CallGraph;
26 import Analysis.Prefetch.*;
27 import Analysis.Loops.WriteBarrier;
28 import Analysis.Loops.GlobalFieldType;
29 import Analysis.Locality.TypeAnalysis;
30 import Analysis.MLP.MLPAnalysis;
31 import Analysis.MLP.VariableSourceToken;
32 import Analysis.MLP.CodePlan;
33 import Analysis.MLP.SESEandAgePair;
35 public class BuildCode {
38 Hashtable paramstable;
43 String localsprefix="___locals___";
44 String localsprefixaddr="&"+localsprefix;
45 String localsprefixderef=localsprefix+".";
46 String fcrevert="___fcrevert___";
47 String paramsprefix="___params___";
48 String oidstr="___nextobject___";
49 String nextobjstr="___nextobject___";
50 String localcopystr="___localcopy___";
51 public static boolean GENERATEPRECISEGC=false;
52 public static String PREFIX="";
53 public static String arraytype="ArrayObject";
54 public static int flagcount = 0;
57 protected int maxtaskparams=0;
58 private int maxcount=0;
59 ClassDescriptor[] cdarray;
60 TypeDescriptor[] arraytable;
61 LocalityAnalysis locality;
62 Hashtable<LocalityBinding, TempDescriptor> reverttable;
63 Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>> backuptable;
67 String mlperrstr = "if(status != 0) { "+
68 "sprintf(errmsg, \"MLP error at %s:%d\", __FILE__, __LINE__); "+
69 "perror(errmsg); exit(-1); }";
70 boolean nonSESEpass=true;
73 DiscoverConflicts recorddc;
78 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa) {
79 this(st, temptovar, typeutil, null, sa, pa, null);
82 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa) {
83 this(st, temptovar, typeutil, null, sa, pa, mlpa);
86 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, PrefetchAnalysis pa, MLPAnalysis mlpa) {
87 this(st, temptovar, typeutil, locality, null, pa, mlpa);
90 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa) {
95 callgraph=new CallGraph(state);
97 oidstr="___objlocation___";
98 this.temptovar=temptovar;
99 paramstable=new Hashtable();
100 tempstable=new Hashtable();
101 fieldorder=new Hashtable();
102 flagorder=new Hashtable();
103 this.typeutil=typeutil;
104 virtualcalls=new Virtual(state,locality);
105 if (locality!=null) {
106 this.locality=locality;
107 this.reverttable=new Hashtable<LocalityBinding, TempDescriptor>();
108 this.backuptable=new Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>>();
109 this.wb=new WriteBarrier(locality, st);
111 if (state.SINGLETM&&state.DCOPTS) {
112 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
113 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
114 this.dc=new DiscoverConflicts(locality, st, typeanalysis, gft);
117 if (state.DELAYCOMP) {
118 //TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
119 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
120 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
121 delaycomp=new DCWrapper(locality, st, typeanalysis, gft);
122 dc=delaycomp.getConflicts();
123 recorddc=new DiscoverConflicts(locality, st, typeanalysis, delaycomp.getCannotDelayMap(), true, true, null);
124 recorddc.doAnalysis();
128 /** The buildCode method outputs C code for all the methods. The Flat
129 * versions of the methods must already be generated and stored in
130 * the State object. */
131 PrintWriter outsandbox=null;
133 public void buildCode() {
134 /* Create output streams to write to */
135 PrintWriter outclassdefs=null;
136 PrintWriter outstructs=null;
137 PrintWriter outrepairstructs=null;
138 PrintWriter outmethodheader=null;
139 PrintWriter outmethod=null;
140 PrintWriter outvirtual=null;
141 PrintWriter outtask=null;
142 PrintWriter outtaskdefs=null;
143 PrintWriter outoptionalarrays=null;
144 PrintWriter optionalheaders=null;
148 outsandbox=new PrintWriter(new FileOutputStream(PREFIX+"sandboxdefs.c"), true);
150 outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
151 outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
152 outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
153 outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
154 outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
156 outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
157 outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
158 if (state.OPTIONAL) {
159 outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
160 optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
163 if (state.structfile!=null) {
164 outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
166 } catch (Exception e) {
171 /* Build the virtual dispatch tables */
172 buildVirtualTables(outvirtual);
174 /* Output includes */
175 outmethodheader.println("#ifndef METHODHEADERS_H");
176 outmethodheader.println("#define METHODHEADERS_H");
177 outmethodheader.println("#include \"structdefs.h\"");
179 outmethodheader.println("#include \"dstm.h\"");
181 outmethodheader.println("#include \"sandbox.h\"");
183 if (state.SINGLETM) {
184 outmethodheader.println("#include \"tm.h\"");
185 outmethodheader.println("#include \"delaycomp.h\"");
186 outmethodheader.println("#include \"inlinestm.h\"");
188 if (state.ABORTREADERS) {
189 outmethodheader.println("#include \"abortreaders.h\"");
190 outmethodheader.println("#include <setjmp.h>");
193 outmethodheader.println("#include <stdlib.h>");
194 outmethodheader.println("#include <stdio.h>");
195 outmethodheader.println("#include <string.h>");
196 outmethodheader.println("#include \"mlp_runtime.h\"");
197 outmethodheader.println("#include \"psemaphore.h\"");
200 /* Output Structures */
201 outputStructs(outstructs);
203 // Output the C class declarations
204 // These could mutually reference each other
205 outputClassDeclarations(outclassdefs);
207 // Output function prototypes and structures for parameters
208 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
209 while(it.hasNext()) {
210 ClassDescriptor cn=(ClassDescriptor)it.next();
211 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader);
213 outclassdefs.close();
216 /* Map flags to integers */
217 /* The runtime keeps track of flags using these integers */
218 it=state.getClassSymbolTable().getDescriptorsIterator();
219 while(it.hasNext()) {
220 ClassDescriptor cn=(ClassDescriptor)it.next();
224 generateTaskStructs(outstructs, outmethodheader);
226 /* Outputs generic task structures if this is a task
228 outputTaskTypes(outtask);
232 // have to initialize some SESE compiler data before
233 // analyzing normal methods, which must happen before
234 // generating SESE internal code
235 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
236 FlatSESEEnterNode fsen = seseit.next();
237 initializeSESE( fsen );
241 /* Build the actual methods */
242 outputMethods(outmethod);
244 // Output function prototypes and structures for SESE's and code
247 // used to differentiate, during code generation, whether we are
248 // passing over SESE body code, or non-SESE code
251 // first generate code for each sese's internals
252 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
253 FlatSESEEnterNode fsen = seseit.next();
254 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
257 // then write the invokeSESE switch to decouple scheduler
258 // from having to do unique details of sese invocation
259 generateSESEinvocationMethod(outmethodheader, outmethod);
263 /* Output code for tasks */
264 outputTaskCode(outtaskdefs, outmethod);
266 /* Record maximum number of task parameters */
267 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
268 } else if (state.main!=null) {
269 /* Generate main method */
270 outputMainMethod(outmethod);
273 /* Generate information for task with optional parameters */
274 if (state.TASK&&state.OPTIONAL) {
275 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
276 outoptionalarrays.close();
279 /* Output structure definitions for repair tool */
280 if (state.structfile!=null) {
281 buildRepairStructs(outrepairstructs);
282 outrepairstructs.close();
286 outmethodheader.println("#endif");
287 outmethodheader.close();
289 outstructs.println("#endif");
294 /* This code just generates the main C method for java programs.
295 * The main C method packs up the arguments into a string array
296 * and passes it to the java main method. */
298 private void outputMainMethod(PrintWriter outmethod) {
299 outmethod.println("int main(int argc, const char *argv[]) {");
300 outmethod.println(" int i;");
303 //outmethod.println(" pthread_once( &mlpOnceObj, mlpInitOncePerThread );");
304 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
308 outmethod.println("#ifdef TRANSSTATS \n");
309 outmethod.println("handle();\n");
310 outmethod.println("#endif\n");
312 if (state.THREAD||state.DSM||state.SINGLETM) {
313 outmethod.println("initializethreads();");
316 outmethod.println("if (dstmStartup(argv[1])) {");
317 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
318 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
320 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
323 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
324 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
326 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
330 outmethod.println(" for(i=2;i<argc;i++) {");
332 outmethod.println(" for(i=1;i<argc;i++) {");
333 outmethod.println(" int length=strlen(argv[i]);");
334 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
335 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
337 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
340 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
342 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
343 outmethod.println(" }");
345 MethodDescriptor md=typeutil.getMain();
346 ClassDescriptor cd=typeutil.getMainClass();
348 outmethod.println(" {");
349 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
350 if (state.DSM||state.SINGLETM) {
351 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
353 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
354 outmethod.println("1, NULL,"+"stringarray};");
355 if (state.DSM||state.SINGLETM)
356 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
358 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
360 if (state.DSM||state.SINGLETM)
361 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
363 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
365 outmethod.println(" }");
368 outmethod.println("}");
371 if (state.THREAD||state.DSM||state.SINGLETM) {
372 outmethod.println("pthread_mutex_lock(&gclistlock);");
373 outmethod.println("threadcount--;");
374 outmethod.println("pthread_cond_signal(&gccond);");
375 outmethod.println("pthread_mutex_unlock(&gclistlock);");
378 if (state.DSM||state.SINGLETM) {
379 outmethod.println("#ifdef TRANSSTATS \n");
380 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
381 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
382 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
383 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
385 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
386 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
387 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
388 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
389 outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
390 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
391 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
392 } else if (state.SINGLETM) {
393 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
394 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
395 outmethod.println("#ifdef STMSTATS\n");
396 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
397 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
398 outmethod.println("}\n");
399 outmethod.println("#endif\n");
400 outmethod.println("fflush(stdout);");
402 outmethod.println("#endif\n");
405 if (state.THREAD||state.SINGLETM)
406 outmethod.println("pthread_exit(NULL);");
409 outmethod.println(" workScheduleBegin();");
412 outmethod.println("}");
415 /* This method outputs code for each task. */
417 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
418 /* Compile task based program */
419 outtaskdefs.println("#include \"task.h\"");
420 outtaskdefs.println("#include \"methodheaders.h\"");
421 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
422 while(taskit.hasNext()) {
423 TaskDescriptor td=(TaskDescriptor)taskit.next();
424 FlatMethod fm=state.getMethodFlat(td);
425 generateFlatMethod(fm, null, outmethod);
426 generateTaskDescriptor(outtaskdefs, fm, td);
429 //Output task descriptors
430 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
431 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
433 while(taskit.hasNext()) {
434 TaskDescriptor td=(TaskDescriptor)taskit.next();
438 outtaskdefs.println(",");
439 outtaskdefs.print("&task_"+td.getSafeSymbol());
441 outtaskdefs.println("};");
443 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
446 /* This method outputs most of the methods.c file. This includes
447 * some standard includes and then an array with the sizes of
448 * objets and array that stores supertype and then the code for
449 * the Java methods.. */
451 protected void outputMethods(PrintWriter outmethod) {
452 outmethod.println("#include \"methodheaders.h\"");
453 outmethod.println("#include \"virtualtable.h\"");
454 outmethod.println("#include \"runtime.h\"");
456 outmethod.println("#include \"sandboxdefs.c\"");
459 outmethod.println("#include \"addPrefetchEnhance.h\"");
460 outmethod.println("#include \"localobjects.h\"");
462 if (state.FASTCHECK) {
463 outmethod.println("#include \"localobjects.h\"");
465 if(state.MULTICORE) {
466 outmethod.println("#include \"task.h\"");
467 outmethod.println("#include \"multicoreruntime.h\"");
468 outmethod.println("#include \"runtime_arch.h\"");
470 if (state.THREAD||state.DSM||state.SINGLETM)
471 outmethod.println("#include <thread.h>");
472 if (state.main!=null) {
473 outmethod.println("#include <string.h>");
475 if (state.CONSCHECK) {
476 outmethod.println("#include \"checkers.h\"");
479 outmethod.println("#include <stdlib.h>");
480 outmethod.println("#include <stdio.h>");
481 outmethod.println("#include \"mlp_runtime.h\"");
482 outmethod.println("#include \"psemaphore.h\"");
486 //Store the sizes of classes & array elements
487 generateSizeArray(outmethod);
489 //Store table of supertypes
490 generateSuperTypeTable(outmethod);
492 //Store the layout of classes
493 generateLayoutStructs(outmethod);
495 /* Generate code for methods */
496 if (state.DSM||state.SINGLETM) {
497 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
498 LocalityBinding lb=lbit.next();
499 MethodDescriptor md=lb.getMethod();
500 FlatMethod fm=state.getMethodFlat(md);
502 if (!md.getModifiers().isNative()) {
503 generateFlatMethod(fm, lb, outmethod);
507 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
508 while(classit.hasNext()) {
509 ClassDescriptor cn=(ClassDescriptor)classit.next();
510 Iterator methodit=cn.getMethods();
511 while(methodit.hasNext()) {
512 /* Classify parameters */
513 MethodDescriptor md=(MethodDescriptor)methodit.next();
514 FlatMethod fm=state.getMethodFlat(md);
515 if (!md.getModifiers().isNative()) {
516 generateFlatMethod(fm, null, outmethod);
523 protected void outputStructs(PrintWriter outstructs) {
524 outstructs.println("#ifndef STRUCTDEFS_H");
525 outstructs.println("#define STRUCTDEFS_H");
526 outstructs.println("#include \"classdefs.h\"");
527 outstructs.println("#ifndef INTPTR");
528 outstructs.println("#ifdef BIT64");
529 outstructs.println("#define INTPTR long");
530 outstructs.println("#else");
531 outstructs.println("#define INTPTR int");
532 outstructs.println("#endif");
533 outstructs.println("#endif");
535 outstructs.println("#include \"mlp_runtime.h\"");
536 outstructs.println("#include \"psemaphore.h\"");
539 /* Output #defines that the runtime uses to determine type
540 * numbers for various objects it needs */
541 outstructs.println("#define MAXCOUNT "+maxcount);
542 if (state.DSM||state.SINGLETM) {
543 LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
545 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
547 else if (state.SINGLETM) {
548 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
550 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
554 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
556 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
557 else if( state.SINGLETM)
558 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
559 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
562 outstructs.println("#define STRINGARRAYTYPE "+
563 (state.getArrayNumber(
564 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
566 outstructs.println("#define OBJECTARRAYTYPE "+
567 (state.getArrayNumber(
568 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
571 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
572 outstructs.println("#define CHARARRAYTYPE "+
573 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
575 outstructs.println("#define BYTEARRAYTYPE "+
576 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
578 outstructs.println("#define BYTEARRAYARRAYTYPE "+
579 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
581 outstructs.println("#define NUMCLASSES "+state.numClasses());
582 int totalClassSize = state.numClasses() + state.numArrays();
583 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
585 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
586 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
587 outstructs.println("#define TAGARRAYTYPE "+
588 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
592 protected void outputClassDeclarations(PrintWriter outclassdefs) {
593 if (state.THREAD||state.DSM||state.SINGLETM)
594 outclassdefs.println("#include <pthread.h>");
595 outclassdefs.println("#ifndef INTPTR");
596 outclassdefs.println("#ifdef BIT64");
597 outclassdefs.println("#define INTPTR long");
598 outclassdefs.println("#else");
599 outclassdefs.println("#define INTPTR int");
600 outclassdefs.println("#endif");
601 outclassdefs.println("#endif");
603 outclassdefs.println("#include \"optionalstruct.h\"");
604 outclassdefs.println("struct "+arraytype+";");
605 /* Start by declaring all structs */
606 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
607 while(it.hasNext()) {
608 ClassDescriptor cn=(ClassDescriptor)it.next();
609 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
611 outclassdefs.println("");
612 //Print out definition for array type
613 outclassdefs.println("struct "+arraytype+" {");
614 outclassdefs.println(" int type;");
616 outclassdefs.println(" pthread_t tid;");
617 outclassdefs.println(" void * lockentry;");
618 outclassdefs.println(" int lockcount;");
621 outclassdefs.println(" int flag;");
622 if(!state.MULTICORE) {
623 outclassdefs.println(" void * flagptr;");
625 outclassdefs.println(" int version;");
626 outclassdefs.println(" int * lock;"); // lock entry for this obj
627 outclassdefs.println(" int mutex;");
628 outclassdefs.println(" int lockcount;");
629 if(state.MULTICOREGC) {
630 outclassdefs.println(" int marked;");
634 outclassdefs.println(" int numfses;");
635 outclassdefs.println(" int * fses;");
638 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
640 if (state.STMARRAY) {
641 outclassdefs.println(" int lowindex;");
642 outclassdefs.println(" int highindex;");
645 outclassdefs.println(" int paddingforarray;");
646 if (state.DUALVIEW) {
647 outclassdefs.println(" int arrayversion;");
650 outclassdefs.println(" int ___length___;");
651 outclassdefs.println("};\n");
652 outclassdefs.println("extern int classsize[];");
653 outclassdefs.println("extern int hasflags[];");
654 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
655 outclassdefs.println("extern int supertypes[];");
658 /** Prints out definitions for generic task structures */
660 private void outputTaskTypes(PrintWriter outtask) {
661 outtask.println("#ifndef _TASK_H");
662 outtask.println("#define _TASK_H");
663 outtask.println("struct parameterdescriptor {");
664 outtask.println("int type;");
665 outtask.println("int numberterms;");
666 outtask.println("int *intarray;");
667 outtask.println("void * queue;");
668 outtask.println("int numbertags;");
669 outtask.println("int *tagarray;");
670 outtask.println("};");
672 outtask.println("struct taskdescriptor {");
673 outtask.println("void * taskptr;");
674 outtask.println("int numParameters;");
675 outtask.println(" int numTotal;");
676 outtask.println("struct parameterdescriptor **descriptorarray;");
677 outtask.println("char * name;");
678 outtask.println("};");
679 outtask.println("extern struct taskdescriptor * taskarray[];");
680 outtask.println("extern numtasks;");
681 outtask.println("#endif");
685 private void buildRepairStructs(PrintWriter outrepairstructs) {
686 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
687 while(classit.hasNext()) {
688 ClassDescriptor cn=(ClassDescriptor)classit.next();
689 outrepairstructs.println("structure "+cn.getSymbol()+" {");
690 outrepairstructs.println(" int __type__;");
692 outrepairstructs.println(" int __flag__;");
693 if(!state.MULTICORE) {
694 outrepairstructs.println(" int __flagptr__;");
697 printRepairStruct(cn, outrepairstructs);
698 outrepairstructs.println("}\n");
701 for(int i=0; i<state.numArrays(); i++) {
702 TypeDescriptor tdarray=arraytable[i];
703 TypeDescriptor tdelement=tdarray.dereference();
704 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
705 outrepairstructs.println(" int __type__;");
706 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
707 outrepairstructs.println(" int length;");
709 // Need to add support to repair tool for this
710 if (tdelement.isClass()||tdelement.isArray())
711 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
713 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
715 outrepairstructs.println("}\n");
719 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
720 ClassDescriptor sp=cn.getSuperDesc();
722 printRepairStruct(sp, output);
724 Vector fields=(Vector)fieldorder.get(cn);
726 for(int i=0; i<fields.size(); i++) {
727 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
728 if (fd.getType().isArray()) {
729 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
730 } else if (fd.getType().isClass())
731 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
732 else if (fd.getType().isFloat())
733 output.println(" int "+fd.getSymbol()+"; /* really float */");
735 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
739 /** This method outputs TaskDescriptor information */
740 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
741 for (int i=0; i<task.numParameters(); i++) {
742 VarDescriptor param_var=task.getParameter(i);
743 TypeDescriptor param_type=task.getParamType(i);
744 FlagExpressionNode param_flag=task.getFlag(param_var);
745 TagExpressionList param_tag=task.getTag(param_var);
748 if (param_flag==null) {
749 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
750 output.println("0x0, 0x0 };");
753 DNFFlag dflag=param_flag.getDNF();
754 dnfterms=dflag.size();
756 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
757 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
758 for(int j=0; j<dflag.size(); j++) {
761 Vector term=dflag.get(j);
764 for(int k=0; k<term.size(); k++) {
765 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
766 FlagDescriptor fd=dfa.getFlag();
767 boolean negated=dfa.getNegated();
768 int flagid=1<<((Integer)flags.get(fd)).intValue();
773 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
775 output.println("};");
778 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
779 //BUG...added next line to fix, test with any task program
781 for(int j=0; j<param_tag.numTags(); j++) {
784 /* for each tag we need */
785 /* which slot it is */
786 /* what type it is */
787 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
788 TempDescriptor tmp=param_tag.getTemp(j);
789 int slot=fm.getTagInt(tmp);
790 output.println(slot+", "+state.getTagId(tvd.getTag()));
792 output.println("};");
794 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
795 output.println("/* type */"+param_type.getClassDesc().getId()+",");
796 output.println("/* number of DNF terms */"+dnfterms+",");
797 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
798 output.println("0,");
799 //BUG, added next line to fix and else statement...test
800 //with any task program
802 output.println("/* number of tags */"+param_tag.numTags()+",");
804 output.println("/* number of tags */ 0,");
805 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
806 output.println("};");
810 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
811 for (int i=0; i<task.numParameters(); i++) {
814 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
816 output.println("};");
818 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
819 output.println("&"+task.getSafeSymbol()+",");
820 output.println("/* number of parameters */" +task.numParameters() + ",");
821 int numtotal=task.numParameters()+fm.numTags();
822 output.println("/* number total parameters */" +numtotal + ",");
823 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
824 output.println("\""+task.getSymbol()+"\"");
825 output.println("};");
829 /** The buildVirtualTables method outputs the virtual dispatch
830 * tables for methods. */
832 protected void buildVirtualTables(PrintWriter outvirtual) {
833 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
834 while(classit.hasNext()) {
835 ClassDescriptor cd=(ClassDescriptor)classit.next();
836 if (virtualcalls.getMethodCount(cd)>maxcount)
837 maxcount=virtualcalls.getMethodCount(cd);
839 MethodDescriptor[][] virtualtable=null;
840 LocalityBinding[][] lbvirtualtable=null;
841 if (state.DSM||state.SINGLETM)
842 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
844 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
846 /* Fill in virtual table */
847 classit=state.getClassSymbolTable().getDescriptorsIterator();
848 while(classit.hasNext()) {
849 ClassDescriptor cd=(ClassDescriptor)classit.next();
850 if (state.DSM||state.SINGLETM)
851 fillinRow(cd, lbvirtualtable, cd.getId());
853 fillinRow(cd, virtualtable, cd.getId());
856 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
857 Iterator arrayit=state.getArrayIterator();
858 while(arrayit.hasNext()) {
859 TypeDescriptor td=(TypeDescriptor)arrayit.next();
860 int id=state.getArrayNumber(td);
861 if (state.DSM||state.SINGLETM)
862 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
864 fillinRow(objectcd, virtualtable, id+state.numClasses());
867 outvirtual.print("void * virtualtable[]={");
868 boolean needcomma=false;
869 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
870 for(int j=0; j<maxcount; j++) {
872 outvirtual.print(", ");
873 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
874 LocalityBinding lb=lbvirtualtable[i][j];
875 MethodDescriptor md=lb.getMethod();
876 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
877 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
878 MethodDescriptor md=virtualtable[i][j];
879 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
881 outvirtual.print("0");
885 outvirtual.println("");
887 outvirtual.println("};");
891 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
892 /* Get inherited methods */
893 if (cd.getSuperDesc()!=null)
894 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
895 /* Override them with our methods */
896 for(Iterator it=cd.getMethods(); it.hasNext();) {
897 MethodDescriptor md=(MethodDescriptor)it.next();
898 if (md.isStatic()||md.getReturnType()==null)
900 int methodnum=virtualcalls.getMethodNumber(md);
901 virtualtable[rownum][methodnum]=md;
905 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
906 /* Get inherited methods */
907 if (cd.getSuperDesc()!=null)
908 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
909 /* Override them with our methods */
910 if (locality.getClassBindings(cd)!=null)
911 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
912 LocalityBinding lb=lbit.next();
913 MethodDescriptor md=lb.getMethod();
914 //Is the method static or a constructor
915 if (md.isStatic()||md.getReturnType()==null)
917 int methodnum=virtualcalls.getLocalityNumber(lb);
918 virtualtable[rownum][methodnum]=lb;
922 /** Generate array that contains the sizes of class objects. The
923 * object allocation functions in the runtime use this
926 private void generateSizeArray(PrintWriter outclassdefs) {
927 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
928 outclassdefs.print("#ifdef TRANSSTATS \n");
929 outclassdefs.print("extern int numTransAbort;\n");
930 outclassdefs.print("extern int numTransCommit;\n");
931 outclassdefs.print("extern int nSoftAbort;\n");
933 outclassdefs.print("extern int nchashSearch;\n");
934 outclassdefs.print("extern int nmhashSearch;\n");
935 outclassdefs.print("extern int nprehashSearch;\n");
936 outclassdefs.print("extern int nRemoteSend;\n");
937 outclassdefs.print("extern int getResponse;\n");
938 outclassdefs.print("extern int bytesSent;\n");
939 outclassdefs.print("extern int bytesRecv;\n");
940 outclassdefs.print("extern void handle();\n");
941 } else if (state.SINGLETM) {
942 outclassdefs.println("extern int nSoftAbortAbort;");
943 outclassdefs.println("extern int nSoftAbortCommit;");
944 outclassdefs.println("#ifdef STMSTATS\n");
945 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
946 outclassdefs.println("#endif\n");
948 outclassdefs.print("#endif\n");
949 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
951 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
952 cdarray=new ClassDescriptor[state.numClasses()];
954 while(it.hasNext()) {
955 ClassDescriptor cd=(ClassDescriptor)it.next();
956 cdarray[cd.getId()]=cd;
959 arraytable=new TypeDescriptor[state.numArrays()];
961 Iterator arrayit=state.getArrayIterator();
962 while(arrayit.hasNext()) {
963 TypeDescriptor td=(TypeDescriptor)arrayit.next();
964 int id=state.getArrayNumber(td);
970 /* Print out types */
971 outclassdefs.println("/* ");
972 for(int i=0; i<state.numClasses(); i++) {
973 ClassDescriptor cd=cdarray[i];
975 outclassdefs.println("NULL " + i);
977 outclassdefs.println(cd +" "+i);
981 for(int i=0; i<state.numArrays(); i++) {
982 TypeDescriptor arraytd=arraytable[i];
983 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
986 outclassdefs.println("*/");
989 outclassdefs.print("int classsize[]={");
991 boolean needcomma=false;
992 for(int i=0; i<state.numClasses(); i++) {
994 outclassdefs.print(", ");
996 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
998 outclassdefs.print("0");
1004 for(int i=0; i<state.numArrays(); i++) {
1006 outclassdefs.print(", ");
1007 TypeDescriptor tdelement=arraytable[i].dereference();
1008 if (tdelement.isArray()||tdelement.isClass())
1009 outclassdefs.print("sizeof(void *)");
1011 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1015 outclassdefs.println("};");
1017 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1019 outclassdefs.print("int typearray[]={");
1020 for(int i=0; i<state.numClasses(); i++) {
1021 ClassDescriptor cd=cdarray[i];
1022 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1024 outclassdefs.print(", ");
1026 outclassdefs.print("-1");
1028 outclassdefs.print(supercd.getId());
1032 for(int i=0; i<state.numArrays(); i++) {
1033 TypeDescriptor arraytd=arraytable[i];
1034 ClassDescriptor arraycd=arraytd.getClassDesc();
1035 if (arraycd==null) {
1037 outclassdefs.print(", ");
1038 outclassdefs.print(objectclass.getId());
1042 ClassDescriptor cd=arraycd.getSuperDesc();
1045 TypeDescriptor supertd=new TypeDescriptor(cd);
1046 supertd.setArrayCount(arraytd.getArrayCount());
1047 type=state.getArrayNumber(supertd);
1049 type+=state.numClasses();
1052 cd=cd.getSuperDesc();
1055 outclassdefs.print(", ");
1056 outclassdefs.print(type);
1060 outclassdefs.println("};");
1065 outclassdefs.print("int typearray2[]={");
1066 for(int i=0; i<state.numArrays(); i++) {
1067 TypeDescriptor arraytd=arraytable[i];
1068 ClassDescriptor arraycd=arraytd.getClassDesc();
1069 if (arraycd==null) {
1071 outclassdefs.print(", ");
1072 outclassdefs.print("-1");
1076 ClassDescriptor cd=arraycd.getSuperDesc();
1077 int level=arraytd.getArrayCount()-1;
1079 for(; level>0; level--) {
1080 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1081 supertd.setArrayCount(level);
1082 type=state.getArrayNumber(supertd);
1084 type+=state.numClasses();
1089 outclassdefs.print(", ");
1090 outclassdefs.print(type);
1094 outclassdefs.println("};");
1097 /** Constructs params and temp objects for each method or task.
1098 * These objects tell the compiler which temps need to be
1101 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1102 MethodDescriptor md=fm.getMethod();
1103 TaskDescriptor task=fm.getTask();
1104 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1105 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1107 paramstable.put(lb, objectparams);
1108 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1109 } else if (md!=null)
1110 paramstable.put(md, objectparams);
1112 paramstable.put(task, objectparams);
1114 for(int i=0; i<fm.numParameters(); i++) {
1115 TempDescriptor temp=fm.getParameter(i);
1116 TypeDescriptor type=temp.getType();
1117 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1118 objectparams.addPtr(temp);
1120 objectparams.addPrim(temp);
1121 if(lb!=null&&saveset.contains(temp)) {
1122 backuptable.get(lb).put(temp, temp.createNew());
1126 for(int i=0; i<fm.numTags(); i++) {
1127 TempDescriptor temp=fm.getTag(i);
1128 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1129 objectparams.addPtr(temp);
1131 objectparams.addPrim(temp);
1134 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1136 tempstable.put(lb, objecttemps);
1138 tempstable.put(md, objecttemps);
1140 tempstable.put(task, objecttemps);
1142 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1143 FlatNode fn=(FlatNode)nodeit.next();
1144 TempDescriptor[] writes=fn.writesTemps();
1145 for(int i=0; i<writes.length; i++) {
1146 TempDescriptor temp=writes[i];
1147 TypeDescriptor type=temp.getType();
1148 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1149 objecttemps.addPtr(temp);
1151 objecttemps.addPrim(temp);
1152 if(lb!=null&&saveset.contains(temp)&&
1153 !backuptable.get(lb).containsKey(temp))
1154 backuptable.get(lb).put(temp, temp.createNew());
1158 /* Create backup temps */
1160 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1161 TempDescriptor tmp=tmpit.next();
1162 TypeDescriptor type=tmp.getType();
1163 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1164 objecttemps.addPtr(tmp);
1166 objecttemps.addPrim(tmp);
1168 /* Create temp to hold revert table */
1169 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1170 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1171 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1172 objecttemps.addPtr(reverttmp);
1174 objecttemps.addPrim(reverttmp);
1175 reverttable.put(lb, reverttmp);
1180 /** This method outputs the following information about classes
1182 * (1) For classes, what are the locations of pointers.
1183 * (2) For arrays, does the array contain pointers or primitives.
1184 * (3) For classes, does the class contain flags.
1187 private void generateLayoutStructs(PrintWriter output) {
1188 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1189 while(it.hasNext()) {
1190 ClassDescriptor cn=(ClassDescriptor)it.next();
1191 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1192 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1194 while(allit.hasNext()) {
1195 FieldDescriptor fd=(FieldDescriptor)allit.next();
1196 TypeDescriptor type=fd.getType();
1197 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1202 output.print(count);
1203 allit=cn.getFieldTable().getAllDescriptorsIterator();
1204 while(allit.hasNext()) {
1205 FieldDescriptor fd=(FieldDescriptor)allit.next();
1206 TypeDescriptor type=fd.getType();
1207 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1210 output.println(",");
1211 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1214 output.println("};");
1216 output.println("unsigned INTPTR * pointerarray[]={");
1217 boolean needcomma=false;
1218 for(int i=0; i<state.numClasses(); i++) {
1219 ClassDescriptor cn=cdarray[i];
1221 output.println(",");
1224 output.print(cn.getSafeSymbol()+"_pointers");
1226 output.print("NULL");
1230 for(int i=0; i<state.numArrays(); i++) {
1232 output.println(", ");
1233 TypeDescriptor tdelement=arraytable[i].dereference();
1234 if (tdelement.isArray()||tdelement.isClass())
1235 output.print("((unsigned INTPTR *)1)");
1241 output.println("};");
1243 output.println("int hasflags[]={");
1244 for(int i=0; i<state.numClasses(); i++) {
1245 ClassDescriptor cn=cdarray[i];
1247 output.println(", ");
1249 if ((cn != null) && (cn.hasFlags()))
1254 output.println("};");
1257 /** Print out table to give us supertypes */
1258 private void generateSuperTypeTable(PrintWriter output) {
1259 output.println("int supertypes[]={");
1260 boolean needcomma=false;
1261 for(int i=0; i<state.numClasses(); i++) {
1262 ClassDescriptor cn=cdarray[i];
1264 output.println(",");
1266 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1267 ClassDescriptor cdsuper=cn.getSuperDesc();
1268 output.print(cdsuper.getId());
1272 output.println("};");
1275 /** Force consistent field ordering between inherited classes. */
1277 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1279 ClassDescriptor sp=cn.getSuperDesc();
1281 printClassStruct(sp, classdefout);
1283 if (!fieldorder.containsKey(cn)) {
1284 Vector fields=new Vector();
1285 fieldorder.put(cn,fields);
1286 Vector fieldvec=cn.getFieldVec();
1287 for(int i=0;i<fieldvec.size();i++) {
1288 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1289 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1293 Vector fields=(Vector)fieldorder.get(cn);
1295 for(int i=0; i<fields.size(); i++) {
1296 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1297 if (fd.getType().isClass()||fd.getType().isArray())
1298 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1300 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1305 /* Map flags to integers consistently between inherited
1308 protected void mapFlags(ClassDescriptor cn) {
1309 ClassDescriptor sp=cn.getSuperDesc();
1313 if (!flagorder.containsKey(cn)) {
1314 Hashtable flags=new Hashtable();
1315 flagorder.put(cn,flags);
1317 Hashtable superflags=(Hashtable)flagorder.get(sp);
1318 Iterator superflagit=superflags.keySet().iterator();
1319 while(superflagit.hasNext()) {
1320 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1321 Integer number=(Integer)superflags.get(fd);
1322 flags.put(fd, number);
1323 if ((number.intValue()+1)>max)
1324 max=number.intValue()+1;
1328 Iterator flagit=cn.getFlags();
1329 while(flagit.hasNext()) {
1330 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1331 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1332 flags.put(fd, new Integer(max++));
1338 /** This function outputs (1) structures that parameters are
1339 * passed in (when PRECISE GC is enabled) and (2) function
1340 * prototypes for the methods */
1342 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1343 /* Output class structure */
1344 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1345 classdefout.println(" int type;");
1347 classdefout.println(" pthread_t tid;");
1348 classdefout.println(" void * lockentry;");
1349 classdefout.println(" int lockcount;");
1353 classdefout.println(" int flag;");
1354 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1355 classdefout.println(" void * flagptr;");
1356 } else if (state.MULTICORE) {
1357 classdefout.println(" int version;");
1358 classdefout.println(" int * lock;"); // lock entry for this obj
1359 classdefout.println(" int mutex;");
1360 classdefout.println(" int lockcount;");
1361 if(state.MULTICOREGC) {
1362 classdefout.println(" int marked;");
1365 if (state.OPTIONAL) {
1366 classdefout.println(" int numfses;");
1367 classdefout.println(" int * fses;");
1370 printClassStruct(cn, classdefout);
1371 classdefout.println("};\n");
1373 if (state.DSM||state.SINGLETM) {
1374 /* Cycle through LocalityBindings */
1375 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1376 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1378 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1379 LocalityBinding lb=lbit.next();
1380 MethodDescriptor md=lb.getMethod();
1381 if (md.getModifiers().isNative()) {
1382 //make sure we only print a native method once
1383 if (nativemethods.contains(md)) {
1384 FlatMethod fm=state.getMethodFlat(md);
1385 generateTempStructs(fm, lb);
1388 nativemethods.add(md);
1390 generateMethod(cn, md, lb, headersout, output);
1393 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1394 MethodDescriptor md=(MethodDescriptor)methodit.next();
1395 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1396 //Need to build param structure for library code
1397 FlatMethod fm=state.getMethodFlat(md);
1398 generateTempStructs(fm, null);
1399 generateMethodParam(cn, md, null, output);
1404 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1405 MethodDescriptor md=(MethodDescriptor)methodit.next();
1406 generateMethod(cn, md, null, headersout, output);
1410 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1411 /* Output parameter structure */
1412 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1413 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1414 if ((state.DSM||state.SINGLETM)&&lb!=null)
1415 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1417 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1418 output.println(" INTPTR size;");
1419 output.println(" void * next;");
1420 for(int i=0; i<objectparams.numPointers(); i++) {
1421 TempDescriptor temp=objectparams.getPointer(i);
1422 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1424 output.println("};\n");
1428 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1429 FlatMethod fm=state.getMethodFlat(md);
1430 generateTempStructs(fm, lb);
1432 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1433 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1435 generateMethodParam(cn, md, lb, output);
1437 /* Output temp structure */
1438 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1439 if (state.DSM||state.SINGLETM)
1440 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1442 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1443 output.println(" INTPTR size;");
1444 output.println(" void * next;");
1445 for(int i=0; i<objecttemps.numPointers(); i++) {
1446 TempDescriptor temp=objecttemps.getPointer(i);
1447 if (temp.getType().isNull())
1448 output.println(" void * "+temp.getSafeSymbol()+";");
1450 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1452 output.println("};\n");
1455 /********* Output method declaration ***********/
1456 if (state.DSM||state.SINGLETM) {
1457 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1459 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1461 /* First the return type */
1462 if (md.getReturnType()!=null) {
1463 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1464 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1466 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1468 //catch the constructor case
1469 headersout.print("void ");
1471 /* Next the method name */
1472 if (state.DSM||state.SINGLETM) {
1473 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1475 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1477 boolean printcomma=false;
1478 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1479 if (state.DSM||state.SINGLETM) {
1480 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1482 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1486 /* Output parameter list*/
1487 for(int i=0; i<objectparams.numPrimitives(); i++) {
1488 TempDescriptor temp=objectparams.getPrimitive(i);
1490 headersout.print(", ");
1492 if (temp.getType().isClass()||temp.getType().isArray())
1493 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1495 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1497 headersout.println(");\n");
1501 /** This function outputs (1) structures that parameters are
1502 * passed in (when PRECISE GC is enabled) and (2) function
1503 * prototypes for the tasks */
1505 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1506 /* Cycle through tasks */
1507 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1509 while(taskit.hasNext()) {
1510 /* Classify parameters */
1511 TaskDescriptor task=(TaskDescriptor)taskit.next();
1512 FlatMethod fm=state.getMethodFlat(task);
1513 generateTempStructs(fm, null);
1515 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1516 TempObject objecttemps=(TempObject) tempstable.get(task);
1518 /* Output parameter structure */
1519 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1520 output.println("struct "+task.getSafeSymbol()+"_params {");
1522 output.println(" INTPTR size;");
1523 output.println(" void * next;");
1524 for(int i=0; i<objectparams.numPointers(); i++) {
1525 TempDescriptor temp=objectparams.getPointer(i);
1526 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1529 output.println("};\n");
1530 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1531 maxtaskparams=objectparams.numPointers()+fm.numTags();
1535 /* Output temp structure */
1536 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1537 output.println("struct "+task.getSafeSymbol()+"_locals {");
1538 output.println(" INTPTR size;");
1539 output.println(" void * next;");
1540 for(int i=0; i<objecttemps.numPointers(); i++) {
1541 TempDescriptor temp=objecttemps.getPointer(i);
1542 if (temp.getType().isNull())
1543 output.println(" void * "+temp.getSafeSymbol()+";");
1544 else if(temp.getType().isTag())
1545 output.println(" struct "+
1546 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1548 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1550 output.println("};\n");
1553 /* Output task declaration */
1554 headersout.print("void " + task.getSafeSymbol()+"(");
1556 boolean printcomma=false;
1557 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1558 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1560 headersout.print("void * parameterarray[]");
1561 headersout.println(");\n");
1565 /***** Generate code for FlatMethod fm. *****/
1567 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1568 static int atomicmethodcount=0;
1571 BranchAnalysis branchanalysis;
1572 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1573 if (State.PRINTFLAT)
1574 System.out.println(fm.printMethod());
1575 MethodDescriptor md=fm.getMethod();
1576 TaskDescriptor task=fm.getTask();
1577 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1578 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1580 HashSet<AtomicRecord> arset=null;
1581 branchanalysis=null;
1583 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1585 if (atomicmethodmap==null)
1586 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1588 //fix these so we get right strings for local variables
1589 localsprefixaddr=localsprefix;
1590 localsprefixderef=localsprefix+"->";
1591 arset=new HashSet<AtomicRecord>();
1593 //build branchanalysis
1594 branchanalysis=new BranchAnalysis(locality, lb, delaycomp.getNotReady(lb), delaycomp.livecode(lb), state);
1596 //Generate commit methods here
1597 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1598 FlatNode fn=fnit.next();
1599 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1600 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
1601 delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
1602 //We have an atomic enter
1603 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1604 Set<FlatNode> exitset=faen.getExits();
1606 String methodname=md.getSymbol()+(atomicmethodcount++);
1607 AtomicRecord ar=new AtomicRecord();
1611 atomicmethodmap.put(faen, ar);
1613 //build data structure declaration
1614 output.println("struct atomicprimitives_"+methodname+" {");
1616 Set<FlatNode> recordset=delaycomp.livecode(lb);
1617 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1618 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1619 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1621 ar.reallivein=new HashSet(liveinto);
1623 ar.liveoutvirtualread=liveoutvirtualread;
1625 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1626 TempDescriptor tmp=it.next();
1627 //remove the pointers
1628 if (tmp.getType().isPtr()) {
1631 //let's print it here
1632 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1635 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1636 TempDescriptor tmp=it.next();
1637 //remove the pointers
1638 if (tmp.getType().isPtr()) {
1640 } else if (!liveinto.contains(tmp)) {
1641 //let's print it here
1642 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1645 output.println("};");
1647 //print out method name
1648 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) {");
1649 //build code for commit method
1651 //first define local primitives
1652 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1653 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1654 TempDescriptor tmp=tmpit.next();
1655 if (!tmp.getType().isPtr()) {
1656 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1657 //read from live into set
1658 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1661 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1665 //turn off write barrier generation
1667 state.SINGLETM=false;
1668 generateCode(faen, fm, lb, exitset, output, false);
1669 state.SINGLETM=true;
1670 //turn on write barrier generation
1672 output.println("}\n\n");
1676 //redefine these back to normal
1678 localsprefixaddr="&"+localsprefix;
1679 localsprefixderef=localsprefix+".";
1681 generateHeader(fm, lb, md!=null ? md : task,output);
1682 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1684 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1685 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1686 AtomicRecord ar=arit.next();
1687 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1691 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1692 if (md!=null&&(state.DSM||state.SINGLETM))
1693 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1694 else if (md!=null&&!(state.DSM||state.SINGLETM))
1695 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1697 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1699 output.print(objecttemp.numPointers()+",");
1700 output.print(paramsprefix);
1701 for(int j=0; j<objecttemp.numPointers(); j++)
1702 output.print(", NULL");
1703 output.println("};");
1706 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1707 TempDescriptor td=objecttemp.getPrimitive(i);
1708 TypeDescriptor type=td.getType();
1710 output.println(" void * "+td.getSafeSymbol()+";");
1711 else if (type.isClass()||type.isArray())
1712 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1714 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1719 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1720 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1721 if( callerSESEplaceholder != mlpa.getMainSESE() ) {
1722 // declare variables for naming static SESE's
1723 output.println(" /* static SESE names */");
1724 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1725 while( pItr.hasNext() ) {
1726 SESEandAgePair p = pItr.next();
1727 output.println(" void* "+p+";");
1730 // declare variables for tracking dynamic sources
1731 output.println(" /* dynamic variable sources */");
1732 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1733 while( dynSrcItr.hasNext() ) {
1734 TempDescriptor dynSrcVar = dynSrcItr.next();
1735 output.println(" void* "+dynSrcVar+"_srcSESE;");
1736 output.println(" int "+dynSrcVar+"_srcOffset;");
1743 /* Check to see if we need to do a GC if this is a
1744 * multi-threaded program...*/
1746 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1747 || this.state.MULTICOREGC) {
1748 //Don't bother if we aren't in recursive methods...The loops case will catch it
1749 if (callgraph.getAllMethods(md).contains(md)) {
1750 if (state.DSM&&lb.isAtomic())
1751 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1752 else if (this.state.MULTICOREGC) {
1753 output.println("if(gcflag) gc("+localsprefixaddr+");");
1755 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1760 generateCode(fm.getNext(0), fm, lb, null, output, true);
1762 output.println("}\n\n");
1766 protected void initializeSESE( FlatSESEEnterNode fsen ) {
1768 FlatMethod fm = fsen.getfmEnclosing();
1769 MethodDescriptor md = fm.getMethod();
1770 ClassDescriptor cn = md.getClassDesc();
1773 // Creates bogus method descriptor to index into tables
1774 Modifiers modBogus = new Modifiers();
1775 MethodDescriptor mdBogus =
1776 new MethodDescriptor( modBogus,
1777 new TypeDescriptor( TypeDescriptor.VOID ),
1778 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1781 mdBogus.setClassDesc( fsen.getcdEnclosing() );
1782 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1783 fsen.setfmBogus( fmBogus );
1784 fsen.setmdBogus( mdBogus );
1786 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1787 inSetAndOutSet.addAll( fsen.getInVarSet() );
1788 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1790 // Build paramsobj for bogus method descriptor
1791 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
1792 paramstable.put( mdBogus, objectparams );
1794 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1795 while( itr.hasNext() ) {
1796 TempDescriptor temp = itr.next();
1797 TypeDescriptor type = temp.getType();
1798 if( type.isPtr() ) {
1799 objectparams.addPtr( temp );
1801 objectparams.addPrim( temp );
1805 // Build normal temp object for bogus method descriptor
1806 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
1807 tempstable.put( mdBogus, objecttemps );
1809 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
1810 FlatNode fn = (FlatNode)nodeit.next();
1811 TempDescriptor[] writes = fn.writesTemps();
1813 for( int i = 0; i < writes.length; i++ ) {
1814 TempDescriptor temp = writes[i];
1815 TypeDescriptor type = temp.getType();
1817 if( type.isPtr() ) {
1818 objecttemps.addPtr( temp );
1820 objecttemps.addPrim( temp );
1826 protected void generateMethodSESE(FlatSESEEnterNode fsen,
1828 PrintWriter outputStructs,
1829 PrintWriter outputMethHead,
1830 PrintWriter outputMethods
1833 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
1834 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
1836 // generate locals structure
1837 outputStructs.println("struct "+
1838 fsen.getcdEnclosing().getSafeSymbol()+
1839 fsen.getmdBogus().getSafeSymbol()+"_"+
1840 fsen.getmdBogus().getSafeMethodDescriptor()+
1842 outputStructs.println(" INTPTR size;");
1843 outputStructs.println(" void * next;");
1844 for(int i=0; i<objecttemps.numPointers(); i++) {
1845 TempDescriptor temp=objecttemps.getPointer(i);
1847 if( fsen.getPrettyIdentifier().equals( "calc" ) ) {
1848 System.out.println( " got a pointer "+temp );
1851 if (temp.getType().isNull())
1852 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1854 outputStructs.println(" struct "+
1855 temp.getType().getSafeSymbol()+" * "+
1856 temp.getSafeSymbol()+";");
1858 outputStructs.println("};\n");
1861 // generate the SESE record structure
1862 outputStructs.println(fsen.getSESErecordName()+" {");
1864 // data common to any SESE, and it must be placed first so
1865 // a module that doesn't know what kind of SESE record this
1866 // is can cast the pointer to a common struct
1867 outputStructs.println(" SESEcommon common;");
1869 // then garbage list stuff
1870 outputStructs.println(" INTPTR size;");
1871 outputStructs.println(" void * next;");
1873 // in-set source tracking
1874 // in-vars that are READY come from parent, don't need anything
1875 // stuff STATIC needs a custom SESE pointer for each age pair
1876 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
1877 while( itrStaticInVarSrcs.hasNext() ) {
1878 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
1879 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
1882 // DYNAMIC stuff needs a source SESE ptr and offset
1883 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
1884 while( itrDynInVars.hasNext() ) {
1885 TempDescriptor dynInVar = itrDynInVars.next();
1886 outputStructs.println(" void* "+dynInVar+"_srcSESE;");
1887 outputStructs.println(" int "+dynInVar+"_srcOffset;");
1890 // space for all in and out set primitives
1891 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1892 inSetAndOutSet.addAll( fsen.getInVarSet() );
1893 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1895 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
1897 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1898 while( itr.hasNext() ) {
1899 TempDescriptor temp = itr.next();
1900 TypeDescriptor type = temp.getType();
1901 if( !type.isPtr() ) {
1902 inSetAndOutSetPrims.add( temp );
1906 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
1907 while( itrPrims.hasNext() ) {
1908 TempDescriptor temp = itrPrims.next();
1909 TypeDescriptor type = temp.getType();
1910 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
1913 for(int i=0; i<objectparams.numPointers(); i++) {
1914 TempDescriptor temp=objectparams.getPointer(i);
1915 if (temp.getType().isNull())
1916 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1918 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1921 outputStructs.println("};\n");
1924 // write method declaration to header file
1925 outputMethHead.print("void ");
1926 outputMethHead.print(fsen.getSESEmethodName()+"(");
1927 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
1928 outputMethHead.println(");\n");
1931 generateFlatMethodSESE( fsen.getfmBogus(),
1932 fsen.getcdEnclosing(),
1938 private void generateFlatMethodSESE(FlatMethod fm,
1940 FlatSESEEnterNode fsen,
1941 FlatSESEExitNode seseExit,
1945 MethodDescriptor md=fm.getMethod();
1947 output.print("void ");
1948 output.print(fsen.getSESEmethodName()+"(");
1949 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
1950 output.println("){\n");
1952 TempObject objecttemp=(TempObject) tempstable.get(md);
1954 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1955 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1956 output.print(objecttemp.numPointers()+",");
1957 output.print("(void*) &("+paramsprefix+"->size)");
1958 for(int j=0; j<objecttemp.numPointers(); j++)
1959 output.print(", NULL");
1960 output.println("};");
1963 output.println(" /* regular local primitives */");
1964 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1965 TempDescriptor td=objecttemp.getPrimitive(i);
1966 TypeDescriptor type=td.getType();
1968 output.println(" void * "+td.getSafeSymbol()+";");
1969 else if (type.isClass()||type.isArray())
1970 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1972 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1976 // declare variables for naming static SESE's
1977 output.println(" /* static SESE names */");
1978 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
1979 while( pItr.hasNext() ) {
1980 SESEandAgePair p = pItr.next();
1981 output.println(" void* "+p+";");
1984 // declare variables for tracking dynamic sources
1985 output.println(" /* dynamic variable sources */");
1986 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
1987 while( dynSrcItr.hasNext() ) {
1988 TempDescriptor dynSrcVar = dynSrcItr.next();
1989 output.println(" void* "+dynSrcVar+"_srcSESE;");
1990 output.println(" int "+dynSrcVar+"_srcOffset;");
1993 // declare local temps for in-set primitives, and if it is
1994 // a ready-source variable, get the value from the record
1995 output.println(" /* local temps for in-set primitives */");
1996 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
1997 while( itrInSet.hasNext() ) {
1998 TempDescriptor temp = itrInSet.next();
1999 TypeDescriptor type = temp.getType();
2000 if( !type.isPtr() ) {
2001 if( fsen.getReadyInVarSet().contains( temp ) ) {
2002 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2004 output.println(" "+type+" "+temp+";");
2009 // declare local temps for out-set primitives if its not already
2010 // in the in-set, and it's value will get written so no problem
2011 output.println(" /* local temp for out-set prim, not already in the in-set */");
2012 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2013 while( itrOutSet.hasNext() ) {
2014 TempDescriptor temp = itrOutSet.next();
2015 TypeDescriptor type = temp.getType();
2016 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2017 output.println(" "+type+" "+temp+";");
2021 // copy in-set into place, ready vars were already
2022 // copied when the SESE was issued
2023 Iterator<TempDescriptor> tempItr;
2025 // static vars are from a known SESE
2026 tempItr = fsen.getStaticInVarSet().iterator();
2027 while( tempItr.hasNext() ) {
2028 TempDescriptor temp = tempItr.next();
2029 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2030 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2032 // can't grab something from this source until it is done
2033 output.println(" {");
2034 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+srcPair+";" );
2035 output.println(" pthread_mutex_lock( &(com->lock) );");
2036 output.println(" while( com->doneExecuting == FALSE ) {");
2037 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2038 output.println(" }");
2039 output.println(" pthread_mutex_unlock( &(com->lock) );");
2041 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2042 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2044 output.println(" }");
2047 // dynamic vars come from an SESE and src
2048 tempItr = fsen.getDynamicInVarSet().iterator();
2049 while( tempItr.hasNext() ) {
2050 TempDescriptor temp = tempItr.next();
2051 TypeDescriptor type = temp.getType();
2053 // go grab it from the SESE source
2054 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2056 // gotta wait until the source is done
2057 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+temp+"_srcSESE;" );
2058 output.println(" pthread_mutex_lock( &(com->lock) );");
2059 output.println(" while( com->doneExecuting == FALSE ) {");
2060 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2061 output.println(" }");
2062 output.println(" pthread_mutex_unlock( &(com->lock) );");
2065 if( type.isNull() ) {
2067 } else if( type.isClass() || type.isArray() ) {
2068 typeStr = "struct "+type.getSafeSymbol()+"*";
2070 typeStr = type.getSafeSymbol();
2073 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2074 " = *(("+typeStr+"*) ("+
2075 paramsprefix+"->"+temp+"_srcSESE + "+
2076 paramsprefix+"->"+temp+"_srcOffset));");
2078 // or if the source was our parent, its in the record to grab
2079 output.println(" } else {");
2080 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2081 " = "+paramsprefix+"->"+temp+";");
2082 output.println(" }");
2085 // Check to see if we need to do a GC if this is a
2086 // multi-threaded program...
2087 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2088 //Don't bother if we aren't in recursive methods...The loops case will catch it
2089 if (callgraph.getAllMethods(md).contains(md)) {
2090 if(this.state.MULTICOREGC) {
2091 output.println("if(gcflag) gc("+localsprefixaddr+");");
2093 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2098 // initialize thread-local var to a non-zero, invalid address
2099 output.println(" seseCaller = (SESEcommon*) 0x2;");
2100 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2101 exitset.add(seseExit);
2102 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2103 output.println("}\n\n");
2107 // when a new mlp thread is created for an issued SESE, it is started
2108 // by running this method which blocks on a cond variable until
2109 // it is allowed to transition to execute. Then a case statement
2110 // allows it to invoke the method with the proper SESE body, and after
2111 // exiting the SESE method, executes proper SESE exit code before the
2112 // thread can be destroyed
2113 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2114 PrintWriter outmethod
2117 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2118 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2119 outmethod.println( " int status;");
2120 outmethod.println( " char errmsg[128];");
2122 // generate a case for each SESE class that can be invoked
2123 outmethod.println( " switch( *((int*)seseRecord) ) {");
2124 outmethod.println( " ");
2125 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
2126 FlatSESEEnterNode fsen = seseit.next();
2128 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2129 outmethod.println( " case "+fsen.getIdentifier()+":");
2130 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2132 if( fsen.equals( mlpa.getMainSESE() ) ) {
2133 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2134 outmethod.println( " exit( 0 );");
2137 outmethod.println( " break;");
2138 outmethod.println( "");
2141 // default case should never be taken, error out
2142 outmethod.println( " default:");
2143 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2144 outmethod.println( " exit(-30);");
2145 outmethod.println( " break;");
2146 outmethod.println( " }");
2147 outmethod.println( " return NULL;");
2148 outmethod.println( "}\n\n");
2152 protected void generateCode(FlatNode first,
2155 Set<FlatNode> stopset,
2156 PrintWriter output, boolean firstpass) {
2158 /* Assign labels to FlatNode's if necessary.*/
2160 Hashtable<FlatNode, Integer> nodetolabel;
2162 if (state.DELAYCOMP&&!firstpass)
2163 nodetolabel=dcassignLabels(first, stopset);
2165 nodetolabel=assignLabels(first, stopset);
2167 Set<FlatNode> storeset=null;
2168 HashSet<FlatNode> genset=null;
2169 HashSet<FlatNode> refset=null;
2170 Set<FlatNode> unionset=null;
2172 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2173 storeset=delaycomp.livecode(lb);
2174 genset=new HashSet<FlatNode>();
2175 if (state.STMARRAY&&!state.DUALVIEW) {
2176 refset=new HashSet<FlatNode>();
2177 refset.addAll(delaycomp.getDeref(lb));
2178 refset.removeAll(delaycomp.getCannotDelay(lb));
2179 refset.removeAll(delaycomp.getOther(lb));
2182 genset.addAll(delaycomp.getCannotDelay(lb));
2183 genset.addAll(delaycomp.getOther(lb));
2185 genset.addAll(delaycomp.getNotReady(lb));
2186 if (state.STMARRAY&&!state.DUALVIEW) {
2187 genset.removeAll(refset);
2190 unionset=new HashSet<FlatNode>();
2191 unionset.addAll(storeset);
2192 unionset.addAll(genset);
2193 if (state.STMARRAY&&!state.DUALVIEW)
2194 unionset.addAll(refset);
2197 /* Do the actual code generation */
2198 FlatNode current_node=null;
2199 HashSet tovisit=new HashSet();
2200 HashSet visited=new HashSet();
2202 tovisit.add(first.getNext(0));
2205 while(current_node!=null||!tovisit.isEmpty()) {
2206 if (current_node==null) {
2207 current_node=(FlatNode)tovisit.iterator().next();
2208 tovisit.remove(current_node);
2209 } else if (tovisit.contains(current_node)) {
2210 tovisit.remove(current_node);
2212 visited.add(current_node);
2213 if (nodetolabel.containsKey(current_node)) {
2214 output.println("L"+nodetolabel.get(current_node)+":");
2216 if (state.INSTRUCTIONFAILURE) {
2217 if (state.THREAD||state.DSM||state.SINGLETM) {
2218 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2220 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2222 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2224 if (!state.DELAYCOMP||firstpass) {
2225 generateFlatNode(fm, lb, current_node, output);
2227 //store primitive variables in out set
2228 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2229 Set<TempDescriptor> liveout=ar.liveout;
2230 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2231 TempDescriptor tmp=tmpit.next();
2232 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2235 if (state.MLP && stopset!=null) {
2236 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2237 assert current_node instanceof FlatSESEExitNode;
2238 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2239 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2240 assert fsen.getFlatExit().equals( fsxn );
2241 assert fsxn.getFlatEnter().equals( fsen );
2243 if (current_node.kind()!=FKind.FlatReturnNode) {
2244 output.println(" return;");
2247 } else if(current_node.numNext()==1) {
2250 current_node.kind()==FKind.FlatSESEEnterNode &&
2251 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2253 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2254 generateFlatNode(fm, lb, current_node, output);
2255 nextnode=fsen.getFlatExit().getNext(0);
2256 } else if (state.DELAYCOMP) {
2257 boolean specialprimitive=false;
2258 //skip literals...no need to add extra overhead
2259 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2260 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2261 if (!typedesc.isClass()&&!typedesc.isArray()) {
2262 specialprimitive=true;
2266 if (genset==null||genset.contains(current_node)||specialprimitive)
2267 generateFlatNode(fm, lb, current_node, output);
2268 if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2269 //need to acquire lock
2270 handleArrayDeref(fm, lb, current_node, output, firstpass);
2272 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2273 TempDescriptor wrtmp=current_node.writesTemps()[0];
2275 //need to store value written by previous node
2276 if (wrtmp.getType().isPtr()) {
2277 //only lock the objects that may actually need locking
2278 if (recorddc.getNeedTrans(lb, current_node)&&
2279 (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2280 wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2281 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2283 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2286 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2289 //need to read value read by previous node
2290 if (wrtmp.getType().isPtr()) {
2291 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2293 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");
2297 nextnode=current_node.getNext(0);
2300 generateFlatNode(fm, lb, current_node, output);
2301 nextnode=current_node.getNext(0);
2303 if (visited.contains(nextnode)) {
2304 output.println("goto L"+nodetolabel.get(nextnode)+";");
2307 current_node=nextnode;
2308 } else if (current_node.numNext()==2) {
2310 if (state.DELAYCOMP) {
2311 boolean computeside=false;
2313 //need to record which way it should go
2314 if (genset==null||genset.contains(current_node)) {
2315 if (storeset!=null&&storeset.contains(current_node)) {
2316 //need to store which way branch goes
2317 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2319 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2321 //which side to execute
2325 if (genset.contains(current_node)) {
2326 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2327 } else if (storeset.contains(current_node)) {
2329 branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2331 //which side to execute
2336 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2338 if (leftset.size()==0)
2340 if (visited.contains(current_node.getNext(branch))) {
2341 //already visited -- build jump
2342 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2345 current_node=current_node.getNext(branch);
2348 if (!visited.contains(current_node.getNext(1)))
2349 tovisit.add(current_node.getNext(1));
2350 if (visited.contains(current_node.getNext(0))) {
2351 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2354 current_node=current_node.getNext(0);
2358 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2359 if (!visited.contains(current_node.getNext(1)))
2360 tovisit.add(current_node.getNext(1));
2361 if (visited.contains(current_node.getNext(0))) {
2362 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2365 current_node=current_node.getNext(0);
2367 } else throw new Error();
2371 protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2372 if (fn.kind()==FKind.FlatSetElementNode) {
2373 FlatSetElementNode fsen=(FlatSetElementNode) fn;
2374 String dst=generateTemp(fm, fsen.getDst(), lb);
2375 String src=generateTemp(fm, fsen.getSrc(), lb);
2376 String index=generateTemp(fm, fsen.getIndex(), lb);
2377 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2379 if (elementtype.isArray()||elementtype.isClass())
2382 type=elementtype.getSafeSymbol()+" ";
2384 output.println("STOREARRAY("+dst+","+index+","+type+")");
2386 output.println("{");
2387 output.println(" struct ArrayObject *array;");
2388 output.println(" int index;");
2389 output.println(" RESTOREARRAY(array,index);");
2390 output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2391 output.println("}");
2393 } else if (fn.kind()==FKind.FlatElementNode) {
2394 FlatElementNode fen=(FlatElementNode) fn;
2395 String src=generateTemp(fm, fen.getSrc(), lb);
2396 String index=generateTemp(fm, fen.getIndex(), lb);
2397 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2398 String dst=generateTemp(fm, fen.getDst(), lb);
2400 if (elementtype.isArray()||elementtype.isClass())
2403 type=elementtype.getSafeSymbol()+" ";
2405 output.println("STOREARRAY("+src+","+index+","+type+")");
2407 output.println("{");
2408 output.println(" struct ArrayObject *array;");
2409 output.println(" int index;");
2410 output.println(" RESTOREARRAY(array,index);");
2411 output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2412 output.println("}");
2416 /** Special label assignment for delaycomputation */
2417 protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2418 HashSet tovisit=new HashSet();
2419 HashSet visited=new HashSet();
2421 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2423 //Label targets of branches
2424 Set<FlatNode> targets=branchanalysis.getTargets();
2425 for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2426 nodetolabel.put(it.next(), new Integer(labelindex++));
2431 /*Assign labels first. A node needs a label if the previous
2432 * node has two exits or this node is a join point. */
2434 while(!tovisit.isEmpty()) {
2435 FlatNode fn=(FlatNode)tovisit.iterator().next();
2440 if(lastset!=null&&lastset.contains(fn)) {
2441 // if last is not null and matches, don't go
2442 // any further for assigning labels
2446 for(int i=0; i<fn.numNext(); i++) {
2447 FlatNode nn=fn.getNext(i);
2450 //1) Edge >1 of node
2451 nodetolabel.put(nn,new Integer(labelindex++));
2453 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2457 nodetolabel.put(nn,new Integer(labelindex++));
2465 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2466 return assignLabels(first, null);
2469 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2470 HashSet tovisit=new HashSet();
2471 HashSet visited=new HashSet();
2473 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2476 /*Assign labels first. A node needs a label if the previous
2477 * node has two exits or this node is a join point. */
2479 while(!tovisit.isEmpty()) {
2480 FlatNode fn=(FlatNode)tovisit.iterator().next();
2485 if(lastset!=null&&lastset.contains(fn)) {
2486 // if last is not null and matches, don't go
2487 // any further for assigning labels
2491 for(int i=0; i<fn.numNext(); i++) {
2492 FlatNode nn=fn.getNext(i);
2495 //1) Edge >1 of node
2496 nodetolabel.put(nn,new Integer(labelindex++));
2498 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2502 nodetolabel.put(nn,new Integer(labelindex++));
2510 /** Generate text string that corresponds to the TempDescriptor td. */
2511 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2512 MethodDescriptor md=fm.getMethod();
2513 TaskDescriptor task=fm.getTask();
2514 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2516 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2517 //System.out.println("generateTemp returns " + td.getSafeSymbol());
2518 return td.getSafeSymbol();
2521 if (objecttemps.isLocalPtr(td)) {
2522 return localsprefixderef+td.getSafeSymbol();
2525 if (objecttemps.isParamPtr(td)) {
2526 return paramsprefix+"->"+td.getSafeSymbol();
2532 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2534 // insert pre-node actions from the code plan
2537 CodePlan cp = mlpa.getCodePlan( fn );
2540 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2542 // for each sese and age pair that this parent statement
2543 // must stall on, take that child's stall semaphore, the
2544 // copying of values comes after the statement
2545 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2546 while( vstItr.hasNext() ) {
2547 VariableSourceToken vst = vstItr.next();
2549 SESEandAgePair p = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2551 output.println(" {");
2552 output.println(" SESEcommon* common = (SESEcommon*) "+p+";");
2554 output.println(" pthread_mutex_lock( &(common->lock) );");
2555 output.println(" while( common->doneExecuting == FALSE ) {");
2556 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2557 output.println(" }");
2558 output.println(" pthread_mutex_unlock( &(common->lock) );");
2560 //output.println(" psem_take( &(common->stallSem) );");
2562 // copy things we might have stalled for
2563 output.println(" "+p.getSESE().getSESErecordName()+"* child = ("+
2564 p.getSESE().getSESErecordName()+"*) "+p+";");
2566 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2567 while( tdItr.hasNext() ) {
2568 TempDescriptor td = tdItr.next();
2569 FlatMethod fmContext;
2570 if( currentSESE.getIsCallerSESEplaceholder() ) {
2571 fmContext = currentSESE.getfmEnclosing();
2573 fmContext = currentSESE.getfmBogus();
2575 output.println(" "+generateTemp( fmContext, td, null )+
2576 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2579 output.println(" }");
2582 // for each variable with a dynamic source, stall just for that variable
2583 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2584 while( dynItr.hasNext() ) {
2585 TempDescriptor dynVar = dynItr.next();
2587 // only stall if the dynamic source is not yourself, denoted by src==NULL
2588 // otherwise the dynamic write nodes will have the local var up-to-date
2589 output.println(" {");
2590 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2591 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2592 output.println(" psem_take( &(common->stallSem) );");
2594 FlatMethod fmContext;
2595 if( currentSESE.getIsCallerSESEplaceholder() ) {
2596 fmContext = currentSESE.getfmEnclosing();
2598 fmContext = currentSESE.getfmBogus();
2600 output.println(" "+generateTemp( fmContext, dynVar, null )+
2601 " = *(("+dynVar.getType()+"*) ("+
2602 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2604 output.println(" }");
2605 output.println(" }");
2608 // for each assignment of a variable to rhs that has a dynamic source,
2609 // copy the dynamic sources
2610 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2611 while( dynAssignItr.hasNext() ) {
2612 Map.Entry me = (Map.Entry) dynAssignItr.next();
2613 TempDescriptor lhs = (TempDescriptor) me.getKey();
2614 TempDescriptor rhs = (TempDescriptor) me.getValue();
2615 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
2616 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2619 // for each lhs that is dynamic from a non-dynamic source, set the
2620 // dynamic source vars to the current SESE
2621 dynItr = cp.getDynAssignCurr().iterator();
2622 while( dynItr.hasNext() ) {
2623 TempDescriptor dynVar = dynItr.next();
2624 output.println(" "+dynVar+"_srcSESE = NULL;");
2630 case FKind.FlatAtomicEnterNode:
2631 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
2634 case FKind.FlatAtomicExitNode:
2635 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
2638 case FKind.FlatInstanceOfNode:
2639 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
2642 case FKind.FlatSESEEnterNode:
2643 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
2646 case FKind.FlatSESEExitNode:
2647 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
2650 case FKind.FlatWriteDynamicVarNode:
2651 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
2654 case FKind.FlatGlobalConvNode:
2655 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
2658 case FKind.FlatTagDeclaration:
2659 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
2662 case FKind.FlatCall:
2663 generateFlatCall(fm, lb, (FlatCall) fn,output);
2666 case FKind.FlatFieldNode:
2667 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
2670 case FKind.FlatElementNode:
2671 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
2674 case FKind.FlatSetElementNode:
2675 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
2678 case FKind.FlatSetFieldNode:
2679 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
2683 generateFlatNew(fm, lb, (FlatNew) fn,output);
2686 case FKind.FlatOpNode:
2687 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
2690 case FKind.FlatCastNode:
2691 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
2694 case FKind.FlatLiteralNode:
2695 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
2698 case FKind.FlatReturnNode:
2699 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
2703 output.println("/* nop */");
2706 case FKind.FlatExit:
2707 output.println("/* exit */");
2710 case FKind.FlatBackEdge:
2711 if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
2712 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
2714 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
2715 || (this.state.MULTICOREGC)) {
2716 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
2717 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
2718 } else if(this.state.MULTICOREGC) {
2719 output.println("if (gcflag) gc("+localsprefixaddr+");");
2721 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2724 output.println("/* nop */");
2727 case FKind.FlatCheckNode:
2728 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
2731 case FKind.FlatFlagActionNode:
2732 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
2735 case FKind.FlatPrefetchNode:
2736 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
2739 case FKind.FlatOffsetNode:
2740 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
2747 // insert post-node actions from the code-plan
2749 CodePlan cp = mlpa.getCodePlan( fn );
2756 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
2757 output.println("/* FlatOffsetNode */");
2758 FieldDescriptor fd=fofn.getField();
2759 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
2760 output.println("/* offset */");
2763 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
2764 if (state.PREFETCH) {
2765 Vector oids = new Vector();
2766 Vector fieldoffset = new Vector();
2767 Vector endoffset = new Vector();
2768 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
2769 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
2770 PrefetchPair pp = (PrefetchPair) it.next();
2771 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
2772 /* Find prefetches that can generate oid */
2773 if(statusbase == LocalityAnalysis.GLOBAL) {
2774 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
2776 } else if (statusbase == LocalityAnalysis.LOCAL) {
2777 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
2784 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
2785 output.println("{");
2786 output.println("/* prefetch */");
2787 output.println("/* prefetchid_" + fpn.siteid + " */");
2788 output.println("void * prefptr;");
2789 output.println("int tmpindex;");
2791 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
2792 /*Create C code for oid array */
2793 output.print(" unsigned int oidarray_[] = {");
2794 boolean needcomma=false;
2795 for (Iterator it = oids.iterator(); it.hasNext();) {
2798 output.print(it.next());
2801 output.println("};");
2803 /*Create C code for endoffset values */
2804 output.print(" unsigned short endoffsetarry_[] = {");
2806 for (Iterator it = endoffset.iterator(); it.hasNext();) {
2809 output.print(it.next());
2812 output.println("};");
2814 /*Create C code for Field Offset Values */
2815 output.print(" short fieldarry_[] = {");
2817 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
2820 output.print(it.next());
2823 output.println("};");
2824 /* make the prefetch call to Runtime */
2825 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
2826 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
2827 output.println(" }");
2828 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
2829 output.println(" } else {");
2830 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
2831 output.println(" }");
2832 output.println("}");
2836 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
2837 short offsetcount = 0;
2841 } else if (localbase) {
2842 for(; breakindex<pp.desc.size(); breakindex++) {
2843 Descriptor desc=pp.getDescAt(breakindex);
2844 if (desc instanceof FieldDescriptor) {
2845 FieldDescriptor fd=(FieldDescriptor)desc;
2846 if (fd.isGlobal()) {
2854 if (breakindex>pp.desc.size()) //all local
2857 TypeDescriptor lasttype=pp.base.getType();
2858 String basestr=generateTemp(fm, pp.base, lb);
2860 boolean maybenull=fm.getMethod().isStatic()||
2861 !pp.base.equals(fm.getParameter(0));
2863 for(int i=0; i<breakindex; i++) {
2864 String indexcheck="";
2866 Descriptor desc=pp.getDescAt(i);
2867 if (desc instanceof FieldDescriptor) {
2868 FieldDescriptor fd=(FieldDescriptor)desc;
2870 if (!teststr.equals(""))
2872 teststr+="((prefptr="+basestr+")!=NULL)";
2873 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
2875 basestr=basestr+"->"+fd.getSafeSymbol();
2878 lasttype=fd.getType();
2880 IndexDescriptor id=(IndexDescriptor)desc;
2881 indexcheck="((tmpindex=";
2882 for(int j=0; j<id.tddesc.size(); j++) {
2883 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
2885 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
2887 if (!teststr.equals(""))
2889 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
2890 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
2892 lasttype=lasttype.dereference();
2897 if (teststr.equals("")) {
2898 oid="((unsigned int)"+basestr+")";
2900 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
2904 for(int i = breakindex; i < pp.desc.size(); i++) {
2905 String newfieldoffset;
2906 Object desc = pp.getDescAt(i);
2907 if(desc instanceof FieldDescriptor) {
2908 FieldDescriptor fd=(FieldDescriptor)desc;
2909 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
2910 lasttype=fd.getType();
2912 newfieldoffset = "";
2913 IndexDescriptor id=(IndexDescriptor)desc;
2914 for(int j = 0; j < id.tddesc.size(); j++) {
2915 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
2917 newfieldoffset += id.offset.toString();
2918 lasttype=lasttype.dereference();
2920 fieldoffset.add(newfieldoffset);
2923 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
2924 base+=pp.desc.size()-breakindex;
2925 endoffset.add(new Short((short)base));
2930 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
2931 if (lb!=fgcn.getLocality())
2933 /* Have to generate flat globalconv */
2934 if (fgcn.getMakePtr()) {
2936 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
2938 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
2939 //need to do translation
2940 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
2941 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
2942 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
2946 /* Need to convert to OID */
2947 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
2948 if (fgcn.doConvert()||(delaycomp!=null&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
2949 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
2951 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
2957 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
2959 if (fion.getType().isArray()) {
2960 type=state.getArrayNumber(fion.getType())+state.numClasses();
2962 type=fion.getType().getClassDesc().getId();
2965 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
2966 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
2968 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
2971 int sandboxcounter=0;
2972 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
2973 /* Check to see if we need to generate code for this atomic */
2974 if (locality==null) {
2975 if (GENERATEPRECISEGC) {
2976 output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
2977 output.println("stopforgc((struct garbagelist *) &___locals___);");
2978 output.println("pthread_mutex_lock(&atomiclock);");
2979 output.println("restartaftergc();");
2980 output.println("}");
2982 output.println("pthread_mutex_lock(&atomiclock);");
2987 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
2991 if (state.SANDBOX) {
2992 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
2993 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
2996 if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
2997 AtomicRecord ar=atomicmethodmap.get(faen);
2999 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3000 TempDescriptor tmp=tmpit.next();
3001 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3004 //copy outs that depend on path
3005 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3006 TempDescriptor tmp=tmpit.next();
3007 if (!ar.livein.contains(tmp))
3008 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3012 /* Backup the temps. */
3013 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3014 TempDescriptor tmp=tmpit.next();
3015 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3018 output.println("goto transstart"+faen.getIdentifier()+";");
3020 /******* Print code to retry aborted transaction *******/
3021 output.println("transretry"+faen.getIdentifier()+":");
3024 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3025 TempDescriptor tmp=tmpit.next();
3026 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3030 /********* Need to revert local object store ********/
3031 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3033 output.println("while ("+revertptr+") {");
3034 output.println("struct ___Object___ * tmpptr;");
3035 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3036 output.println("REVERT_OBJ("+revertptr+");");
3037 output.println(revertptr+"=tmpptr;");
3038 output.println("}");
3040 /******* Tell the runtime to start the transaction *******/
3042 output.println("transstart"+faen.getIdentifier()+":");
3043 if (state.SANDBOX) {
3044 output.println("transaction_check_counter=*counter_reset_pointer;");
3047 output.println("transStart();");
3049 if (state.ABORTREADERS||state.SANDBOX) {
3051 output.println("abortenabled=1;");
3052 output.println("if (_setjmp(aborttrans)) {");
3053 output.println(" goto transretry"+faen.getIdentifier()+"; }");
3057 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3058 /* Check to see if we need to generate code for this atomic */
3059 if (locality==null) {
3060 output.println("pthread_mutex_unlock(&atomiclock);");
3063 if (locality.getAtomic(lb).get(faen).intValue()>0)
3065 //store the revert list before we lose the transaction object
3068 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3069 output.println(revertptr+"=revertlist;");
3070 output.println("if (transCommit()) {");
3071 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3072 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3073 output.println("} else {");
3074 /* Need to commit local object store */
3075 output.println("while ("+revertptr+") {");
3076 output.println("struct ___Object___ * tmpptr;");
3077 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3078 output.println("COMMIT_OBJ("+revertptr+");");
3079 output.println(revertptr+"=tmpptr;");
3080 output.println("}");
3081 output.println("}");
3085 if (!state.DELAYCOMP) {
3087 output.println("if (transCommit()) {");
3088 /* Transaction aborts if it returns true */
3089 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3090 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3091 output.println("}");
3093 if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
3094 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3095 output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3097 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3098 TempDescriptor tmp=tmpit.next();
3099 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3101 } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3102 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3104 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3105 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3106 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3107 output.println("}");
3109 output.println("else {");
3110 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3111 TempDescriptor tmp=tmpit.next();
3112 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3114 output.println("}");
3116 output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3117 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3118 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3119 output.println("}");
3124 public void generateFlatSESEEnterNode( FlatMethod fm,
3126 FlatSESEEnterNode fsen,
3130 // if MLP flag is off, okay that SESE nodes are in IR graph,
3131 // just skip over them and code generates exactly the same
3136 // there may be an SESE in an unreachable method, skip over
3137 if( !mlpa.getAllSESEs().contains( fsen ) ) {
3141 // also, if we have encountered a placeholder, just skip it
3142 if( fsen.getIsCallerSESEplaceholder() ) {
3146 output.println(" {");
3148 // set up the parent
3149 if( fsen == mlpa.getMainSESE() ) {
3150 output.println(" SESEcommon* parentCommon = NULL;");
3152 if( fsen.getParent() == null ) {
3153 System.out.println( "in "+fm+", "+fsen+" has null parent" );
3155 assert fsen.getParent() != null;
3156 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3157 output.println(" SESEcommon* parentCommon = &("+paramsprefix+"->common);");
3159 //output.println(" SESEcommon* parentCommon = (SESEcommon*) peekItem( seseCallStack );");
3160 output.println(" SESEcommon* parentCommon = seseCaller;");
3164 // before doing anything, lock your own record and increment the running children
3165 if( fsen != mlpa.getMainSESE() ) {
3166 output.println(" pthread_mutex_lock( &(parentCommon->lock) );");
3167 output.println(" ++(parentCommon->numRunningChildren);");
3168 output.println(" pthread_mutex_unlock( &(parentCommon->lock) );");
3171 // just allocate the space for this record
3172 output.println(" "+fsen.getSESErecordName()+"* seseToIssue = ("+
3173 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3174 fsen.getSESErecordName()+" ) );");
3176 // and keep the thread-local sese stack up to date
3177 //output.println(" addNewItem( seseCallStack, (void*) seseToIssue);");
3179 // fill in common data
3180 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3181 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
3183 output.println(" seseToIssue->common.forwardList = createQueue();");
3184 output.println(" seseToIssue->common.unresolvedDependencies = 0;");
3185 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3186 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3187 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3188 output.println(" seseToIssue->common.numRunningChildren = 0;");
3189 output.println(" seseToIssue->common.parent = parentCommon;");
3191 // all READY in-vars should be copied now and be done with it
3192 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3193 while( tempItr.hasNext() ) {
3194 TempDescriptor temp = tempItr.next();
3196 // when we are issuing the main SESE or an SESE with placeholder
3197 // caller SESE as parent, generate temp child child's eclosing method,
3198 // otherwise use the parent's enclosing method as the context
3199 boolean useParentContext = false;
3201 if( fsen != mlpa.getMainSESE() ) {
3202 assert fsen.getParent() != null;
3203 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3204 useParentContext = true;
3208 if( useParentContext ) {
3209 output.println(" seseToIssue->"+temp+" = "+
3210 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3212 output.println(" seseToIssue->"+temp+" = "+
3213 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3217 // before potentially adding this SESE to other forwarding lists,
3218 // create it's lock and take it immediately
3219 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3220 output.println(" pthread_mutex_lock( &(seseToIssue->common.lock) );");
3222 if( fsen != mlpa.getMainSESE() ) {
3223 // count up outstanding dependencies, static first, then dynamic
3224 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3225 while( staticSrcsItr.hasNext() ) {
3226 SESEandAgePair srcPair = staticSrcsItr.next();
3227 output.println(" {");
3228 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3229 output.println(" pthread_mutex_lock( &(src->lock) );");
3230 output.println(" if( !isEmpty( src->forwardList ) &&");
3231 output.println(" seseToIssue == peekItem( src->forwardList ) ) {");
3232 output.println(" printf( \"This shouldnt already be here\\n\");");
3233 output.println(" exit( -1 );");
3234 output.println(" }");
3235 output.println(" if( !src->doneExecuting ) {");
3236 output.println(" addNewItem( src->forwardList, seseToIssue );");
3237 output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3238 output.println(" }");
3239 output.println(" pthread_mutex_unlock( &(src->lock) );");
3240 output.println(" }");
3242 // whether or not it is an outstanding dependency, make sure
3243 // to pass the static name to the child's record
3244 output.println(" seseToIssue->"+srcPair+" = "+srcPair+";");
3247 // dynamic sources might already be accounted for in the static list,
3248 // so only add them to forwarding lists if they're not already there
3249 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3250 while( dynVarsItr.hasNext() ) {
3251 TempDescriptor dynInVar = dynVarsItr.next();
3252 output.println(" {");
3253 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3255 // the dynamic source is NULL if it comes from your own space--you can't pass
3256 // the address off to the new child, because you're not done executing and
3257 // might change the variable, so copy it right now
3258 output.println(" if( src != NULL ) {");
3259 output.println(" pthread_mutex_lock( &(src->lock) );");
3260 output.println(" if( isEmpty( src->forwardList ) ||");
3261 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3262 output.println(" if( !src->doneExecuting ) {");
3263 output.println(" addNewItem( src->forwardList, seseToIssue );");
3264 output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3265 output.println(" }");
3266 output.println(" }");
3267 output.println(" pthread_mutex_unlock( &(src->lock) );");
3268 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3269 output.println(" } else {");
3271 boolean useParentContext = false;
3272 if( fsen != mlpa.getMainSESE() ) {
3273 assert fsen.getParent() != null;
3274 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3275 useParentContext = true;
3278 if( useParentContext ) {
3279 output.println(" seseToIssue->"+dynInVar+" = "+
3280 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3282 output.println(" seseToIssue->"+dynInVar+" = "+
3283 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3286 output.println(" }");
3287 output.println(" }");
3289 // even if the value is already copied, make sure your NULL source
3290 // gets passed so child knows it already has the dynamic value
3291 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3294 // maintain pointers for for finding dynamic SESE
3295 // instances from static names
3296 SESEandAgePair p = new SESEandAgePair( fsen, 0 );
3297 if( fsen.getParent() != null &&
3298 //!fsen.getParent().getIsCallerSESEplaceholder() &&
3299 fsen.getParent().getNeededStaticNames().contains( p )
3302 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3303 SESEandAgePair p1 = new SESEandAgePair( fsen, i );
3304 SESEandAgePair p2 = new SESEandAgePair( fsen, i-1 );
3305 output.println(" "+p1+" = "+p2+";");
3307 output.println(" "+p+" = seseToIssue;");
3311 // if there were no outstanding dependencies, issue here
3312 output.println(" if( seseToIssue->common.unresolvedDependencies == 0 ) {");
3313 output.println(" workScheduleSubmit( (void*)seseToIssue );");
3314 output.println(" }");
3316 // release this SESE for siblings to update its dependencies or,
3317 // eventually, for it to mark itself finished
3318 output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3319 output.println(" }");
3323 public void generateFlatSESEExitNode( FlatMethod fm,
3325 FlatSESEExitNode fsexn,
3329 // if MLP flag is off, okay that SESE nodes are in IR graph,
3330 // just skip over them and code generates exactly the same
3335 // get the enter node for this exit that has meta data embedded
3336 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
3338 // there may be an SESE in an unreachable method, skip over
3339 if( !mlpa.getAllSESEs().contains( fsen ) ) {
3343 // also, if we have encountered a placeholder, just jump it
3344 if( fsen.getIsCallerSESEplaceholder() ) {
3348 output.println(" /* SESE exiting */");
3350 String com = paramsprefix+"->common";
3352 // this SESE cannot be done until all of its children are done
3353 // so grab your own lock with the condition variable for watching
3354 // that the number of your running children is greater than zero
3355 output.println(" pthread_mutex_lock( &("+com+".lock) );");
3356 output.println(" while( "+com+".numRunningChildren > 0 ) {");
3357 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
3358 output.println(" }");
3360 // copy out-set from local temps into the sese record
3361 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
3362 while( itr.hasNext() ) {
3363 TempDescriptor temp = itr.next();
3365 // only have to do this for primitives
3366 if( !temp.getType().isPrimitive() ) {
3370 // have to determine the context enclosing this sese
3371 boolean useParentContext = false;
3373 if( fsen != mlpa.getMainSESE() ) {
3374 assert fsen.getParent() != null;
3375 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3376 useParentContext = true;
3381 if( useParentContext ) {
3382 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
3384 from = generateTemp( fsen.getfmEnclosing(), temp, null );
3387 output.println(" "+paramsprefix+
3388 "->"+temp.getSafeSymbol()+
3392 // mark yourself done, your SESE data is now read-only
3393 output.println(" "+com+".doneExecuting = TRUE;");
3394 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
3395 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
3397 // decrement dependency count for all SESE's on your forwarding list
3398 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
3399 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
3400 output.println(" pthread_mutex_lock( &(consumer->lock) );");
3401 output.println(" --(consumer->unresolvedDependencies);");
3402 output.println(" if( consumer->unresolvedDependencies == 0 ) {");
3403 output.println(" workScheduleSubmit( (void*)consumer );");
3404 output.println(" }");
3405 output.println(" pthread_mutex_unlock( &(consumer->lock) );");
3406 output.println(" }");
3408 // if parent is stalling on you, let them know you're done
3409 if( fsexn.getFlatEnter() != mlpa.getMainSESE() ) {
3410 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
3413 // last of all, decrement your parent's number of running children
3414 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
3415 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
3416 output.println(" --("+paramsprefix+"->common.parent->numRunningChildren);");
3417 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
3418 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
3419 output.println(" }");
3421 // this is a thread-only variable that can be handled when critical sese-to-sese
3422 // data has been taken care of--set sese pointer to remember self over method
3423 // calls to a non-zero, invalid address
3424 output.println(" seseCaller = (SESEcommon*) 0x1;");
3427 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
3429 FlatWriteDynamicVarNode fwdvn,
3433 // should node should not be in an IR graph if the
3434 // MLP flag is not set
3435 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
3438 Hashtable<TempDescriptor, VariableSourceToken> writeDynamic =
3441 assert writeDynamic != null;
3443 Iterator wdItr = writeDynamic.entrySet().iterator();
3444 while( wdItr.hasNext() ) {
3445 Map.Entry me = (Map.Entry) wdItr.next();
3446 TempDescriptor refVar = (TempDescriptor) me.getKey();
3447 VariableSourceToken vst = (VariableSourceToken) me.getValue();
3449 FlatSESEEnterNode current = fwdvn.getEnclosingSESE();
3451 // only do this if the variable in question should be tracked,
3452 // meaning that it was explicitly added to the dynamic var set
3453 if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
3457 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
3459 output.println(" {");
3461 if( current.equals( vst.getSESE() ) ) {
3462 // if the src comes from this SESE, it's a method local variable,
3463 // mark src pointer NULL to signify that the var is up-to-date
3464 output.println(" "+vst.getAddrVar()+"_srcSESE = NULL;");
3467 // otherwise we track where it will come from
3468 output.println(" "+vst.getAddrVar()+"_srcSESE = "+instance+";");
3469 output.println(" "+vst.getAddrVar()+"_srcOffset = (int) &((("+
3470 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
3473 output.println(" }");
3478 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
3479 if (state.CONSCHECK) {
3480 String specname=fcn.getSpec();
3481 String varname="repairstate___";
3482 output.println("{");
3483 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
3485 TempDescriptor[] temps=fcn.getTemps();
3486 String[] vars=fcn.getVars();
3487 for(int i=0; i<temps.length; i++) {
3488 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
3491 output.println("if (doanalysis"+specname+"("+varname+")) {");
3492 output.println("free"+specname+"_state("+varname+");");
3493 output.println("} else {");
3494 output.println("/* Bad invariant */");
3495 output.println("free"+specname+"_state("+varname+");");
3496 output.println("abort_task();");
3497 output.println("}");
3498 output.println("}");
3502 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
3504 if( state.MLP && !nonSESEpass ) {
3505 output.println(" seseCaller = (SESEcommon*)"+paramsprefix+";");
3508 MethodDescriptor md=fc.getMethod();
3509 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
3510 ClassDescriptor cn=md.getClassDesc();
3511 output.println("{");
3512 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3514 LocalityBinding fclb=locality.getBinding(lb, fc);
3515 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3517 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3519 output.print(objectparams.numPointers());
3520 output.print(", "+localsprefixaddr);
3521 if (md.getThis()!=null) {
3523 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
3525 if (fc.getThis()!=null&&md.getThis()==null) {
3526 System.out.println("WARNING!!!!!!!!!!!!");
3527 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
3531 for(int i=0; i<fc.numArgs(); i++) {
3532 Descriptor var=md.getParameter(i);
3533 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3534 if (objectparams.isParamPtr(paramtemp)) {
3535 TempDescriptor targ=fc.getArg(i);
3537 TypeDescriptor td=md.getParamType(i);
3539 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3541 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3544 output.println("};");
3549 if (fc.getReturnTemp()!=null)
3550 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
3552 /* Do we need to do virtual dispatch? */
3553 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
3556 LocalityBinding fclb=locality.getBinding(lb, fc);
3557 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3559 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3564 if (md.getReturnType().isClass()||md.getReturnType().isArray())
3565 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3567 output.print(md.getReturnType().getSafeSymbol()+" ");
3568 output.print("(*)(");
3570 boolean printcomma=false;
3571 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3573 LocalityBinding fclb=locality.getBinding(lb, fc);
3574 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3576 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3580 for(int i=0; i<objectparams.numPrimitives(); i++) {
3581 TempDescriptor temp=objectparams.getPrimitive(i);
3585 if (temp.getType().isClass()||temp.getType().isArray())
3586 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
3588 output.print(temp.getType().getSafeSymbol());
3593 LocalityBinding fclb=locality.getBinding(lb, fc);
3594 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
3596 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
3600 boolean needcomma=false;
3601 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3602 output.print("&__parameterlist__");
3606 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
3607 if (fc.getThis()!=null) {
3608 TypeDescriptor ptd=md.getThis().getType();
3611 if (ptd.isClass()&&!ptd.isArray())
3612 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3613 output.print(generateTemp(fm,fc.getThis(),lb));
3618 for(int i=0; i<fc.numArgs(); i++) {
3619 Descriptor var=md.getParameter(i);
3620 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3621 if (objectparams.isParamPrim(paramtemp)) {
3622 TempDescriptor targ=fc.getArg(i);
3626 TypeDescriptor ptd=md.getParamType(i);
3627 if (ptd.isClass()&&!ptd.isArray())
3628 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3629 output.print(generateTemp(fm, targ,lb));
3633 output.println(");");
3634 output.println(" }");
3637 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
3638 Set subclasses=typeutil.getSubClasses(thiscd);
3639 if (subclasses==null)
3641 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
3642 ClassDescriptor cd=(ClassDescriptor)classit.next();
3643 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
3644 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
3645 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
3646 if (md.matches(matchmd))
3653 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
3654 if (state.SINGLETM) {
3655 //single machine transactional memory case
3656 String field=ffn.getField().getSafeSymbol();
3657 String src=generateTemp(fm, ffn.getSrc(),lb);
3658 String dst=generateTemp(fm, ffn.getDst(),lb);
3660 output.println(dst+"="+ src +"->"+field+ ";");
3661 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
3662 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
3663 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
3664 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
3665 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
3666 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
3667 output.println("TRANSREADRD("+dst+", "+dst+");");
3670 } else if (state.DSM) {
3671 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
3672 if (status==LocalityAnalysis.GLOBAL) {
3673 String field=ffn.getField().getSafeSymbol();
3674 String src=generateTemp(fm, ffn.getSrc(),lb);
3675 String dst=generateTemp(fm, ffn.getDst(),lb);
3677 if (ffn.getField().getType().isPtr()) {
3679 //TODO: Uncomment this when we have runtime support
3680 //if (ffn.getSrc()==ffn.getDst()) {
3681 //output.println("{");
3682 //output.println("void * temp="+src+";");
3683 //output.println("if (temp&0x1) {");
3684 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
3685 //output.println(src+"->"+field+"="+temp+";");
3686 //output.println("}");
3687 //output.println(dst+"=temp;");
3688 //output.println("}");
3690 output.println(dst+"="+ src +"->"+field+ ";");
3691 //output.println("if ("+dst+"&0x1) {");
3692 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3693 //output.println(src+"->"+field+"="+src+"->"+field+";");
3694 //output.println("}");
3697 output.println(dst+"="+ src+"->"+field+";");
3699 } else if (status==LocalityAnalysis.LOCAL) {
3700 if (ffn.getField().getType().isPtr()&&
3701 ffn.getField().isGlobal()) {
3702 String field=ffn.getField().getSafeSymbol();
3703 String src=generateTemp(fm, ffn.getSrc(),lb);
3704 String dst=generateTemp(fm, ffn.getDst(),lb);
3705 output.println(dst+"="+ src +"->"+field+ ";");
3706 if (locality.getAtomic(lb).get(ffn).intValue()>0)
3707 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3709 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3710 } else if (status==LocalityAnalysis.EITHER) {
3711 //Code is reading from a null pointer
3712 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
3713 output.println("#ifndef RAW");
3714 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
3715 output.println("#endif");
3716 //This should throw a suitable null pointer error
3717 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3719 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
3721 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3725 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
3726 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
3727 throw new Error("Can't set array length");
3728 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3729 //Single Machine Transaction Case
3730 boolean srcptr=fsfn.getSrc().getType().isPtr();
3731 String src=generateTemp(fm,fsfn.getSrc(),lb);
3732 String dst=generateTemp(fm,fsfn.getDst(),lb);
3733 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
3734 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
3735 output.println("{");
3736 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
3737 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
3738 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3740 output.println("INTPTR srcoid=(INTPTR)"+src+";");
3743 if (wb.needBarrier(fsfn)&&
3744 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
3745 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
3747 if (srcptr&!fsfn.getSrc().getType().isNull()) {
3748 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
3749 output.println("}");
3751 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3753 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3754 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
3755 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
3756 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
3758 String src=generateTemp(fm,fsfn.getSrc(),lb);
3759 String dst=generateTemp(fm,fsfn.getDst(),lb);
3761 output.println("{");
3762 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3764 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
3767 if (wb.needBarrier(fsfn))
3768 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
3770 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
3772 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3773 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
3774 /** Check if we need to copy */
3775 output.println("if(!"+dst+"->"+localcopystr+") {");
3776 /* Link object into list */
3777 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3778 output.println(revertptr+"=revertlist;");
3779 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3780 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3782 output.println("COPY_OBJ("+dst+");");
3783 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3784 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3785 output.println("}");
3787 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
3789 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3790 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
3791 //writing to a null...bad
3792 output.println("if ("+dst+") {");
3793 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
3795 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
3797 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3800 output.println("}");
3803 if (state.FASTCHECK) {
3804 String dst=generateTemp(fm, fsfn.getDst(),lb);
3805 output.println("if(!"+dst+"->"+localcopystr+") {");
3806 /* Link object into list */
3807 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3808 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3810 output.println("COPY_OBJ("+dst+");");
3811 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3812 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3813 output.println("}");
3815 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
3819 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
3820 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
3823 if (elementtype.isArray()||elementtype.isClass())
3826 type=elementtype.getSafeSymbol()+" ";
3828 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
3829 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
3830 output.println("failedboundschk();");
3832 if (state.SINGLETM) {
3833 //Single machine transaction case
3834 String dst=generateTemp(fm, fen.getDst(),lb);
3835 if ((!state.STMARRAY)||(!wb.needBarrier(fen))||locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())==LocalityAnalysis.SCRATCH||locality.getAtomic(lb).get(fen).intValue()==0||
3836 (state.READSET&&!dc.getNeedGet(lb, fen))) {
3837 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3839 output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
3842 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
3843 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
3844 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
3845 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
3846 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
3847 output.println("TRANSREADRD("+dst+", "+dst+");");
3850 } else if (state.DSM) {
3851 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
3852 if (status==LocalityAnalysis.GLOBAL) {
3853 String dst=generateTemp(fm, fen.getDst(),lb);
3854 if (elementtype.isPtr()) {
3855 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3856 output.println("TRANSREAD("+dst+", "+dst+");");
3858 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3860 } else if (status==LocalityAnalysis.LOCAL) {
3861 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3862 } else if (status==LocalityAnalysis.EITHER) {
3863 //Code is reading from a null pointer
3864 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
3865 output.println("#ifndef RAW");
3866 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
3867 output.println("#endif");
3868 //This should throw a suitable null pointer error
3869 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3871 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
3873 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
3877 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
3878 //TODO: need dynamic check to make sure this assignment is actually legal
3879 //Because Object[] could actually be something more specific...ie. Integer[]
3881 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
3884 if (elementtype.isArray()||elementtype.isClass())
3887 type=elementtype.getSafeSymbol()+" ";
3889 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
3890 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
3891 output.println("failedboundschk();");
3894 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
3895 //Transaction set element case
3896 if (wb.needBarrier(fsen)&&
3897 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
3898 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
3900 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
3901 output.println("{");
3902 String src=generateTemp(fm, fsen.getSrc(), lb);
3903 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
3904 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
3905 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3907 output.println("INTPTR srcoid=(INTPTR)"+src+";");
3909 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
3910 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
3912 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
3914 output.println("}");
3916 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
3917 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
3919 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3922 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
3923 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
3924 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
3925 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
3926 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
3927 boolean dstlocal=statusdst==LocalityAnalysis.LOCAL;
3930 if (wb.needBarrier(fsen))
3931 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
3932 } else if (dstlocal) {
3933 /** Check if we need to copy */
3934 String dst=generateTemp(fm, fsen.getDst(),lb);
3935 output.println("if(!"+dst+"->"+localcopystr+") {");
3936 /* Link object into list */
3937 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3938 output.println(revertptr+"=revertlist;");
3939 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
3940 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3942 output.println("COPY_OBJ("+dst+");");
3943 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
3944 output.println("revertlist=(struct ___Object___ *)"+dst+";");
3945 output.println("}");
3946 } else throw new Error("Unknown array type");
3948 output.println("{");
3949 String src=generateTemp(fm, fsen.getSrc(), lb);
3950 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3951 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
3952 output.println("}");
3954 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3957 if (state.FASTCHECK) {
3958 String dst=generateTemp(fm, fsen.getDst(),lb);
3959 output.println("if(!"+dst+"->"+localcopystr+") {");
3960 /* Link object into list */
3961 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
3962 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
3964 output.println("COPY_OBJ("+dst+");");
3965 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
3966 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
3967 output.println("}");
3969 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
3973 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
3974 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
3975 //Stash pointer in case of GC
3976 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3977 output.println(revertptr+"=revertlist;");
3979 if (state.SINGLETM) {
3980 if (fn.getType().isArray()) {
3981 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
3982 if (locality.getAtomic(lb).get(fn).intValue()>0) {
3983 //inside transaction
3984 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3986 //outside transaction
3987 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
3990 if (locality.getAtomic(lb).get(fn).intValue()>0) {
3991 //inside transaction
3992 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3994 //outside transaction
3995 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
3998 } else if (fn.getType().isArray()) {
3999 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4000 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4001 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4002 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4003 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4005 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4008 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4009 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
4010 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4011 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4013 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
4016 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4017 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4018 String dst=generateTemp(fm,fn.getDst(),lb);
4019 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4020 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4021 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4023 if (state.FASTCHECK) {
4024 String dst=generateTemp(fm,fn.getDst(),lb);
4025 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4026 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4027 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4031 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
4032 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4033 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
4035 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
4039 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
4040 if (fon.getRight()!=null) {
4041 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
4042 if (fon.getLeft().getType().isLong())
4043 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4045 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4047 } else if (dc!=null) {
4048 output.print(generateTemp(fm, fon.getDest(),lb)+" = ");
4049 if (dc.getNeedLeftSrcTrans(lb, fon))
4050 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
4052 output.print(generateTemp(fm, fon.getLeft(),lb));
4053 output.print(fon.getOp().toString());
4054 if (dc.getNeedRightSrcTrans(lb, fon))
4055 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL);");
4057 output.println(generateTemp(fm,fon.getRight(),lb)+";");
4059 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
4060 } else if (fon.getOp().getOp()==Operation.ASSIGN)
4061 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4062 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
4063 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4064 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
4065 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
4066 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
4067 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
4068 else if (fon.getOp().getOp()==Operation.COMP)
4069 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
4070 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
4071 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
4073 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
4076 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
4077 /* TODO: Do type check here */
4078 if (fcn.getType().isArray()) {
4079 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4080 } else if (fcn.getType().isClass())
4081 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4083 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
4086 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
4087 if (fln.getValue()==null)
4088 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4089 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
4090 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4091 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4092 //Stash pointer in case of GC
4093 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4094 output.println(revertptr+"=revertlist;");
4096 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4097 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4098 //Stash pointer in case of GC
4099 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4100 output.println("revertlist="+revertptr+";");
4103 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4105 } else if (fln.getType().isBoolean()) {
4106 if (((Boolean)fln.getValue()).booleanValue())
4107 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
4109 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4110 } else if (fln.getType().isChar()) {
4111 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
4112 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
4113 } else if (fln.getType().isLong()) {
4114 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
4116 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
4119 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
4120 if (frn.getReturnTemp()!=null) {
4121 if (frn.getReturnTemp().getType().isPtr())
4122 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4124 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4126 output.println("return;");
4130 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4133 //only record if this group has more than one exit
4134 if (branchanalysis.numJumps(fcb)>1) {
4135 left=branchanalysis.jumpValue(fcb, 0);
4136 right=branchanalysis.jumpValue(fcb, 1);
4138 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
4140 output.println("STOREBRANCH("+right+");");
4141 output.println("goto "+label+";");
4142 output.println("}");
4144 output.println("STOREBRANCH("+left+");");
4147 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4148 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
4151 /** This method generates header information for the method or
4152 * task referenced by the Descriptor des. */
4153 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
4154 generateHeader(fm, lb, des, output, false);
4157 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
4159 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
4160 MethodDescriptor md=null;
4161 TaskDescriptor task=null;
4162 if (des instanceof MethodDescriptor)
4163 md=(MethodDescriptor) des;
4165 task=(TaskDescriptor) des;
4167 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
4169 if (md!=null&&md.getReturnType()!=null) {
4170 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4171 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4173 output.print(md.getReturnType().getSafeSymbol()+" ");
4175 //catch the constructor case
4176 output.print("void ");
4178 if (state.DSM||state.SINGLETM) {
4179 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4181 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4183 output.print(task.getSafeSymbol()+"(");
4185 boolean printcomma=false;
4186 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4188 if (state.DSM||state.SINGLETM) {
4189 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4191 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4193 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
4199 for(int i=0; i<objectparams.numPrimitives(); i++) {
4200 TempDescriptor temp=objectparams.getPrimitive(i);
4204 if (temp.getType().isClass()||temp.getType().isArray())
4205 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
4207 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
4209 output.println(") {");
4210 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4211 /* Imprecise Task */
4212 output.println("void * parameterarray[]) {");
4213 /* Unpack variables */
4214 for(int i=0; i<objectparams.numPrimitives(); i++) {
4215 TempDescriptor temp=objectparams.getPrimitive(i);
4216 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
4218 for(int i=0; i<fm.numTags(); i++) {
4219 TempDescriptor temp=fm.getTag(i);
4220 int offset=i+objectparams.numPrimitives();
4221 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
4224 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
4225 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
4226 } else output.println(") {");
4229 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
4230 output.println("/* FlatFlagActionNode */");
4233 /* Process tag changes */
4234 Relation tagsettable=new Relation();
4235 Relation tagcleartable=new Relation();
4237 Iterator tagsit=ffan.getTempTagPairs();
4238 while (tagsit.hasNext()) {
4239 TempTagPair ttp=(TempTagPair) tagsit.next();
4240 TempDescriptor objtmp=ttp.getTemp();
4241 TagDescriptor tag=ttp.getTag();
4242 TempDescriptor tagtmp=ttp.getTagTemp();
4243 boolean tagstatus=ffan.getTagChange(ttp);
4245 tagsettable.put(objtmp, tagtmp);
4247 tagcleartable.put(objtmp, tagtmp);
4252 Hashtable flagandtable=new Hashtable();
4253 Hashtable flagortable=new Hashtable();
4255 /* Process flag changes */
4256 Iterator flagsit=ffan.getTempFlagPairs();
4257 while(flagsit.hasNext()) {
4258 TempFlagPair tfp=(TempFlagPair)flagsit.next();
4259 TempDescriptor temp=tfp.getTemp();
4260 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
4261 FlagDescriptor flag=tfp.getFlag();
4263 //Newly allocate objects that don't set any flags case
4264 if (flagortable.containsKey(temp)) {
4268 flagortable.put(temp,new Integer(mask));
4270 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
4271 boolean flagstatus=ffan.getFlagChange(tfp);
4274 if (flagortable.containsKey(temp)) {
4275 mask=((Integer)flagortable.get(temp)).intValue();
4278 flagortable.put(temp,new Integer(mask));
4280 int mask=0xFFFFFFFF;
4281 if (flagandtable.containsKey(temp)) {
4282 mask=((Integer)flagandtable.get(temp)).intValue();
4284 mask&=(0xFFFFFFFF^flagid);
4285 flagandtable.put(temp,new Integer(mask));
4291 HashSet flagtagset=new HashSet();
4292 flagtagset.addAll(flagortable.keySet());
4293 flagtagset.addAll(flagandtable.keySet());
4294 flagtagset.addAll(tagsettable.keySet());
4295 flagtagset.addAll(tagcleartable.keySet());
4297 Iterator ftit=flagtagset.iterator();
4298 while(ftit.hasNext()) {
4299 TempDescriptor temp=(TempDescriptor)ftit.next();
4302 Set tagtmps=tagcleartable.get(temp);
4303 if (tagtmps!=null) {
4304 Iterator tagit=tagtmps.iterator();
4305 while(tagit.hasNext()) {
4306 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4307 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4308 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4310 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4314 tagtmps=tagsettable.get(temp);
4315 if (tagtmps!=null) {
4316 Iterator tagit=tagtmps.iterator();
4317 while(tagit.hasNext()) {
4318 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4319 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4320 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4322 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
4327 int andmask=0xFFFFFFF;
4329 if (flagortable.containsKey(temp))
4330 ormask=((Integer)flagortable.get(temp)).intValue();
4331 if (flagandtable.containsKey(temp))
4332 andmask=((Integer)flagandtable.get(temp)).intValue();
4333 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
4334 generateObjectDistribute(ffan, fm, lb, temp, output);
4338 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
4339 PrintWriter output, int ormask, int andmask) {
4340 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
4341 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4343 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4347 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
4348 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
4351 void generateOptionalHeader(PrintWriter headers) {
4354 headers.println("#include \"task.h\"\n\n");
4355 headers.println("#ifndef _OPTIONAL_STRUCT_");
4356 headers.println("#define _OPTIONAL_STRUCT_");
4358 //STRUCT PREDICATEMEMBER
4359 headers.println("struct predicatemember{");
4360 headers.println("int type;");
4361 headers.println("int numdnfterms;");
4362 headers.println("int * flags;");
4363 headers.println("int numtags;");
4364 headers.println("int * tags;\n};\n\n");
4366 //STRUCT OPTIONALTASKDESCRIPTOR
4367 headers.println("struct optionaltaskdescriptor{");
4368 headers.println("struct taskdescriptor * task;");
4369 headers.println("int index;");
4370 headers.println("int numenterflags;");
4371 headers.println("int * enterflags;");
4372 headers.println("int numpredicatemembers;");
4373 headers.println("struct predicatemember ** predicatememberarray;");
4374 headers.println("};\n\n");
4376 //STRUCT TASKFAILURE
4377 headers.println("struct taskfailure {");
4378 headers.println("struct taskdescriptor * task;");
4379 headers.println("int index;");
4380 headers.println("int numoptionaltaskdescriptors;");
4381 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4383 //STRUCT FSANALYSISWRAPPER
4384 headers.println("struct fsanalysiswrapper{");
4385 headers.println("int flags;");
4386 headers.println("int numtags;");
4387 headers.println("int * tags;");
4388 headers.println("int numtaskfailures;");
4389 headers.println("struct taskfailure ** taskfailurearray;");
4390 headers.println("int numoptionaltaskdescriptors;");
4391 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4393 //STRUCT CLASSANALYSISWRAPPER
4394 headers.println("struct classanalysiswrapper{");
4395 headers.println("int type;");
4396 headers.println("int numotd;");
4397 headers.println("struct optionaltaskdescriptor ** otdarray;");
4398 headers.println("int numfsanalysiswrappers;");
4399 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
4401 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
4403 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
4404 while(taskit.hasNext()) {
4405 TaskDescriptor td=(TaskDescriptor)taskit.next();
4406 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
4411 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
4412 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
4413 int predicateindex = 0;
4414 //iterate through the classes concerned by the predicate
4415 Set c_vard = predicate.vardescriptors;
4416 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
4419 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
4420 VarDescriptor vard = (VarDescriptor)vard_it.next();
4421 TypeDescriptor typed = vard.getType();
4423 //generate for flags
4424 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
4425 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4427 if (fen_hashset!=null) {
4428 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
4429 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
4431 DNFFlag dflag=fen.getDNF();
4432 numberterms+=dflag.size();
4434 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
4436 for(int j=0; j<dflag.size(); j++) {
4438 output.println(",");
4439 Vector term=dflag.get(j);
4442 for(int k=0; k<term.size(); k++) {
4443 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
4444 FlagDescriptor fd=dfa.getFlag();
4445 boolean negated=dfa.getNegated();
4446 int flagid=1<<((Integer)flags.get(fd)).intValue();
4451 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
4456 output.println("};\n");
4459 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
4460 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4463 for(int j=0; j<tagel.numTags(); j++) {
4465 output.println(",");
4466 TempDescriptor tmp=tagel.getTemp(j);
4467 if (!slotnumber.containsKey(tmp)) {
4468 Integer slotint=new Integer(current_slot++);
4469 slotnumber.put(tmp,slotint);
4471 int slot=slotnumber.get(tmp).intValue();
4472 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
4474 numtags = tagel.numTags();
4476 output.println("};");
4478 //store the result into a predicatemember struct
4479 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4480 output.println("/*type*/"+typed.getClassDesc().getId()+",");
4481 output.println("/* number of dnf terms */"+numberterms+",");
4482 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4483 output.println("/* number of tag */"+numtags+",");
4484 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4485 output.println("};\n");
4490 //generate an array that stores the entire predicate
4491 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4492 for( int j = 0; j<predicateindex; j++) {
4493 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4494 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4496 output.println("};\n");
4497 return predicateindex;
4501 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
4502 generateOptionalHeader(headers);
4504 output.println("#include \"optionalstruct.h\"\n\n");
4505 output.println("#include \"stdlib.h\"\n");
4507 HashSet processedcd = new HashSet();
4509 Enumeration e = safeexecution.keys();
4510 while (e.hasMoreElements()) {
4513 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
4514 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
4516 //Generate the struct of optionals
4517 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4518 numotd = c_otd.size();
4519 if(maxotd<numotd) maxotd = numotd;
4520 if( !c_otd.isEmpty() ) {
4521 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4522 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4524 //generate the int arrays for the predicate
4525 Predicate predicate = otd.predicate;
4526 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
4527 TreeSet<Integer> fsset=new TreeSet<Integer>();
4528 //iterate through possible FSes corresponding to
4529 //the state when entering
4531 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
4532 FlagState fs = (FlagState)fses.next();
4534 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4535 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4536 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4539 fsset.add(new Integer(flagid));
4540 //tag information not needed because tag
4541 //changes are not tolerated.
4544 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4545 boolean needcomma=false;
4546 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
4549 output.println(it.next());
4552 output.println("};\n");
4555 //generate optionaltaskdescriptor that actually
4556 //includes exit fses, predicate and the task
4558 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4559 output.println("&task_"+otd.td.getSafeSymbol()+",");
4560 output.println("/*index*/"+otd.getIndex()+",");
4561 output.println("/*number of enter flags*/"+fsset.size()+",");
4562 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4563 output.println("/*number of members */"+predicateindex+",");
4564 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4565 output.println("};\n");
4569 // if there are no optionals, there is no need to build the rest of the struct
4571 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
4572 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4573 if( !c_otd.isEmpty() ) {
4574 boolean needcomma=false;
4575 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4576 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4578 output.println(",");
4580 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4583 output.println("};\n");
4585 //get all the possible flagstates reachable by an object
4586 Hashtable hashtbtemp = safeexecution.get(cdtemp);
4588 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
4589 fsts.addAll(hashtbtemp.keySet());
4590 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
4591 FlagState fs = (FlagState)fsit.next();
4594 //get the set of OptionalTaskDescriptors corresponding
4595 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
4596 //iterate through the OptionalTaskDescriptors and
4597 //store the pointers to the optionals struct (see on
4598 //top) into an array
4600 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
4601 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
4602 OptionalTaskDescriptor mm = mos.next();
4604 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
4606 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4609 output.println("};\n");
4611 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
4614 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4615 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4616 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4620 //process tag information
4623 boolean first = true;
4624 Enumeration tag_enum = fs.getTags();
4625 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4626 while(tag_enum.hasMoreElements()) {
4628 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
4632 output.println(", ");
4633 output.println("/*tagid*/"+state.getTagId(tagd));
4635 output.println("};");
4637 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
4638 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4639 TaskIndex ti=itti.next();
4643 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
4645 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
4646 boolean needcomma=false;
4647 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
4648 OptionalTaskDescriptor otd=otdit.next();
4652 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4654 output.println("};");
4656 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
4657 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
4658 output.print(ti.getIndex()+", ");
4659 output.print(otdset.size()+", ");
4660 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
4661 output.println("};");
4664 tiset=sa.getTaskIndex(fs);
4665 boolean needcomma=false;
4667 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4668 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4669 TaskIndex ti=itti.next();
4670 if (ti.isRuntime()) {
4677 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
4679 output.println("};\n");
4681 //Store the result in fsanalysiswrapper
4683 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
4684 output.println("/*flag*/"+flagid+",");
4685 output.println("/* number of tags*/"+tagcounter+",");
4686 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4687 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
4688 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4689 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
4690 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
4691 output.println("};\n");
4695 //Build the array of fsanalysiswrappers
4696 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
4697 boolean needcomma=false;
4698 for(int i = 0; i<fscounter; i++) {
4699 if (needcomma) output.print(",");
4700 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
4703 output.println("};");
4705 //Build the classanalysiswrapper referring to the previous array
4706 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
4707 output.println("/*type*/"+cdtemp.getId()+",");
4708 output.println("/*numotd*/"+numotd+",");
4709 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
4710 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
4711 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
4712 processedcd.add(cdtemp);
4715 //build an array containing every classes for which code has been build
4716 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
4717 for(int i=0; i<state.numClasses(); i++) {
4718 ClassDescriptor cn=cdarray[i];
4721 if ((cn != null) && (processedcd.contains(cn)))
4722 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
4724 output.print("NULL");
4726 output.println("};");
4728 output.println("#define MAXOTD "+maxotd);
4729 headers.println("#endif");
4732 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
4733 Relation r=new Relation();
4734 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
4735 OptionalTaskDescriptor otd=otdit.next();
4736 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
4740 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
4741 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
4742 Set s=r.get(it.next());
4743 for(Iterator it2=s.iterator(); it2.hasNext();) {
4744 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
4752 protected void outputTransCode(PrintWriter output) {