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.ConflictGraph;
31 import Analysis.MLP.ConflictNode;
32 import Analysis.MLP.MLPAnalysis;
33 import Analysis.MLP.ParentChildConflictsMap;
34 import Analysis.MLP.SESELock;
35 import Analysis.MLP.VariableSourceToken;
36 import Analysis.MLP.VSTWrapper;
37 import Analysis.MLP.CodePlan;
38 import Analysis.MLP.SESEandAgePair;
39 import Analysis.MLP.WaitingElement;
41 public class BuildCode {
44 Hashtable paramstable;
49 String localsprefix="___locals___";
50 String localsprefixaddr="&"+localsprefix;
51 String localsprefixderef=localsprefix+".";
52 String fcrevert="___fcrevert___";
53 String paramsprefix="___params___";
54 String oidstr="___nextobject___";
55 String nextobjstr="___nextobject___";
56 String localcopystr="___localcopy___";
57 public static boolean GENERATEPRECISEGC=false;
58 public static String PREFIX="";
59 public static String arraytype="ArrayObject";
60 public static int flagcount = 0;
63 protected int maxtaskparams=0;
64 private int maxcount=0;
65 ClassDescriptor[] cdarray;
66 TypeDescriptor[] arraytable;
67 LocalityAnalysis locality;
68 Hashtable<LocalityBinding, TempDescriptor> reverttable;
69 Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>> backuptable;
73 String mlperrstr = "if(status != 0) { "+
74 "sprintf(errmsg, \"MLP error at %s:%d\", __FILE__, __LINE__); "+
75 "perror(errmsg); exit(-1); }";
76 boolean nonSESEpass=true;
79 DiscoverConflicts recorddc;
84 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa) {
85 this(st, temptovar, typeutil, null, sa, pa, null);
88 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa) {
89 this(st, temptovar, typeutil, null, sa, pa, mlpa);
92 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, PrefetchAnalysis pa, MLPAnalysis mlpa) {
93 this(st, temptovar, typeutil, locality, null, pa, mlpa);
96 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa) {
101 callgraph=new CallGraph(state);
103 oidstr="___objlocation___";
104 this.temptovar=temptovar;
105 paramstable=new Hashtable();
106 tempstable=new Hashtable();
107 fieldorder=new Hashtable();
108 flagorder=new Hashtable();
109 this.typeutil=typeutil;
110 virtualcalls=new Virtual(state,locality);
111 if (locality!=null) {
112 this.locality=locality;
113 this.reverttable=new Hashtable<LocalityBinding, TempDescriptor>();
114 this.backuptable=new Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>>();
115 this.wb=new WriteBarrier(locality, st);
117 if (state.SINGLETM&&state.DCOPTS) {
118 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
119 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
120 this.dc=new DiscoverConflicts(locality, st, typeanalysis, gft);
123 if (state.DELAYCOMP) {
124 //TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
125 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
126 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
127 delaycomp=new DCWrapper(locality, st, typeanalysis, gft);
128 dc=delaycomp.getConflicts();
129 recorddc=new DiscoverConflicts(locality, st, typeanalysis, delaycomp.getCannotDelayMap(), true, true, null);
130 recorddc.doAnalysis();
134 /** The buildCode method outputs C code for all the methods. The Flat
135 * versions of the methods must already be generated and stored in
136 * the State object. */
137 PrintWriter outsandbox=null;
139 public void buildCode() {
140 /* Create output streams to write to */
141 PrintWriter outclassdefs=null;
142 PrintWriter outstructs=null;
143 PrintWriter outrepairstructs=null;
144 PrintWriter outmethodheader=null;
145 PrintWriter outmethod=null;
146 PrintWriter outvirtual=null;
147 PrintWriter outtask=null;
148 PrintWriter outtaskdefs=null;
149 PrintWriter outoptionalarrays=null;
150 PrintWriter optionalheaders=null;
154 outsandbox=new PrintWriter(new FileOutputStream(PREFIX+"sandboxdefs.c"), true);
156 outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
157 outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
158 outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
159 outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
160 outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
162 outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
163 outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
164 if (state.OPTIONAL) {
165 outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
166 optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
169 if (state.structfile!=null) {
170 outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
172 } catch (Exception e) {
177 /* Build the virtual dispatch tables */
178 buildVirtualTables(outvirtual);
180 /* Output includes */
181 outmethodheader.println("#ifndef METHODHEADERS_H");
182 outmethodheader.println("#define METHODHEADERS_H");
183 outmethodheader.println("#include \"structdefs.h\"");
185 outmethodheader.println("#include \"dstm.h\"");
187 outmethodheader.println("#include \"sandbox.h\"");
189 if (state.EVENTMONITOR) {
190 outmethodheader.println("#include \"monitor.h\"");
192 if (state.SINGLETM) {
193 outmethodheader.println("#include \"tm.h\"");
194 outmethodheader.println("#include \"delaycomp.h\"");
195 outmethodheader.println("#include \"inlinestm.h\"");
197 if (state.ABORTREADERS) {
198 outmethodheader.println("#include \"abortreaders.h\"");
199 outmethodheader.println("#include <setjmp.h>");
202 outmethodheader.println("#include <stdlib.h>");
203 outmethodheader.println("#include <stdio.h>");
204 outmethodheader.println("#include <string.h>");
205 outmethodheader.println("#include \"mlp_runtime.h\"");
206 outmethodheader.println("#include \"psemaphore.h\"");
209 /* Output Structures */
210 outputStructs(outstructs);
212 // Output the C class declarations
213 // These could mutually reference each other
214 outputClassDeclarations(outclassdefs);
216 // Output function prototypes and structures for parameters
217 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
218 while(it.hasNext()) {
219 ClassDescriptor cn=(ClassDescriptor)it.next();
220 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader);
222 outclassdefs.close();
225 /* Map flags to integers */
226 /* The runtime keeps track of flags using these integers */
227 it=state.getClassSymbolTable().getDescriptorsIterator();
228 while(it.hasNext()) {
229 ClassDescriptor cn=(ClassDescriptor)it.next();
233 generateTaskStructs(outstructs, outmethodheader);
235 /* Outputs generic task structures if this is a task
237 outputTaskTypes(outtask);
241 // have to initialize some SESE compiler data before
242 // analyzing normal methods, which must happen before
243 // generating SESE internal code
244 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
245 FlatSESEEnterNode fsen = seseit.next();
246 initializeSESE( fsen );
250 /* Build the actual methods */
251 outputMethods(outmethod);
253 // Output function prototypes and structures for SESE's and code
256 // used to differentiate, during code generation, whether we are
257 // passing over SESE body code, or non-SESE code
260 // first generate code for each sese's internals
261 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
262 FlatSESEEnterNode fsen = seseit.next();
263 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
266 // then write the invokeSESE switch to decouple scheduler
267 // from having to do unique details of sese invocation
268 generateSESEinvocationMethod(outmethodheader, outmethod);
272 /* Output code for tasks */
273 outputTaskCode(outtaskdefs, outmethod);
275 /* Record maximum number of task parameters */
276 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
277 } else if (state.main!=null) {
278 /* Generate main method */
279 outputMainMethod(outmethod);
282 /* Generate information for task with optional parameters */
283 if (state.TASK&&state.OPTIONAL) {
284 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
285 outoptionalarrays.close();
288 /* Output structure definitions for repair tool */
289 if (state.structfile!=null) {
290 buildRepairStructs(outrepairstructs);
291 outrepairstructs.close();
295 outmethodheader.println("#endif");
296 outmethodheader.close();
298 outstructs.println("#endif");
303 /* This code just generates the main C method for java programs.
304 * The main C method packs up the arguments into a string array
305 * and passes it to the java main method. */
307 private void outputMainMethod(PrintWriter outmethod) {
308 outmethod.println("int main(int argc, const char *argv[]) {");
309 outmethod.println(" int i;");
312 //outmethod.println(" pthread_once( &mlpOnceObj, mlpInitOncePerThread );");
313 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
317 if (state.DSMRECOVERYSTATS) {
318 outmethod.println("#ifdef RECOVERYSTATS \n");
319 outmethod.println("handle();\n");
320 outmethod.println("#endif\n");
322 outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
323 outmethod.println("handle();\n");
324 outmethod.println("#endif\n");
328 if (state.THREAD||state.DSM||state.SINGLETM) {
329 outmethod.println("initializethreads();");
332 outmethod.println("if (dstmStartup(argv[1])) {");
333 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
334 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
336 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
339 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
340 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
342 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
346 outmethod.println(" for(i=2;i<argc;i++) {");
348 outmethod.println(" for(i=1;i<argc;i++) {");
349 outmethod.println(" int length=strlen(argv[i]);");
350 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
351 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
353 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
356 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
358 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
359 outmethod.println(" }");
361 MethodDescriptor md=typeutil.getMain();
362 ClassDescriptor cd=typeutil.getMainClass();
364 outmethod.println(" {");
365 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
366 if (state.DSM||state.SINGLETM) {
367 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
369 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
370 outmethod.println("1, NULL,"+"stringarray};");
371 if (state.DSM||state.SINGLETM)
372 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
374 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
376 if (state.DSM||state.SINGLETM)
377 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
379 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
381 outmethod.println(" }");
384 outmethod.println("}");
387 if (state.THREAD||state.DSM||state.SINGLETM) {
388 outmethod.println("pthread_mutex_lock(&gclistlock);");
389 outmethod.println("threadcount--;");
390 outmethod.println("pthread_cond_signal(&gccond);");
391 outmethod.println("pthread_mutex_unlock(&gclistlock);");
394 if (state.DSM||state.SINGLETM) {
395 //outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
396 outmethod.println("#if defined(TRANSSTATS) \n");
397 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
398 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
399 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
400 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
402 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
403 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
404 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
405 outmethod.println("printf(\"ndirtyCacheObj= %d\\n\", ndirtyCacheObj);");
406 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
407 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
408 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
409 outmethod.println("printf(\"totalObjSize= %d\\n\", totalObjSize);");
410 outmethod.println("printf(\"sendRemoteReq= %d\\n\", sendRemoteReq);");
411 outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
412 } else if (state.SINGLETM) {
413 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
414 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
415 outmethod.println("#ifdef STMSTATS\n");
416 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
417 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
418 outmethod.println("}\n");
419 outmethod.println("#endif\n");
420 outmethod.println("fflush(stdout);");
422 outmethod.println("#endif\n");
425 if (state.EVENTMONITOR) {
426 outmethod.println("dumpdata();");
429 if (state.THREAD||state.SINGLETM)
430 outmethod.println("pthread_exit(NULL);");
433 outmethod.println(" workScheduleBegin();");
436 outmethod.println("}");
439 /* This method outputs code for each task. */
441 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
442 /* Compile task based program */
443 outtaskdefs.println("#include \"task.h\"");
444 outtaskdefs.println("#include \"methodheaders.h\"");
445 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
446 while(taskit.hasNext()) {
447 TaskDescriptor td=(TaskDescriptor)taskit.next();
448 FlatMethod fm=state.getMethodFlat(td);
449 generateFlatMethod(fm, null, outmethod);
450 generateTaskDescriptor(outtaskdefs, fm, td);
453 //Output task descriptors
454 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
455 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
457 while(taskit.hasNext()) {
458 TaskDescriptor td=(TaskDescriptor)taskit.next();
462 outtaskdefs.println(",");
463 outtaskdefs.print("&task_"+td.getSafeSymbol());
465 outtaskdefs.println("};");
467 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
470 /* This method outputs most of the methods.c file. This includes
471 * some standard includes and then an array with the sizes of
472 * objets and array that stores supertype and then the code for
473 * the Java methods.. */
475 protected void outputMethods(PrintWriter outmethod) {
476 outmethod.println("#include \"methodheaders.h\"");
477 outmethod.println("#include \"virtualtable.h\"");
478 outmethod.println("#include \"runtime.h\"");
480 outmethod.println("#include \"sandboxdefs.c\"");
483 outmethod.println("#include \"addPrefetchEnhance.h\"");
484 outmethod.println("#include \"localobjects.h\"");
486 if (state.FASTCHECK) {
487 outmethod.println("#include \"localobjects.h\"");
489 if(state.MULTICORE) {
490 outmethod.println("#include \"task.h\"");
491 outmethod.println("#include \"multicoreruntime.h\"");
492 outmethod.println("#include \"runtime_arch.h\"");
494 if (state.THREAD||state.DSM||state.SINGLETM)
495 outmethod.println("#include <thread.h>");
496 if (state.main!=null) {
497 outmethod.println("#include <string.h>");
499 if (state.CONSCHECK) {
500 outmethod.println("#include \"checkers.h\"");
503 outmethod.println("#include <stdlib.h>");
504 outmethod.println("#include <stdio.h>");
505 outmethod.println("#include \"mlp_runtime.h\"");
506 outmethod.println("#include \"psemaphore.h\"");
510 //Store the sizes of classes & array elements
511 generateSizeArray(outmethod);
513 //Store table of supertypes
514 generateSuperTypeTable(outmethod);
516 //Store the layout of classes
517 generateLayoutStructs(outmethod);
519 /* Generate code for methods */
520 if (state.DSM||state.SINGLETM) {
521 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
522 LocalityBinding lb=lbit.next();
523 MethodDescriptor md=lb.getMethod();
524 FlatMethod fm=state.getMethodFlat(md);
526 if (!md.getModifiers().isNative()) {
527 generateFlatMethod(fm, lb, outmethod);
528 //System.out.println("fm= " + fm + " md= " + md);
532 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
533 while(classit.hasNext()) {
534 ClassDescriptor cn=(ClassDescriptor)classit.next();
535 Iterator methodit=cn.getMethods();
536 while(methodit.hasNext()) {
537 /* Classify parameters */
538 MethodDescriptor md=(MethodDescriptor)methodit.next();
539 FlatMethod fm=state.getMethodFlat(md);
540 if (!md.getModifiers().isNative()) {
541 generateFlatMethod(fm, null, outmethod);
548 protected void outputStructs(PrintWriter outstructs) {
549 outstructs.println("#ifndef STRUCTDEFS_H");
550 outstructs.println("#define STRUCTDEFS_H");
551 outstructs.println("#include \"classdefs.h\"");
552 outstructs.println("#ifndef INTPTR");
553 outstructs.println("#ifdef BIT64");
554 outstructs.println("#define INTPTR long");
555 outstructs.println("#else");
556 outstructs.println("#define INTPTR int");
557 outstructs.println("#endif");
558 outstructs.println("#endif");
560 outstructs.println("#include \"mlp_runtime.h\"");
561 outstructs.println("#include \"psemaphore.h\"");
564 /* Output #defines that the runtime uses to determine type
565 * numbers for various objects it needs */
566 outstructs.println("#define MAXCOUNT "+maxcount);
567 if (state.DSM||state.SINGLETM) {
568 LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
570 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
572 else if (state.SINGLETM) {
573 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
575 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
579 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
581 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
582 else if( state.SINGLETM)
583 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
584 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
587 outstructs.println("#define STRINGARRAYTYPE "+
588 (state.getArrayNumber(
589 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
591 outstructs.println("#define OBJECTARRAYTYPE "+
592 (state.getArrayNumber(
593 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
596 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
597 outstructs.println("#define CHARARRAYTYPE "+
598 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
600 outstructs.println("#define BYTEARRAYTYPE "+
601 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
603 outstructs.println("#define BYTEARRAYARRAYTYPE "+
604 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
606 outstructs.println("#define NUMCLASSES "+state.numClasses());
607 int totalClassSize = state.numClasses() + state.numArrays();
608 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
610 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
611 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
612 outstructs.println("#define TAGARRAYTYPE "+
613 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
617 protected void outputClassDeclarations(PrintWriter outclassdefs) {
618 if (state.THREAD||state.DSM||state.SINGLETM)
619 outclassdefs.println("#include <pthread.h>");
620 outclassdefs.println("#ifndef INTPTR");
621 outclassdefs.println("#ifdef BIT64");
622 outclassdefs.println("#define INTPTR long");
623 outclassdefs.println("#else");
624 outclassdefs.println("#define INTPTR int");
625 outclassdefs.println("#endif");
626 outclassdefs.println("#endif");
628 outclassdefs.println("#include \"optionalstruct.h\"");
629 outclassdefs.println("struct "+arraytype+";");
630 /* Start by declaring all structs */
631 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
632 while(it.hasNext()) {
633 ClassDescriptor cn=(ClassDescriptor)it.next();
634 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
636 outclassdefs.println("");
637 //Print out definition for array type
638 outclassdefs.println("struct "+arraytype+" {");
639 outclassdefs.println(" int type;");
640 if (state.EVENTMONITOR) {
641 outclassdefs.println(" int objuid;");
644 outclassdefs.println(" pthread_t tid;");
645 outclassdefs.println(" void * lockentry;");
646 outclassdefs.println(" int lockcount;");
649 outclassdefs.println(" int flag;");
650 if(!state.MULTICORE) {
651 outclassdefs.println(" void * flagptr;");
653 outclassdefs.println(" int version;");
654 outclassdefs.println(" int * lock;"); // lock entry for this obj
655 outclassdefs.println(" int mutex;");
656 outclassdefs.println(" int lockcount;");
657 if(state.MULTICOREGC) {
658 outclassdefs.println(" int marked;");
662 outclassdefs.println(" int numfses;");
663 outclassdefs.println(" int * fses;");
666 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
668 if (state.STMARRAY) {
669 outclassdefs.println(" int lowindex;");
670 outclassdefs.println(" int highindex;");
673 outclassdefs.println(" int paddingforarray;");
674 if (state.DUALVIEW) {
675 outclassdefs.println(" int arrayversion;");
678 outclassdefs.println(" int ___length___;");
679 outclassdefs.println("};\n");
680 outclassdefs.println("extern int classsize[];");
681 outclassdefs.println("extern int hasflags[];");
682 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
683 outclassdefs.println("extern int supertypes[];");
686 /** Prints out definitions for generic task structures */
688 private void outputTaskTypes(PrintWriter outtask) {
689 outtask.println("#ifndef _TASK_H");
690 outtask.println("#define _TASK_H");
691 outtask.println("struct parameterdescriptor {");
692 outtask.println("int type;");
693 outtask.println("int numberterms;");
694 outtask.println("int *intarray;");
695 outtask.println("void * queue;");
696 outtask.println("int numbertags;");
697 outtask.println("int *tagarray;");
698 outtask.println("};");
700 outtask.println("struct taskdescriptor {");
701 outtask.println("void * taskptr;");
702 outtask.println("int numParameters;");
703 outtask.println(" int numTotal;");
704 outtask.println("struct parameterdescriptor **descriptorarray;");
705 outtask.println("char * name;");
706 outtask.println("};");
707 outtask.println("extern struct taskdescriptor * taskarray[];");
708 outtask.println("extern numtasks;");
709 outtask.println("#endif");
713 private void buildRepairStructs(PrintWriter outrepairstructs) {
714 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
715 while(classit.hasNext()) {
716 ClassDescriptor cn=(ClassDescriptor)classit.next();
717 outrepairstructs.println("structure "+cn.getSymbol()+" {");
718 outrepairstructs.println(" int __type__;");
720 outrepairstructs.println(" int __flag__;");
721 if(!state.MULTICORE) {
722 outrepairstructs.println(" int __flagptr__;");
725 printRepairStruct(cn, outrepairstructs);
726 outrepairstructs.println("}\n");
729 for(int i=0; i<state.numArrays(); i++) {
730 TypeDescriptor tdarray=arraytable[i];
731 TypeDescriptor tdelement=tdarray.dereference();
732 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
733 outrepairstructs.println(" int __type__;");
734 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
735 outrepairstructs.println(" int length;");
737 // Need to add support to repair tool for this
738 if (tdelement.isClass()||tdelement.isArray())
739 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
741 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
743 outrepairstructs.println("}\n");
747 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
748 ClassDescriptor sp=cn.getSuperDesc();
750 printRepairStruct(sp, output);
752 Vector fields=(Vector)fieldorder.get(cn);
754 for(int i=0; i<fields.size(); i++) {
755 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
756 if (fd.getType().isArray()) {
757 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
758 } else if (fd.getType().isClass())
759 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
760 else if (fd.getType().isFloat())
761 output.println(" int "+fd.getSymbol()+"; /* really float */");
763 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
767 /** This method outputs TaskDescriptor information */
768 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
769 for (int i=0; i<task.numParameters(); i++) {
770 VarDescriptor param_var=task.getParameter(i);
771 TypeDescriptor param_type=task.getParamType(i);
772 FlagExpressionNode param_flag=task.getFlag(param_var);
773 TagExpressionList param_tag=task.getTag(param_var);
776 if (param_flag==null) {
777 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
778 output.println("0x0, 0x0 };");
781 DNFFlag dflag=param_flag.getDNF();
782 dnfterms=dflag.size();
784 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
785 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
786 for(int j=0; j<dflag.size(); j++) {
789 Vector term=dflag.get(j);
792 for(int k=0; k<term.size(); k++) {
793 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
794 FlagDescriptor fd=dfa.getFlag();
795 boolean negated=dfa.getNegated();
796 int flagid=1<<((Integer)flags.get(fd)).intValue();
801 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
803 output.println("};");
806 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
807 //BUG...added next line to fix, test with any task program
809 for(int j=0; j<param_tag.numTags(); j++) {
812 /* for each tag we need */
813 /* which slot it is */
814 /* what type it is */
815 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
816 TempDescriptor tmp=param_tag.getTemp(j);
817 int slot=fm.getTagInt(tmp);
818 output.println(slot+", "+state.getTagId(tvd.getTag()));
820 output.println("};");
822 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
823 output.println("/* type */"+param_type.getClassDesc().getId()+",");
824 output.println("/* number of DNF terms */"+dnfterms+",");
825 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
826 output.println("0,");
827 //BUG, added next line to fix and else statement...test
828 //with any task program
830 output.println("/* number of tags */"+param_tag.numTags()+",");
832 output.println("/* number of tags */ 0,");
833 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
834 output.println("};");
838 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
839 for (int i=0; i<task.numParameters(); i++) {
842 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
844 output.println("};");
846 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
847 output.println("&"+task.getSafeSymbol()+",");
848 output.println("/* number of parameters */" +task.numParameters() + ",");
849 int numtotal=task.numParameters()+fm.numTags();
850 output.println("/* number total parameters */" +numtotal + ",");
851 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
852 output.println("\""+task.getSymbol()+"\"");
853 output.println("};");
857 /** The buildVirtualTables method outputs the virtual dispatch
858 * tables for methods. */
860 protected void buildVirtualTables(PrintWriter outvirtual) {
861 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
862 while(classit.hasNext()) {
863 ClassDescriptor cd=(ClassDescriptor)classit.next();
864 if (virtualcalls.getMethodCount(cd)>maxcount)
865 maxcount=virtualcalls.getMethodCount(cd);
867 MethodDescriptor[][] virtualtable=null;
868 LocalityBinding[][] lbvirtualtable=null;
869 if (state.DSM||state.SINGLETM)
870 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
872 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
874 /* Fill in virtual table */
875 classit=state.getClassSymbolTable().getDescriptorsIterator();
876 while(classit.hasNext()) {
877 ClassDescriptor cd=(ClassDescriptor)classit.next();
878 if (state.DSM||state.SINGLETM)
879 fillinRow(cd, lbvirtualtable, cd.getId());
881 fillinRow(cd, virtualtable, cd.getId());
884 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
885 Iterator arrayit=state.getArrayIterator();
886 while(arrayit.hasNext()) {
887 TypeDescriptor td=(TypeDescriptor)arrayit.next();
888 int id=state.getArrayNumber(td);
889 if (state.DSM||state.SINGLETM)
890 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
892 fillinRow(objectcd, virtualtable, id+state.numClasses());
895 outvirtual.print("void * virtualtable[]={");
896 boolean needcomma=false;
897 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
898 for(int j=0; j<maxcount; j++) {
900 outvirtual.print(", ");
901 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
902 LocalityBinding lb=lbvirtualtable[i][j];
903 MethodDescriptor md=lb.getMethod();
904 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
905 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
906 MethodDescriptor md=virtualtable[i][j];
907 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
909 outvirtual.print("0");
913 outvirtual.println("");
915 outvirtual.println("};");
919 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
920 /* Get inherited methods */
921 if (cd.getSuperDesc()!=null)
922 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
923 /* Override them with our methods */
924 for(Iterator it=cd.getMethods(); it.hasNext();) {
925 MethodDescriptor md=(MethodDescriptor)it.next();
926 if (md.isStatic()||md.getReturnType()==null)
928 int methodnum=virtualcalls.getMethodNumber(md);
929 virtualtable[rownum][methodnum]=md;
933 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
934 /* Get inherited methods */
935 if (cd.getSuperDesc()!=null)
936 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
937 /* Override them with our methods */
938 if (locality.getClassBindings(cd)!=null)
939 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
940 LocalityBinding lb=lbit.next();
941 MethodDescriptor md=lb.getMethod();
942 //Is the method static or a constructor
943 if (md.isStatic()||md.getReturnType()==null)
945 int methodnum=virtualcalls.getLocalityNumber(lb);
946 virtualtable[rownum][methodnum]=lb;
950 /** Generate array that contains the sizes of class objects. The
951 * object allocation functions in the runtime use this
954 private void generateSizeArray(PrintWriter outclassdefs) {
955 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
956 outclassdefs.print("#ifdef TRANSSTATS \n");
957 outclassdefs.print("extern int numTransAbort;\n");
958 outclassdefs.print("extern int numTransCommit;\n");
959 outclassdefs.print("extern int nSoftAbort;\n");
961 outclassdefs.print("extern int nchashSearch;\n");
962 outclassdefs.print("extern int nmhashSearch;\n");
963 outclassdefs.print("extern int nprehashSearch;\n");
964 outclassdefs.print("extern int ndirtyCacheObj;\n");
965 outclassdefs.print("extern int nRemoteSend;\n");
966 outclassdefs.print("extern int sendRemoteReq;\n");
967 outclassdefs.print("extern int getResponse;\n");
968 outclassdefs.print("extern int bytesSent;\n");
969 outclassdefs.print("extern int bytesRecv;\n");
970 outclassdefs.print("extern int totalObjSize;\n");
971 outclassdefs.print("extern void handle();\n");
972 } else if (state.SINGLETM) {
973 outclassdefs.println("extern int nSoftAbortAbort;");
974 outclassdefs.println("extern int nSoftAbortCommit;");
975 outclassdefs.println("#ifdef STMSTATS\n");
976 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
977 outclassdefs.println("#endif\n");
979 outclassdefs.print("#endif\n");
981 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
983 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
984 cdarray=new ClassDescriptor[state.numClasses()];
986 while(it.hasNext()) {
987 ClassDescriptor cd=(ClassDescriptor)it.next();
988 cdarray[cd.getId()]=cd;
991 arraytable=new TypeDescriptor[state.numArrays()];
993 Iterator arrayit=state.getArrayIterator();
994 while(arrayit.hasNext()) {
995 TypeDescriptor td=(TypeDescriptor)arrayit.next();
996 int id=state.getArrayNumber(td);
1002 /* Print out types */
1003 outclassdefs.println("/* ");
1004 for(int i=0; i<state.numClasses(); i++) {
1005 ClassDescriptor cd=cdarray[i];
1007 outclassdefs.println("NULL " + i);
1009 outclassdefs.println(cd +" "+i);
1013 for(int i=0; i<state.numArrays(); i++) {
1014 TypeDescriptor arraytd=arraytable[i];
1015 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
1018 outclassdefs.println("*/");
1021 outclassdefs.print("int classsize[]={");
1023 boolean needcomma=false;
1024 for(int i=0; i<state.numClasses(); i++) {
1026 outclassdefs.print(", ");
1028 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1030 outclassdefs.print("0");
1036 for(int i=0; i<state.numArrays(); i++) {
1038 outclassdefs.print(", ");
1039 TypeDescriptor tdelement=arraytable[i].dereference();
1040 if (tdelement.isArray()||tdelement.isClass())
1041 outclassdefs.print("sizeof(void *)");
1043 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1047 outclassdefs.println("};");
1049 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1051 outclassdefs.print("int typearray[]={");
1052 for(int i=0; i<state.numClasses(); i++) {
1053 ClassDescriptor cd=cdarray[i];
1054 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1056 outclassdefs.print(", ");
1058 outclassdefs.print("-1");
1060 outclassdefs.print(supercd.getId());
1064 for(int i=0; i<state.numArrays(); i++) {
1065 TypeDescriptor arraytd=arraytable[i];
1066 ClassDescriptor arraycd=arraytd.getClassDesc();
1067 if (arraycd==null) {
1069 outclassdefs.print(", ");
1070 outclassdefs.print(objectclass.getId());
1074 ClassDescriptor cd=arraycd.getSuperDesc();
1077 TypeDescriptor supertd=new TypeDescriptor(cd);
1078 supertd.setArrayCount(arraytd.getArrayCount());
1079 type=state.getArrayNumber(supertd);
1081 type+=state.numClasses();
1084 cd=cd.getSuperDesc();
1087 outclassdefs.print(", ");
1088 outclassdefs.print(type);
1092 outclassdefs.println("};");
1097 outclassdefs.print("int typearray2[]={");
1098 for(int i=0; i<state.numArrays(); i++) {
1099 TypeDescriptor arraytd=arraytable[i];
1100 ClassDescriptor arraycd=arraytd.getClassDesc();
1101 if (arraycd==null) {
1103 outclassdefs.print(", ");
1104 outclassdefs.print("-1");
1108 ClassDescriptor cd=arraycd.getSuperDesc();
1109 int level=arraytd.getArrayCount()-1;
1111 for(; level>0; level--) {
1112 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1113 supertd.setArrayCount(level);
1114 type=state.getArrayNumber(supertd);
1116 type+=state.numClasses();
1121 outclassdefs.print(", ");
1122 outclassdefs.print(type);
1126 outclassdefs.println("};");
1129 /** Constructs params and temp objects for each method or task.
1130 * These objects tell the compiler which temps need to be
1133 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1134 MethodDescriptor md=fm.getMethod();
1135 TaskDescriptor task=fm.getTask();
1136 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1137 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1139 paramstable.put(lb, objectparams);
1140 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1141 } else if (md!=null)
1142 paramstable.put(md, objectparams);
1144 paramstable.put(task, objectparams);
1146 for(int i=0; i<fm.numParameters(); i++) {
1147 TempDescriptor temp=fm.getParameter(i);
1148 TypeDescriptor type=temp.getType();
1149 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1150 objectparams.addPtr(temp);
1152 objectparams.addPrim(temp);
1153 if(lb!=null&&saveset.contains(temp)) {
1154 backuptable.get(lb).put(temp, temp.createNew());
1158 for(int i=0; i<fm.numTags(); i++) {
1159 TempDescriptor temp=fm.getTag(i);
1160 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1161 objectparams.addPtr(temp);
1163 objectparams.addPrim(temp);
1166 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1168 tempstable.put(lb, objecttemps);
1170 tempstable.put(md, objecttemps);
1172 tempstable.put(task, objecttemps);
1174 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1175 FlatNode fn=(FlatNode)nodeit.next();
1176 TempDescriptor[] writes=fn.writesTemps();
1177 for(int i=0; i<writes.length; i++) {
1178 TempDescriptor temp=writes[i];
1179 TypeDescriptor type=temp.getType();
1180 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1181 objecttemps.addPtr(temp);
1183 objecttemps.addPrim(temp);
1184 if(lb!=null&&saveset.contains(temp)&&
1185 !backuptable.get(lb).containsKey(temp))
1186 backuptable.get(lb).put(temp, temp.createNew());
1190 /* Create backup temps */
1192 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1193 TempDescriptor tmp=tmpit.next();
1194 TypeDescriptor type=tmp.getType();
1195 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1196 objecttemps.addPtr(tmp);
1198 objecttemps.addPrim(tmp);
1200 /* Create temp to hold revert table */
1201 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1202 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1203 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1204 objecttemps.addPtr(reverttmp);
1206 objecttemps.addPrim(reverttmp);
1207 reverttable.put(lb, reverttmp);
1212 /** This method outputs the following information about classes
1214 * (1) For classes, what are the locations of pointers.
1215 * (2) For arrays, does the array contain pointers or primitives.
1216 * (3) For classes, does the class contain flags.
1219 private void generateLayoutStructs(PrintWriter output) {
1220 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1221 while(it.hasNext()) {
1222 ClassDescriptor cn=(ClassDescriptor)it.next();
1223 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1224 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1226 while(allit.hasNext()) {
1227 FieldDescriptor fd=(FieldDescriptor)allit.next();
1228 TypeDescriptor type=fd.getType();
1229 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1234 output.print(count);
1235 allit=cn.getFieldTable().getAllDescriptorsIterator();
1236 while(allit.hasNext()) {
1237 FieldDescriptor fd=(FieldDescriptor)allit.next();
1238 TypeDescriptor type=fd.getType();
1239 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1242 output.println(",");
1243 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1246 output.println("};");
1248 output.println("unsigned INTPTR * pointerarray[]={");
1249 boolean needcomma=false;
1250 for(int i=0; i<state.numClasses(); i++) {
1251 ClassDescriptor cn=cdarray[i];
1253 output.println(",");
1256 output.print(cn.getSafeSymbol()+"_pointers");
1258 output.print("NULL");
1262 for(int i=0; i<state.numArrays(); i++) {
1264 output.println(", ");
1265 TypeDescriptor tdelement=arraytable[i].dereference();
1266 if (tdelement.isArray()||tdelement.isClass())
1267 output.print("((unsigned INTPTR *)1)");
1273 output.println("};");
1275 output.println("int hasflags[]={");
1276 for(int i=0; i<state.numClasses(); i++) {
1277 ClassDescriptor cn=cdarray[i];
1279 output.println(", ");
1281 if ((cn != null) && (cn.hasFlags()))
1286 output.println("};");
1289 /** Print out table to give us supertypes */
1290 private void generateSuperTypeTable(PrintWriter output) {
1291 output.println("int supertypes[]={");
1292 boolean needcomma=false;
1293 for(int i=0; i<state.numClasses(); i++) {
1294 ClassDescriptor cn=cdarray[i];
1296 output.println(",");
1298 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1299 ClassDescriptor cdsuper=cn.getSuperDesc();
1300 output.print(cdsuper.getId());
1304 output.println("};");
1307 /** Force consistent field ordering between inherited classes. */
1309 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1311 ClassDescriptor sp=cn.getSuperDesc();
1313 printClassStruct(sp, classdefout);
1315 if (!fieldorder.containsKey(cn)) {
1316 Vector fields=new Vector();
1317 fieldorder.put(cn,fields);
1318 Vector fieldvec=cn.getFieldVec();
1319 for(int i=0;i<fieldvec.size();i++) {
1320 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1321 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1325 Vector fields=(Vector)fieldorder.get(cn);
1327 for(int i=0; i<fields.size(); i++) {
1328 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1329 if (fd.getType().isClass()||fd.getType().isArray())
1330 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1332 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1337 /* Map flags to integers consistently between inherited
1340 protected void mapFlags(ClassDescriptor cn) {
1341 ClassDescriptor sp=cn.getSuperDesc();
1345 if (!flagorder.containsKey(cn)) {
1346 Hashtable flags=new Hashtable();
1347 flagorder.put(cn,flags);
1349 Hashtable superflags=(Hashtable)flagorder.get(sp);
1350 Iterator superflagit=superflags.keySet().iterator();
1351 while(superflagit.hasNext()) {
1352 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1353 Integer number=(Integer)superflags.get(fd);
1354 flags.put(fd, number);
1355 if ((number.intValue()+1)>max)
1356 max=number.intValue()+1;
1360 Iterator flagit=cn.getFlags();
1361 while(flagit.hasNext()) {
1362 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1363 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1364 flags.put(fd, new Integer(max++));
1370 /** This function outputs (1) structures that parameters are
1371 * passed in (when PRECISE GC is enabled) and (2) function
1372 * prototypes for the methods */
1374 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1375 /* Output class structure */
1376 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1377 classdefout.println(" int type;");
1378 if (state.EVENTMONITOR) {
1379 classdefout.println(" int objuid;");
1382 classdefout.println(" pthread_t tid;");
1383 classdefout.println(" void * lockentry;");
1384 classdefout.println(" int lockcount;");
1388 classdefout.println(" int flag;");
1389 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1390 classdefout.println(" void * flagptr;");
1391 } else if (state.MULTICORE) {
1392 classdefout.println(" int version;");
1393 classdefout.println(" int * lock;"); // lock entry for this obj
1394 classdefout.println(" int mutex;");
1395 classdefout.println(" int lockcount;");
1396 if(state.MULTICOREGC) {
1397 classdefout.println(" int marked;");
1400 if (state.OPTIONAL) {
1401 classdefout.println(" int numfses;");
1402 classdefout.println(" int * fses;");
1405 printClassStruct(cn, classdefout);
1406 classdefout.println("};\n");
1408 if (state.DSM||state.SINGLETM) {
1409 /* Cycle through LocalityBindings */
1410 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1411 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1413 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1414 LocalityBinding lb=lbit.next();
1415 MethodDescriptor md=lb.getMethod();
1416 if (md.getModifiers().isNative()) {
1417 //make sure we only print a native method once
1418 if (nativemethods.contains(md)) {
1419 FlatMethod fm=state.getMethodFlat(md);
1420 generateTempStructs(fm, lb);
1423 nativemethods.add(md);
1425 generateMethod(cn, md, lb, headersout, output);
1428 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1429 MethodDescriptor md=(MethodDescriptor)methodit.next();
1430 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1431 //Need to build param structure for library code
1432 FlatMethod fm=state.getMethodFlat(md);
1433 generateTempStructs(fm, null);
1434 generateMethodParam(cn, md, null, output);
1439 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1440 MethodDescriptor md=(MethodDescriptor)methodit.next();
1441 generateMethod(cn, md, null, headersout, output);
1445 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1446 /* Output parameter structure */
1447 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1448 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1449 if ((state.DSM||state.SINGLETM)&&lb!=null)
1450 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1452 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1453 output.println(" INTPTR size;");
1454 output.println(" void * next;");
1455 for(int i=0; i<objectparams.numPointers(); i++) {
1456 TempDescriptor temp=objectparams.getPointer(i);
1457 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1459 output.println("};\n");
1463 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1464 FlatMethod fm=state.getMethodFlat(md);
1465 generateTempStructs(fm, lb);
1467 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1468 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1470 generateMethodParam(cn, md, lb, output);
1472 /* Output temp structure */
1473 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1474 if (state.DSM||state.SINGLETM)
1475 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1477 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1478 output.println(" INTPTR size;");
1479 output.println(" void * next;");
1480 for(int i=0; i<objecttemps.numPointers(); i++) {
1481 TempDescriptor temp=objecttemps.getPointer(i);
1482 if (temp.getType().isNull())
1483 output.println(" void * "+temp.getSafeSymbol()+";");
1485 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1487 output.println("};\n");
1490 /********* Output method declaration ***********/
1491 if (state.DSM||state.SINGLETM) {
1492 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1494 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1496 /* First the return type */
1497 if (md.getReturnType()!=null) {
1498 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1499 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1501 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1503 //catch the constructor case
1504 headersout.print("void ");
1506 /* Next the method name */
1507 if (state.DSM||state.SINGLETM) {
1508 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1510 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1512 boolean printcomma=false;
1513 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1514 if (state.DSM||state.SINGLETM) {
1515 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1517 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1521 /* Output parameter list*/
1522 for(int i=0; i<objectparams.numPrimitives(); i++) {
1523 TempDescriptor temp=objectparams.getPrimitive(i);
1525 headersout.print(", ");
1527 if (temp.getType().isClass()||temp.getType().isArray())
1528 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1530 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1532 headersout.println(");\n");
1536 /** This function outputs (1) structures that parameters are
1537 * passed in (when PRECISE GC is enabled) and (2) function
1538 * prototypes for the tasks */
1540 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1541 /* Cycle through tasks */
1542 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1544 while(taskit.hasNext()) {
1545 /* Classify parameters */
1546 TaskDescriptor task=(TaskDescriptor)taskit.next();
1547 FlatMethod fm=state.getMethodFlat(task);
1548 generateTempStructs(fm, null);
1550 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1551 TempObject objecttemps=(TempObject) tempstable.get(task);
1553 /* Output parameter structure */
1554 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1555 output.println("struct "+task.getSafeSymbol()+"_params {");
1557 output.println(" INTPTR size;");
1558 output.println(" void * next;");
1559 for(int i=0; i<objectparams.numPointers(); i++) {
1560 TempDescriptor temp=objectparams.getPointer(i);
1561 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1564 output.println("};\n");
1565 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1566 maxtaskparams=objectparams.numPointers()+fm.numTags();
1570 /* Output temp structure */
1571 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1572 output.println("struct "+task.getSafeSymbol()+"_locals {");
1573 output.println(" INTPTR size;");
1574 output.println(" void * next;");
1575 for(int i=0; i<objecttemps.numPointers(); i++) {
1576 TempDescriptor temp=objecttemps.getPointer(i);
1577 if (temp.getType().isNull())
1578 output.println(" void * "+temp.getSafeSymbol()+";");
1579 else if(temp.getType().isTag())
1580 output.println(" struct "+
1581 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1583 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1585 output.println("};\n");
1588 /* Output task declaration */
1589 headersout.print("void " + task.getSafeSymbol()+"(");
1591 boolean printcomma=false;
1592 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1593 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1595 headersout.print("void * parameterarray[]");
1596 headersout.println(");\n");
1600 /***** Generate code for FlatMethod fm. *****/
1602 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1603 static int atomicmethodcount=0;
1606 BranchAnalysis branchanalysis;
1607 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1608 if (State.PRINTFLAT)
1609 System.out.println(fm.printMethod());
1610 MethodDescriptor md=fm.getMethod();
1611 TaskDescriptor task=fm.getTask();
1612 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1613 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1615 HashSet<AtomicRecord> arset=null;
1616 branchanalysis=null;
1618 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1620 if (atomicmethodmap==null)
1621 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1623 //fix these so we get right strings for local variables
1624 localsprefixaddr=localsprefix;
1625 localsprefixderef=localsprefix+"->";
1626 arset=new HashSet<AtomicRecord>();
1628 //build branchanalysis
1629 branchanalysis=new BranchAnalysis(locality, lb, delaycomp.getNotReady(lb), delaycomp.livecode(lb), state);
1631 //Generate commit methods here
1632 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1633 FlatNode fn=fnit.next();
1634 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1635 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
1636 delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
1637 //We have an atomic enter
1638 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1639 Set<FlatNode> exitset=faen.getExits();
1641 String methodname=md.getSymbol()+(atomicmethodcount++);
1642 AtomicRecord ar=new AtomicRecord();
1646 atomicmethodmap.put(faen, ar);
1648 //build data structure declaration
1649 output.println("struct atomicprimitives_"+methodname+" {");
1651 Set<FlatNode> recordset=delaycomp.livecode(lb);
1652 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1653 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1654 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1656 ar.reallivein=new HashSet(liveinto);
1658 ar.liveoutvirtualread=liveoutvirtualread;
1661 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1662 TempDescriptor tmp=it.next();
1663 //remove the pointers
1664 if (tmp.getType().isPtr()) {
1667 //let's print it here
1668 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1671 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1672 TempDescriptor tmp=it.next();
1673 //remove the pointers
1674 if (tmp.getType().isPtr()) {
1676 } else if (!liveinto.contains(tmp)) {
1677 //let's print it here
1678 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1681 output.println("};");
1683 //print out method name
1684 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) {");
1685 //build code for commit method
1687 //first define local primitives
1688 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1689 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1690 TempDescriptor tmp=tmpit.next();
1691 if (!tmp.getType().isPtr()) {
1692 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1693 //read from live into set
1694 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1697 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1701 //turn off write barrier generation
1703 state.SINGLETM=false;
1704 generateCode(faen, fm, lb, exitset, output, false);
1705 state.SINGLETM=true;
1706 //turn on write barrier generation
1708 output.println("}\n\n");
1712 //redefine these back to normal
1714 localsprefixaddr="&"+localsprefix;
1715 localsprefixderef=localsprefix+".";
1717 generateHeader(fm, lb, md!=null ? md : task,output);
1718 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1720 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1721 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1722 AtomicRecord ar=arit.next();
1723 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1727 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1728 if (md!=null&&(state.DSM||state.SINGLETM))
1729 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1730 else if (md!=null&&!(state.DSM||state.SINGLETM))
1731 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1733 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1735 output.print(objecttemp.numPointers()+",");
1736 output.print(paramsprefix);
1737 for(int j=0; j<objecttemp.numPointers(); j++)
1738 output.print(", NULL");
1739 output.println("};");
1742 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1743 TempDescriptor td=objecttemp.getPrimitive(i);
1744 TypeDescriptor type=td.getType();
1746 output.println(" void * "+td.getSafeSymbol()+";");
1747 else if (type.isClass()||type.isArray())
1748 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1750 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1755 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1756 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1757 if( callerSESEplaceholder != mlpa.getMainSESE() ) {
1758 // declare variables for naming static SESE's
1759 output.println(" /* static SESE names */");
1760 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1761 while( pItr.hasNext() ) {
1762 SESEandAgePair pair = pItr.next();
1763 output.println(" void* "+pair+";");
1766 // declare variables for tracking dynamic sources
1767 output.println(" /* dynamic variable sources */");
1768 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1769 while( dynSrcItr.hasNext() ) {
1770 TempDescriptor dynSrcVar = dynSrcItr.next();
1771 output.println(" void* "+dynSrcVar+"_srcSESE;");
1772 output.println(" int "+dynSrcVar+"_srcOffset;");
1777 // set up related allocation sites's waiting queues
1779 ConflictGraph graph = null;
1780 graph = mlpa.getConflictGraphResults().get(fm);
1781 if (graph != null) {
1782 output.println(" /* set up waiting queues */");
1783 output.println(" int numMemoryQueue=0;");
1784 output.println(" int memoryQueueItemID=0;");
1785 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
1787 System.out.println("lockset="+lockSet);
1788 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1789 SESELock seseLock = (SESELock) iterator.next();
1790 System.out.println("id="+seseLock.getID());
1791 System.out.println("#="+seseLock);
1793 System.out.println("size="+lockSet.size());
1794 if (lockSet.size() > 0) {
1795 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1797 .println(" seseCaller->numMemoryQueue=numMemoryQueue;");
1799 .println(" seseCaller->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1806 /* Check to see if we need to do a GC if this is a
1807 * multi-threaded program...*/
1809 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1810 || this.state.MULTICOREGC) {
1811 //Don't bother if we aren't in recursive methods...The loops case will catch it
1812 if (callgraph.getAllMethods(md).contains(md)) {
1813 if (state.DSM&&lb.isAtomic())
1814 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1815 else if (this.state.MULTICOREGC) {
1816 output.println("if(gcflag) gc("+localsprefixaddr+");");
1818 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1823 generateCode(fm.getNext(0), fm, lb, null, output, true);
1825 output.println("}\n\n");
1829 protected void initializeSESE( FlatSESEEnterNode fsen ) {
1831 FlatMethod fm = fsen.getfmEnclosing();
1832 MethodDescriptor md = fm.getMethod();
1833 ClassDescriptor cn = md.getClassDesc();
1836 // Creates bogus method descriptor to index into tables
1837 Modifiers modBogus = new Modifiers();
1838 MethodDescriptor mdBogus =
1839 new MethodDescriptor( modBogus,
1840 new TypeDescriptor( TypeDescriptor.VOID ),
1841 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1844 mdBogus.setClassDesc( fsen.getcdEnclosing() );
1845 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1846 fsen.setfmBogus( fmBogus );
1847 fsen.setmdBogus( mdBogus );
1849 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1850 inSetAndOutSet.addAll( fsen.getInVarSet() );
1851 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1853 // Build paramsobj for bogus method descriptor
1854 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
1855 paramstable.put( mdBogus, objectparams );
1857 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1858 while( itr.hasNext() ) {
1859 TempDescriptor temp = itr.next();
1860 TypeDescriptor type = temp.getType();
1861 if( type.isPtr() ) {
1862 objectparams.addPtr( temp );
1864 objectparams.addPrim( temp );
1868 // Build normal temp object for bogus method descriptor
1869 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
1870 tempstable.put( mdBogus, objecttemps );
1872 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
1873 FlatNode fn = (FlatNode)nodeit.next();
1874 TempDescriptor[] writes = fn.writesTemps();
1876 for( int i = 0; i < writes.length; i++ ) {
1877 TempDescriptor temp = writes[i];
1878 TypeDescriptor type = temp.getType();
1880 if( type.isPtr() ) {
1881 objecttemps.addPtr( temp );
1883 objecttemps.addPrim( temp );
1889 protected void generateMethodSESE(FlatSESEEnterNode fsen,
1891 PrintWriter outputStructs,
1892 PrintWriter outputMethHead,
1893 PrintWriter outputMethods
1896 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
1897 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
1899 // generate locals structure
1900 outputStructs.println("struct "+
1901 fsen.getcdEnclosing().getSafeSymbol()+
1902 fsen.getmdBogus().getSafeSymbol()+"_"+
1903 fsen.getmdBogus().getSafeMethodDescriptor()+
1905 outputStructs.println(" INTPTR size;");
1906 outputStructs.println(" void * next;");
1907 for(int i=0; i<objecttemps.numPointers(); i++) {
1908 TempDescriptor temp=objecttemps.getPointer(i);
1910 if (temp.getType().isNull())
1911 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1913 outputStructs.println(" struct "+
1914 temp.getType().getSafeSymbol()+" * "+
1915 temp.getSafeSymbol()+";");
1917 outputStructs.println("};\n");
1920 // generate the SESE record structure
1921 outputStructs.println(fsen.getSESErecordName()+" {");
1923 // data common to any SESE, and it must be placed first so
1924 // a module that doesn't know what kind of SESE record this
1925 // is can cast the pointer to a common struct
1926 outputStructs.println(" SESEcommon common;");
1928 // then garbage list stuff
1929 outputStructs.println(" INTPTR size;");
1930 outputStructs.println(" void * next;");
1932 // in-set source tracking
1933 // in-vars that are READY come from parent, don't need anything
1934 // stuff STATIC needs a custom SESE pointer for each age pair
1935 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
1936 while( itrStaticInVarSrcs.hasNext() ) {
1937 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
1938 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
1941 // DYNAMIC stuff needs a source SESE ptr and offset
1942 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
1943 while( itrDynInVars.hasNext() ) {
1944 TempDescriptor dynInVar = itrDynInVars.next();
1945 outputStructs.println(" void* "+dynInVar+"_srcSESE;");
1946 outputStructs.println(" int "+dynInVar+"_srcOffset;");
1949 // space for all in and out set primitives
1950 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1951 inSetAndOutSet.addAll( fsen.getInVarSet() );
1952 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1954 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
1956 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1957 while( itr.hasNext() ) {
1958 TempDescriptor temp = itr.next();
1959 TypeDescriptor type = temp.getType();
1960 if( !type.isPtr() ) {
1961 inSetAndOutSetPrims.add( temp );
1965 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
1966 while( itrPrims.hasNext() ) {
1967 TempDescriptor temp = itrPrims.next();
1968 TypeDescriptor type = temp.getType();
1969 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
1972 for(int i=0; i<objectparams.numPointers(); i++) {
1973 TempDescriptor temp=objectparams.getPointer(i);
1974 if (temp.getType().isNull())
1975 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1977 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1980 outputStructs.println("};\n");
1983 // write method declaration to header file
1984 outputMethHead.print("void ");
1985 outputMethHead.print(fsen.getSESEmethodName()+"(");
1986 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
1987 outputMethHead.println(");\n");
1990 generateFlatMethodSESE( fsen.getfmBogus(),
1991 fsen.getcdEnclosing(),
1997 private void generateFlatMethodSESE(FlatMethod fm,
1999 FlatSESEEnterNode fsen,
2000 FlatSESEExitNode seseExit,
2004 MethodDescriptor md=fm.getMethod();
2006 output.print("void ");
2007 output.print(fsen.getSESEmethodName()+"(");
2008 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
2009 output.println("){\n");
2011 TempObject objecttemp=(TempObject) tempstable.get(md);
2013 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2014 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2015 output.print(objecttemp.numPointers()+",");
2016 output.print("(void*) &("+paramsprefix+"->size)");
2017 for(int j=0; j<objecttemp.numPointers(); j++)
2018 output.print(", NULL");
2019 output.println("};");
2022 output.println(" /* regular local primitives */");
2023 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2024 TempDescriptor td=objecttemp.getPrimitive(i);
2025 TypeDescriptor type=td.getType();
2027 output.println(" void * "+td.getSafeSymbol()+";");
2028 else if (type.isClass()||type.isArray())
2029 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2031 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2035 // declare variables for naming static SESE's
2036 output.println(" /* static SESE names */");
2037 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
2038 while( pItr.hasNext() ) {
2039 SESEandAgePair pair = pItr.next();
2040 output.println(" void* "+pair+";");
2043 // declare variables for tracking dynamic sources
2044 output.println(" /* dynamic variable sources */");
2045 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
2046 while( dynSrcItr.hasNext() ) {
2047 TempDescriptor dynSrcVar = dynSrcItr.next();
2048 output.println(" void* "+dynSrcVar+"_srcSESE;");
2049 output.println(" int "+dynSrcVar+"_srcOffset;");
2052 // declare local temps for in-set primitives, and if it is
2053 // a ready-source variable, get the value from the record
2054 output.println(" /* local temps for in-set primitives */");
2055 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2056 while( itrInSet.hasNext() ) {
2057 TempDescriptor temp = itrInSet.next();
2058 TypeDescriptor type = temp.getType();
2059 if( !type.isPtr() ) {
2060 if( fsen.getReadyInVarSet().contains( temp ) ) {
2061 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2063 output.println(" "+type+" "+temp+";");
2068 // declare local temps for out-set primitives if its not already
2069 // in the in-set, and it's value will get written so no problem
2070 output.println(" /* local temp for out-set prim, not already in the in-set */");
2071 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2072 while( itrOutSet.hasNext() ) {
2073 TempDescriptor temp = itrOutSet.next();
2074 TypeDescriptor type = temp.getType();
2075 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2076 output.println(" "+type+" "+temp+";");
2080 // setup memory queue
2082 output.println(" // set up memory queues ");
2083 output.println(" int numMemoryQueue=0;");
2084 output.println(" int memoryQueueItemID=0;");
2085 ConflictGraph graph = null;
2086 graph = mlpa.getConflictGraphResults().get(fsen);
2087 if (graph != null) {
2088 output.println(" {");
2090 .println(" SESEcommon* parentCommon = &(___params___->common);");
2091 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
2094 if (lockSet.size() > 0) {
2095 output.println(" numMemoryQueue=" + lockSet.size() + ";");
2097 .println(" parentCommon->numMemoryQueue=numMemoryQueue;");
2099 .println(" parentCommon->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2102 output.println(" }");
2106 // copy in-set into place, ready vars were already
2107 // copied when the SESE was issued
2108 Iterator<TempDescriptor> tempItr;
2110 // static vars are from a known SESE
2111 tempItr = fsen.getStaticInVarSet().iterator();
2112 while( tempItr.hasNext() ) {
2113 TempDescriptor temp = tempItr.next();
2114 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2115 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2117 // can't grab something from this source until it is done
2118 output.println(" {");
2120 If we are running, everything is done. This check is redundant.
2122 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+srcPair+";" );
2123 output.println(" pthread_mutex_lock( &(com->lock) );");
2124 output.println(" while( com->doneExecuting == FALSE ) {");
2125 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2126 output.println(" }");
2127 output.println(" pthread_mutex_unlock( &(com->lock) );");
2129 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2130 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2132 output.println(" }");
2135 // dynamic vars come from an SESE and src
2136 tempItr = fsen.getDynamicInVarSet().iterator();
2137 while( tempItr.hasNext() ) {
2138 TempDescriptor temp = tempItr.next();
2139 TypeDescriptor type = temp.getType();
2141 // go grab it from the SESE source
2142 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2144 // gotta wait until the source is done
2145 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+temp+"_srcSESE;" );
2147 If we are running, everything is done!
2148 output.println(" pthread_mutex_lock( &(com->lock) );");
2149 output.println(" while( com->doneExecuting == FALSE ) {");
2150 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2151 output.println(" }");
2152 output.println(" pthread_mutex_unlock( &(com->lock) );");
2156 if( type.isNull() ) {
2158 } else if( type.isClass() || type.isArray() ) {
2159 typeStr = "struct "+type.getSafeSymbol()+"*";
2161 typeStr = type.getSafeSymbol();
2164 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2165 " = *(("+typeStr+"*) ("+
2166 paramsprefix+"->"+temp+"_srcSESE + "+
2167 paramsprefix+"->"+temp+"_srcOffset));");
2169 // or if the source was our parent, its in the record to grab
2170 output.println(" } else {");
2171 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2172 " = "+paramsprefix+"->"+temp+";");
2173 output.println(" }");
2176 // Check to see if we need to do a GC if this is a
2177 // multi-threaded program...
2178 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2179 //Don't bother if we aren't in recursive methods...The loops case will catch it
2180 if (callgraph.getAllMethods(md).contains(md)) {
2181 if(this.state.MULTICOREGC) {
2182 output.println("if(gcflag) gc("+localsprefixaddr+");");
2184 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2189 // initialize thread-local var to a non-zero, invalid address
2190 output.println(" seseCaller = (SESEcommon*) 0x2;");
2191 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2192 exitset.add(seseExit);
2193 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2194 output.println("}\n\n");
2199 // when a new mlp thread is created for an issued SESE, it is started
2200 // by running this method which blocks on a cond variable until
2201 // it is allowed to transition to execute. Then a case statement
2202 // allows it to invoke the method with the proper SESE body, and after
2203 // exiting the SESE method, executes proper SESE exit code before the
2204 // thread can be destroyed
2205 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2206 PrintWriter outmethod
2209 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2210 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2211 outmethod.println( " int status;");
2212 outmethod.println( " char errmsg[128];");
2214 // generate a case for each SESE class that can be invoked
2215 outmethod.println( " switch( *((int*)seseRecord) ) {");
2216 outmethod.println( " ");
2217 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
2218 FlatSESEEnterNode fsen = seseit.next();
2220 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2221 outmethod.println( " case "+fsen.getIdentifier()+":");
2222 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2224 if( fsen.equals( mlpa.getMainSESE() ) ) {
2225 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2226 outmethod.println( " exit( 0 );");
2229 outmethod.println( " break;");
2230 outmethod.println( "");
2233 // default case should never be taken, error out
2234 outmethod.println( " default:");
2235 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2236 outmethod.println( " exit(-30);");
2237 outmethod.println( " break;");
2238 outmethod.println( " }");
2239 outmethod.println( " return NULL;");
2240 outmethod.println( "}\n\n");
2244 protected void generateCode(FlatNode first,
2247 Set<FlatNode> stopset,
2248 PrintWriter output, boolean firstpass) {
2250 /* Assign labels to FlatNode's if necessary.*/
2252 Hashtable<FlatNode, Integer> nodetolabel;
2254 if (state.DELAYCOMP&&!firstpass)
2255 nodetolabel=dcassignLabels(first, stopset);
2257 nodetolabel=assignLabels(first, stopset);
2259 Set<FlatNode> storeset=null;
2260 HashSet<FlatNode> genset=null;
2261 HashSet<FlatNode> refset=null;
2262 Set<FlatNode> unionset=null;
2264 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2265 storeset=delaycomp.livecode(lb);
2266 genset=new HashSet<FlatNode>();
2267 if (state.STMARRAY&&!state.DUALVIEW) {
2268 refset=new HashSet<FlatNode>();
2269 refset.addAll(delaycomp.getDeref(lb));
2270 refset.removeAll(delaycomp.getCannotDelay(lb));
2271 refset.removeAll(delaycomp.getOther(lb));
2274 genset.addAll(delaycomp.getCannotDelay(lb));
2275 genset.addAll(delaycomp.getOther(lb));
2277 genset.addAll(delaycomp.getNotReady(lb));
2278 if (state.STMARRAY&&!state.DUALVIEW) {
2279 genset.removeAll(refset);
2282 unionset=new HashSet<FlatNode>();
2283 unionset.addAll(storeset);
2284 unionset.addAll(genset);
2285 if (state.STMARRAY&&!state.DUALVIEW)
2286 unionset.addAll(refset);
2289 /* Do the actual code generation */
2290 FlatNode current_node=null;
2291 HashSet tovisit=new HashSet();
2292 HashSet visited=new HashSet();
2294 tovisit.add(first.getNext(0));
2297 while(current_node!=null||!tovisit.isEmpty()) {
2298 if (current_node==null) {
2299 current_node=(FlatNode)tovisit.iterator().next();
2300 tovisit.remove(current_node);
2301 } else if (tovisit.contains(current_node)) {
2302 tovisit.remove(current_node);
2304 visited.add(current_node);
2305 if (nodetolabel.containsKey(current_node)) {
2306 output.println("L"+nodetolabel.get(current_node)+":");
2308 if (state.INSTRUCTIONFAILURE) {
2309 if (state.THREAD||state.DSM||state.SINGLETM) {
2310 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2312 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2314 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2316 if (!state.DELAYCOMP||firstpass) {
2317 generateFlatNode(fm, lb, current_node, output);
2319 //store primitive variables in out set
2320 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2321 Set<TempDescriptor> liveout=ar.liveout;
2322 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2323 TempDescriptor tmp=tmpit.next();
2324 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2327 if (state.MLP && stopset!=null) {
2328 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2329 assert current_node instanceof FlatSESEExitNode;
2330 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2331 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2332 assert fsen.getFlatExit().equals( fsxn );
2333 assert fsxn.getFlatEnter().equals( fsen );
2335 if (current_node.kind()!=FKind.FlatReturnNode) {
2336 output.println(" return;");
2339 } else if(current_node.numNext()==1) {
2342 current_node.kind()==FKind.FlatSESEEnterNode &&
2343 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2345 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2346 generateFlatNode(fm, lb, current_node, output);
2347 nextnode=fsen.getFlatExit().getNext(0);
2348 } else if (state.DELAYCOMP) {
2349 boolean specialprimitive=false;
2350 //skip literals...no need to add extra overhead
2351 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2352 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2353 if (!typedesc.isClass()&&!typedesc.isArray()) {
2354 specialprimitive=true;
2358 if (genset==null||genset.contains(current_node)||specialprimitive)
2359 generateFlatNode(fm, lb, current_node, output);
2360 if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2361 //need to acquire lock
2362 handleArrayDeref(fm, lb, current_node, output, firstpass);
2364 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2365 TempDescriptor wrtmp=current_node.writesTemps()[0];
2367 //need to store value written by previous node
2368 if (wrtmp.getType().isPtr()) {
2369 //only lock the objects that may actually need locking
2370 if (recorddc.getNeedTrans(lb, current_node)&&
2371 (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2372 wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2373 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2375 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2378 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2381 //need to read value read by previous node
2382 if (wrtmp.getType().isPtr()) {
2383 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2385 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");
2389 nextnode=current_node.getNext(0);
2392 generateFlatNode(fm, lb, current_node, output);
2393 nextnode=current_node.getNext(0);
2395 if (visited.contains(nextnode)) {
2396 output.println("goto L"+nodetolabel.get(nextnode)+";");
2399 current_node=nextnode;
2400 } else if (current_node.numNext()==2) {
2402 if (state.DELAYCOMP) {
2403 boolean computeside=false;
2405 //need to record which way it should go
2406 if (genset==null||genset.contains(current_node)) {
2407 if (storeset!=null&&storeset.contains(current_node)) {
2408 //need to store which way branch goes
2409 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2411 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2413 //which side to execute
2417 if (genset.contains(current_node)) {
2418 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2419 } else if (storeset.contains(current_node)) {
2421 branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2423 //which side to execute
2428 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2430 if (leftset.size()==0)
2432 if (visited.contains(current_node.getNext(branch))) {
2433 //already visited -- build jump
2434 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2437 current_node=current_node.getNext(branch);
2440 if (!visited.contains(current_node.getNext(1)))
2441 tovisit.add(current_node.getNext(1));
2442 if (visited.contains(current_node.getNext(0))) {
2443 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2446 current_node=current_node.getNext(0);
2450 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2451 if (!visited.contains(current_node.getNext(1)))
2452 tovisit.add(current_node.getNext(1));
2453 if (visited.contains(current_node.getNext(0))) {
2454 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2457 current_node=current_node.getNext(0);
2459 } else throw new Error();
2463 protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2464 if (fn.kind()==FKind.FlatSetElementNode) {
2465 FlatSetElementNode fsen=(FlatSetElementNode) fn;
2466 String dst=generateTemp(fm, fsen.getDst(), lb);
2467 String src=generateTemp(fm, fsen.getSrc(), lb);
2468 String index=generateTemp(fm, fsen.getIndex(), lb);
2469 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2471 if (elementtype.isArray()||elementtype.isClass())
2474 type=elementtype.getSafeSymbol()+" ";
2476 output.println("STOREARRAY("+dst+","+index+","+type+")");
2478 output.println("{");
2479 output.println(" struct ArrayObject *array;");
2480 output.println(" int index;");
2481 output.println(" RESTOREARRAY(array,index);");
2482 output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2483 output.println("}");
2485 } else if (fn.kind()==FKind.FlatElementNode) {
2486 FlatElementNode fen=(FlatElementNode) fn;
2487 String src=generateTemp(fm, fen.getSrc(), lb);
2488 String index=generateTemp(fm, fen.getIndex(), lb);
2489 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2490 String dst=generateTemp(fm, fen.getDst(), lb);
2492 if (elementtype.isArray()||elementtype.isClass())
2495 type=elementtype.getSafeSymbol()+" ";
2497 output.println("STOREARRAY("+src+","+index+","+type+")");
2499 output.println("{");
2500 output.println(" struct ArrayObject *array;");
2501 output.println(" int index;");
2502 output.println(" RESTOREARRAY(array,index);");
2503 output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2504 output.println("}");
2508 /** Special label assignment for delaycomputation */
2509 protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2510 HashSet tovisit=new HashSet();
2511 HashSet visited=new HashSet();
2513 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2515 //Label targets of branches
2516 Set<FlatNode> targets=branchanalysis.getTargets();
2517 for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2518 nodetolabel.put(it.next(), new Integer(labelindex++));
2523 /*Assign labels first. A node needs a label if the previous
2524 * node has two exits or this node is a join point. */
2526 while(!tovisit.isEmpty()) {
2527 FlatNode fn=(FlatNode)tovisit.iterator().next();
2532 if(lastset!=null&&lastset.contains(fn)) {
2533 // if last is not null and matches, don't go
2534 // any further for assigning labels
2538 for(int i=0; i<fn.numNext(); i++) {
2539 FlatNode nn=fn.getNext(i);
2542 //1) Edge >1 of node
2543 nodetolabel.put(nn,new Integer(labelindex++));
2545 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2549 nodetolabel.put(nn,new Integer(labelindex++));
2557 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2558 return assignLabels(first, null);
2561 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2562 HashSet tovisit=new HashSet();
2563 HashSet visited=new HashSet();
2565 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2568 /*Assign labels first. A node needs a label if the previous
2569 * node has two exits or this node is a join point. */
2571 while(!tovisit.isEmpty()) {
2572 FlatNode fn=(FlatNode)tovisit.iterator().next();
2577 if(lastset!=null&&lastset.contains(fn)) {
2578 // if last is not null and matches, don't go
2579 // any further for assigning labels
2583 for(int i=0; i<fn.numNext(); i++) {
2584 FlatNode nn=fn.getNext(i);
2587 //1) Edge >1 of node
2588 nodetolabel.put(nn,new Integer(labelindex++));
2590 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2594 nodetolabel.put(nn,new Integer(labelindex++));
2602 /** Generate text string that corresponds to the TempDescriptor td. */
2603 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2604 MethodDescriptor md=fm.getMethod();
2605 TaskDescriptor task=fm.getTask();
2606 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2608 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2609 return td.getSafeSymbol();
2612 if (objecttemps.isLocalPtr(td)) {
2613 return localsprefixderef+td.getSafeSymbol();
2616 if (objecttemps.isParamPtr(td)) {
2617 return paramsprefix+"->"+td.getSafeSymbol();
2623 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2625 // insert pre-node actions from the code plan
2628 CodePlan cp = mlpa.getCodePlan( fn );
2631 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2633 // for each sese and age pair that this parent statement
2634 // must stall on, take that child's stall semaphore, the
2635 // copying of values comes after the statement
2636 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2637 while( vstItr.hasNext() ) {
2638 VariableSourceToken vst = vstItr.next();
2640 SESEandAgePair pair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2642 output.println(" {");
2643 output.println(" SESEcommon* common = (SESEcommon*) "+pair+";");
2645 output.println(" pthread_mutex_lock( &(common->lock) );");
2646 output.println(" while( common->doneExecuting == FALSE ) {");
2647 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2648 output.println(" }");
2649 output.println(" pthread_mutex_unlock( &(common->lock) );");
2651 // copy things we might have stalled for
2652 output.println(" "+pair.getSESE().getSESErecordName()+"* child = ("+
2653 pair.getSESE().getSESErecordName()+"*) "+pair+";");
2655 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2656 while( tdItr.hasNext() ) {
2657 TempDescriptor td = tdItr.next();
2658 FlatMethod fmContext;
2659 if( currentSESE.getIsCallerSESEplaceholder() ) {
2660 fmContext = currentSESE.getfmEnclosing();
2662 fmContext = currentSESE.getfmBogus();
2664 output.println(" "+generateTemp( fmContext, td, null )+
2665 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2668 output.println(" }");
2671 // for each variable with a dynamic source, stall just for that variable
2672 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2673 while( dynItr.hasNext() ) {
2674 TempDescriptor dynVar = dynItr.next();
2676 // only stall if the dynamic source is not yourself, denoted by src==NULL
2677 // otherwise the dynamic write nodes will have the local var up-to-date
2678 output.println(" {");
2679 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2680 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2681 output.println(" psem_take( &(common->stallSem) );");
2683 FlatMethod fmContext;
2684 if( currentSESE.getIsCallerSESEplaceholder() ) {
2685 fmContext = currentSESE.getfmEnclosing();
2687 fmContext = currentSESE.getfmBogus();
2689 output.println(" "+generateTemp( fmContext, dynVar, null )+
2690 " = *(("+dynVar.getType()+"*) ("+
2691 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2693 output.println(" }");
2694 output.println(" }");
2697 // for each assignment of a variable to rhs that has a dynamic source,
2698 // copy the dynamic sources
2699 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2700 while( dynAssignItr.hasNext() ) {
2701 Map.Entry me = (Map.Entry) dynAssignItr.next();
2702 TempDescriptor lhs = (TempDescriptor) me.getKey();
2703 TempDescriptor rhs = (TempDescriptor) me.getValue();
2704 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
2705 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2708 // for each lhs that is dynamic from a non-dynamic source, set the
2709 // dynamic source vars to the current SESE
2710 dynItr = cp.getDynAssignCurr().iterator();
2711 while( dynItr.hasNext() ) {
2712 TempDescriptor dynVar = dynItr.next();
2713 assert currentSESE.getDynamicVarSet().contains( dynVar );
2714 output.println(" "+dynVar+"_srcSESE = NULL;");
2718 // handling stall site
2719 ParentChildConflictsMap conflictsMap = mlpa.getConflictsResults().get(fn);
2720 if (conflictsMap != null) {
2721 Set<Long> allocSet = conflictsMap.getAllocationSiteIDSetofStallSite();
2722 if (allocSet.size() > 0) {
2723 FlatNode enclosingFlatNode=null;
2724 if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
2725 enclosingFlatNode=currentSESE.getfmEnclosing();
2727 enclosingFlatNode=currentSESE;
2729 ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
2730 HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
2731 Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
2733 if(waitingElementSet.size()>0){
2734 output.println("// stall on parent's stall sites ");
2735 output.println(" {");
2736 output.println(" REntry* rentry;");
2738 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
2739 WaitingElement waitingElement = (WaitingElement) iterator.next();
2741 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
2742 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", seseCaller);");
2744 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller, ___locals___."+ waitingElement.getDynID() + ");");
2746 output.println(" psem_init( &(rentry->parentStallSem) );");
2747 output.println(" rentry->queue=seseCaller->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
2749 .println(" if(ADDRENTRY(seseCaller->memoryQueueArray["+ waitingElement.getQueueID()
2750 + "],rentry)==NOTREADY){");
2751 output.println(" psem_take( &(rentry->parentStallSem) );");
2752 output.println(" } ");
2754 output.println(" }");
2763 case FKind.FlatAtomicEnterNode:
2764 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
2767 case FKind.FlatAtomicExitNode:
2768 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
2771 case FKind.FlatInstanceOfNode:
2772 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
2775 case FKind.FlatSESEEnterNode:
2776 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
2779 case FKind.FlatSESEExitNode:
2780 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
2783 case FKind.FlatWriteDynamicVarNode:
2784 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
2787 case FKind.FlatGlobalConvNode:
2788 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
2791 case FKind.FlatTagDeclaration:
2792 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
2795 case FKind.FlatCall:
2796 generateFlatCall(fm, lb, (FlatCall) fn,output);
2799 case FKind.FlatFieldNode:
2800 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
2803 case FKind.FlatElementNode:
2804 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
2807 case FKind.FlatSetElementNode:
2808 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
2811 case FKind.FlatSetFieldNode:
2812 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
2816 generateFlatNew(fm, lb, (FlatNew) fn,output);
2819 case FKind.FlatOpNode:
2820 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
2823 case FKind.FlatCastNode:
2824 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
2827 case FKind.FlatLiteralNode:
2828 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
2831 case FKind.FlatReturnNode:
2832 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
2836 output.println("/* nop */");
2839 case FKind.FlatExit:
2840 output.println("/* exit */");
2843 case FKind.FlatBackEdge:
2844 if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
2845 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
2847 if(state.DSM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
2848 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
2850 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
2851 || (this.state.MULTICOREGC)) {
2852 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
2853 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
2854 } else if(this.state.MULTICOREGC) {
2855 output.println("if (gcflag) gc("+localsprefixaddr+");");
2857 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2860 output.println("/* nop */");
2863 case FKind.FlatCheckNode:
2864 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
2867 case FKind.FlatFlagActionNode:
2868 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
2871 case FKind.FlatPrefetchNode:
2872 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
2875 case FKind.FlatOffsetNode:
2876 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
2883 // insert post-node actions from the code-plan
2885 CodePlan cp = mlpa.getCodePlan( fn );
2892 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
2893 output.println("/* FlatOffsetNode */");
2894 FieldDescriptor fd=fofn.getField();
2895 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
2896 output.println("/* offset */");
2899 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
2900 if (state.PREFETCH) {
2901 Vector oids = new Vector();
2902 Vector fieldoffset = new Vector();
2903 Vector endoffset = new Vector();
2904 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
2905 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
2906 PrefetchPair pp = (PrefetchPair) it.next();
2907 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
2908 /* Find prefetches that can generate oid */
2909 if(statusbase == LocalityAnalysis.GLOBAL) {
2910 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
2912 } else if (statusbase == LocalityAnalysis.LOCAL) {
2913 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
2920 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
2921 output.println("{");
2922 output.println("/* prefetch */");
2923 output.println("/* prefetchid_" + fpn.siteid + " */");
2924 output.println("void * prefptr;");
2925 output.println("int tmpindex;");
2927 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
2928 /*Create C code for oid array */
2929 output.print(" unsigned int oidarray_[] = {");
2930 boolean needcomma=false;
2931 for (Iterator it = oids.iterator(); it.hasNext();) {
2934 output.print(it.next());
2937 output.println("};");
2939 /*Create C code for endoffset values */
2940 output.print(" unsigned short endoffsetarry_[] = {");
2942 for (Iterator it = endoffset.iterator(); it.hasNext();) {
2945 output.print(it.next());
2948 output.println("};");
2950 /*Create C code for Field Offset Values */
2951 output.print(" short fieldarry_[] = {");
2953 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
2956 output.print(it.next());
2959 output.println("};");
2960 /* make the prefetch call to Runtime */
2961 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
2962 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
2963 output.println(" }");
2964 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
2965 output.println(" } else {");
2966 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
2967 output.println(" }");
2968 output.println("}");
2972 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
2973 short offsetcount = 0;
2977 } else if (localbase) {
2978 for(; breakindex<pp.desc.size(); breakindex++) {
2979 Descriptor desc=pp.getDescAt(breakindex);
2980 if (desc instanceof FieldDescriptor) {
2981 FieldDescriptor fd=(FieldDescriptor)desc;
2982 if (fd.isGlobal()) {
2990 if (breakindex>pp.desc.size()) //all local
2993 TypeDescriptor lasttype=pp.base.getType();
2994 String basestr=generateTemp(fm, pp.base, lb);
2996 boolean maybenull=fm.getMethod().isStatic()||
2997 !pp.base.equals(fm.getParameter(0));
2999 for(int i=0; i<breakindex; i++) {
3000 String indexcheck="";
3002 Descriptor desc=pp.getDescAt(i);
3003 if (desc instanceof FieldDescriptor) {
3004 FieldDescriptor fd=(FieldDescriptor)desc;
3006 if (!teststr.equals(""))
3008 teststr+="((prefptr="+basestr+")!=NULL)";
3009 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3011 basestr=basestr+"->"+fd.getSafeSymbol();
3014 lasttype=fd.getType();
3016 IndexDescriptor id=(IndexDescriptor)desc;
3017 indexcheck="((tmpindex=";
3018 for(int j=0; j<id.tddesc.size(); j++) {
3019 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3021 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3023 if (!teststr.equals(""))
3025 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3026 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3028 lasttype=lasttype.dereference();
3033 if (teststr.equals("")) {
3034 oid="((unsigned int)"+basestr+")";
3036 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3040 for(int i = breakindex; i < pp.desc.size(); i++) {
3041 String newfieldoffset;
3042 Object desc = pp.getDescAt(i);
3043 if(desc instanceof FieldDescriptor) {
3044 FieldDescriptor fd=(FieldDescriptor)desc;
3045 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3046 lasttype=fd.getType();
3048 newfieldoffset = "";
3049 IndexDescriptor id=(IndexDescriptor)desc;
3050 for(int j = 0; j < id.tddesc.size(); j++) {
3051 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3053 newfieldoffset += id.offset.toString();
3054 lasttype=lasttype.dereference();
3056 fieldoffset.add(newfieldoffset);
3059 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3060 base+=pp.desc.size()-breakindex;
3061 endoffset.add(new Short((short)base));
3066 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3067 if (lb!=fgcn.getLocality())
3069 /* Have to generate flat globalconv */
3070 if (fgcn.getMakePtr()) {
3072 //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3073 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3075 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3076 //need to do translation
3077 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3078 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3079 if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3080 output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3082 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3086 /* Need to convert to OID */
3087 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3088 if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3089 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3091 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3097 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3099 if (fion.getType().isArray()) {
3100 type=state.getArrayNumber(fion.getType())+state.numClasses();
3102 type=fion.getType().getClassDesc().getId();
3105 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3106 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3108 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3111 int sandboxcounter=0;
3112 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3113 /* Check to see if we need to generate code for this atomic */
3114 if (locality==null) {
3115 if (GENERATEPRECISEGC) {
3116 output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3117 output.println("stopforgc((struct garbagelist *) &___locals___);");
3118 output.println("pthread_mutex_lock(&atomiclock);");
3119 output.println("restartaftergc();");
3120 output.println("}");
3122 output.println("pthread_mutex_lock(&atomiclock);");
3127 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3131 if (state.SANDBOX) {
3132 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3133 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3136 if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3137 AtomicRecord ar=atomicmethodmap.get(faen);
3139 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3140 TempDescriptor tmp=tmpit.next();
3141 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3144 //copy outs that depend on path
3145 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3146 TempDescriptor tmp=tmpit.next();
3147 if (!ar.livein.contains(tmp))
3148 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3152 /* Backup the temps. */
3153 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3154 TempDescriptor tmp=tmpit.next();
3155 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3158 output.println("goto transstart"+faen.getIdentifier()+";");
3160 /******* Print code to retry aborted transaction *******/
3161 output.println("transretry"+faen.getIdentifier()+":");
3164 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3165 TempDescriptor tmp=tmpit.next();
3166 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3170 /********* Need to revert local object store ********/
3171 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3173 output.println("while ("+revertptr+") {");
3174 output.println("struct ___Object___ * tmpptr;");
3175 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3176 output.println("REVERT_OBJ("+revertptr+");");
3177 output.println(revertptr+"=tmpptr;");
3178 output.println("}");
3180 /******* Tell the runtime to start the transaction *******/
3182 output.println("transstart"+faen.getIdentifier()+":");
3183 if (state.SANDBOX) {
3184 output.println("transaction_check_counter=*counter_reset_pointer;");
3187 output.println("transStart();");
3189 if (state.ABORTREADERS||state.SANDBOX) {
3191 output.println("abortenabled=1;");
3192 output.println("if (_setjmp(aborttrans)) {");
3193 output.println(" goto transretry"+faen.getIdentifier()+"; }");
3197 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3198 /* Check to see if we need to generate code for this atomic */
3199 if (locality==null) {
3200 output.println("pthread_mutex_unlock(&atomiclock);");
3203 if (locality.getAtomic(lb).get(faen).intValue()>0)
3205 //store the revert list before we lose the transaction object
3208 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3209 output.println(revertptr+"=revertlist;");
3210 output.println("if (transCommit()) {");
3211 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3212 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3213 output.println("} else {");
3214 /* Need to commit local object store */
3215 output.println("while ("+revertptr+") {");
3216 output.println("struct ___Object___ * tmpptr;");
3217 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3218 output.println("COMMIT_OBJ("+revertptr+");");
3219 output.println(revertptr+"=tmpptr;");
3220 output.println("}");
3221 output.println("}");
3225 if (!state.DELAYCOMP) {
3227 output.println("if (transCommit()) {");
3228 /* Transaction aborts if it returns true */
3229 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3230 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3231 output.println("}");
3233 if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
3234 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3235 output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3237 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3238 TempDescriptor tmp=tmpit.next();
3239 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3241 } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3242 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3244 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3245 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3246 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3247 output.println("}");
3249 output.println("else {");
3250 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3251 TempDescriptor tmp=tmpit.next();
3252 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3254 output.println("}");
3256 output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3257 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3258 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3259 output.println("}");
3264 public void generateFlatSESEEnterNode( FlatMethod fm,
3266 FlatSESEEnterNode fsen,
3270 // if MLP flag is off, okay that SESE nodes are in IR graph,
3271 // just skip over them and code generates exactly the same
3276 // there may be an SESE in an unreachable method, skip over
3277 if( !mlpa.getAllSESEs().contains( fsen ) ) {
3281 // also, if we have encountered a placeholder, just skip it
3282 if( fsen.getIsCallerSESEplaceholder() ) {
3286 output.println(" {");
3288 // set up the parent
3289 if( fsen == mlpa.getMainSESE() ) {
3290 output.println(" SESEcommon* parentCommon = NULL;");
3292 if( fsen.getParent() == null ) {
3293 System.out.println( "in "+fm+", "+fsen+" has null parent" );
3295 assert fsen.getParent() != null;
3296 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3297 output.println(" SESEcommon* parentCommon = &("+paramsprefix+"->common);");
3299 //output.println(" SESEcommon* parentCommon = (SESEcommon*) peekItem( seseCallStack );");
3300 output.println(" SESEcommon* parentCommon = seseCaller;");
3304 // before doing anything, lock your own record and increment the running children
3305 if( fsen != mlpa.getMainSESE() ) {
3306 output.println(" atomic_inc(&parentCommon->numRunningChildren);");
3309 // just allocate the space for this record
3310 output.println(" "+fsen.getSESErecordName()+"* seseToIssue = ("+
3311 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3312 fsen.getSESErecordName()+" ) );");
3314 // and keep the thread-local sese stack up to date
3315 //output.println(" addNewItem( seseCallStack, (void*) seseToIssue);");
3317 // fill in common data
3318 output.println(" int localCount=0;");
3319 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3320 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
3322 output.println(" seseToIssue->common.forwardList = createQueue();");
3323 output.println(" seseToIssue->common.unresolvedDependencies = 10000;");
3324 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3325 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3326 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3327 output.println(" seseToIssue->common.numRunningChildren = 0;");
3328 output.println(" seseToIssue->common.parent = parentCommon;");
3330 // all READY in-vars should be copied now and be done with it
3331 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3332 while( tempItr.hasNext() ) {
3333 TempDescriptor temp = tempItr.next();
3335 // when we are issuing the main SESE or an SESE with placeholder
3336 // caller SESE as parent, generate temp child child's eclosing method,
3337 // otherwise use the parent's enclosing method as the context
3338 boolean useParentContext = false;
3340 if( fsen != mlpa.getMainSESE() ) {
3341 assert fsen.getParent() != null;
3342 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3343 useParentContext = true;
3347 if( useParentContext ) {
3348 output.println(" seseToIssue->"+temp+" = "+
3349 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3351 output.println(" seseToIssue->"+temp+" = "+
3352 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3356 // before potentially adding this SESE to other forwarding lists,
3357 // create it's lock and take it immediately
3358 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3359 // output.println(" pthread_mutex_lock( &(seseToIssue->common.lock) );");
3361 // count up memory conflict dependencies,
3363 ConflictGraph graph = null;
3364 FlatSESEEnterNode parent = fsen.getParent();
3365 if (parent != null) {
3366 if (parent.isCallerSESEplaceholder) {
3367 graph = mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
3369 graph = mlpa.getConflictGraphResults().get(parent);
3372 if (graph != null) {
3373 HashSet<SESELock> seseLockSet = mlpa.getConflictGraphLockMap().get(
3376 output.println(" //add memory queue element");
3377 Set<WaitingElement> waitingQueueSet = graph
3378 .getWaitingElementSetBySESEID(fsen.getIdentifier(),
3380 if (waitingQueueSet.size() > 0) {
3381 output.println(" {");
3382 output.println(" REntry* rentry=NULL;");
3383 output.println(" seseToIssue->common.rentryIdx=0;");
3384 for (Iterator iterator = waitingQueueSet.iterator(); iterator
3386 WaitingElement waitingElement = (WaitingElement) iterator
3389 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3390 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", seseToIssue);");
3392 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseToIssue, seseToIssue->"+ waitingElement.getDynID() + ");");
3394 output.println(" rentry->queue=parentCommon->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3395 output.println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
3397 .println(" if(ADDRENTRY(parentCommon->memoryQueueArray["
3398 + waitingElement.getQueueID()
3399 + "],rentry)==NOTREADY){");
3400 output.println(" ++(localCount);");
3401 output.println(" } ");
3404 output.println(" }");
3409 if( fsen != mlpa.getMainSESE() ) {
3410 // count up outstanding dependencies, static first, then dynamic
3411 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3412 while( staticSrcsItr.hasNext() ) {
3413 SESEandAgePair srcPair = staticSrcsItr.next();
3414 output.println(" {");
3415 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3416 output.println(" pthread_mutex_lock( &(src->lock) );");
3417 output.println(" if( !isEmpty( src->forwardList ) &&");
3418 output.println(" seseToIssue == peekItem( src->forwardList ) ) {");
3419 output.println(" printf( \"This shouldnt already be here\\n\");");
3420 output.println(" exit( -1 );");
3421 output.println(" }");
3422 output.println(" if( !src->doneExecuting ) {");
3423 output.println(" addNewItem( src->forwardList, seseToIssue );");
3424 // output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3425 output.println(" ++(localCount);");
3426 output.println(" }");
3427 output.println(" pthread_mutex_unlock( &(src->lock) );");
3428 output.println(" }");
3430 // whether or not it is an outstanding dependency, make sure
3431 // to pass the static name to the child's record
3432 output.println(" seseToIssue->"+srcPair+" = "+srcPair+";");
3435 // dynamic sources might already be accounted for in the static list,
3436 // so only add them to forwarding lists if they're not already there
3437 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3438 while( dynVarsItr.hasNext() ) {
3439 TempDescriptor dynInVar = dynVarsItr.next();
3440 output.println(" {");
3441 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3443 // the dynamic source is NULL if it comes from your own space--you can't pass
3444 // the address off to the new child, because you're not done executing and
3445 // might change the variable, so copy it right now
3446 output.println(" if( src != NULL ) {");
3447 output.println(" pthread_mutex_lock( &(src->lock) );");
3448 output.println(" if( isEmpty( src->forwardList ) ||");
3449 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3450 output.println(" if( !src->doneExecuting ) {");
3451 output.println(" addNewItem( src->forwardList, seseToIssue );");
3452 // output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3453 output.println(" ++(localCount);");
3454 output.println(" }");
3455 output.println(" }");
3456 output.println(" pthread_mutex_unlock( &(src->lock) );");
3457 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3458 output.println(" } else {");
3460 boolean useParentContext = false;
3461 if( fsen != mlpa.getMainSESE() ) {
3462 assert fsen.getParent() != null;
3463 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3464 useParentContext = true;
3467 if( useParentContext ) {
3468 output.println(" seseToIssue->"+dynInVar+" = "+
3469 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3471 output.println(" seseToIssue->"+dynInVar+" = "+
3472 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3475 output.println(" }");
3476 output.println(" }");
3478 // even if the value is already copied, make sure your NULL source
3479 // gets passed so child knows it already has the dynamic value
3480 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3483 // maintain pointers for finding dynamic SESE
3484 // instances from static names
3485 SESEandAgePair pair = new SESEandAgePair( fsen, 0 );
3486 if( fsen.getParent() != null &&
3487 //!fsen.getParent().getIsCallerSESEplaceholder() &&
3488 fsen.getParent().getNeededStaticNames().contains( pair )
3491 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3492 SESEandAgePair pair1 = new SESEandAgePair( fsen, i );
3493 SESEandAgePair pair2 = new SESEandAgePair( fsen, i-1 );
3494 output.println(" "+pair1+" = "+pair2+";");
3496 output.println(" "+pair+" = seseToIssue;");
3501 // release this SESE for siblings to update its dependencies or,
3502 // eventually, for it to mark itself finished
3503 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3505 // if there were no outstanding dependencies, issue here
3506 output.println(" if( atomic_sub_and_test(10000-localCount,&(seseToIssue->common.unresolvedDependencies) ) ) {");
3507 output.println(" workScheduleSubmit( (void*)seseToIssue );");
3508 output.println(" }");
3510 output.println(" if( seseToIssue->common.unresolvedDependencies == 0 ) {");
3511 output.println(" workScheduleSubmit( (void*)seseToIssue );");
3512 output.println(" }");
3514 // release this SESE for siblings to update its dependencies or,
3515 // eventually, for it to mark itself finished
3516 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3517 output.println(" }");
3521 public void generateFlatSESEExitNode( FlatMethod fm,
3523 FlatSESEExitNode fsexn,
3527 // if MLP flag is off, okay that SESE nodes are in IR graph,
3528 // just skip over them and code generates exactly the same
3533 // get the enter node for this exit that has meta data embedded
3534 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
3536 // there may be an SESE in an unreachable method, skip over
3537 if( !mlpa.getAllSESEs().contains( fsen ) ) {
3541 // also, if we have encountered a placeholder, just jump it
3542 if( fsen.getIsCallerSESEplaceholder() ) {
3546 output.println(" /* SESE exiting */");
3548 String com = paramsprefix+"->common";
3550 // this SESE cannot be done until all of its children are done
3551 // so grab your own lock with the condition variable for watching
3552 // that the number of your running children is greater than zero
3553 output.println(" pthread_mutex_lock( &("+com+".lock) );");
3554 output.println(" while( "+com+".numRunningChildren > 0 ) {");
3555 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
3556 output.println(" }");
3558 // copy out-set from local temps into the sese record
3559 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
3560 while( itr.hasNext() ) {
3561 TempDescriptor temp = itr.next();
3563 // only have to do this for primitives non-arrays
3565 temp.getType().isPrimitive() && !temp.getType().isArray()
3571 // have to determine the context enclosing this sese
3572 boolean useParentContext = false;
3574 if( fsen != mlpa.getMainSESE() ) {
3575 assert fsen.getParent() != null;
3576 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3577 useParentContext = true;
3582 if( useParentContext ) {
3583 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
3585 from = generateTemp( fsen.getfmEnclosing(), temp, null );
3588 output.println(" "+paramsprefix+
3589 "->"+temp.getSafeSymbol()+
3593 // mark yourself done, your SESE data is now read-only
3594 output.println(" "+com+".doneExecuting = TRUE;");
3595 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
3596 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
3598 // decrement dependency count for all SESE's on your forwarding list
3599 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
3600 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
3601 // output.println(" pthread_mutex_lock( &(consumer->lock) );");
3602 // output.println(" --(consumer->unresolvedDependencies);");
3603 // output.println(" if( consumer->unresolvedDependencies == 0 ) {");
3604 output.println(" if( atomic_sub_and_test(1, &(consumer->unresolvedDependencies)) ){");
3605 output.println(" workScheduleSubmit( (void*)consumer );");
3606 output.println(" }");
3607 // output.println(" pthread_mutex_unlock( &(consumer->lock) );");
3608 output.println(" }");
3612 // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
3613 if( fsen != mlpa.getMainSESE() ) {
3616 output.println(" /* check memory dependency*/");
3617 output.println(" {");
3618 output.println(" int idx;");
3619 output.println(" for(idx=0;idx<___params___->common.rentryIdx;idx++){");
3620 output.println(" REntry* re=___params___->common.rentryArray[idx];");
3621 output.println(" RETIRERENTRY(re->queue,re);");
3622 output.println(" }");
3623 output.println(" }");
3627 // if parent is stalling on you, let them know you're done
3628 if( fsexn.getFlatEnter() != mlpa.getMainSESE() ) {
3629 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
3632 // last of all, decrement your parent's number of running children
3633 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
3634 output.println(" if (atomic_sub_and_test(1, &"+paramsprefix+"->common.parent->numRunningChildren)) {");
3635 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
3636 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
3637 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
3638 output.println(" }");
3639 output.println(" }");
3641 // this is a thread-only variable that can be handled when critical sese-to-sese
3642 // data has been taken care of--set sese pointer to remember self over method
3643 // calls to a non-zero, invalid address
3644 output.println(" seseCaller = (SESEcommon*) 0x1;");
3648 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
3650 FlatWriteDynamicVarNode fwdvn,
3654 // should node should not be in an IR graph if the
3655 // MLP flag is not set
3656 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
3659 Hashtable<TempDescriptor, VSTWrapper> writeDynamic = fwdvn.getVar2src();
3661 assert writeDynamic != null;
3663 Iterator wdItr = writeDynamic.entrySet().iterator();
3664 while( wdItr.hasNext() ) {
3665 Map.Entry me = (Map.Entry) wdItr.next();
3666 TempDescriptor refVar = (TempDescriptor) me.getKey();
3667 VSTWrapper vstW = (VSTWrapper) me.getValue();
3668 VariableSourceToken vst = vstW.vst;
3671 // only do this if the variable in question should be tracked,
3672 // meaning that it was explicitly added to the dynamic var set
3673 if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
3679 // if there is no given source, this variable is ready so
3680 // mark src pointer NULL to signify that the var is up-to-date
3681 output.println(" "+refVar+"_srcSESE = NULL;");
3685 // otherwise we track where it will come from
3686 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
3687 output.println(" "+refVar+"_srcSESE = "+instance+";");
3688 output.println(" "+refVar+"_srcOffset = (int) &((("+
3689 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
3694 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
3695 if (state.CONSCHECK) {
3696 String specname=fcn.getSpec();
3697 String varname="repairstate___";
3698 output.println("{");
3699 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
3701 TempDescriptor[] temps=fcn.getTemps();
3702 String[] vars=fcn.getVars();
3703 for(int i=0; i<temps.length; i++) {
3704 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
3707 output.println("if (doanalysis"+specname+"("+varname+")) {");
3708 output.println("free"+specname+"_state("+varname+");");
3709 output.println("} else {");
3710 output.println("/* Bad invariant */");
3711 output.println("free"+specname+"_state("+varname+");");
3712 output.println("abort_task();");
3713 output.println("}");
3714 output.println("}");
3718 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
3720 if( state.MLP && !nonSESEpass ) {
3721 output.println(" seseCaller = (SESEcommon*)"+paramsprefix+";");
3724 MethodDescriptor md=fc.getMethod();
3725 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
3726 ClassDescriptor cn=md.getClassDesc();
3727 output.println("{");
3728 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3730 LocalityBinding fclb=locality.getBinding(lb, fc);
3731 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3733 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3735 output.print(objectparams.numPointers());
3736 output.print(", "+localsprefixaddr);
3737 if (md.getThis()!=null) {
3739 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
3741 if (fc.getThis()!=null&&md.getThis()==null) {
3742 System.out.println("WARNING!!!!!!!!!!!!");
3743 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
3747 for(int i=0; i<fc.numArgs(); i++) {
3748 Descriptor var=md.getParameter(i);
3749 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3750 if (objectparams.isParamPtr(paramtemp)) {
3751 TempDescriptor targ=fc.getArg(i);
3753 TypeDescriptor td=md.getParamType(i);
3755 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3757 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3760 output.println("};");
3765 if (fc.getReturnTemp()!=null)
3766 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
3768 /* Do we need to do virtual dispatch? */
3769 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
3772 LocalityBinding fclb=locality.getBinding(lb, fc);
3773 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3775 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3780 if (md.getReturnType().isClass()||md.getReturnType().isArray())
3781 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3783 output.print(md.getReturnType().getSafeSymbol()+" ");
3784 output.print("(*)(");
3786 boolean printcomma=false;
3787 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3789 LocalityBinding fclb=locality.getBinding(lb, fc);
3790 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3792 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3796 for(int i=0; i<objectparams.numPrimitives(); i++) {
3797 TempDescriptor temp=objectparams.getPrimitive(i);
3801 if (temp.getType().isClass()||temp.getType().isArray())
3802 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
3804 output.print(temp.getType().getSafeSymbol());
3809 LocalityBinding fclb=locality.getBinding(lb, fc);
3810 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
3812 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
3816 boolean needcomma=false;
3817 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3818 output.print("&__parameterlist__");
3822 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
3823 if (fc.getThis()!=null) {
3824 TypeDescriptor ptd=md.getThis().getType();
3827 if (ptd.isClass()&&!ptd.isArray())
3828 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3829 output.print(generateTemp(fm,fc.getThis(),lb));
3834 for(int i=0; i<fc.numArgs(); i++) {
3835 Descriptor var=md.getParameter(i);
3836 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3837 if (objectparams.isParamPrim(paramtemp)) {
3838 TempDescriptor targ=fc.getArg(i);
3842 TypeDescriptor ptd=md.getParamType(i);
3843 if (ptd.isClass()&&!ptd.isArray())
3844 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3845 output.print(generateTemp(fm, targ,lb));
3849 output.println(");");
3850 output.println(" }");
3853 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
3854 Set subclasses=typeutil.getSubClasses(thiscd);
3855 if (subclasses==null)
3857 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
3858 ClassDescriptor cd=(ClassDescriptor)classit.next();
3859 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
3860 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
3861 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
3862 if (md.matches(matchmd))
3869 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
3870 if (state.SINGLETM) {
3871 //single machine transactional memory case
3872 String field=ffn.getField().getSafeSymbol();
3873 String src=generateTemp(fm, ffn.getSrc(),lb);
3874 String dst=generateTemp(fm, ffn.getDst(),lb);
3876 output.println(dst+"="+ src +"->"+field+ ";");
3877 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
3878 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
3879 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
3880 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
3881 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
3882 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
3883 if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
3884 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
3886 output.println("TRANSREADRD("+dst+", "+dst+");");
3889 } else if (state.DSM) {
3890 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
3891 if (status==LocalityAnalysis.GLOBAL) {
3892 String field=ffn.getField().getSafeSymbol();
3893 String src=generateTemp(fm, ffn.getSrc(),lb);
3894 String dst=generateTemp(fm, ffn.getDst(),lb);
3896 if (ffn.getField().getType().isPtr()) {
3898 //TODO: Uncomment this when we have runtime support
3899 //if (ffn.getSrc()==ffn.getDst()) {
3900 //output.println("{");
3901 //output.println("void * temp="+src+";");
3902 //output.println("if (temp&0x1) {");
3903 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
3904 //output.println(src+"->"+field+"="+temp+";");
3905 //output.println("}");
3906 //output.println(dst+"=temp;");
3907 //output.println("}");
3909 output.println(dst+"="+ src +"->"+field+ ";");
3910 //output.println("if ("+dst+"&0x1) {");
3911 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
3912 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3913 //output.println(src+"->"+field+"="+src+"->"+field+";");
3914 //output.println("}");
3917 output.println(dst+"="+ src+"->"+field+";");
3919 } else if (status==LocalityAnalysis.LOCAL) {
3920 if (ffn.getField().getType().isPtr()&&
3921 ffn.getField().isGlobal()) {
3922 String field=ffn.getField().getSafeSymbol();
3923 String src=generateTemp(fm, ffn.getSrc(),lb);
3924 String dst=generateTemp(fm, ffn.getDst(),lb);
3925 output.println(dst+"="+ src +"->"+field+ ";");
3926 if (locality.getAtomic(lb).get(ffn).intValue()>0)
3927 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
3928 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
3930 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3931 } else if (status==LocalityAnalysis.EITHER) {
3932 //Code is reading from a null pointer
3933 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
3934 output.println("#ifndef RAW");
3935 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
3936 output.println("#endif");
3937 //This should throw a suitable null pointer error
3938 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3940 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
3942 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
3946 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
3947 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
3948 throw new Error("Can't set array length");
3949 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3950 //Single Machine Transaction Case
3951 boolean srcptr=fsfn.getSrc().getType().isPtr();
3952 String src=generateTemp(fm,fsfn.getSrc(),lb);
3953 String dst=generateTemp(fm,fsfn.getDst(),lb);
3954 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
3955 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
3956 output.println("{");
3957 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
3958 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
3959 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3961 output.println("INTPTR srcoid=(INTPTR)"+src+";");
3964 if (wb.needBarrier(fsfn)&&
3965 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
3966 if (state.EVENTMONITOR) {
3967 output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
3969 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
3971 if (srcptr&!fsfn.getSrc().getType().isNull()) {
3972 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
3973 output.println("}");
3975 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3977 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
3978 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
3979 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
3980 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
3982 String src=generateTemp(fm,fsfn.getSrc(),lb);
3983 String dst=generateTemp(fm,fsfn.getDst(),lb);
3985 output.println("{");
3986 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
3988 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
3991 if (wb.needBarrier(fsfn))
3992 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
3994 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
3996 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
3997 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
3998 /** Check if we need to copy */
3999 output.println("if(!"+dst+"->"+localcopystr+") {");
4000 /* Link object into list */
4001 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4002 output.println(revertptr+"=revertlist;");
4003 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4004 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4006 output.println("COPY_OBJ("+dst+");");
4007 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4008 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4009 output.println("}");
4011 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4013 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4014 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
4015 //writing to a null...bad
4016 output.println("if ("+dst+") {");
4017 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
4019 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4021 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4024 output.println("}");
4027 if (state.FASTCHECK) {
4028 String dst=generateTemp(fm, fsfn.getDst(),lb);
4029 output.println("if(!"+dst+"->"+localcopystr+") {");
4030 /* Link object into list */
4031 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4032 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4034 output.println("COPY_OBJ("+dst+");");
4035 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4036 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4037 output.println("}");
4039 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4043 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
4044 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
4047 if (elementtype.isArray()||elementtype.isClass())
4050 type=elementtype.getSafeSymbol()+" ";
4052 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
4053 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
4054 output.println("failedboundschk();");
4056 if (state.SINGLETM) {
4057 //Single machine transaction case
4058 String dst=generateTemp(fm, fen.getDst(),lb);
4059 if ((!state.STMARRAY)||(!wb.needBarrier(fen))||locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())==LocalityAnalysis.SCRATCH||locality.getAtomic(lb).get(fen).intValue()==0||(state.READSET&&!dc.getNeedGet(lb, fen))) {
4060 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4062 output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
4065 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
4066 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
4067 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
4068 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
4069 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
4070 if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
4071 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4073 output.println("TRANSREADRD("+dst+", "+dst+");");
4076 } else if (state.DSM) {
4077 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
4078 if (status==LocalityAnalysis.GLOBAL) {
4079 String dst=generateTemp(fm, fen.getDst(),lb);
4080 if (elementtype.isPtr()) {
4081 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4082 //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
4083 output.println("TRANSREAD("+dst+", "+dst+");");
4085 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4087 } else if (status==LocalityAnalysis.LOCAL) {
4088 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4089 } else if (status==LocalityAnalysis.EITHER) {
4090 //Code is reading from a null pointer
4091 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
4092 output.println("#ifndef RAW");
4093 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4094 output.println("#endif");
4095 //This should throw a suitable null pointer error
4096 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4098 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4100 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4104 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
4105 //TODO: need dynamic check to make sure this assignment is actually legal
4106 //Because Object[] could actually be something more specific...ie. Integer[]
4108 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
4111 if (elementtype.isArray()||elementtype.isClass())
4114 type=elementtype.getSafeSymbol()+" ";
4116 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
4117 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
4118 output.println("failedboundschk();");
4121 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4122 //Transaction set element case
4123 if (wb.needBarrier(fsen)&&
4124 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
4125 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
4127 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
4128 output.println("{");
4129 String src=generateTemp(fm, fsen.getSrc(), lb);
4130 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
4131 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
4132 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4134 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4136 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4137 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
4139 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4141 output.println("}");
4143 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4144 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
4146 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4149 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4150 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
4151 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
4152 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4153 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
4154 boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
4157 if (wb.needBarrier(fsen))
4158 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
4159 } else if (dstlocal) {
4160 /** Check if we need to copy */
4161 String dst=generateTemp(fm, fsen.getDst(),lb);
4162 output.println("if(!"+dst+"->"+localcopystr+") {");
4163 /* Link object into list */
4164 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4165 output.println(revertptr+"=revertlist;");
4166 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
4167 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4169 output.println("COPY_OBJ("+dst+");");
4170 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4171 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4172 output.println("}");
4174 System.out.println("Node: "+fsen);
4175 System.out.println(lb);
4176 System.out.println("statusdst="+statusdst);
4177 System.out.println(fm.printMethod());
4178 throw new Error("Unknown array type");
4181 output.println("{");
4182 String src=generateTemp(fm, fsen.getSrc(), lb);
4183 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4184 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4185 output.println("}");
4187 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4190 if (state.FASTCHECK) {
4191 String dst=generateTemp(fm, fsen.getDst(),lb);
4192 output.println("if(!"+dst+"->"+localcopystr+") {");
4193 /* Link object into list */
4194 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4195 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4197 output.println("COPY_OBJ("+dst+");");
4198 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4199 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4200 output.println("}");
4202 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4206 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
4207 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4208 //Stash pointer in case of GC
4209 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4210 output.println(revertptr+"=revertlist;");
4212 if (state.SINGLETM) {
4213 if (fn.getType().isArray()) {
4214 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4215 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4216 //inside transaction
4217 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4219 //outside transaction
4220 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4223 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4224 //inside transaction
4225 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4227 //outside transaction
4228 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4231 } else if (fn.getType().isArray()) {
4232 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4233 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4234 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4235 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4236 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4238 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4241 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4242 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
4243 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4244 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4246 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
4249 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4250 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4251 String dst=generateTemp(fm,fn.getDst(),lb);
4252 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4253 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4254 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4256 if (state.FASTCHECK) {
4257 String dst=generateTemp(fm,fn.getDst(),lb);
4258 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4259 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4260 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4264 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
4265 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4266 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
4268 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
4272 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
4273 if (fon.getRight()!=null) {
4274 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
4275 if (fon.getLeft().getType().isLong())
4276 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4278 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4280 } else if (dc!=null) {
4281 output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
4282 if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4283 output.print("(void *)");
4284 if (dc.getNeedLeftSrcTrans(lb, fon))
4285 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
4287 output.print(generateTemp(fm, fon.getLeft(),lb));
4288 output.print(")"+fon.getOp().toString()+"(");
4289 if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4290 output.print("(void *)");
4291 if (dc.getNeedRightSrcTrans(lb, fon))
4292 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
4294 output.println(generateTemp(fm,fon.getRight(),lb)+");");
4296 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
4297 } else if (fon.getOp().getOp()==Operation.ASSIGN)
4298 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4299 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
4300 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4301 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
4302 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
4303 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
4304 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
4305 else if (fon.getOp().getOp()==Operation.COMP)
4306 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
4307 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
4308 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
4310 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
4313 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
4314 /* TODO: Do type check here */
4315 if (fcn.getType().isArray()) {
4316 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4317 } else if (fcn.getType().isClass())
4318 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4320 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
4323 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
4324 if (fln.getValue()==null)
4325 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4326 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
4327 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4328 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4329 //Stash pointer in case of GC
4330 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4331 output.println(revertptr+"=revertlist;");
4333 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4334 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4335 //Stash pointer in case of GC
4336 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4337 output.println("revertlist="+revertptr+";");
4340 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4342 } else if (fln.getType().isBoolean()) {
4343 if (((Boolean)fln.getValue()).booleanValue())
4344 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
4346 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4347 } else if (fln.getType().isChar()) {
4348 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
4349 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
4350 } else if (fln.getType().isLong()) {
4351 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
4353 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
4356 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
4357 if (frn.getReturnTemp()!=null) {
4358 if (frn.getReturnTemp().getType().isPtr())
4359 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4361 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4363 output.println("return;");
4367 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4370 //only record if this group has more than one exit
4371 if (branchanalysis.numJumps(fcb)>1) {
4372 left=branchanalysis.jumpValue(fcb, 0);
4373 right=branchanalysis.jumpValue(fcb, 1);
4375 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
4377 output.println("STOREBRANCH("+right+");");
4378 output.println("goto "+label+";");
4379 output.println("}");
4381 output.println("STOREBRANCH("+left+");");
4384 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4385 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
4388 /** This method generates header information for the method or
4389 * task referenced by the Descriptor des. */
4390 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
4391 generateHeader(fm, lb, des, output, false);
4394 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
4396 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
4397 MethodDescriptor md=null;
4398 TaskDescriptor task=null;
4399 if (des instanceof MethodDescriptor)
4400 md=(MethodDescriptor) des;
4402 task=(TaskDescriptor) des;
4404 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
4406 if (md!=null&&md.getReturnType()!=null) {
4407 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4408 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4410 output.print(md.getReturnType().getSafeSymbol()+" ");
4412 //catch the constructor case
4413 output.print("void ");
4415 if (state.DSM||state.SINGLETM) {
4416 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4418 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4420 output.print(task.getSafeSymbol()+"(");
4422 boolean printcomma=false;
4423 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4425 if (state.DSM||state.SINGLETM) {
4426 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4428 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4430 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
4436 for(int i=0; i<objectparams.numPrimitives(); i++) {
4437 TempDescriptor temp=objectparams.getPrimitive(i);
4441 if (temp.getType().isClass()||temp.getType().isArray())
4442 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
4444 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
4446 output.println(") {");
4447 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4448 /* Imprecise Task */
4449 output.println("void * parameterarray[]) {");
4450 /* Unpack variables */
4451 for(int i=0; i<objectparams.numPrimitives(); i++) {
4452 TempDescriptor temp=objectparams.getPrimitive(i);
4453 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
4455 for(int i=0; i<fm.numTags(); i++) {
4456 TempDescriptor temp=fm.getTag(i);
4457 int offset=i+objectparams.numPrimitives();
4458 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
4461 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
4462 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
4463 } else output.println(") {");
4466 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
4467 output.println("/* FlatFlagActionNode */");
4470 /* Process tag changes */
4471 Relation tagsettable=new Relation();
4472 Relation tagcleartable=new Relation();
4474 Iterator tagsit=ffan.getTempTagPairs();
4475 while (tagsit.hasNext()) {
4476 TempTagPair ttp=(TempTagPair) tagsit.next();
4477 TempDescriptor objtmp=ttp.getTemp();
4478 TagDescriptor tag=ttp.getTag();
4479 TempDescriptor tagtmp=ttp.getTagTemp();
4480 boolean tagstatus=ffan.getTagChange(ttp);
4482 tagsettable.put(objtmp, tagtmp);
4484 tagcleartable.put(objtmp, tagtmp);
4489 Hashtable flagandtable=new Hashtable();
4490 Hashtable flagortable=new Hashtable();
4492 /* Process flag changes */
4493 Iterator flagsit=ffan.getTempFlagPairs();
4494 while(flagsit.hasNext()) {
4495 TempFlagPair tfp=(TempFlagPair)flagsit.next();
4496 TempDescriptor temp=tfp.getTemp();
4497 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
4498 FlagDescriptor flag=tfp.getFlag();
4500 //Newly allocate objects that don't set any flags case
4501 if (flagortable.containsKey(temp)) {
4505 flagortable.put(temp,new Integer(mask));
4507 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
4508 boolean flagstatus=ffan.getFlagChange(tfp);
4511 if (flagortable.containsKey(temp)) {
4512 mask=((Integer)flagortable.get(temp)).intValue();
4515 flagortable.put(temp,new Integer(mask));
4517 int mask=0xFFFFFFFF;
4518 if (flagandtable.containsKey(temp)) {
4519 mask=((Integer)flagandtable.get(temp)).intValue();
4521 mask&=(0xFFFFFFFF^flagid);
4522 flagandtable.put(temp,new Integer(mask));
4528 HashSet flagtagset=new HashSet();
4529 flagtagset.addAll(flagortable.keySet());
4530 flagtagset.addAll(flagandtable.keySet());
4531 flagtagset.addAll(tagsettable.keySet());
4532 flagtagset.addAll(tagcleartable.keySet());
4534 Iterator ftit=flagtagset.iterator();
4535 while(ftit.hasNext()) {
4536 TempDescriptor temp=(TempDescriptor)ftit.next();
4539 Set tagtmps=tagcleartable.get(temp);
4540 if (tagtmps!=null) {
4541 Iterator tagit=tagtmps.iterator();
4542 while(tagit.hasNext()) {
4543 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4544 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4545 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4547 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4551 tagtmps=tagsettable.get(temp);
4552 if (tagtmps!=null) {
4553 Iterator tagit=tagtmps.iterator();
4554 while(tagit.hasNext()) {
4555 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4556 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4557 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4559 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
4564 int andmask=0xFFFFFFF;
4566 if (flagortable.containsKey(temp))
4567 ormask=((Integer)flagortable.get(temp)).intValue();
4568 if (flagandtable.containsKey(temp))
4569 andmask=((Integer)flagandtable.get(temp)).intValue();
4570 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
4571 generateObjectDistribute(ffan, fm, lb, temp, output);
4575 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
4576 PrintWriter output, int ormask, int andmask) {
4577 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
4578 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4580 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4584 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
4585 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
4588 void generateOptionalHeader(PrintWriter headers) {
4591 headers.println("#include \"task.h\"\n\n");
4592 headers.println("#ifndef _OPTIONAL_STRUCT_");
4593 headers.println("#define _OPTIONAL_STRUCT_");
4595 //STRUCT PREDICATEMEMBER
4596 headers.println("struct predicatemember{");
4597 headers.println("int type;");
4598 headers.println("int numdnfterms;");
4599 headers.println("int * flags;");
4600 headers.println("int numtags;");
4601 headers.println("int * tags;\n};\n\n");
4603 //STRUCT OPTIONALTASKDESCRIPTOR
4604 headers.println("struct optionaltaskdescriptor{");
4605 headers.println("struct taskdescriptor * task;");
4606 headers.println("int index;");
4607 headers.println("int numenterflags;");
4608 headers.println("int * enterflags;");
4609 headers.println("int numpredicatemembers;");
4610 headers.println("struct predicatemember ** predicatememberarray;");
4611 headers.println("};\n\n");
4613 //STRUCT TASKFAILURE
4614 headers.println("struct taskfailure {");
4615 headers.println("struct taskdescriptor * task;");
4616 headers.println("int index;");
4617 headers.println("int numoptionaltaskdescriptors;");
4618 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4620 //STRUCT FSANALYSISWRAPPER
4621 headers.println("struct fsanalysiswrapper{");
4622 headers.println("int flags;");
4623 headers.println("int numtags;");
4624 headers.println("int * tags;");
4625 headers.println("int numtaskfailures;");
4626 headers.println("struct taskfailure ** taskfailurearray;");
4627 headers.println("int numoptionaltaskdescriptors;");
4628 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4630 //STRUCT CLASSANALYSISWRAPPER
4631 headers.println("struct classanalysiswrapper{");
4632 headers.println("int type;");
4633 headers.println("int numotd;");
4634 headers.println("struct optionaltaskdescriptor ** otdarray;");
4635 headers.println("int numfsanalysiswrappers;");
4636 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
4638 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
4640 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
4641 while(taskit.hasNext()) {
4642 TaskDescriptor td=(TaskDescriptor)taskit.next();
4643 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
4648 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
4649 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
4650 int predicateindex = 0;
4651 //iterate through the classes concerned by the predicate
4652 Set c_vard = predicate.vardescriptors;
4653 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
4656 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
4657 VarDescriptor vard = (VarDescriptor)vard_it.next();
4658 TypeDescriptor typed = vard.getType();
4660 //generate for flags
4661 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
4662 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4664 if (fen_hashset!=null) {
4665 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
4666 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
4668 DNFFlag dflag=fen.getDNF();
4669 numberterms+=dflag.size();
4671 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
4673 for(int j=0; j<dflag.size(); j++) {
4675 output.println(",");
4676 Vector term=dflag.get(j);
4679 for(int k=0; k<term.size(); k++) {
4680 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
4681 FlagDescriptor fd=dfa.getFlag();
4682 boolean negated=dfa.getNegated();
4683 int flagid=1<<((Integer)flags.get(fd)).intValue();
4688 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
4693 output.println("};\n");
4696 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
4697 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4700 for(int j=0; j<tagel.numTags(); j++) {
4702 output.println(",");
4703 TempDescriptor tmp=tagel.getTemp(j);
4704 if (!slotnumber.containsKey(tmp)) {
4705 Integer slotint=new Integer(current_slot++);
4706 slotnumber.put(tmp,slotint);
4708 int slot=slotnumber.get(tmp).intValue();
4709 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
4711 numtags = tagel.numTags();
4713 output.println("};");
4715 //store the result into a predicatemember struct
4716 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4717 output.println("/*type*/"+typed.getClassDesc().getId()+",");
4718 output.println("/* number of dnf terms */"+numberterms+",");
4719 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4720 output.println("/* number of tag */"+numtags+",");
4721 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4722 output.println("};\n");
4727 //generate an array that stores the entire predicate
4728 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4729 for( int j = 0; j<predicateindex; j++) {
4730 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4731 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4733 output.println("};\n");
4734 return predicateindex;
4738 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
4739 generateOptionalHeader(headers);
4741 output.println("#include \"optionalstruct.h\"\n\n");
4742 output.println("#include \"stdlib.h\"\n");
4744 HashSet processedcd = new HashSet();
4746 Enumeration e = safeexecution.keys();
4747 while (e.hasMoreElements()) {
4750 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
4751 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
4753 //Generate the struct of optionals
4754 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4755 numotd = c_otd.size();
4756 if(maxotd<numotd) maxotd = numotd;
4757 if( !c_otd.isEmpty() ) {
4758 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4759 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4761 //generate the int arrays for the predicate
4762 Predicate predicate = otd.predicate;
4763 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
4764 TreeSet<Integer> fsset=new TreeSet<Integer>();
4765 //iterate through possible FSes corresponding to
4766 //the state when entering
4768 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
4769 FlagState fs = (FlagState)fses.next();
4771 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4772 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4773 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4776 fsset.add(new Integer(flagid));
4777 //tag information not needed because tag
4778 //changes are not tolerated.
4781 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4782 boolean needcomma=false;
4783 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
4786 output.println(it.next());
4789 output.println("};\n");
4792 //generate optionaltaskdescriptor that actually
4793 //includes exit fses, predicate and the task
4795 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4796 output.println("&task_"+otd.td.getSafeSymbol()+",");
4797 output.println("/*index*/"+otd.getIndex()+",");
4798 output.println("/*number of enter flags*/"+fsset.size()+",");
4799 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4800 output.println("/*number of members */"+predicateindex+",");
4801 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4802 output.println("};\n");
4806 // if there are no optionals, there is no need to build the rest of the struct
4808 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
4809 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4810 if( !c_otd.isEmpty() ) {
4811 boolean needcomma=false;
4812 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4813 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4815 output.println(",");
4817 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4820 output.println("};\n");
4822 //get all the possible flagstates reachable by an object
4823 Hashtable hashtbtemp = safeexecution.get(cdtemp);
4825 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
4826 fsts.addAll(hashtbtemp.keySet());
4827 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
4828 FlagState fs = (FlagState)fsit.next();
4831 //get the set of OptionalTaskDescriptors corresponding
4832 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
4833 //iterate through the OptionalTaskDescriptors and
4834 //store the pointers to the optionals struct (see on
4835 //top) into an array
4837 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
4838 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
4839 OptionalTaskDescriptor mm = mos.next();
4841 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
4843 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4846 output.println("};\n");
4848 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
4851 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4852 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4853 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4857 //process tag information
4860 boolean first = true;
4861 Enumeration tag_enum = fs.getTags();
4862 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4863 while(tag_enum.hasMoreElements()) {
4865 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
4869 output.println(", ");
4870 output.println("/*tagid*/"+state.getTagId(tagd));
4872 output.println("};");
4874 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
4875 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4876 TaskIndex ti=itti.next();
4880 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
4882 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
4883 boolean needcomma=false;
4884 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
4885 OptionalTaskDescriptor otd=otdit.next();
4889 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4891 output.println("};");
4893 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
4894 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
4895 output.print(ti.getIndex()+", ");
4896 output.print(otdset.size()+", ");
4897 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
4898 output.println("};");
4901 tiset=sa.getTaskIndex(fs);
4902 boolean needcomma=false;
4904 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4905 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4906 TaskIndex ti=itti.next();
4907 if (ti.isRuntime()) {
4914 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
4916 output.println("};\n");
4918 //Store the result in fsanalysiswrapper
4920 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
4921 output.println("/*flag*/"+flagid+",");
4922 output.println("/* number of tags*/"+tagcounter+",");
4923 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4924 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
4925 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
4926 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
4927 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
4928 output.println("};\n");
4932 //Build the array of fsanalysiswrappers
4933 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
4934 boolean needcomma=false;
4935 for(int i = 0; i<fscounter; i++) {
4936 if (needcomma) output.print(",");
4937 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
4940 output.println("};");
4942 //Build the classanalysiswrapper referring to the previous array
4943 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
4944 output.println("/*type*/"+cdtemp.getId()+",");
4945 output.println("/*numotd*/"+numotd+",");
4946 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
4947 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
4948 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
4949 processedcd.add(cdtemp);
4952 //build an array containing every classes for which code has been build
4953 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
4954 for(int i=0; i<state.numClasses(); i++) {
4955 ClassDescriptor cn=cdarray[i];
4958 if ((cn != null) && (processedcd.contains(cn)))
4959 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
4961 output.print("NULL");
4963 output.println("};");
4965 output.println("#define MAXOTD "+maxotd);
4966 headers.println("#endif");
4969 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
4970 Relation r=new Relation();
4971 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
4972 OptionalTaskDescriptor otd=otdit.next();
4973 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
4977 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
4978 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
4979 Set s=r.get(it.next());
4980 for(Iterator it2=s.iterator(); it2.hasNext();) {
4981 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
4989 protected void outputTransCode(PrintWriter output) {