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.OoOJava.OoOJavaAnalysis;
27 import Analysis.Prefetch.*;
28 import Analysis.Loops.WriteBarrier;
29 import Analysis.Loops.GlobalFieldType;
30 import Analysis.Locality.TypeAnalysis;
31 import Analysis.MLP.ConflictGraph;
32 import Analysis.MLP.ConflictNode;
33 import Analysis.MLP.MLPAnalysis;
34 import Analysis.MLP.ParentChildConflictsMap;
35 import Analysis.MLP.SESELock;
36 import Analysis.MLP.SESEWaitingQueue;
37 import Analysis.MLP.VariableSourceToken;
38 import Analysis.MLP.VSTWrapper;
39 import Analysis.MLP.CodePlan;
40 import Analysis.MLP.SESEandAgePair;
41 import Analysis.MLP.WaitingElement;
43 public class BuildCode {
46 Hashtable paramstable;
51 String localsprefix="___locals___";
52 String localsprefixaddr="&"+localsprefix;
53 String localsprefixderef=localsprefix+".";
54 String fcrevert="___fcrevert___";
55 String paramsprefix="___params___";
56 String oidstr="___nextobject___";
57 String nextobjstr="___nextobject___";
58 String localcopystr="___localcopy___";
59 public static boolean GENERATEPRECISEGC=false;
60 public static String PREFIX="";
61 public static String arraytype="ArrayObject";
62 public static int flagcount = 0;
65 protected int maxtaskparams=0;
66 private int maxcount=0;
67 ClassDescriptor[] cdarray;
68 TypeDescriptor[] arraytable;
69 LocalityAnalysis locality;
70 Hashtable<LocalityBinding, TempDescriptor> reverttable;
71 Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>> backuptable;
76 String mlperrstr = "if(status != 0) { "+
77 "sprintf(errmsg, \"MLP error at %s:%d\", __FILE__, __LINE__); "+
78 "perror(errmsg); exit(-1); }";
79 boolean nonSESEpass=true;
82 DiscoverConflicts recorddc;
87 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa) {
88 this(st, temptovar, typeutil, null, sa, pa, null, null);
91 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
92 this(st, temptovar, typeutil, null, sa, pa, mlpa, oooa);
95 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
96 this(st, temptovar, typeutil, locality, null, pa, mlpa, oooa);
99 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
105 callgraph=new CallGraph(state);
107 oidstr="___objlocation___";
108 this.temptovar=temptovar;
109 paramstable=new Hashtable();
110 tempstable=new Hashtable();
111 fieldorder=new Hashtable();
112 flagorder=new Hashtable();
113 this.typeutil=typeutil;
114 virtualcalls=new Virtual(state,locality);
115 if (locality!=null) {
116 this.locality=locality;
117 this.reverttable=new Hashtable<LocalityBinding, TempDescriptor>();
118 this.backuptable=new Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>>();
119 this.wb=new WriteBarrier(locality, st);
121 if (state.SINGLETM&&state.DCOPTS) {
122 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
123 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
124 this.dc=new DiscoverConflicts(locality, st, typeanalysis, gft);
127 if (state.DELAYCOMP) {
128 //TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
129 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
130 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
131 delaycomp=new DCWrapper(locality, st, typeanalysis, gft);
132 dc=delaycomp.getConflicts();
133 recorddc=new DiscoverConflicts(locality, st, typeanalysis, delaycomp.getCannotDelayMap(), true, true, null);
134 recorddc.doAnalysis();
138 /** The buildCode method outputs C code for all the methods. The Flat
139 * versions of the methods must already be generated and stored in
140 * the State object. */
141 PrintWriter outsandbox=null;
143 public void buildCode() {
144 /* Create output streams to write to */
145 PrintWriter outclassdefs=null;
146 PrintWriter outstructs=null;
147 PrintWriter outrepairstructs=null;
148 PrintWriter outmethodheader=null;
149 PrintWriter outmethod=null;
150 PrintWriter outvirtual=null;
151 PrintWriter outtask=null;
152 PrintWriter outtaskdefs=null;
153 PrintWriter outoptionalarrays=null;
154 PrintWriter optionalheaders=null;
158 outsandbox=new PrintWriter(new FileOutputStream(PREFIX+"sandboxdefs.c"), true);
160 outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
161 outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
162 outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
163 outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
164 outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
166 outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
167 outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
168 if (state.OPTIONAL) {
169 outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
170 optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
173 if (state.structfile!=null) {
174 outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
176 } catch (Exception e) {
181 /* Build the virtual dispatch tables */
182 buildVirtualTables(outvirtual);
184 /* Output includes */
185 outmethodheader.println("#ifndef METHODHEADERS_H");
186 outmethodheader.println("#define METHODHEADERS_H");
187 outmethodheader.println("#include \"structdefs.h\"");
189 outmethodheader.println("#include \"dstm.h\"");
191 outmethodheader.println("#include \"sandbox.h\"");
193 if (state.EVENTMONITOR) {
194 outmethodheader.println("#include \"monitor.h\"");
196 if (state.SINGLETM) {
197 outmethodheader.println("#include \"tm.h\"");
198 outmethodheader.println("#include \"delaycomp.h\"");
199 outmethodheader.println("#include \"inlinestm.h\"");
201 if (state.ABORTREADERS) {
202 outmethodheader.println("#include \"abortreaders.h\"");
203 outmethodheader.println("#include <setjmp.h>");
205 if (state.MLP || state.OOOJAVA) {
206 outmethodheader.println("#include <stdlib.h>");
207 outmethodheader.println("#include <stdio.h>");
208 outmethodheader.println("#include <string.h>");
209 outmethodheader.println("#include \"mlp_runtime.h\"");
210 outmethodheader.println("#include \"psemaphore.h\"");
213 /* Output Structures */
214 outputStructs(outstructs);
216 // Output the C class declarations
217 // These could mutually reference each other
218 outputClassDeclarations(outclassdefs);
220 // Output function prototypes and structures for parameters
221 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
222 while(it.hasNext()) {
223 ClassDescriptor cn=(ClassDescriptor)it.next();
224 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader);
226 outclassdefs.close();
229 /* Map flags to integers */
230 /* The runtime keeps track of flags using these integers */
231 it=state.getClassSymbolTable().getDescriptorsIterator();
232 while(it.hasNext()) {
233 ClassDescriptor cn=(ClassDescriptor)it.next();
237 generateTaskStructs(outstructs, outmethodheader);
239 /* Outputs generic task structures if this is a task
241 outputTaskTypes(outtask);
244 if( state.MLP || state.OOOJAVA) {
245 // have to initialize some SESE compiler data before
246 // analyzing normal methods, which must happen before
247 // generating SESE internal code
249 Iterator<FlatSESEEnterNode> seseit;
251 seseit=mlpa.getAllSESEs().iterator();
253 seseit=oooa.getAllSESEs().iterator();
255 while(seseit.hasNext()){
256 FlatSESEEnterNode fsen = seseit.next();
257 initializeSESE( fsen );
262 /* Build the actual methods */
263 outputMethods(outmethod);
265 // Output function prototypes and structures for SESE's and code
266 if( state.MLP || state.OOOJAVA ) {
268 // used to differentiate, during code generation, whether we are
269 // passing over SESE body code, or non-SESE code
272 // first generate code for each sese's internals
273 Iterator<FlatSESEEnterNode> seseit;
275 seseit=mlpa.getAllSESEs().iterator();
277 seseit=oooa.getAllSESEs().iterator();
280 while(seseit.hasNext()) {
281 FlatSESEEnterNode fsen = seseit.next();
282 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
285 // then write the invokeSESE switch to decouple scheduler
286 // from having to do unique details of sese invocation
287 generateSESEinvocationMethod(outmethodheader, outmethod);
291 /* Output code for tasks */
292 outputTaskCode(outtaskdefs, outmethod);
294 /* Record maximum number of task parameters */
295 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
296 } else if (state.main!=null) {
297 /* Generate main method */
298 outputMainMethod(outmethod);
301 /* Generate information for task with optional parameters */
302 if (state.TASK&&state.OPTIONAL) {
303 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
304 outoptionalarrays.close();
307 /* Output structure definitions for repair tool */
308 if (state.structfile!=null) {
309 buildRepairStructs(outrepairstructs);
310 outrepairstructs.close();
314 outmethodheader.println("#endif");
315 outmethodheader.close();
317 outstructs.println("#endif");
322 /* This code just generates the main C method for java programs.
323 * The main C method packs up the arguments into a string array
324 * and passes it to the java main method. */
326 private void outputMainMethod(PrintWriter outmethod) {
327 outmethod.println("int main(int argc, const char *argv[]) {");
328 outmethod.println(" int i;");
330 if (state.MLP || state.OOOJAVA) {
331 //outmethod.println(" pthread_once( &mlpOnceObj, mlpInitOncePerThread );");
333 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
337 if (state.DSMRECOVERYSTATS) {
338 outmethod.println("#ifdef RECOVERYSTATS \n");
339 outmethod.println("handle();\n");
340 outmethod.println("#endif\n");
342 outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
343 outmethod.println("handle();\n");
344 outmethod.println("#endif\n");
348 if (state.THREAD||state.DSM||state.SINGLETM) {
349 outmethod.println("initializethreads();");
352 outmethod.println("if (dstmStartup(argv[1])) {");
353 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
354 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
356 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
359 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
360 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
362 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
366 outmethod.println(" for(i=2;i<argc;i++) {");
368 outmethod.println(" for(i=1;i<argc;i++) {");
369 outmethod.println(" int length=strlen(argv[i]);");
370 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
371 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
373 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
376 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
378 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
379 outmethod.println(" }");
381 MethodDescriptor md=typeutil.getMain();
382 ClassDescriptor cd=typeutil.getMainClass();
384 outmethod.println(" {");
385 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
386 if (state.DSM||state.SINGLETM) {
387 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
389 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
390 outmethod.println("1, NULL,"+"stringarray};");
391 if (state.DSM||state.SINGLETM)
392 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
394 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
396 if (state.DSM||state.SINGLETM)
397 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
399 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
401 outmethod.println(" }");
404 outmethod.println("}");
407 if (state.THREAD||state.DSM||state.SINGLETM) {
408 outmethod.println("pthread_mutex_lock(&gclistlock);");
409 outmethod.println("threadcount--;");
410 outmethod.println("pthread_cond_signal(&gccond);");
411 outmethod.println("pthread_mutex_unlock(&gclistlock);");
414 if (state.DSM||state.SINGLETM) {
415 //outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
416 outmethod.println("#if defined(TRANSSTATS) \n");
417 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
418 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
419 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
420 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
422 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
423 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
424 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
425 outmethod.println("printf(\"ndirtyCacheObj= %d\\n\", ndirtyCacheObj);");
426 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
427 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
428 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
429 outmethod.println("printf(\"totalObjSize= %d\\n\", totalObjSize);");
430 outmethod.println("printf(\"sendRemoteReq= %d\\n\", sendRemoteReq);");
431 outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
432 } else if (state.SINGLETM) {
433 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
434 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
435 outmethod.println("#ifdef STMSTATS\n");
436 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
437 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
438 outmethod.println("}\n");
439 outmethod.println("#endif\n");
440 outmethod.println("fflush(stdout);");
442 outmethod.println("#endif\n");
445 if (state.EVENTMONITOR) {
446 outmethod.println("dumpdata();");
449 if (state.THREAD||state.SINGLETM)
450 outmethod.println("pthread_exit(NULL);");
452 if (state.MLP || state.OOOJAVA ) {
453 outmethod.println(" workScheduleBegin();");
456 outmethod.println("}");
459 /* This method outputs code for each task. */
461 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
462 /* Compile task based program */
463 outtaskdefs.println("#include \"task.h\"");
464 outtaskdefs.println("#include \"methodheaders.h\"");
465 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
466 while(taskit.hasNext()) {
467 TaskDescriptor td=(TaskDescriptor)taskit.next();
468 FlatMethod fm=state.getMethodFlat(td);
469 generateFlatMethod(fm, null, outmethod);
470 generateTaskDescriptor(outtaskdefs, fm, td);
473 //Output task descriptors
474 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
475 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
477 while(taskit.hasNext()) {
478 TaskDescriptor td=(TaskDescriptor)taskit.next();
482 outtaskdefs.println(",");
483 outtaskdefs.print("&task_"+td.getSafeSymbol());
485 outtaskdefs.println("};");
487 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
490 /* This method outputs most of the methods.c file. This includes
491 * some standard includes and then an array with the sizes of
492 * objets and array that stores supertype and then the code for
493 * the Java methods.. */
495 protected void outputMethods(PrintWriter outmethod) {
496 outmethod.println("#include \"methodheaders.h\"");
497 outmethod.println("#include \"virtualtable.h\"");
498 outmethod.println("#include \"runtime.h\"");
500 outmethod.println("#include \"sandboxdefs.c\"");
503 outmethod.println("#include \"addPrefetchEnhance.h\"");
504 outmethod.println("#include \"localobjects.h\"");
506 if (state.FASTCHECK) {
507 outmethod.println("#include \"localobjects.h\"");
509 if(state.MULTICORE) {
510 outmethod.println("#include \"task.h\"");
511 outmethod.println("#include \"multicoreruntime.h\"");
512 outmethod.println("#include \"runtime_arch.h\"");
514 if (state.THREAD||state.DSM||state.SINGLETM)
515 outmethod.println("#include <thread.h>");
516 if (state.main!=null) {
517 outmethod.println("#include <string.h>");
519 if (state.CONSCHECK) {
520 outmethod.println("#include \"checkers.h\"");
522 if (state.MLP || state.OOOJAVA ) {
523 outmethod.println("#include <stdlib.h>");
524 outmethod.println("#include <stdio.h>");
525 outmethod.println("#include \"mlp_runtime.h\"");
526 outmethod.println("#include \"psemaphore.h\"");
528 if (state.COREPROF) {
529 outmethod.println("#include \"coreprof.h\"");
532 //Store the sizes of classes & array elements
533 generateSizeArray(outmethod);
535 //Store table of supertypes
536 generateSuperTypeTable(outmethod);
538 //Store the layout of classes
539 generateLayoutStructs(outmethod);
541 /* Generate code for methods */
542 if (state.DSM||state.SINGLETM) {
543 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
544 LocalityBinding lb=lbit.next();
545 MethodDescriptor md=lb.getMethod();
546 FlatMethod fm=state.getMethodFlat(md);
548 if (!md.getModifiers().isNative()) {
549 generateFlatMethod(fm, lb, outmethod);
550 //System.out.println("fm= " + fm + " md= " + md);
554 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
555 while(classit.hasNext()) {
556 ClassDescriptor cn=(ClassDescriptor)classit.next();
557 Iterator methodit=cn.getMethods();
558 while(methodit.hasNext()) {
559 /* Classify parameters */
560 MethodDescriptor md=(MethodDescriptor)methodit.next();
561 FlatMethod fm=state.getMethodFlat(md);
562 if (!md.getModifiers().isNative()) {
563 generateFlatMethod(fm, null, outmethod);
570 protected void outputStructs(PrintWriter outstructs) {
571 outstructs.println("#ifndef STRUCTDEFS_H");
572 outstructs.println("#define STRUCTDEFS_H");
573 outstructs.println("#include \"classdefs.h\"");
574 outstructs.println("#ifndef INTPTR");
575 outstructs.println("#ifdef BIT64");
576 outstructs.println("#define INTPTR long");
577 outstructs.println("#else");
578 outstructs.println("#define INTPTR int");
579 outstructs.println("#endif");
580 outstructs.println("#endif");
581 if( state.MLP || state.OOOJAVA ) {
582 outstructs.println("#include \"mlp_runtime.h\"");
583 outstructs.println("#include \"psemaphore.h\"");
586 /* Output #defines that the runtime uses to determine type
587 * numbers for various objects it needs */
588 outstructs.println("#define MAXCOUNT "+maxcount);
589 if (state.DSM||state.SINGLETM) {
590 LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
592 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
594 else if (state.SINGLETM) {
595 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
597 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
601 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
603 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
604 else if( state.SINGLETM)
605 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
606 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
609 outstructs.println("#define STRINGARRAYTYPE "+
610 (state.getArrayNumber(
611 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
613 outstructs.println("#define OBJECTARRAYTYPE "+
614 (state.getArrayNumber(
615 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
618 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
619 outstructs.println("#define CHARARRAYTYPE "+
620 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
622 outstructs.println("#define BYTEARRAYTYPE "+
623 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
625 outstructs.println("#define BYTEARRAYARRAYTYPE "+
626 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
628 outstructs.println("#define NUMCLASSES "+state.numClasses());
629 int totalClassSize = state.numClasses() + state.numArrays();
630 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
632 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
633 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
634 outstructs.println("#define TAGARRAYTYPE "+
635 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
639 protected void outputClassDeclarations(PrintWriter outclassdefs) {
640 if (state.THREAD||state.DSM||state.SINGLETM)
641 outclassdefs.println("#include <pthread.h>");
642 outclassdefs.println("#ifndef INTPTR");
643 outclassdefs.println("#ifdef BIT64");
644 outclassdefs.println("#define INTPTR long");
645 outclassdefs.println("#else");
646 outclassdefs.println("#define INTPTR int");
647 outclassdefs.println("#endif");
648 outclassdefs.println("#endif");
650 outclassdefs.println("#include \"optionalstruct.h\"");
651 outclassdefs.println("struct "+arraytype+";");
652 /* Start by declaring all structs */
653 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
654 while(it.hasNext()) {
655 ClassDescriptor cn=(ClassDescriptor)it.next();
656 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
658 outclassdefs.println("");
659 //Print out definition for array type
660 outclassdefs.println("struct "+arraytype+" {");
661 outclassdefs.println(" int type;");
662 if(state.MLP || state.OOOJAVA ){
663 outclassdefs.println(" int oid;");
665 if (state.EVENTMONITOR) {
666 outclassdefs.println(" int objuid;");
669 outclassdefs.println(" pthread_t tid;");
670 outclassdefs.println(" void * lockentry;");
671 outclassdefs.println(" int lockcount;");
674 outclassdefs.println(" int flag;");
675 if(!state.MULTICORE) {
676 outclassdefs.println(" void * flagptr;");
678 outclassdefs.println(" int version;");
679 outclassdefs.println(" int * lock;"); // lock entry for this obj
680 outclassdefs.println(" int mutex;");
681 outclassdefs.println(" int lockcount;");
682 if(state.MULTICOREGC) {
683 outclassdefs.println(" int marked;");
687 outclassdefs.println(" int numfses;");
688 outclassdefs.println(" int * fses;");
691 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
693 if (state.STMARRAY) {
694 outclassdefs.println(" int lowindex;");
695 outclassdefs.println(" int highindex;");
698 outclassdefs.println(" int paddingforarray;");
699 if (state.DUALVIEW) {
700 outclassdefs.println(" int arrayversion;");
703 outclassdefs.println(" int ___length___;");
704 outclassdefs.println("};\n");
705 outclassdefs.println("extern int classsize[];");
706 outclassdefs.println("extern int hasflags[];");
707 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
708 outclassdefs.println("extern int supertypes[];");
711 /** Prints out definitions for generic task structures */
713 private void outputTaskTypes(PrintWriter outtask) {
714 outtask.println("#ifndef _TASK_H");
715 outtask.println("#define _TASK_H");
716 outtask.println("struct parameterdescriptor {");
717 outtask.println("int type;");
718 outtask.println("int numberterms;");
719 outtask.println("int *intarray;");
720 outtask.println("void * queue;");
721 outtask.println("int numbertags;");
722 outtask.println("int *tagarray;");
723 outtask.println("};");
725 outtask.println("struct taskdescriptor {");
726 outtask.println("void * taskptr;");
727 outtask.println("int numParameters;");
728 outtask.println(" int numTotal;");
729 outtask.println("struct parameterdescriptor **descriptorarray;");
730 outtask.println("char * name;");
731 outtask.println("};");
732 outtask.println("extern struct taskdescriptor * taskarray[];");
733 outtask.println("extern numtasks;");
734 outtask.println("#endif");
738 private void buildRepairStructs(PrintWriter outrepairstructs) {
739 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
740 while(classit.hasNext()) {
741 ClassDescriptor cn=(ClassDescriptor)classit.next();
742 outrepairstructs.println("structure "+cn.getSymbol()+" {");
743 outrepairstructs.println(" int __type__;");
745 outrepairstructs.println(" int __flag__;");
746 if(!state.MULTICORE) {
747 outrepairstructs.println(" int __flagptr__;");
750 printRepairStruct(cn, outrepairstructs);
751 outrepairstructs.println("}\n");
754 for(int i=0; i<state.numArrays(); i++) {
755 TypeDescriptor tdarray=arraytable[i];
756 TypeDescriptor tdelement=tdarray.dereference();
757 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
758 outrepairstructs.println(" int __type__;");
759 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
760 outrepairstructs.println(" int length;");
762 // Need to add support to repair tool for this
763 if (tdelement.isClass()||tdelement.isArray())
764 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
766 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
768 outrepairstructs.println("}\n");
772 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
773 ClassDescriptor sp=cn.getSuperDesc();
775 printRepairStruct(sp, output);
777 Vector fields=(Vector)fieldorder.get(cn);
779 for(int i=0; i<fields.size(); i++) {
780 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
781 if (fd.getType().isArray()) {
782 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
783 } else if (fd.getType().isClass())
784 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
785 else if (fd.getType().isFloat())
786 output.println(" int "+fd.getSymbol()+"; /* really float */");
788 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
792 /** This method outputs TaskDescriptor information */
793 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
794 for (int i=0; i<task.numParameters(); i++) {
795 VarDescriptor param_var=task.getParameter(i);
796 TypeDescriptor param_type=task.getParamType(i);
797 FlagExpressionNode param_flag=task.getFlag(param_var);
798 TagExpressionList param_tag=task.getTag(param_var);
801 if (param_flag==null) {
802 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
803 output.println("0x0, 0x0 };");
806 DNFFlag dflag=param_flag.getDNF();
807 dnfterms=dflag.size();
809 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
810 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
811 for(int j=0; j<dflag.size(); j++) {
814 Vector term=dflag.get(j);
817 for(int k=0; k<term.size(); k++) {
818 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
819 FlagDescriptor fd=dfa.getFlag();
820 boolean negated=dfa.getNegated();
821 int flagid=1<<((Integer)flags.get(fd)).intValue();
826 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
828 output.println("};");
831 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
832 //BUG...added next line to fix, test with any task program
834 for(int j=0; j<param_tag.numTags(); j++) {
837 /* for each tag we need */
838 /* which slot it is */
839 /* what type it is */
840 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
841 TempDescriptor tmp=param_tag.getTemp(j);
842 int slot=fm.getTagInt(tmp);
843 output.println(slot+", "+state.getTagId(tvd.getTag()));
845 output.println("};");
847 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
848 output.println("/* type */"+param_type.getClassDesc().getId()+",");
849 output.println("/* number of DNF terms */"+dnfterms+",");
850 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
851 output.println("0,");
852 //BUG, added next line to fix and else statement...test
853 //with any task program
855 output.println("/* number of tags */"+param_tag.numTags()+",");
857 output.println("/* number of tags */ 0,");
858 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
859 output.println("};");
863 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
864 for (int i=0; i<task.numParameters(); i++) {
867 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
869 output.println("};");
871 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
872 output.println("&"+task.getSafeSymbol()+",");
873 output.println("/* number of parameters */" +task.numParameters() + ",");
874 int numtotal=task.numParameters()+fm.numTags();
875 output.println("/* number total parameters */" +numtotal + ",");
876 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
877 output.println("\""+task.getSymbol()+"\"");
878 output.println("};");
882 /** The buildVirtualTables method outputs the virtual dispatch
883 * tables for methods. */
885 protected void buildVirtualTables(PrintWriter outvirtual) {
886 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
887 while(classit.hasNext()) {
888 ClassDescriptor cd=(ClassDescriptor)classit.next();
889 if (virtualcalls.getMethodCount(cd)>maxcount)
890 maxcount=virtualcalls.getMethodCount(cd);
892 MethodDescriptor[][] virtualtable=null;
893 LocalityBinding[][] lbvirtualtable=null;
894 if (state.DSM||state.SINGLETM)
895 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
897 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
899 /* Fill in virtual table */
900 classit=state.getClassSymbolTable().getDescriptorsIterator();
901 while(classit.hasNext()) {
902 ClassDescriptor cd=(ClassDescriptor)classit.next();
903 if (state.DSM||state.SINGLETM)
904 fillinRow(cd, lbvirtualtable, cd.getId());
906 fillinRow(cd, virtualtable, cd.getId());
909 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
910 Iterator arrayit=state.getArrayIterator();
911 while(arrayit.hasNext()) {
912 TypeDescriptor td=(TypeDescriptor)arrayit.next();
913 int id=state.getArrayNumber(td);
914 if (state.DSM||state.SINGLETM)
915 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
917 fillinRow(objectcd, virtualtable, id+state.numClasses());
920 outvirtual.print("void * virtualtable[]={");
921 boolean needcomma=false;
922 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
923 for(int j=0; j<maxcount; j++) {
925 outvirtual.print(", ");
926 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
927 LocalityBinding lb=lbvirtualtable[i][j];
928 MethodDescriptor md=lb.getMethod();
929 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
930 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
931 MethodDescriptor md=virtualtable[i][j];
932 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
934 outvirtual.print("0");
938 outvirtual.println("");
940 outvirtual.println("};");
944 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
945 /* Get inherited methods */
946 if (cd.getSuperDesc()!=null)
947 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
948 /* Override them with our methods */
949 for(Iterator it=cd.getMethods(); it.hasNext();) {
950 MethodDescriptor md=(MethodDescriptor)it.next();
951 if (md.isStatic()||md.getReturnType()==null)
953 int methodnum=virtualcalls.getMethodNumber(md);
954 virtualtable[rownum][methodnum]=md;
958 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
959 /* Get inherited methods */
960 if (cd.getSuperDesc()!=null)
961 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
962 /* Override them with our methods */
963 if (locality.getClassBindings(cd)!=null)
964 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
965 LocalityBinding lb=lbit.next();
966 MethodDescriptor md=lb.getMethod();
967 //Is the method static or a constructor
968 if (md.isStatic()||md.getReturnType()==null)
970 int methodnum=virtualcalls.getLocalityNumber(lb);
971 virtualtable[rownum][methodnum]=lb;
975 /** Generate array that contains the sizes of class objects. The
976 * object allocation functions in the runtime use this
979 private void generateSizeArray(PrintWriter outclassdefs) {
980 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
981 outclassdefs.print("#ifdef TRANSSTATS \n");
982 outclassdefs.print("extern int numTransAbort;\n");
983 outclassdefs.print("extern int numTransCommit;\n");
984 outclassdefs.print("extern int nSoftAbort;\n");
986 outclassdefs.print("extern int nchashSearch;\n");
987 outclassdefs.print("extern int nmhashSearch;\n");
988 outclassdefs.print("extern int nprehashSearch;\n");
989 outclassdefs.print("extern int ndirtyCacheObj;\n");
990 outclassdefs.print("extern int nRemoteSend;\n");
991 outclassdefs.print("extern int sendRemoteReq;\n");
992 outclassdefs.print("extern int getResponse;\n");
993 outclassdefs.print("extern int bytesSent;\n");
994 outclassdefs.print("extern int bytesRecv;\n");
995 outclassdefs.print("extern int totalObjSize;\n");
996 outclassdefs.print("extern void handle();\n");
997 } else if (state.SINGLETM) {
998 outclassdefs.println("extern int nSoftAbortAbort;");
999 outclassdefs.println("extern int nSoftAbortCommit;");
1000 outclassdefs.println("#ifdef STMSTATS\n");
1001 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
1002 outclassdefs.println("#endif\n");
1004 outclassdefs.print("#endif\n");
1006 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
1007 if(this.state.MLP || state.OOOJAVA ){
1008 outclassdefs.print("extern __thread int oid;\n");
1009 outclassdefs.print("extern int numWorkers;\n");
1012 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1013 cdarray=new ClassDescriptor[state.numClasses()];
1015 while(it.hasNext()) {
1016 ClassDescriptor cd=(ClassDescriptor)it.next();
1017 cdarray[cd.getId()]=cd;
1020 arraytable=new TypeDescriptor[state.numArrays()];
1022 Iterator arrayit=state.getArrayIterator();
1023 while(arrayit.hasNext()) {
1024 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1025 int id=state.getArrayNumber(td);
1031 /* Print out types */
1032 outclassdefs.println("/* ");
1033 for(int i=0; i<state.numClasses(); i++) {
1034 ClassDescriptor cd=cdarray[i];
1036 outclassdefs.println("NULL " + i);
1038 outclassdefs.println(cd +" "+i);
1042 for(int i=0; i<state.numArrays(); i++) {
1043 TypeDescriptor arraytd=arraytable[i];
1044 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
1047 outclassdefs.println("*/");
1050 outclassdefs.print("int classsize[]={");
1052 boolean needcomma=false;
1053 for(int i=0; i<state.numClasses(); i++) {
1055 outclassdefs.print(", ");
1057 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1059 outclassdefs.print("0");
1065 for(int i=0; i<state.numArrays(); i++) {
1067 outclassdefs.print(", ");
1068 TypeDescriptor tdelement=arraytable[i].dereference();
1069 if (tdelement.isArray()||tdelement.isClass())
1070 outclassdefs.print("sizeof(void *)");
1072 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1076 outclassdefs.println("};");
1078 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1080 outclassdefs.print("int typearray[]={");
1081 for(int i=0; i<state.numClasses(); i++) {
1082 ClassDescriptor cd=cdarray[i];
1083 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1085 outclassdefs.print(", ");
1087 outclassdefs.print("-1");
1089 outclassdefs.print(supercd.getId());
1093 for(int i=0; i<state.numArrays(); i++) {
1094 TypeDescriptor arraytd=arraytable[i];
1095 ClassDescriptor arraycd=arraytd.getClassDesc();
1096 if (arraycd==null) {
1098 outclassdefs.print(", ");
1099 outclassdefs.print(objectclass.getId());
1103 ClassDescriptor cd=arraycd.getSuperDesc();
1106 TypeDescriptor supertd=new TypeDescriptor(cd);
1107 supertd.setArrayCount(arraytd.getArrayCount());
1108 type=state.getArrayNumber(supertd);
1110 type+=state.numClasses();
1113 cd=cd.getSuperDesc();
1116 outclassdefs.print(", ");
1117 outclassdefs.print(type);
1121 outclassdefs.println("};");
1126 outclassdefs.print("int typearray2[]={");
1127 for(int i=0; i<state.numArrays(); i++) {
1128 TypeDescriptor arraytd=arraytable[i];
1129 ClassDescriptor arraycd=arraytd.getClassDesc();
1130 if (arraycd==null) {
1132 outclassdefs.print(", ");
1133 outclassdefs.print("-1");
1137 ClassDescriptor cd=arraycd.getSuperDesc();
1138 int level=arraytd.getArrayCount()-1;
1140 for(; level>0; level--) {
1141 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1142 supertd.setArrayCount(level);
1143 type=state.getArrayNumber(supertd);
1145 type+=state.numClasses();
1150 outclassdefs.print(", ");
1151 outclassdefs.print(type);
1155 outclassdefs.println("};");
1158 /** Constructs params and temp objects for each method or task.
1159 * These objects tell the compiler which temps need to be
1162 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1163 MethodDescriptor md=fm.getMethod();
1164 TaskDescriptor task=fm.getTask();
1165 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1166 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1168 paramstable.put(lb, objectparams);
1169 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1170 } else if (md!=null)
1171 paramstable.put(md, objectparams);
1173 paramstable.put(task, objectparams);
1175 for(int i=0; i<fm.numParameters(); i++) {
1176 TempDescriptor temp=fm.getParameter(i);
1177 TypeDescriptor type=temp.getType();
1178 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1179 objectparams.addPtr(temp);
1181 objectparams.addPrim(temp);
1182 if(lb!=null&&saveset.contains(temp)) {
1183 backuptable.get(lb).put(temp, temp.createNew());
1187 for(int i=0; i<fm.numTags(); i++) {
1188 TempDescriptor temp=fm.getTag(i);
1189 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1190 objectparams.addPtr(temp);
1192 objectparams.addPrim(temp);
1195 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1197 tempstable.put(lb, objecttemps);
1199 tempstable.put(md, objecttemps);
1201 tempstable.put(task, objecttemps);
1203 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1204 FlatNode fn=(FlatNode)nodeit.next();
1205 TempDescriptor[] writes=fn.writesTemps();
1206 for(int i=0; i<writes.length; i++) {
1207 TempDescriptor temp=writes[i];
1208 TypeDescriptor type=temp.getType();
1209 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1210 objecttemps.addPtr(temp);
1212 objecttemps.addPrim(temp);
1213 if(lb!=null&&saveset.contains(temp)&&
1214 !backuptable.get(lb).containsKey(temp))
1215 backuptable.get(lb).put(temp, temp.createNew());
1219 /* Create backup temps */
1221 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1222 TempDescriptor tmp=tmpit.next();
1223 TypeDescriptor type=tmp.getType();
1224 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1225 objecttemps.addPtr(tmp);
1227 objecttemps.addPrim(tmp);
1229 /* Create temp to hold revert table */
1230 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1231 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1232 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1233 objecttemps.addPtr(reverttmp);
1235 objecttemps.addPrim(reverttmp);
1236 reverttable.put(lb, reverttmp);
1241 /** This method outputs the following information about classes
1243 * (1) For classes, what are the locations of pointers.
1244 * (2) For arrays, does the array contain pointers or primitives.
1245 * (3) For classes, does the class contain flags.
1248 private void generateLayoutStructs(PrintWriter output) {
1249 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1250 while(it.hasNext()) {
1251 ClassDescriptor cn=(ClassDescriptor)it.next();
1252 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1253 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1255 while(allit.hasNext()) {
1256 FieldDescriptor fd=(FieldDescriptor)allit.next();
1257 TypeDescriptor type=fd.getType();
1258 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1263 output.print(count);
1264 allit=cn.getFieldTable().getAllDescriptorsIterator();
1265 while(allit.hasNext()) {
1266 FieldDescriptor fd=(FieldDescriptor)allit.next();
1267 TypeDescriptor type=fd.getType();
1268 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1271 output.println(",");
1272 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1275 output.println("};");
1277 output.println("unsigned INTPTR * pointerarray[]={");
1278 boolean needcomma=false;
1279 for(int i=0; i<state.numClasses(); i++) {
1280 ClassDescriptor cn=cdarray[i];
1282 output.println(",");
1285 output.print(cn.getSafeSymbol()+"_pointers");
1287 output.print("NULL");
1291 for(int i=0; i<state.numArrays(); i++) {
1293 output.println(", ");
1294 TypeDescriptor tdelement=arraytable[i].dereference();
1295 if (tdelement.isArray()||tdelement.isClass())
1296 output.print("((unsigned INTPTR *)1)");
1302 output.println("};");
1304 output.println("int hasflags[]={");
1305 for(int i=0; i<state.numClasses(); i++) {
1306 ClassDescriptor cn=cdarray[i];
1308 output.println(", ");
1310 if ((cn != null) && (cn.hasFlags()))
1315 output.println("};");
1318 /** Print out table to give us supertypes */
1319 private void generateSuperTypeTable(PrintWriter output) {
1320 output.println("int supertypes[]={");
1321 boolean needcomma=false;
1322 for(int i=0; i<state.numClasses(); i++) {
1323 ClassDescriptor cn=cdarray[i];
1325 output.println(",");
1327 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1328 ClassDescriptor cdsuper=cn.getSuperDesc();
1329 output.print(cdsuper.getId());
1333 output.println("};");
1336 /** Force consistent field ordering between inherited classes. */
1338 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1340 ClassDescriptor sp=cn.getSuperDesc();
1342 printClassStruct(sp, classdefout);
1344 if (!fieldorder.containsKey(cn)) {
1345 Vector fields=new Vector();
1346 fieldorder.put(cn,fields);
1347 Vector fieldvec=cn.getFieldVec();
1348 for(int i=0;i<fieldvec.size();i++) {
1349 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1350 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1354 Vector fields=(Vector)fieldorder.get(cn);
1356 for(int i=0; i<fields.size(); i++) {
1357 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1358 if (fd.getType().isClass()||fd.getType().isArray())
1359 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1361 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1366 /* Map flags to integers consistently between inherited
1369 protected void mapFlags(ClassDescriptor cn) {
1370 ClassDescriptor sp=cn.getSuperDesc();
1374 if (!flagorder.containsKey(cn)) {
1375 Hashtable flags=new Hashtable();
1376 flagorder.put(cn,flags);
1378 Hashtable superflags=(Hashtable)flagorder.get(sp);
1379 Iterator superflagit=superflags.keySet().iterator();
1380 while(superflagit.hasNext()) {
1381 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1382 Integer number=(Integer)superflags.get(fd);
1383 flags.put(fd, number);
1384 if ((number.intValue()+1)>max)
1385 max=number.intValue()+1;
1389 Iterator flagit=cn.getFlags();
1390 while(flagit.hasNext()) {
1391 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1392 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1393 flags.put(fd, new Integer(max++));
1399 /** This function outputs (1) structures that parameters are
1400 * passed in (when PRECISE GC is enabled) and (2) function
1401 * prototypes for the methods */
1403 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1404 /* Output class structure */
1405 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1406 classdefout.println(" int type;");
1407 if(state.MLP || state.OOOJAVA){
1408 classdefout.println(" int oid;");
1410 if (state.EVENTMONITOR) {
1411 classdefout.println(" int objuid;");
1414 classdefout.println(" pthread_t tid;");
1415 classdefout.println(" void * lockentry;");
1416 classdefout.println(" int lockcount;");
1420 classdefout.println(" int flag;");
1421 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1422 classdefout.println(" void * flagptr;");
1423 } else if (state.MULTICORE) {
1424 classdefout.println(" int version;");
1425 classdefout.println(" int * lock;"); // lock entry for this obj
1426 classdefout.println(" int mutex;");
1427 classdefout.println(" int lockcount;");
1428 if(state.MULTICOREGC) {
1429 classdefout.println(" int marked;");
1432 if (state.OPTIONAL) {
1433 classdefout.println(" int numfses;");
1434 classdefout.println(" int * fses;");
1437 printClassStruct(cn, classdefout);
1438 classdefout.println("};\n");
1440 if (state.DSM||state.SINGLETM) {
1441 /* Cycle through LocalityBindings */
1442 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1443 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1445 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1446 LocalityBinding lb=lbit.next();
1447 MethodDescriptor md=lb.getMethod();
1448 if (md.getModifiers().isNative()) {
1449 //make sure we only print a native method once
1450 if (nativemethods.contains(md)) {
1451 FlatMethod fm=state.getMethodFlat(md);
1452 generateTempStructs(fm, lb);
1455 nativemethods.add(md);
1457 generateMethod(cn, md, lb, headersout, output);
1460 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1461 MethodDescriptor md=(MethodDescriptor)methodit.next();
1462 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1463 //Need to build param structure for library code
1464 FlatMethod fm=state.getMethodFlat(md);
1465 generateTempStructs(fm, null);
1466 generateMethodParam(cn, md, null, output);
1471 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1472 MethodDescriptor md=(MethodDescriptor)methodit.next();
1473 generateMethod(cn, md, null, headersout, output);
1477 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1478 /* Output parameter structure */
1479 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1480 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1481 if ((state.DSM||state.SINGLETM)&&lb!=null)
1482 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1484 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1485 output.println(" int size;");
1486 output.println(" void * next;");
1487 for(int i=0; i<objectparams.numPointers(); i++) {
1488 TempDescriptor temp=objectparams.getPointer(i);
1489 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1491 output.println("};\n");
1495 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1496 FlatMethod fm=state.getMethodFlat(md);
1497 generateTempStructs(fm, lb);
1499 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1500 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1502 generateMethodParam(cn, md, lb, output);
1504 /* Output temp structure */
1505 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1506 if (state.DSM||state.SINGLETM)
1507 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1509 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1510 output.println(" int size;");
1511 output.println(" void * next;");
1512 for(int i=0; i<objecttemps.numPointers(); i++) {
1513 TempDescriptor temp=objecttemps.getPointer(i);
1514 if (temp.getType().isNull())
1515 output.println(" void * "+temp.getSafeSymbol()+";");
1517 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1519 output.println("};\n");
1522 /********* Output method declaration ***********/
1523 if (state.DSM||state.SINGLETM) {
1524 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1526 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1528 /* First the return type */
1529 if (md.getReturnType()!=null) {
1530 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1531 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1533 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1535 //catch the constructor case
1536 headersout.print("void ");
1538 /* Next the method name */
1539 if (state.DSM||state.SINGLETM) {
1540 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1542 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1544 boolean printcomma=false;
1545 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1546 if (state.DSM||state.SINGLETM) {
1547 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1549 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1553 /* Output parameter list*/
1554 for(int i=0; i<objectparams.numPrimitives(); i++) {
1555 TempDescriptor temp=objectparams.getPrimitive(i);
1557 headersout.print(", ");
1559 if (temp.getType().isClass()||temp.getType().isArray())
1560 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1562 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1564 headersout.println(");\n");
1568 /** This function outputs (1) structures that parameters are
1569 * passed in (when PRECISE GC is enabled) and (2) function
1570 * prototypes for the tasks */
1572 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1573 /* Cycle through tasks */
1574 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1576 while(taskit.hasNext()) {
1577 /* Classify parameters */
1578 TaskDescriptor task=(TaskDescriptor)taskit.next();
1579 FlatMethod fm=state.getMethodFlat(task);
1580 generateTempStructs(fm, null);
1582 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1583 TempObject objecttemps=(TempObject) tempstable.get(task);
1585 /* Output parameter structure */
1586 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1587 output.println("struct "+task.getSafeSymbol()+"_params {");
1588 output.println(" int size;");
1589 output.println(" void * next;");
1590 for(int i=0; i<objectparams.numPointers(); i++) {
1591 TempDescriptor temp=objectparams.getPointer(i);
1592 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1595 output.println("};\n");
1596 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1597 maxtaskparams=objectparams.numPointers()+fm.numTags();
1601 /* Output temp structure */
1602 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1603 output.println("struct "+task.getSafeSymbol()+"_locals {");
1604 output.println(" int size;");
1605 output.println(" void * next;");
1606 for(int i=0; i<objecttemps.numPointers(); i++) {
1607 TempDescriptor temp=objecttemps.getPointer(i);
1608 if (temp.getType().isNull())
1609 output.println(" void * "+temp.getSafeSymbol()+";");
1610 else if(temp.getType().isTag())
1611 output.println(" struct "+
1612 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1614 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1616 output.println("};\n");
1619 /* Output task declaration */
1620 headersout.print("void " + task.getSafeSymbol()+"(");
1622 boolean printcomma=false;
1623 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1624 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1626 headersout.print("void * parameterarray[]");
1627 headersout.println(");\n");
1631 /***** Generate code for FlatMethod fm. *****/
1633 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1634 static int atomicmethodcount=0;
1637 BranchAnalysis branchanalysis;
1638 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1639 if (State.PRINTFLAT)
1640 System.out.println(fm.printMethod());
1641 MethodDescriptor md=fm.getMethod();
1642 TaskDescriptor task=fm.getTask();
1643 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1644 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1646 HashSet<AtomicRecord> arset=null;
1647 branchanalysis=null;
1649 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1651 if (atomicmethodmap==null)
1652 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1654 //fix these so we get right strings for local variables
1655 localsprefixaddr=localsprefix;
1656 localsprefixderef=localsprefix+"->";
1657 arset=new HashSet<AtomicRecord>();
1659 //build branchanalysis
1660 branchanalysis=new BranchAnalysis(locality, lb, delaycomp.getNotReady(lb), delaycomp.livecode(lb), state);
1662 //Generate commit methods here
1663 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1664 FlatNode fn=fnit.next();
1665 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1666 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
1667 delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
1668 //We have an atomic enter
1669 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1670 Set<FlatNode> exitset=faen.getExits();
1672 String methodname=md.getSymbol()+(atomicmethodcount++);
1673 AtomicRecord ar=new AtomicRecord();
1677 atomicmethodmap.put(faen, ar);
1679 //build data structure declaration
1680 output.println("struct atomicprimitives_"+methodname+" {");
1682 Set<FlatNode> recordset=delaycomp.livecode(lb);
1683 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1684 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1685 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1687 ar.reallivein=new HashSet(liveinto);
1689 ar.liveoutvirtualread=liveoutvirtualread;
1692 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1693 TempDescriptor tmp=it.next();
1694 //remove the pointers
1695 if (tmp.getType().isPtr()) {
1698 //let's print it here
1699 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1702 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1703 TempDescriptor tmp=it.next();
1704 //remove the pointers
1705 if (tmp.getType().isPtr()) {
1707 } else if (!liveinto.contains(tmp)) {
1708 //let's print it here
1709 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1712 output.println("};");
1714 //print out method name
1715 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) {");
1716 //build code for commit method
1718 //first define local primitives
1719 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1720 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1721 TempDescriptor tmp=tmpit.next();
1722 if (!tmp.getType().isPtr()) {
1723 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1724 //read from live into set
1725 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1728 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1732 //turn off write barrier generation
1734 state.SINGLETM=false;
1735 generateCode(faen, fm, lb, exitset, output, false);
1736 state.SINGLETM=true;
1737 //turn on write barrier generation
1739 output.println("}\n\n");
1743 //redefine these back to normal
1745 localsprefixaddr="&"+localsprefix;
1746 localsprefixderef=localsprefix+".";
1748 generateHeader(fm, lb, md!=null ? md : task,output);
1749 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1751 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1752 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1753 AtomicRecord ar=arit.next();
1754 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1758 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1759 if (md!=null&&(state.DSM||state.SINGLETM))
1760 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1761 else if (md!=null&&!(state.DSM||state.SINGLETM))
1762 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1764 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1765 output.print(objecttemp.numPointers()+",");
1766 output.print(paramsprefix);
1767 for(int j=0; j<objecttemp.numPointers(); j++)
1768 output.print(", NULL");
1769 output.println("};");
1772 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1773 TempDescriptor td=objecttemp.getPrimitive(i);
1774 TypeDescriptor type=td.getType();
1776 output.println(" void * "+td.getSafeSymbol()+";");
1777 else if (type.isClass()||type.isArray())
1778 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1780 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1784 if( state.MLP || state.OOOJAVA ) {
1785 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1786 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1787 if( (state.MLP && callerSESEplaceholder != mlpa.getMainSESE()) ||
1788 (state.OOOJAVA && callerSESEplaceholder != oooa.getMainSESE())
1790 // declare variables for naming static SESE's
1791 output.println(" /* static SESE names */");
1792 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1793 while( pItr.hasNext() ) {
1794 SESEandAgePair pair = pItr.next();
1795 output.println(" void* "+pair+";");
1798 // declare variables for tracking dynamic sources
1799 output.println(" /* dynamic variable sources */");
1800 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1801 while( dynSrcItr.hasNext() ) {
1802 TempDescriptor dynSrcVar = dynSrcItr.next();
1803 output.println(" void* "+dynSrcVar+"_srcSESE;");
1804 output.println(" int "+dynSrcVar+"_srcOffset;");
1809 // set up related allocation sites's waiting queues
1812 ConflictGraph graph = null;
1813 graph = mlpa.getConflictGraphResults().get(fm);
1814 if (graph != null && graph.hasConflictEdge()) {
1815 output.println(" /* set up waiting queues */");
1816 output.println(" int numMemoryQueue=0;");
1817 output.println(" int memoryQueueItemID=0;");
1818 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
1820 System.out.println("#lockSet="+lockSet.hashCode());
1821 System.out.println("lockset="+lockSet);
1822 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1823 SESELock seseLock = (SESELock) iterator.next();
1824 System.out.println("id="+seseLock.getID());
1825 System.out.println("#="+seseLock);
1827 System.out.println("size="+lockSet.size());
1828 if (lockSet.size() > 0) {
1829 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1831 .println(" seseCaller->numMemoryQueue=numMemoryQueue;");
1833 .println(" seseCaller->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1838 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1839 if(callerSESEplaceholder!= oooa.getMainSESE()){
1840 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(callerSESEplaceholder);
1841 if (graph != null && graph.hasConflictEdge()) {
1842 output.println(" // set up waiting queues ");
1843 output.println(" int numMemoryQueue=0;");
1844 output.println(" int memoryQueueItemID=0;");
1845 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
1846 System.out.println("#lockSet="+lockSet.hashCode());
1847 System.out.println("lockset="+lockSet);
1848 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1849 Analysis.OoOJava.SESELock seseLock = (Analysis.OoOJava.SESELock) iterator.next();
1850 System.out.println("id="+seseLock.getID());
1851 System.out.println("#="+seseLock);
1853 System.out.println("size="+lockSet.size());
1854 if (lockSet.size() > 0) {
1855 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1857 .println(" seseCaller->numMemoryQueue=numMemoryQueue;");
1859 .println(" seseCaller->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1869 /* Check to see if we need to do a GC if this is a
1870 * multi-threaded program...*/
1872 if (((state.MLP||state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1873 || this.state.MULTICOREGC) {
1874 //Don't bother if we aren't in recursive methods...The loops case will catch it
1875 if (callgraph.getAllMethods(md).contains(md)) {
1876 if (state.DSM&&lb.isAtomic())
1877 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1878 else if (this.state.MULTICOREGC) {
1879 output.println("if(gcflag) gc("+localsprefixaddr+");");
1881 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1886 generateCode(fm.getNext(0), fm, lb, null, output, true);
1888 output.println("}\n\n");
1892 protected void initializeSESE( FlatSESEEnterNode fsen ) {
1894 FlatMethod fm = fsen.getfmEnclosing();
1895 MethodDescriptor md = fm.getMethod();
1896 ClassDescriptor cn = md.getClassDesc();
1899 // Creates bogus method descriptor to index into tables
1900 Modifiers modBogus = new Modifiers();
1901 MethodDescriptor mdBogus =
1902 new MethodDescriptor( modBogus,
1903 new TypeDescriptor( TypeDescriptor.VOID ),
1904 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1907 mdBogus.setClassDesc( fsen.getcdEnclosing() );
1908 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1909 fsen.setfmBogus( fmBogus );
1910 fsen.setmdBogus( mdBogus );
1912 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1913 inSetAndOutSet.addAll( fsen.getInVarSet() );
1914 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1916 // Build paramsobj for bogus method descriptor
1917 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
1918 paramstable.put( mdBogus, objectparams );
1920 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1921 while( itr.hasNext() ) {
1922 TempDescriptor temp = itr.next();
1923 TypeDescriptor type = temp.getType();
1924 if( type.isPtr() ) {
1925 objectparams.addPtr( temp );
1927 objectparams.addPrim( temp );
1931 // Build normal temp object for bogus method descriptor
1932 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
1933 tempstable.put( mdBogus, objecttemps );
1935 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
1936 FlatNode fn = (FlatNode)nodeit.next();
1937 TempDescriptor[] writes = fn.writesTemps();
1939 for( int i = 0; i < writes.length; i++ ) {
1940 TempDescriptor temp = writes[i];
1941 TypeDescriptor type = temp.getType();
1943 if( type.isPtr() ) {
1944 objecttemps.addPtr( temp );
1946 objecttemps.addPrim( temp );
1952 protected void generateMethodSESE(FlatSESEEnterNode fsen,
1954 PrintWriter outputStructs,
1955 PrintWriter outputMethHead,
1956 PrintWriter outputMethods
1959 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
1960 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
1962 // generate locals structure
1963 outputStructs.println("struct "+
1964 fsen.getcdEnclosing().getSafeSymbol()+
1965 fsen.getmdBogus().getSafeSymbol()+"_"+
1966 fsen.getmdBogus().getSafeMethodDescriptor()+
1968 outputStructs.println(" int size;");
1969 outputStructs.println(" void * next;");
1970 for(int i=0; i<objecttemps.numPointers(); i++) {
1971 TempDescriptor temp=objecttemps.getPointer(i);
1973 if (temp.getType().isNull())
1974 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1976 outputStructs.println(" struct "+
1977 temp.getType().getSafeSymbol()+" * "+
1978 temp.getSafeSymbol()+";");
1980 outputStructs.println("};\n");
1983 // generate the SESE record structure
1984 outputStructs.println(fsen.getSESErecordName()+" {");
1986 // data common to any SESE, and it must be placed first so
1987 // a module that doesn't know what kind of SESE record this
1988 // is can cast the pointer to a common struct
1989 outputStructs.println(" SESEcommon common;");
1991 // then garbage list stuff
1992 outputStructs.println(" int size;");
1993 outputStructs.println(" void * next;");
1995 // DYNAMIC stuff was here
1997 // invar source taking was here
1999 // space for all in and out set primitives
2000 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
2001 inSetAndOutSet.addAll( fsen.getInVarSet() );
2002 inSetAndOutSet.addAll( fsen.getOutVarSet() );
2004 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
2006 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
2007 while( itr.hasNext() ) {
2008 TempDescriptor temp = itr.next();
2009 TypeDescriptor type = temp.getType();
2010 if( !type.isPtr() ) {
2011 inSetAndOutSetPrims.add( temp );
2015 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
2016 while( itrPrims.hasNext() ) {
2017 TempDescriptor temp = itrPrims.next();
2018 TypeDescriptor type = temp.getType();
2019 if(!type.isPrimitive()){
2020 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
2024 for(int i=0; i<objectparams.numPointers(); i++) {
2025 TempDescriptor temp=objectparams.getPointer(i);
2026 if (temp.getType().isNull())
2027 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
2029 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
2032 // DYNAMIC stuff needs a source SESE ptr and offset
2033 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
2034 while( itrDynInVars.hasNext() ) {
2035 TempDescriptor dynInVar = itrDynInVars.next();
2036 // outputStructs.println(" void* "+dynInVar+"_srcSESE;");
2037 outputStructs.println(" int "+dynInVar+"_srcOffset;");
2040 itrPrims = inSetAndOutSetPrims.iterator();
2041 while( itrPrims.hasNext() ) {
2042 TempDescriptor temp = itrPrims.next();
2043 TypeDescriptor type = temp.getType();
2044 if(type.isPrimitive()){
2045 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
2049 outputStructs.println(" int prevSESECount;");
2051 // DYNAMIC stuff needs a source SESE ptr and offset
2052 itrDynInVars = fsen.getDynamicInVarSet().iterator();
2053 while( itrDynInVars.hasNext() ) {
2054 TempDescriptor dynInVar = itrDynInVars.next();
2055 outputStructs.println(" void* "+dynInVar+"_srcSESE;");
2056 // outputStructs.println(" int "+dynInVar+"_srcOffset;");
2059 // in-set source tracking
2060 // in-vars that are READY come from parent, don't need anything
2061 // stuff STATIC needs a custom SESE pointer for each age pair
2062 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
2063 while( itrStaticInVarSrcs.hasNext() ) {
2064 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
2065 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
2068 outputStructs.println("};\n");
2071 // write method declaration to header file
2072 outputMethHead.print("void ");
2073 outputMethHead.print(fsen.getSESEmethodName()+"(");
2074 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
2075 outputMethHead.println(");\n");
2078 generateFlatMethodSESE( fsen.getfmBogus(),
2079 fsen.getcdEnclosing(),
2085 private void generateFlatMethodSESE(FlatMethod fm,
2087 FlatSESEEnterNode fsen,
2088 FlatSESEExitNode seseExit,
2092 MethodDescriptor md=fm.getMethod();
2094 output.print("void ");
2095 output.print(fsen.getSESEmethodName()+"(");
2096 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
2097 output.println("){\n");
2099 TempObject objecttemp=(TempObject) tempstable.get(md);
2101 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2102 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2103 output.print(objecttemp.numPointers()+",");
2104 output.print("&(((SESEcommon*)(___params___))[1])");
2105 for(int j=0; j<objecttemp.numPointers(); j++)
2106 output.print(", NULL");
2107 output.println("};");
2110 output.println(" /* regular local primitives */");
2111 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2112 TempDescriptor td=objecttemp.getPrimitive(i);
2113 TypeDescriptor type=td.getType();
2115 output.println(" void * "+td.getSafeSymbol()+";");
2116 else if (type.isClass()||type.isArray())
2117 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2119 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2123 // declare variables for naming static SESE's
2124 output.println(" /* static SESE names */");
2125 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
2126 while( pItr.hasNext() ) {
2127 SESEandAgePair pair = pItr.next();
2128 output.println(" void* "+pair+";");
2131 // declare variables for tracking dynamic sources
2132 output.println(" /* dynamic variable sources */");
2133 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
2134 while( dynSrcItr.hasNext() ) {
2135 TempDescriptor dynSrcVar = dynSrcItr.next();
2136 output.println(" void* "+dynSrcVar+"_srcSESE;");
2137 output.println(" int "+dynSrcVar+"_srcOffset;");
2140 // declare local temps for in-set primitives, and if it is
2141 // a ready-source variable, get the value from the record
2142 output.println(" /* local temps for in-set primitives */");
2143 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2144 while( itrInSet.hasNext() ) {
2145 TempDescriptor temp = itrInSet.next();
2146 TypeDescriptor type = temp.getType();
2147 if( !type.isPtr() ) {
2148 if( fsen.getReadyInVarSet().contains( temp ) ) {
2149 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2151 output.println(" "+type+" "+temp+";");
2156 // declare local temps for out-set primitives if its not already
2157 // in the in-set, and it's value will get written so no problem
2158 output.println(" /* local temp for out-set prim, not already in the in-set */");
2159 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2160 while( itrOutSet.hasNext() ) {
2161 TempDescriptor temp = itrOutSet.next();
2162 TypeDescriptor type = temp.getType();
2163 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2164 output.println(" "+type+" "+temp+";");
2168 // setup memory queue
2171 output.println(" // set up memory queues ");
2172 output.println(" int numMemoryQueue=0;");
2173 output.println(" int memoryQueueItemID=0;");
2174 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(fsen);
2175 if (graph != null && graph.hasConflictEdge()) {
2176 output.println(" {");
2178 .println(" SESEcommon* parentCommon = &(___params___->common);");
2179 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
2180 System.out.println("#lockSet="+lockSet);
2181 if (lockSet.size() > 0) {
2182 output.println(" numMemoryQueue=" + lockSet.size() + ";");
2184 .println(" parentCommon->numMemoryQueue=numMemoryQueue;");
2186 .println(" parentCommon->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2189 output.println(" }");
2192 output.println(" // set up memory queues ");
2193 output.println(" int numMemoryQueue=0;");
2194 output.println(" int memoryQueueItemID=0;");
2195 ConflictGraph graph = null;
2196 graph = mlpa.getConflictGraphResults().get(fsen);
2197 if (graph != null && graph.hasConflictEdge()) {
2198 output.println(" {");
2200 .println(" SESEcommon* parentCommon = &(___params___->common);");
2201 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
2203 System.out.println("#lockSet="+lockSet);
2205 if (lockSet.size() > 0) {
2206 output.println(" numMemoryQueue=" + lockSet.size() + "; ");
2208 .println(" parentCommon->numMemoryQueue=numMemoryQueue;");
2210 .println(" parentCommon->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2213 output.println(" }");
2219 // copy in-set into place, ready vars were already
2220 // copied when the SESE was issued
2221 Iterator<TempDescriptor> tempItr;
2223 // static vars are from a known SESE
2224 tempItr = fsen.getStaticInVarSet().iterator();
2225 while( tempItr.hasNext() ) {
2226 TempDescriptor temp = tempItr.next();
2227 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2228 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2230 // can't grab something from this source until it is done
2231 output.println(" {");
2233 If we are running, everything is done. This check is redundant.
2235 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+srcPair+";" );
2236 output.println(" pthread_mutex_lock( &(com->lock) );");
2237 output.println(" while( com->doneExecuting == FALSE ) {");
2238 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2239 output.println(" }");
2240 output.println(" pthread_mutex_unlock( &(com->lock) );");
2242 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2243 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2245 output.println(" }");
2248 // dynamic vars come from an SESE and src
2249 tempItr = fsen.getDynamicInVarSet().iterator();
2250 while( tempItr.hasNext() ) {
2251 TempDescriptor temp = tempItr.next();
2252 TypeDescriptor type = temp.getType();
2254 // go grab it from the SESE source
2255 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2257 // gotta wait until the source is done
2258 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+temp+"_srcSESE;" );
2260 If we are running, everything is done!
2261 output.println(" pthread_mutex_lock( &(com->lock) );");
2262 output.println(" while( com->doneExecuting == FALSE ) {");
2263 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2264 output.println(" }");
2265 output.println(" pthread_mutex_unlock( &(com->lock) );");
2269 if( type.isNull() ) {
2271 } else if( type.isClass() || type.isArray() ) {
2272 typeStr = "struct "+type.getSafeSymbol()+"*";
2274 typeStr = type.getSafeSymbol();
2277 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2278 " = *(("+typeStr+"*) ("+
2279 paramsprefix+"->"+temp+"_srcSESE + "+
2280 paramsprefix+"->"+temp+"_srcOffset));");
2282 // or if the source was our parent, its in the record to grab
2283 output.println(" } else {");
2284 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2285 " = "+paramsprefix+"->"+temp+";");
2286 output.println(" }");
2289 // Check to see if we need to do a GC if this is a
2290 // multi-threaded program...
2291 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2292 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2293 //Don't bother if we aren't in recursive methods...The loops case will catch it
2294 // if (callgraph.getAllMethods(md).contains(md)) {
2295 // if(this.state.MULTICOREGC) {
2296 // output.println("if(gcflag) gc("+localsprefixaddr+");");
2298 // output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2303 // initialize thread-local var to a non-zero, invalid address
2304 output.println(" seseCaller = (SESEcommon*) 0x2;");
2305 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2306 exitset.add(seseExit);
2307 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2308 output.println("}\n\n");
2313 // when a new mlp thread is created for an issued SESE, it is started
2314 // by running this method which blocks on a cond variable until
2315 // it is allowed to transition to execute. Then a case statement
2316 // allows it to invoke the method with the proper SESE body, and after
2317 // exiting the SESE method, executes proper SESE exit code before the
2318 // thread can be destroyed
2319 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2320 PrintWriter outmethod
2323 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2324 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2325 outmethod.println( " int status;");
2326 outmethod.println( " char errmsg[128];");
2328 // generate a case for each SESE class that can be invoked
2329 outmethod.println( " switch( *((int*)seseRecord) ) {");
2330 outmethod.println( " ");
2331 Iterator<FlatSESEEnterNode> seseit;
2333 seseit=mlpa.getAllSESEs().iterator();
2335 seseit=oooa.getAllSESEs().iterator();
2337 while(seseit.hasNext()){
2338 FlatSESEEnterNode fsen = seseit.next();
2340 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2341 outmethod.println( " case "+fsen.getIdentifier()+":");
2342 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2344 if( (state.MLP && fsen.equals( mlpa.getMainSESE() )) ||
2345 (state.OOOJAVA && fsen.equals( oooa.getMainSESE() ))
2347 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2348 if (state.COREPROF) {
2349 outmethod.println("EXITPROFILER();");
2350 outmethod.println("DUMPPROFILER();");
2352 outmethod.println( " exit( 0 );");
2355 outmethod.println( " break;");
2356 outmethod.println( "");
2359 // default case should never be taken, error out
2360 outmethod.println( " default:");
2361 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2362 outmethod.println( " exit(-30);");
2363 outmethod.println( " break;");
2364 outmethod.println( " }");
2365 outmethod.println( " return NULL;");
2366 outmethod.println( "}\n\n");
2370 protected void generateCode(FlatNode first,
2373 Set<FlatNode> stopset,
2374 PrintWriter output, boolean firstpass) {
2376 /* Assign labels to FlatNode's if necessary.*/
2378 Hashtable<FlatNode, Integer> nodetolabel;
2380 if (state.DELAYCOMP&&!firstpass)
2381 nodetolabel=dcassignLabels(first, stopset);
2383 nodetolabel=assignLabels(first, stopset);
2385 Set<FlatNode> storeset=null;
2386 HashSet<FlatNode> genset=null;
2387 HashSet<FlatNode> refset=null;
2388 Set<FlatNode> unionset=null;
2390 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2391 storeset=delaycomp.livecode(lb);
2392 genset=new HashSet<FlatNode>();
2393 if (state.STMARRAY&&!state.DUALVIEW) {
2394 refset=new HashSet<FlatNode>();
2395 refset.addAll(delaycomp.getDeref(lb));
2396 refset.removeAll(delaycomp.getCannotDelay(lb));
2397 refset.removeAll(delaycomp.getOther(lb));
2400 genset.addAll(delaycomp.getCannotDelay(lb));
2401 genset.addAll(delaycomp.getOther(lb));
2403 genset.addAll(delaycomp.getNotReady(lb));
2404 if (state.STMARRAY&&!state.DUALVIEW) {
2405 genset.removeAll(refset);
2408 unionset=new HashSet<FlatNode>();
2409 unionset.addAll(storeset);
2410 unionset.addAll(genset);
2411 if (state.STMARRAY&&!state.DUALVIEW)
2412 unionset.addAll(refset);
2415 /* Do the actual code generation */
2416 FlatNode current_node=null;
2417 HashSet tovisit=new HashSet();
2418 HashSet visited=new HashSet();
2420 tovisit.add(first.getNext(0));
2423 while(current_node!=null||!tovisit.isEmpty()) {
2424 if (current_node==null) {
2425 current_node=(FlatNode)tovisit.iterator().next();
2426 tovisit.remove(current_node);
2427 } else if (tovisit.contains(current_node)) {
2428 tovisit.remove(current_node);
2430 visited.add(current_node);
2431 if (nodetolabel.containsKey(current_node)) {
2432 output.println("L"+nodetolabel.get(current_node)+":");
2434 if (state.INSTRUCTIONFAILURE) {
2435 if (state.THREAD||state.DSM||state.SINGLETM) {
2436 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2438 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2440 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2442 if (!state.DELAYCOMP||firstpass) {
2443 generateFlatNode(fm, lb, current_node, output);
2445 //store primitive variables in out set
2446 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2447 Set<TempDescriptor> liveout=ar.liveout;
2448 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2449 TempDescriptor tmp=tmpit.next();
2450 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2453 if ((state.MLP || state.OOOJAVA) && stopset!=null) {
2454 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2455 assert current_node instanceof FlatSESEExitNode;
2456 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2457 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2458 assert fsen.getFlatExit().equals( fsxn );
2459 assert fsxn.getFlatEnter().equals( fsen );
2461 if (current_node.kind()!=FKind.FlatReturnNode) {
2462 output.println(" return;");
2465 } else if(current_node.numNext()==1) {
2467 if ((state.MLP|| state.OOOJAVA) &&
2468 current_node.kind()==FKind.FlatSESEEnterNode &&
2469 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2471 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2472 generateFlatNode(fm, lb, current_node, output);
2473 nextnode=fsen.getFlatExit().getNext(0);
2474 } else if (state.DELAYCOMP) {
2475 boolean specialprimitive=false;
2476 //skip literals...no need to add extra overhead
2477 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2478 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2479 if (!typedesc.isClass()&&!typedesc.isArray()) {
2480 specialprimitive=true;
2484 if (genset==null||genset.contains(current_node)||specialprimitive)
2485 generateFlatNode(fm, lb, current_node, output);
2486 if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2487 //need to acquire lock
2488 handleArrayDeref(fm, lb, current_node, output, firstpass);
2490 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2491 TempDescriptor wrtmp=current_node.writesTemps()[0];
2493 //need to store value written by previous node
2494 if (wrtmp.getType().isPtr()) {
2495 //only lock the objects that may actually need locking
2496 if (recorddc.getNeedTrans(lb, current_node)&&
2497 (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2498 wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2499 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2501 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2504 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2507 //need to read value read by previous node
2508 if (wrtmp.getType().isPtr()) {
2509 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2511 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");
2515 nextnode=current_node.getNext(0);
2518 generateFlatNode(fm, lb, current_node, output);
2519 nextnode=current_node.getNext(0);
2521 if (visited.contains(nextnode)) {
2522 output.println("goto L"+nodetolabel.get(nextnode)+";");
2525 current_node=nextnode;
2526 } else if (current_node.numNext()==2) {
2528 if (state.DELAYCOMP) {
2529 boolean computeside=false;
2531 //need to record which way it should go
2532 if (genset==null||genset.contains(current_node)) {
2533 if (storeset!=null&&storeset.contains(current_node)) {
2534 //need to store which way branch goes
2535 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2537 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2539 //which side to execute
2543 if (genset.contains(current_node)) {
2544 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2545 } else if (storeset.contains(current_node)) {
2547 branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2549 //which side to execute
2554 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2556 if (leftset.size()==0)
2558 if (visited.contains(current_node.getNext(branch))) {
2559 //already visited -- build jump
2560 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2563 current_node=current_node.getNext(branch);
2566 if (!visited.contains(current_node.getNext(1)))
2567 tovisit.add(current_node.getNext(1));
2568 if (visited.contains(current_node.getNext(0))) {
2569 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2572 current_node=current_node.getNext(0);
2576 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2577 if (!visited.contains(current_node.getNext(1)))
2578 tovisit.add(current_node.getNext(1));
2579 if (visited.contains(current_node.getNext(0))) {
2580 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2583 current_node=current_node.getNext(0);
2585 } else throw new Error();
2589 protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2590 if (fn.kind()==FKind.FlatSetElementNode) {
2591 FlatSetElementNode fsen=(FlatSetElementNode) fn;
2592 String dst=generateTemp(fm, fsen.getDst(), lb);
2593 String src=generateTemp(fm, fsen.getSrc(), lb);
2594 String index=generateTemp(fm, fsen.getIndex(), lb);
2595 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2597 if (elementtype.isArray()||elementtype.isClass())
2600 type=elementtype.getSafeSymbol()+" ";
2602 output.println("STOREARRAY("+dst+","+index+","+type+")");
2604 output.println("{");
2605 output.println(" struct ArrayObject *array;");
2606 output.println(" int index;");
2607 output.println(" RESTOREARRAY(array,index);");
2608 output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2609 output.println("}");
2611 } else if (fn.kind()==FKind.FlatElementNode) {
2612 FlatElementNode fen=(FlatElementNode) fn;
2613 String src=generateTemp(fm, fen.getSrc(), lb);
2614 String index=generateTemp(fm, fen.getIndex(), lb);
2615 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2616 String dst=generateTemp(fm, fen.getDst(), lb);
2618 if (elementtype.isArray()||elementtype.isClass())
2621 type=elementtype.getSafeSymbol()+" ";
2623 output.println("STOREARRAY("+src+","+index+","+type+")");
2625 output.println("{");
2626 output.println(" struct ArrayObject *array;");
2627 output.println(" int index;");
2628 output.println(" RESTOREARRAY(array,index);");
2629 output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2630 output.println("}");
2634 /** Special label assignment for delaycomputation */
2635 protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2636 HashSet tovisit=new HashSet();
2637 HashSet visited=new HashSet();
2639 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2641 //Label targets of branches
2642 Set<FlatNode> targets=branchanalysis.getTargets();
2643 for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2644 nodetolabel.put(it.next(), new Integer(labelindex++));
2649 /*Assign labels first. A node needs a label if the previous
2650 * node has two exits or this node is a join point. */
2652 while(!tovisit.isEmpty()) {
2653 FlatNode fn=(FlatNode)tovisit.iterator().next();
2658 if(lastset!=null&&lastset.contains(fn)) {
2659 // if last is not null and matches, don't go
2660 // any further for assigning labels
2664 for(int i=0; i<fn.numNext(); i++) {
2665 FlatNode nn=fn.getNext(i);
2668 //1) Edge >1 of node
2669 nodetolabel.put(nn,new Integer(labelindex++));
2671 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2675 nodetolabel.put(nn,new Integer(labelindex++));
2683 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2684 return assignLabels(first, null);
2687 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2688 HashSet tovisit=new HashSet();
2689 HashSet visited=new HashSet();
2691 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2694 /*Assign labels first. A node needs a label if the previous
2695 * node has two exits or this node is a join point. */
2697 while(!tovisit.isEmpty()) {
2698 FlatNode fn=(FlatNode)tovisit.iterator().next();
2703 if(lastset!=null&&lastset.contains(fn)) {
2704 // if last is not null and matches, don't go
2705 // any further for assigning labels
2709 for(int i=0; i<fn.numNext(); i++) {
2710 FlatNode nn=fn.getNext(i);
2713 //1) Edge >1 of node
2714 nodetolabel.put(nn,new Integer(labelindex++));
2716 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2720 nodetolabel.put(nn,new Integer(labelindex++));
2728 /** Generate text string that corresponds to the TempDescriptor td. */
2729 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2730 MethodDescriptor md=fm.getMethod();
2731 TaskDescriptor task=fm.getTask();
2732 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2734 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2735 return td.getSafeSymbol();
2738 if (objecttemps.isLocalPtr(td)) {
2739 return localsprefixderef+td.getSafeSymbol();
2742 if (objecttemps.isParamPtr(td)) {
2743 return paramsprefix+"->"+td.getSafeSymbol();
2749 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2751 // insert pre-node actions from the code plan
2752 if( state.MLP|| state.OOOJAVA ) {
2756 cp = mlpa.getCodePlan( fn );
2758 cp = oooa.getCodePlan(fn);
2763 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2765 // for each sese and age pair that this parent statement
2766 // must stall on, take that child's stall semaphore, the
2767 // copying of values comes after the statement
2768 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2769 while( vstItr.hasNext() ) {
2770 VariableSourceToken vst = vstItr.next();
2772 SESEandAgePair pair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2774 output.println(" {");
2775 output.println(" SESEcommon* common = (SESEcommon*) "+pair+";");
2777 output.println(" pthread_mutex_lock( &(common->lock) );");
2778 output.println(" while( common->doneExecuting == FALSE ) {");
2779 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2780 output.println(" }");
2781 output.println(" pthread_mutex_unlock( &(common->lock) );");
2783 // copy things we might have stalled for
2784 output.println(" "+pair.getSESE().getSESErecordName()+"* child = ("+
2785 pair.getSESE().getSESErecordName()+"*) "+pair+";");
2787 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2788 while( tdItr.hasNext() ) {
2789 TempDescriptor td = tdItr.next();
2790 FlatMethod fmContext;
2791 if( currentSESE.getIsCallerSESEplaceholder() ) {
2792 fmContext = currentSESE.getfmEnclosing();
2794 fmContext = currentSESE.getfmBogus();
2796 output.println(" "+generateTemp( fmContext, td, null )+
2797 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2800 output.println(" }");
2803 // for each variable with a dynamic source, stall just for that variable
2804 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2805 while( dynItr.hasNext() ) {
2806 TempDescriptor dynVar = dynItr.next();
2808 // only stall if the dynamic source is not yourself, denoted by src==NULL
2809 // otherwise the dynamic write nodes will have the local var up-to-date
2810 output.println(" {");
2811 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2812 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2813 output.println(" psem_take( &(common->stallSem) );");
2815 FlatMethod fmContext;
2816 if( currentSESE.getIsCallerSESEplaceholder() ) {
2817 fmContext = currentSESE.getfmEnclosing();
2819 fmContext = currentSESE.getfmBogus();
2822 TypeDescriptor type=dynVar.getType();
2824 if( type.isNull() ) {
2826 } else if( type.isClass() || type.isArray() ) {
2827 typeStr = "struct "+type.getSafeSymbol()+"*";
2829 typeStr = type.getSafeSymbol();
2832 output.println(" "+generateTemp( fmContext, dynVar, null )+
2833 " = *(("+typeStr+"*) ("+
2834 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2836 output.println(" }");
2837 output.println(" }");
2840 // for each assignment of a variable to rhs that has a dynamic source,
2841 // copy the dynamic sources
2842 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2843 while( dynAssignItr.hasNext() ) {
2844 Map.Entry me = (Map.Entry) dynAssignItr.next();
2845 TempDescriptor lhs = (TempDescriptor) me.getKey();
2846 TempDescriptor rhs = (TempDescriptor) me.getValue();
2847 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
2848 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2851 // for each lhs that is dynamic from a non-dynamic source, set the
2852 // dynamic source vars to the current SESE
2853 dynItr = cp.getDynAssignCurr().iterator();
2854 while( dynItr.hasNext() ) {
2855 TempDescriptor dynVar = dynItr.next();
2856 assert currentSESE.getDynamicVarSet().contains( dynVar );
2857 output.println(" "+dynVar+"_srcSESE = NULL;");
2861 // handling stall site
2862 if (state.OOOJAVA) {
2863 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(currentSESE);
2865 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
2866 Set<Analysis.OoOJava.WaitingElement> waitingElementSet =
2867 graph.getStallSiteWaitingElementSet(fn, seseLockSet);
2869 if(waitingElementSet.size()>0){
2870 output.println("// stall on parent's stall sites ");
2871 output.println(" {");
2872 output.println(" REntry* rentry;");
2874 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
2875 Analysis.OoOJava.WaitingElement waitingElement = (Analysis.OoOJava.WaitingElement) iterator.next();
2877 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
2878 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", seseCaller);");
2880 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller, (void*)&" +generateTemp(fm,waitingElement.getTempDesc(),lb)+ ");");
2882 output.println(" psem_init( &(rentry->parentStallSem) );");
2883 output.println(" rentry->queue=seseCaller->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
2885 .println(" if(ADDRENTRY(seseCaller->memoryQueueArray["+ waitingElement.getQueueID()
2886 + "],rentry)==NOTREADY){");
2887 output.println(" psem_take( &(rentry->parentStallSem) );");
2888 output.println(" } ");
2890 output.println(" }");
2894 ParentChildConflictsMap conflictsMap = mlpa.getConflictsResults().get(fn);
2895 if (conflictsMap != null) {
2896 Set<Long> allocSet = conflictsMap.getAllocationSiteIDSetofStallSite();
2897 if (allocSet.size() > 0) {
2898 FlatNode enclosingFlatNode=null;
2899 if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
2900 enclosingFlatNode=currentSESE.getfmEnclosing();
2902 enclosingFlatNode=currentSESE;
2904 ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
2905 HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
2906 Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
2908 if(waitingElementSet.size()>0){
2909 output.println("// stall on parent's stall sites ");
2910 output.println(" {");
2911 output.println(" REntry* rentry;");
2913 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
2914 WaitingElement waitingElement = (WaitingElement) iterator.next();
2916 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
2917 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", seseCaller);");
2919 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller, (void*)&___locals___."+ waitingElement.getDynID() + ");");
2920 // output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller, ___locals___."+ waitingElement.getDynID() + "->oid);");
2922 output.println(" psem_init( &(rentry->parentStallSem) );");
2923 output.println(" rentry->queue=seseCaller->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
2925 .println(" if(ADDRENTRY(seseCaller->memoryQueueArray["+ waitingElement.getQueueID()
2926 + "],rentry)==NOTREADY){");
2927 output.println(" psem_take( &(rentry->parentStallSem) );");
2928 output.println(" } ");
2930 output.println(" }");
2941 case FKind.FlatAtomicEnterNode:
2942 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
2945 case FKind.FlatAtomicExitNode:
2946 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
2949 case FKind.FlatInstanceOfNode:
2950 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
2953 case FKind.FlatSESEEnterNode:
2954 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
2957 case FKind.FlatSESEExitNode:
2958 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
2961 case FKind.FlatWriteDynamicVarNode:
2962 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
2965 case FKind.FlatGlobalConvNode:
2966 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
2969 case FKind.FlatTagDeclaration:
2970 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
2973 case FKind.FlatCall:
2974 generateFlatCall(fm, lb, (FlatCall) fn,output);
2977 case FKind.FlatFieldNode:
2978 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
2981 case FKind.FlatElementNode:
2982 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
2985 case FKind.FlatSetElementNode:
2986 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
2989 case FKind.FlatSetFieldNode:
2990 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
2994 generateFlatNew(fm, lb, (FlatNew) fn,output);
2997 case FKind.FlatOpNode:
2998 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
3001 case FKind.FlatCastNode:
3002 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
3005 case FKind.FlatLiteralNode:
3006 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
3009 case FKind.FlatReturnNode:
3010 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
3014 output.println("/* nop */");
3017 case FKind.FlatExit:
3018 output.println("/* exit */");
3021 case FKind.FlatBackEdge:
3022 if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3023 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3025 if(state.DSM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3026 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3028 if (((state.MLP|| state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
3029 || (this.state.MULTICOREGC)) {
3030 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
3031 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
3032 } else if(this.state.MULTICOREGC) {
3033 output.println("if (gcflag) gc("+localsprefixaddr+");");
3035 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3038 output.println("/* nop */");
3041 case FKind.FlatCheckNode:
3042 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
3045 case FKind.FlatFlagActionNode:
3046 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
3049 case FKind.FlatPrefetchNode:
3050 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
3053 case FKind.FlatOffsetNode:
3054 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
3061 // insert post-node actions from the code-plan
3064 CodePlan cp = mlpa.getCodePlan( fn );
3072 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
3073 output.println("/* FlatOffsetNode */");
3074 FieldDescriptor fd=fofn.getField();
3075 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
3076 output.println("/* offset */");
3079 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
3080 if (state.PREFETCH) {
3081 Vector oids = new Vector();
3082 Vector fieldoffset = new Vector();
3083 Vector endoffset = new Vector();
3084 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
3085 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
3086 PrefetchPair pp = (PrefetchPair) it.next();
3087 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
3088 /* Find prefetches that can generate oid */
3089 if(statusbase == LocalityAnalysis.GLOBAL) {
3090 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
3092 } else if (statusbase == LocalityAnalysis.LOCAL) {
3093 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
3100 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
3101 output.println("{");
3102 output.println("/* prefetch */");
3103 output.println("/* prefetchid_" + fpn.siteid + " */");
3104 output.println("void * prefptr;");
3105 output.println("int tmpindex;");
3107 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
3108 /*Create C code for oid array */
3109 output.print(" unsigned int oidarray_[] = {");
3110 boolean needcomma=false;
3111 for (Iterator it = oids.iterator(); it.hasNext();) {
3114 output.print(it.next());
3117 output.println("};");
3119 /*Create C code for endoffset values */
3120 output.print(" unsigned short endoffsetarry_[] = {");
3122 for (Iterator it = endoffset.iterator(); it.hasNext();) {
3125 output.print(it.next());
3128 output.println("};");
3130 /*Create C code for Field Offset Values */
3131 output.print(" short fieldarry_[] = {");
3133 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
3136 output.print(it.next());
3139 output.println("};");
3140 /* make the prefetch call to Runtime */
3141 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
3142 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
3143 output.println(" }");
3144 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
3145 output.println(" } else {");
3146 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
3147 output.println(" }");
3148 output.println("}");
3152 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
3153 short offsetcount = 0;
3157 } else if (localbase) {
3158 for(; breakindex<pp.desc.size(); breakindex++) {
3159 Descriptor desc=pp.getDescAt(breakindex);
3160 if (desc instanceof FieldDescriptor) {
3161 FieldDescriptor fd=(FieldDescriptor)desc;
3162 if (fd.isGlobal()) {
3170 if (breakindex>pp.desc.size()) //all local
3173 TypeDescriptor lasttype=pp.base.getType();
3174 String basestr=generateTemp(fm, pp.base, lb);
3176 boolean maybenull=fm.getMethod().isStatic()||
3177 !pp.base.equals(fm.getParameter(0));
3179 for(int i=0; i<breakindex; i++) {
3180 String indexcheck="";
3182 Descriptor desc=pp.getDescAt(i);
3183 if (desc instanceof FieldDescriptor) {
3184 FieldDescriptor fd=(FieldDescriptor)desc;
3186 if (!teststr.equals(""))
3188 teststr+="((prefptr="+basestr+")!=NULL)";
3189 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3191 basestr=basestr+"->"+fd.getSafeSymbol();
3194 lasttype=fd.getType();
3196 IndexDescriptor id=(IndexDescriptor)desc;
3197 indexcheck="((tmpindex=";
3198 for(int j=0; j<id.tddesc.size(); j++) {
3199 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3201 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3203 if (!teststr.equals(""))
3205 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3206 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3208 lasttype=lasttype.dereference();
3213 if (teststr.equals("")) {
3214 oid="((unsigned int)"+basestr+")";
3216 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3220 for(int i = breakindex; i < pp.desc.size(); i++) {
3221 String newfieldoffset;
3222 Object desc = pp.getDescAt(i);
3223 if(desc instanceof FieldDescriptor) {
3224 FieldDescriptor fd=(FieldDescriptor)desc;
3225 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3226 lasttype=fd.getType();
3228 newfieldoffset = "";
3229 IndexDescriptor id=(IndexDescriptor)desc;
3230 for(int j = 0; j < id.tddesc.size(); j++) {
3231 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3233 newfieldoffset += id.offset.toString();
3234 lasttype=lasttype.dereference();
3236 fieldoffset.add(newfieldoffset);
3239 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3240 base+=pp.desc.size()-breakindex;
3241 endoffset.add(new Short((short)base));
3246 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3247 if (lb!=fgcn.getLocality())
3249 /* Have to generate flat globalconv */
3250 if (fgcn.getMakePtr()) {
3252 //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3253 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3255 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3256 //need to do translation
3257 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3258 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3259 if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3260 output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3262 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3266 /* Need to convert to OID */
3267 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3268 if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3269 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3271 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3277 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3279 if (fion.getType().isArray()) {
3280 type=state.getArrayNumber(fion.getType())+state.numClasses();
3282 type=fion.getType().getClassDesc().getId();
3285 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3286 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3288 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3291 int sandboxcounter=0;
3292 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3293 /* Check to see if we need to generate code for this atomic */
3294 if (locality==null) {
3295 if (GENERATEPRECISEGC) {
3296 output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3297 output.println("stopforgc((struct garbagelist *) &___locals___);");
3298 output.println("pthread_mutex_lock(&atomiclock);");
3299 output.println("restartaftergc();");
3300 output.println("}");
3302 output.println("pthread_mutex_lock(&atomiclock);");
3307 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3311 if (state.SANDBOX) {
3312 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3313 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3316 if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3317 AtomicRecord ar=atomicmethodmap.get(faen);
3319 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3320 TempDescriptor tmp=tmpit.next();
3321 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3324 //copy outs that depend on path
3325 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3326 TempDescriptor tmp=tmpit.next();
3327 if (!ar.livein.contains(tmp))
3328 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3332 /* Backup the temps. */
3333 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3334 TempDescriptor tmp=tmpit.next();
3335 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3338 output.println("goto transstart"+faen.getIdentifier()+";");
3340 /******* Print code to retry aborted transaction *******/
3341 output.println("transretry"+faen.getIdentifier()+":");
3344 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3345 TempDescriptor tmp=tmpit.next();
3346 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3350 /********* Need to revert local object store ********/
3351 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3353 output.println("while ("+revertptr+") {");
3354 output.println("struct ___Object___ * tmpptr;");
3355 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3356 output.println("REVERT_OBJ("+revertptr+");");
3357 output.println(revertptr+"=tmpptr;");
3358 output.println("}");
3360 /******* Tell the runtime to start the transaction *******/
3362 output.println("transstart"+faen.getIdentifier()+":");
3363 if (state.SANDBOX) {
3364 output.println("transaction_check_counter=*counter_reset_pointer;");
3367 output.println("transStart();");
3369 if (state.ABORTREADERS||state.SANDBOX) {
3371 output.println("abortenabled=1;");
3372 output.println("if (_setjmp(aborttrans)) {");
3373 output.println(" goto transretry"+faen.getIdentifier()+"; }");
3377 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3378 /* Check to see if we need to generate code for this atomic */
3379 if (locality==null) {
3380 output.println("pthread_mutex_unlock(&atomiclock);");
3383 if (locality.getAtomic(lb).get(faen).intValue()>0)
3385 //store the revert list before we lose the transaction object
3388 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3389 output.println(revertptr+"=revertlist;");
3390 output.println("if (transCommit()) {");
3391 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3392 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3393 output.println("} else {");
3394 /* Need to commit local object store */
3395 output.println("while ("+revertptr+") {");
3396 output.println("struct ___Object___ * tmpptr;");
3397 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3398 output.println("COMMIT_OBJ("+revertptr+");");
3399 output.println(revertptr+"=tmpptr;");
3400 output.println("}");
3401 output.println("}");
3405 if (!state.DELAYCOMP) {
3407 output.println("if (transCommit()) {");
3408 /* Transaction aborts if it returns true */
3409 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3410 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3411 output.println("}");
3413 if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
3414 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3415 output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3417 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3418 TempDescriptor tmp=tmpit.next();
3419 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3421 } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3422 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3424 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3425 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3426 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3427 output.println("}");
3429 output.println("else {");
3430 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3431 TempDescriptor tmp=tmpit.next();
3432 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3434 output.println("}");
3436 output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3437 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3438 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3439 output.println("}");
3444 public void generateFlatSESEEnterNode( FlatMethod fm,
3446 FlatSESEEnterNode fsen,
3449 // if MLP flag is off, okay that SESE nodes are in IR graph,
3450 // just skip over them and code generates exactly the same
3451 if( !(state.MLP || state.OOOJAVA) ) {
3454 // there may be an SESE in an unreachable method, skip over
3455 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
3456 (state.OOOJAVA && !oooa.getAllSESEs().contains(fsen))
3461 // also, if we have encountered a placeholder, just skip it
3462 if( fsen.getIsCallerSESEplaceholder() ) {
3466 output.println(" {");
3468 // set up the parent
3469 if( (state.MLP && fsen == mlpa.getMainSESE()) ||
3470 (state.OOOJAVA && fsen == oooa.getMainSESE())
3472 output.println(" SESEcommon* parentCommon = NULL;");
3474 if( fsen.getParent() == null ) {
3475 System.out.println( "in "+fm+", "+fsen+" has null parent" );
3477 assert fsen.getParent() != null;
3478 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3479 output.println(" SESEcommon* parentCommon = &("+paramsprefix+"->common);");
3481 //output.println(" SESEcommon* parentCommon = (SESEcommon*) peekItem( seseCallStack );");
3482 output.println(" SESEcommon* parentCommon = seseCaller;");
3486 // before doing anything, lock your own record and increment the running children
3487 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3488 (state.OOOJAVA && fsen != oooa.getMainSESE())
3490 output.println(" atomic_inc(&parentCommon->numRunningChildren);");
3493 // just allocate the space for this record
3494 output.println(" "+fsen.getSESErecordName()+"* seseToIssue = ("+
3495 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3496 fsen.getSESErecordName()+" ) );");
3497 //eomgc need to set next, size
3498 // output.println(" struct garbagelist * gl= (struct garbagelist *)&(((SESEcommon*)(seseToIssue))[1]);");
3499 output.println(" struct garbagelist * gl= (struct garbagelist *)&(((SESEcommon*)(seseToIssue))[1]);");
3500 // sizeof(int)*2 + sizeof(void*)*calculateSizeOfSESEParamList(fsen)
3501 //output.println(" // sizeof(int)*2+sizeof(void*)*"+calculateSizeOfSESEParamList(fsen));
3502 //output.println(" // blah="+calculateSizeOfSESEParamSize(fsen));
3503 output.println(" (seseToIssue->common).offsetsize=sizeof(int)+sizeof(void*)+sizeof(void*)*"+calculateSizeOfSESEParamList(fsen)+calculateSizeOfSESEParamSize(fsen)+";");
3504 output.println(" gl->size="+calculateSizeOfSESEParamList(fsen)+";");
3505 // output.println(" gl->next = (struct garbagelist *)&___locals___;");
3506 output.println(" seseToIssue->prevSESECount="+calculatePrevSESECount(fsen)+";");
3507 // output.println(" seseToIssue->prevSESECount=50;");
3508 output.println(" gl->next = NULL;");
3509 // output.println(" seseToIssue->size = "+calculateSizeOfSESEParamList(fsen)+";");
3510 // output.println(" seseToIssue->next = &___locals___;");
3513 // and keep the thread-local sese stack up to date
3514 //output.println(" addNewItem( seseCallStack, (void*) seseToIssue);");
3516 // fill in common data
3517 output.println(" int localCount=0;");
3518 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3519 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
3521 output.println(" seseToIssue->common.forwardList = createQueue();");
3522 output.println(" seseToIssue->common.unresolvedDependencies = 10000;");
3523 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3524 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3525 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3526 output.println(" seseToIssue->common.numRunningChildren = 0;");
3527 output.println(" seseToIssue->common.parent = parentCommon;");
3529 // all READY in-vars should be copied now and be done with it
3530 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3531 while( tempItr.hasNext() ) {
3532 TempDescriptor temp = tempItr.next();
3534 // when we are issuing the main SESE or an SESE with placeholder
3535 // caller SESE as parent, generate temp child child's eclosing method,
3536 // otherwise use the parent's enclosing method as the context
3537 boolean useParentContext = false;
3539 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3540 (state.OOOJAVA && fsen != oooa.getMainSESE())
3542 assert fsen.getParent() != null;
3543 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3544 useParentContext = true;
3548 if( useParentContext ) {
3549 output.println(" seseToIssue->"+temp+" = "+
3550 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3552 output.println(" seseToIssue->"+temp+" = "+
3553 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3557 // before potentially adding this SESE to other forwarding lists,
3558 // create it's lock and take it immediately
3559 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3560 // output.println(" pthread_mutex_lock( &(seseToIssue->common.lock) );");
3562 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3563 (state.OOOJAVA && fsen != oooa.getMainSESE())
3565 // count up outstanding dependencies, static first, then dynamic
3566 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3567 while( staticSrcsItr.hasNext() ) {
3568 SESEandAgePair srcPair = staticSrcsItr.next();
3569 output.println(" {");
3570 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3572 if(GENERATEPRECISEGC){
3573 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3575 output.println(" pthread_mutex_lock( &(src->lock) );");
3576 if(GENERATEPRECISEGC){
3577 output.println(" restartaftergc();");
3579 output.println(" if( !isEmpty( src->forwardList ) &&");
3580 output.println(" seseToIssue == peekItem( src->forwardList ) ) {");
3581 output.println(" printf( \"This shouldnt already be here\\n\");");
3582 output.println(" exit( -1 );");
3583 output.println(" }");
3584 output.println(" if( !src->doneExecuting ) {");
3585 output.println(" addNewItem( src->forwardList, seseToIssue );");
3586 // output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3587 output.println(" ++(localCount);");
3588 output.println(" }");
3589 output.println(" pthread_mutex_unlock( &(src->lock) );");
3590 output.println(" }");
3592 // whether or not it is an outstanding dependency, make sure
3593 // to pass the static name to the child's record
3594 output.println(" seseToIssue->"+srcPair+" = "+srcPair+";");
3597 // dynamic sources might already be accounted for in the static list,
3598 // so only add them to forwarding lists if they're not already there
3599 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3600 while( dynVarsItr.hasNext() ) {
3601 TempDescriptor dynInVar = dynVarsItr.next();
3602 output.println(" {");
3603 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3605 // the dynamic source is NULL if it comes from your own space--you can't pass
3606 // the address off to the new child, because you're not done executing and
3607 // might change the variable, so copy it right now
3608 output.println(" if( src != NULL ) {");
3610 if(GENERATEPRECISEGC){
3611 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3613 output.println(" pthread_mutex_lock( &(src->lock) );");
3614 if(GENERATEPRECISEGC){
3615 output.println(" restartaftergc();");
3617 output.println(" if( isEmpty( src->forwardList ) ||");
3618 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3619 output.println(" if( !src->doneExecuting ) {");
3620 output.println(" addNewItem( src->forwardList, seseToIssue );");
3621 // output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3622 output.println(" ++(localCount);");
3623 output.println(" }");
3624 output.println(" }");
3625 output.println(" pthread_mutex_unlock( &(src->lock) );");
3626 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3627 output.println(" } else {");
3629 boolean useParentContext = false;
3630 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3631 (state.OOOJAVA && fsen != oooa.getMainSESE())
3633 assert fsen.getParent() != null;
3634 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3635 useParentContext = true;
3638 if( useParentContext ) {
3639 output.println(" seseToIssue->"+dynInVar+" = "+
3640 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3642 output.println(" seseToIssue->"+dynInVar+" = "+
3643 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3646 output.println(" }");
3647 output.println(" }");
3649 // even if the value is already copied, make sure your NULL source
3650 // gets passed so child knows it already has the dynamic value
3651 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3654 // maintain pointers for finding dynamic SESE
3655 // instances from static names
3656 SESEandAgePair pair = new SESEandAgePair( fsen, 0 );
3657 if( fsen.getParent() != null &&
3658 //!fsen.getParent().getIsCallerSESEplaceholder() &&
3659 fsen.getParent().getNeededStaticNames().contains( pair )
3662 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3663 SESEandAgePair pair1 = new SESEandAgePair( fsen, i );
3664 SESEandAgePair pair2 = new SESEandAgePair( fsen, i-1 );
3665 output.println(" "+pair1+" = "+pair2+";");
3667 output.println(" "+pair+" = seseToIssue;");
3671 // count up memory conflict dependencies,
3675 FlatSESEEnterNode parent = fsen.getParent();
3676 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(parent);
3677 if (graph != null && graph.hasConflictEdge()) {
3678 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
3680 output.println(" //add memory queue element");
3681 Analysis.OoOJava.SESEWaitingQueue seseWaitingQueue=
3682 graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet);
3683 if(seseWaitingQueue.getWaitingElementSize()>0){
3684 output.println(" {");
3685 output.println(" REntry* rentry=NULL;");
3686 output.println(" INTPTR* pointer=NULL;");
3687 output.println(" seseToIssue->common.rentryIdx=0;");
3689 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
3690 for (Iterator iterator = queueIDSet.iterator(); iterator
3692 Integer key = (Integer) iterator.next();
3693 int queueID=key.intValue();
3694 Set<Analysis.OoOJava.WaitingElement> waitingQueueSet =
3695 seseWaitingQueue.getWaitingElementSet(queueID);
3696 int enqueueType=seseWaitingQueue.getType(queueID);
3697 if(enqueueType==SESEWaitingQueue.EXCEPTION){
3698 output.println(" INITIALIZEBUF(parentCommon->memoryQueueArray["
3701 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2
3703 Analysis.OoOJava.WaitingElement waitingElement
3704 = (Analysis.OoOJava.WaitingElement) iterator2.next();
3705 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
3706 output.println(" rentry=mlpCreateREntry("
3707 + waitingElement.getStatus()
3708 + ", seseToIssue);");
3710 TempDescriptor td = waitingElement
3712 // decide whether waiting element is dynamic or static
3713 if (fsen.getDynamicInVarSet().contains(td)) {
3714 // dynamic in-var case
3715 output.println(" pointer=seseToIssue->"
3716 + waitingElement.getDynID()
3717 + "_srcSESE+seseToIssue->"
3718 + waitingElement.getDynID()
3721 .println(" rentry=mlpCreateFineREntry("
3724 + ", seseToIssue, pointer );");
3725 } else if (fsen.getStaticInVarSet()
3727 // static in-var case
3728 VariableSourceToken vst = fsen
3729 .getStaticInVarSrc(td);
3732 String srcId = "SESE_"
3734 .getPrettyIdentifier()
3735 + vst.getSESE().getIdentifier()
3736 + "_" + vst.getAge();
3738 .println(" pointer=(void*)&seseToIssue->"
3745 .println(" rentry=mlpCreateFineREntry("
3748 + ", seseToIssue, pointer );");
3753 .println(" rentry=mlpCreateFineREntry("
3756 + ", seseToIssue, (void*)&seseToIssue->"
3757 + waitingElement.getDynID()
3762 .println(" rentry->queue=parentCommon->memoryQueueArray["
3763 + waitingElement.getQueueID()
3766 if(enqueueType==SESEWaitingQueue.NORMAL){
3768 .println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
3770 .println(" if(ADDRENTRY(parentCommon->memoryQueueArray["
3771 + waitingElement.getQueueID()
3772 + "],rentry)==NOTREADY){");
3773 output.println(" ++(localCount);");
3774 output.println(" }");
3777 .println(" ADDRENTRYTOBUF(parentCommon->memoryQueueArray["
3778 + waitingElement.getQueueID()
3782 if(enqueueType!=SESEWaitingQueue.NORMAL){
3783 output.println(" localCount+=RESOLVEBUF(parentCommon->memoryQueueArray["
3784 + queueID+ "],&seseToIssue->common);");
3787 output.println(" }");
3793 ConflictGraph graph = null;
3794 FlatSESEEnterNode parent = fsen.getParent();
3795 if (parent != null) {
3796 if (parent.isCallerSESEplaceholder) {
3797 graph = mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
3799 graph = mlpa.getConflictGraphResults().get(parent);
3802 if (graph != null && graph.hasConflictEdge()) {
3803 HashSet<SESELock> seseLockSet = mlpa.getConflictGraphLockMap()
3806 output.println(" //add memory queue element");
3807 SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(fsen.getIdentifier(),
3809 if(seseWaitingQueue.getWaitingElementSize()>0){
3810 output.println(" {");
3811 output.println(" REntry* rentry=NULL;");
3812 output.println(" INTPTR* pointer=NULL;");
3813 output.println(" seseToIssue->common.rentryIdx=0;");
3815 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
3816 for (Iterator iterator = queueIDSet.iterator(); iterator
3818 Integer key = (Integer) iterator.next();
3819 int queueID=key.intValue();
3820 Set<WaitingElement> waitingQueueSet = seseWaitingQueue.getWaitingElementSet(queueID);
3821 int enqueueType=seseWaitingQueue.getType(queueID);
3822 if(enqueueType==SESEWaitingQueue.EXCEPTION){
3823 output.println(" INITIALIZEBUF(parentCommon->memoryQueueArray["
3826 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2
3828 WaitingElement waitingElement = (WaitingElement) iterator2
3830 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
3831 output.println(" rentry=mlpCreateREntry("
3832 + waitingElement.getStatus()
3833 + ", seseToIssue);");
3835 TempDescriptor td = waitingElement
3837 // decide whether waiting element is dynamic or
3839 if (fsen.getDynamicInVarSet().contains(td)) {
3840 // dynamic in-var case
3841 output.println(" pointer=seseToIssue->"
3842 + waitingElement.getDynID()
3843 + "_srcSESE+seseToIssue->"
3844 + waitingElement.getDynID()
3847 .println(" rentry=mlpCreateFineREntry("
3850 + ", seseToIssue, pointer );");
3851 } else if (fsen.getStaticInVarSet()
3853 // static in-var case
3854 VariableSourceToken vst = fsen
3855 .getStaticInVarSrc(td);
3858 String srcId = "SESE_"
3860 .getPrettyIdentifier()
3861 + vst.getSESE().getIdentifier()
3862 + "_" + vst.getAge();
3864 .println(" pointer=(void*)&seseToIssue->"
3871 .println(" rentry=mlpCreateFineREntry("
3874 + ", seseToIssue, pointer );");
3879 .println(" rentry=mlpCreateFineREntry("
3882 + ", seseToIssue, (void*)&seseToIssue->"
3883 + waitingElement.getDynID()
3888 .println(" rentry->queue=parentCommon->memoryQueueArray["
3889 + waitingElement.getQueueID()
3892 if(enqueueType==SESEWaitingQueue.NORMAL){
3894 .println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
3896 .println(" if(ADDRENTRY(parentCommon->memoryQueueArray["
3897 + waitingElement.getQueueID()
3898 + "],rentry)==NOTREADY){");
3899 output.println(" ++(localCount);");
3900 output.println(" } ");
3903 .println(" ADDRENTRYTOBUF(parentCommon->memoryQueueArray["
3904 + waitingElement.getQueueID()
3908 if(enqueueType!=SESEWaitingQueue.NORMAL){
3909 output.println(" localCount+=RESOLVEBUF(parentCommon->memoryQueueArray["
3910 + queueID+ "],&seseToIssue->common);");
3913 output.println(" }");
3921 // release this SESE for siblings to update its dependencies or,
3922 // eventually, for it to mark itself finished
3923 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3925 // if there were no outstanding dependencies, issue here
3926 output.println(" if( atomic_sub_and_test(10000-localCount,&(seseToIssue->common.unresolvedDependencies) ) ) {");
3927 output.println(" workScheduleSubmit( (void*)seseToIssue );");
3928 output.println(" }");
3930 output.println(" if( seseToIssue->common.unresolvedDependencies == 0 ) {");
3931 output.println(" workScheduleSubmit( (void*)seseToIssue );");
3932 output.println(" }");
3934 // release this SESE for siblings to update its dependencies or,
3935 // eventually, for it to mark itself finished
3936 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3937 output.println(" }");
3941 public void generateFlatSESEExitNode( FlatMethod fm,
3943 FlatSESEExitNode fsexn,
3947 // if MLP flag is off, okay that SESE nodes are in IR graph,
3948 // just skip over them and code generates exactly the same
3949 if( ! (state.MLP || state.OOOJAVA) ) {
3953 // get the enter node for this exit that has meta data embedded
3954 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
3956 // there may be an SESE in an unreachable method, skip over
3957 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
3958 (state.OOOJAVA && !oooa.getAllSESEs().contains( fsen ))
3963 // also, if we have encountered a placeholder, just jump it
3964 if( fsen.getIsCallerSESEplaceholder() ) {
3968 output.println(" /* SESE exiting */");
3970 String com = paramsprefix+"->common";
3972 // this SESE cannot be done until all of its children are done
3973 // so grab your own lock with the condition variable for watching
3974 // that the number of your running children is greater than zero
3975 if (GENERATEPRECISEGC){
3976 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3978 output.println(" pthread_mutex_lock( &("+com+".lock) );");
3979 if (GENERATEPRECISEGC){
3980 output.println(" restartaftergc();");
3982 output.println(" while( "+com+".numRunningChildren > 0 ) {");
3983 if (GENERATEPRECISEGC){
3984 // output.println(" stopforgc((struct garbagelist *)&(((SESEcommon*)(___params___))[1]));");
3985 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3987 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
3988 if (GENERATEPRECISEGC){
3989 output.println(" restartaftergc();");
3991 output.println(" }");
3994 // copy out-set from local temps into the sese record
3995 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
3996 while( itr.hasNext() ) {
3997 TempDescriptor temp = itr.next();
3999 // only have to do this for primitives non-arrays
4001 temp.getType().isPrimitive() && !temp.getType().isArray()
4007 // have to determine the context enclosing this sese
4008 boolean useParentContext = false;
4010 if( (state.MLP &&fsen != mlpa.getMainSESE()) ||
4011 (state.OOOJAVA &&fsen != oooa.getMainSESE())
4013 assert fsen.getParent() != null;
4014 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
4015 useParentContext = true;
4020 if( useParentContext ) {
4021 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
4023 from = generateTemp( fsen.getfmEnclosing(), temp, null );
4026 output.println(" "+paramsprefix+
4027 "->"+temp.getSafeSymbol()+
4031 // mark yourself done, your SESE data is now read-only
4032 output.println(" "+com+".doneExecuting = TRUE;");
4033 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
4034 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
4036 // decrement dependency count for all SESE's on your forwarding list
4037 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
4038 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
4041 output.println(" if(consumer->rentryIdx>0){");
4042 output.println(" // resolved null pointer");
4043 output.println(" int idx;");
4044 output.println(" for(idx=0;idx<consumer->rentryIdx;idx++){");
4045 output.println(" resolvePointer(consumer->rentryArray[idx]);");
4046 output.println(" }");
4047 output.println(" }");
4050 // output.println(" pthread_mutex_lock( &(consumer->lock) );");
4051 // output.println(" --(consumer->unresolvedDependencies);");
4052 // output.println(" if( consumer->unresolvedDependencies == 0 ) {");
4053 output.println(" if( atomic_sub_and_test(1, &(consumer->unresolvedDependencies)) ){");
4054 output.println(" workScheduleSubmit( (void*)consumer );");
4055 output.println(" }");
4056 // output.println(" pthread_mutex_unlock( &(consumer->lock) );");
4057 output.println(" }");
4061 // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
4062 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4063 (state.OOOJAVA && fsen != oooa.getMainSESE())
4067 output.println(" /* check memory dependency*/");
4068 output.println(" {");
4069 output.println(" int idx;");
4070 output.println(" for(idx=0;idx<___params___->common.rentryIdx;idx++){");
4071 output.println(" REntry* re=___params___->common.rentryArray[idx];");
4072 output.println(" RETIRERENTRY(re->queue,re);");
4073 output.println(" }");
4074 output.println(" }");
4078 // if parent is stalling on you, let them know you're done
4079 if( (state.MLP && fsexn.getFlatEnter() != mlpa.getMainSESE()) ||
4080 (state.OOOJAVA && fsexn.getFlatEnter() != oooa.getMainSESE())
4082 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
4085 // last of all, decrement your parent's number of running children
4086 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
4087 output.println(" if (atomic_sub_and_test(1, &"+paramsprefix+"->common.parent->numRunningChildren)) {");
4088 if (GENERATEPRECISEGC){
4089 output.println(" stopforgc((struct garbagelist *)&___locals___);");
4091 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
4092 if (GENERATEPRECISEGC){
4093 output.println(" restartaftergc();");
4095 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
4096 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
4097 output.println(" }");
4098 output.println(" }");
4100 // this is a thread-only variable that can be handled when critical sese-to-sese
4101 // data has been taken care of--set sese pointer to remember self over method
4102 // calls to a non-zero, invalid address
4103 output.println(" seseCaller = (SESEcommon*) 0x1;");
4107 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
4109 FlatWriteDynamicVarNode fwdvn,
4112 if( !(state.MLP || state.OOOJAVA) ) {
4113 // should node should not be in an IR graph if the
4114 // MLP flag is not set
4115 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
4118 Hashtable<TempDescriptor, VSTWrapper> writeDynamic = fwdvn.getVar2src();
4120 assert writeDynamic != null;
4122 Iterator wdItr = writeDynamic.entrySet().iterator();
4123 while( wdItr.hasNext() ) {
4124 Map.Entry me = (Map.Entry) wdItr.next();
4125 TempDescriptor refVar = (TempDescriptor) me.getKey();
4126 VSTWrapper vstW = (VSTWrapper) me.getValue();
4127 VariableSourceToken vst = vstW.vst;
4130 // only do this if the variable in question should be tracked,
4131 // meaning that it was explicitly added to the dynamic var set
4132 if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
4138 // if there is no given source, this variable is ready so
4139 // mark src pointer NULL to signify that the var is up-to-date
4140 output.println(" "+refVar+"_srcSESE = NULL;");
4144 // otherwise we track where it will come from
4145 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
4146 output.println(" "+refVar+"_srcSESE = "+instance+";");
4147 output.println(" "+refVar+"_srcOffset = (int) &((("+
4148 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
4153 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
4154 if (state.CONSCHECK) {
4155 String specname=fcn.getSpec();
4156 String varname="repairstate___";
4157 output.println("{");
4158 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
4160 TempDescriptor[] temps=fcn.getTemps();
4161 String[] vars=fcn.getVars();
4162 for(int i=0; i<temps.length; i++) {
4163 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
4166 output.println("if (doanalysis"+specname+"("+varname+")) {");
4167 output.println("free"+specname+"_state("+varname+");");
4168 output.println("} else {");
4169 output.println("/* Bad invariant */");
4170 output.println("free"+specname+"_state("+varname+");");
4171 output.println("abort_task();");
4172 output.println("}");
4173 output.println("}");
4177 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
4179 if( (state.MLP && !nonSESEpass) ||
4180 (state.OOOJAVA && !nonSESEpass)
4182 output.println(" seseCaller = (SESEcommon*)"+paramsprefix+";");
4185 MethodDescriptor md=fc.getMethod();
4186 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
4187 ClassDescriptor cn=md.getClassDesc();
4188 output.println("{");
4189 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4191 LocalityBinding fclb=locality.getBinding(lb, fc);
4192 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4194 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4195 output.print(objectparams.numPointers());
4196 output.print(", "+localsprefixaddr);
4197 if (md.getThis()!=null) {
4199 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
4201 if (fc.getThis()!=null&&md.getThis()==null) {
4202 System.out.println("WARNING!!!!!!!!!!!!");
4203 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
4207 for(int i=0; i<fc.numArgs(); i++) {
4208 Descriptor var=md.getParameter(i);
4209 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4210 if (objectparams.isParamPtr(paramtemp)) {
4211 TempDescriptor targ=fc.getArg(i);
4213 TypeDescriptor td=md.getParamType(i);
4215 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4217 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4220 output.println("};");
4225 if (fc.getReturnTemp()!=null)
4226 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
4228 /* Do we need to do virtual dispatch? */
4229 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
4232 LocalityBinding fclb=locality.getBinding(lb, fc);
4233 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4235 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4240 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4241 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4243 output.print(md.getReturnType().getSafeSymbol()+" ");
4244 output.print("(*)(");
4246 boolean printcomma=false;
4247 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4249 LocalityBinding fclb=locality.getBinding(lb, fc);
4250 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4252 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4256 for(int i=0; i<objectparams.numPrimitives(); i++) {
4257 TempDescriptor temp=objectparams.getPrimitive(i);
4261 if (temp.getType().isClass()||temp.getType().isArray())
4262 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
4264 output.print(temp.getType().getSafeSymbol());
4269 LocalityBinding fclb=locality.getBinding(lb, fc);
4270 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
4272 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
4276 boolean needcomma=false;
4277 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4278 output.print("&__parameterlist__");
4282 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4283 if (fc.getThis()!=null) {
4284 TypeDescriptor ptd=md.getThis().getType();
4287 if (ptd.isClass()&&!ptd.isArray())
4288 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4289 output.print(generateTemp(fm,fc.getThis(),lb));
4294 for(int i=0; i<fc.numArgs(); i++) {
4295 Descriptor var=md.getParameter(i);
4296 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4297 if (objectparams.isParamPrim(paramtemp)) {
4298 TempDescriptor targ=fc.getArg(i);
4302 TypeDescriptor ptd=md.getParamType(i);
4303 if (ptd.isClass()&&!ptd.isArray())
4304 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4305 output.print(generateTemp(fm, targ,lb));
4309 output.println(");");
4310 output.println(" }");
4313 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
4314 Set subclasses=typeutil.getSubClasses(thiscd);
4315 if (subclasses==null)
4317 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
4318 ClassDescriptor cd=(ClassDescriptor)classit.next();
4319 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
4320 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
4321 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
4322 if (md.matches(matchmd))
4329 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
4330 if (state.SINGLETM) {
4331 //single machine transactional memory case
4332 String field=ffn.getField().getSafeSymbol();
4333 String src=generateTemp(fm, ffn.getSrc(),lb);
4334 String dst=generateTemp(fm, ffn.getDst(),lb);
4336 output.println(dst+"="+ src +"->"+field+ ";");
4337 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
4338 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
4339 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
4340 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
4341 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
4342 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
4343 if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
4344 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4346 output.println("TRANSREADRD("+dst+", "+dst+");");
4349 } else if (state.DSM) {
4350 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
4351 if (status==LocalityAnalysis.GLOBAL) {
4352 String field=ffn.getField().getSafeSymbol();
4353 String src=generateTemp(fm, ffn.getSrc(),lb);
4354 String dst=generateTemp(fm, ffn.getDst(),lb);
4356 if (ffn.getField().getType().isPtr()) {
4358 //TODO: Uncomment this when we have runtime support
4359 //if (ffn.getSrc()==ffn.getDst()) {
4360 //output.println("{");
4361 //output.println("void * temp="+src+";");
4362 //output.println("if (temp&0x1) {");
4363 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
4364 //output.println(src+"->"+field+"="+temp+";");
4365 //output.println("}");
4366 //output.println(dst+"=temp;");
4367 //output.println("}");
4369 output.println(dst+"="+ src +"->"+field+ ";");
4370 //output.println("if ("+dst+"&0x1) {");
4371 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4372 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4373 //output.println(src+"->"+field+"="+src+"->"+field+";");
4374 //output.println("}");
4377 output.println(dst+"="+ src+"->"+field+";");
4379 } else if (status==LocalityAnalysis.LOCAL) {
4380 if (ffn.getField().getType().isPtr()&&
4381 ffn.getField().isGlobal()) {
4382 String field=ffn.getField().getSafeSymbol();
4383 String src=generateTemp(fm, ffn.getSrc(),lb);
4384 String dst=generateTemp(fm, ffn.getDst(),lb);
4385 output.println(dst+"="+ src +"->"+field+ ";");
4386 if (locality.getAtomic(lb).get(ffn).intValue()>0)
4387 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4388 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4390 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4391 } else if (status==LocalityAnalysis.EITHER) {
4392 //Code is reading from a null pointer
4393 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
4394 output.println("#ifndef RAW");
4395 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4396 output.println("#endif");
4397 //This should throw a suitable null pointer error
4398 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4400 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4402 // DEBUG if(!ffn.getDst().getType().isPrimitive()){
4403 // DEBUG output.println("within((void*)"+generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+");");
4405 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4410 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
4411 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
4412 throw new Error("Can't set array length");
4413 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4414 //Single Machine Transaction Case
4415 boolean srcptr=fsfn.getSrc().getType().isPtr();
4416 String src=generateTemp(fm,fsfn.getSrc(),lb);
4417 String dst=generateTemp(fm,fsfn.getDst(),lb);
4418 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
4419 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
4420 output.println("{");
4421 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
4422 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
4423 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4425 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4428 if (wb.needBarrier(fsfn)&&
4429 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
4430 if (state.EVENTMONITOR) {
4431 output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
4433 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
4435 if (srcptr&!fsfn.getSrc().getType().isNull()) {
4436 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4437 output.println("}");
4439 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4441 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4442 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
4443 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
4444 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4446 String src=generateTemp(fm,fsfn.getSrc(),lb);
4447 String dst=generateTemp(fm,fsfn.getDst(),lb);
4449 output.println("{");
4450 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4452 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
4455 if (wb.needBarrier(fsfn))
4456 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
4458 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4460 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4461 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
4462 /** Check if we need to copy */
4463 output.println("if(!"+dst+"->"+localcopystr+") {");
4464 /* Link object into list */
4465 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4466 output.println(revertptr+"=revertlist;");
4467 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4468 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4470 output.println("COPY_OBJ("+dst+");");
4471 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4472 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4473 output.println("}");
4475 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4477 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4478 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
4479 //writing to a null...bad
4480 output.println("if ("+dst+") {");
4481 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
4483 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4485 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4488 output.println("}");
4491 if (state.FASTCHECK) {
4492 String dst=generateTemp(fm, fsfn.getDst(),lb);
4493 output.println("if(!"+dst+"->"+localcopystr+") {");
4494 /* Link object into list */
4495 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4496 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4498 output.println("COPY_OBJ("+dst+");");
4499 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4500 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4501 output.println("}");
4504 // DEBUG if(!fsfn.getField().getType().isPrimitive()){
4505 // DEBUG output.println("within((void*)"+generateTemp(fm,fsfn.getSrc(),lb)+");");
4507 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4511 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
4512 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
4515 if (elementtype.isArray()||elementtype.isClass())
4518 type=elementtype.getSafeSymbol()+" ";
4520 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
4521 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
4522 output.println("failedboundschk();");
4524 if (state.SINGLETM) {
4525 //Single machine transaction case
4526 String dst=generateTemp(fm, fen.getDst(),lb);
4527 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))) {
4528 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4530 output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
4533 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
4534 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
4535 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
4536 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
4537 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
4538 if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
4539 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4541 output.println("TRANSREADRD("+dst+", "+dst+");");
4544 } else if (state.DSM) {
4545 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
4546 if (status==LocalityAnalysis.GLOBAL) {
4547 String dst=generateTemp(fm, fen.getDst(),lb);
4548 if (elementtype.isPtr()) {
4549 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4550 //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
4551 output.println("TRANSREAD("+dst+", "+dst+");");
4553 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4555 } else if (status==LocalityAnalysis.LOCAL) {
4556 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4557 } else if (status==LocalityAnalysis.EITHER) {
4558 //Code is reading from a null pointer
4559 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
4560 output.println("#ifndef RAW");
4561 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4562 output.println("#endif");
4563 //This should throw a suitable null pointer error
4564 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4566 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4568 // DEBUG output.println("within((void*)"+generateTemp(fm,fen.getSrc(),lb)+");");
4569 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4573 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
4574 //TODO: need dynamic check to make sure this assignment is actually legal
4575 //Because Object[] could actually be something more specific...ie. Integer[]
4577 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
4580 if (elementtype.isArray()||elementtype.isClass())
4583 type=elementtype.getSafeSymbol()+" ";
4585 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
4586 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
4587 output.println("failedboundschk();");
4590 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4591 //Transaction set element case
4592 if (wb.needBarrier(fsen)&&
4593 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
4594 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
4596 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
4597 output.println("{");
4598 String src=generateTemp(fm, fsen.getSrc(), lb);
4599 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
4600 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
4601 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4603 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4605 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4606 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
4608 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4610 output.println("}");
4612 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4613 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
4615 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4618 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4619 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
4620 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
4621 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4622 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
4623 boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
4626 if (wb.needBarrier(fsen))
4627 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
4628 } else if (dstlocal) {
4629 /** Check if we need to copy */
4630 String dst=generateTemp(fm, fsen.getDst(),lb);
4631 output.println("if(!"+dst+"->"+localcopystr+") {");
4632 /* Link object into list */
4633 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4634 output.println(revertptr+"=revertlist;");
4635 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
4636 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4638 output.println("COPY_OBJ("+dst+");");
4639 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4640 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4641 output.println("}");
4643 System.out.println("Node: "+fsen);
4644 System.out.println(lb);
4645 System.out.println("statusdst="+statusdst);
4646 System.out.println(fm.printMethod());
4647 throw new Error("Unknown array type");
4650 output.println("{");
4651 String src=generateTemp(fm, fsen.getSrc(), lb);
4652 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4653 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4654 output.println("}");
4656 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4659 if (state.FASTCHECK) {
4660 String dst=generateTemp(fm, fsen.getDst(),lb);
4661 output.println("if(!"+dst+"->"+localcopystr+") {");
4662 /* Link object into list */
4663 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4664 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4666 output.println("COPY_OBJ("+dst+");");
4667 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4668 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4669 output.println("}");
4671 // DEBUG output.println("within((void*)"+generateTemp(fm,fsen.getDst(),lb)+");");
4672 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4676 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
4677 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4678 //Stash pointer in case of GC
4679 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4680 output.println(revertptr+"=revertlist;");
4682 if (state.SINGLETM) {
4683 if (fn.getType().isArray()) {
4684 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4685 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4686 //inside transaction
4687 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4689 //outside transaction
4690 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4693 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4694 //inside transaction
4695 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4697 //outside transaction
4698 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4701 } else if (fn.getType().isArray()) {
4702 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4703 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4704 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4705 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4706 if(this.state.MLP || state.OOOJAVA){
4707 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray_oid("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+", oid);");
4708 output.println(" oid += numWorkers;");
4710 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4713 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4716 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4717 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
4718 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4719 if (this.state.MLP || state.OOOJAVA){
4720 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new_oid("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+", oid);");
4721 output.println(" oid += numWorkers;");
4723 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4726 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
4729 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4730 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4731 String dst=generateTemp(fm,fn.getDst(),lb);
4732 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4733 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4734 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4736 if (state.FASTCHECK) {
4737 String dst=generateTemp(fm,fn.getDst(),lb);
4738 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4739 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4740 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4744 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
4745 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4746 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
4748 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
4752 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
4753 if (fon.getRight()!=null) {
4754 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
4755 if (fon.getLeft().getType().isLong())
4756 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4758 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4760 } else if (dc!=null) {
4761 output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
4762 if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4763 output.print("(void *)");
4764 if (dc.getNeedLeftSrcTrans(lb, fon))
4765 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
4767 output.print(generateTemp(fm, fon.getLeft(),lb));
4768 output.print(")"+fon.getOp().toString()+"(");
4769 if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4770 output.print("(void *)");
4771 if (dc.getNeedRightSrcTrans(lb, fon))
4772 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
4774 output.println(generateTemp(fm,fon.getRight(),lb)+");");
4776 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
4777 } else if (fon.getOp().getOp()==Operation.ASSIGN)
4778 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4779 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
4780 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4781 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
4782 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
4783 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
4784 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
4785 else if (fon.getOp().getOp()==Operation.COMP)
4786 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
4787 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
4788 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
4790 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
4793 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
4794 /* TODO: Do type check here */
4795 if (fcn.getType().isArray()) {
4796 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4797 } else if (fcn.getType().isClass())
4798 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4800 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
4803 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
4804 if (fln.getValue()==null)
4805 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4806 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
4807 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4808 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4809 //Stash pointer in case of GC
4810 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4811 output.println(revertptr+"=revertlist;");
4813 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4814 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4815 //Stash pointer in case of GC
4816 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4817 output.println("revertlist="+revertptr+";");
4820 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4822 } else if (fln.getType().isBoolean()) {
4823 if (((Boolean)fln.getValue()).booleanValue())
4824 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
4826 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4827 } else if (fln.getType().isChar()) {
4828 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
4829 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
4830 } else if (fln.getType().isLong()) {
4831 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
4833 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
4836 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
4837 if (frn.getReturnTemp()!=null) {
4838 if (frn.getReturnTemp().getType().isPtr())
4839 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4841 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4843 output.println("return;");
4847 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4850 //only record if this group has more than one exit
4851 if (branchanalysis.numJumps(fcb)>1) {
4852 left=branchanalysis.jumpValue(fcb, 0);
4853 right=branchanalysis.jumpValue(fcb, 1);
4855 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
4857 output.println("STOREBRANCH("+right+");");
4858 output.println("goto "+label+";");
4859 output.println("}");
4861 output.println("STOREBRANCH("+left+");");
4864 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4865 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
4868 /** This method generates header information for the method or
4869 * task referenced by the Descriptor des. */
4870 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
4871 generateHeader(fm, lb, des, output, false);
4874 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
4876 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
4877 MethodDescriptor md=null;
4878 TaskDescriptor task=null;
4879 if (des instanceof MethodDescriptor)
4880 md=(MethodDescriptor) des;
4882 task=(TaskDescriptor) des;
4884 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
4886 if (md!=null&&md.getReturnType()!=null) {
4887 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4888 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4890 output.print(md.getReturnType().getSafeSymbol()+" ");
4892 //catch the constructor case
4893 output.print("void ");
4895 if (state.DSM||state.SINGLETM) {
4896 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4898 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4900 output.print(task.getSafeSymbol()+"(");
4902 boolean printcomma=false;
4903 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4905 if (state.DSM||state.SINGLETM) {
4906 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4908 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4910 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
4916 for(int i=0; i<objectparams.numPrimitives(); i++) {
4917 TempDescriptor temp=objectparams.getPrimitive(i);
4921 if (temp.getType().isClass()||temp.getType().isArray())
4922 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
4924 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
4926 output.println(") {");
4927 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4928 /* Imprecise Task */
4929 output.println("void * parameterarray[]) {");
4930 /* Unpack variables */
4931 for(int i=0; i<objectparams.numPrimitives(); i++) {
4932 TempDescriptor temp=objectparams.getPrimitive(i);
4933 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
4935 for(int i=0; i<fm.numTags(); i++) {
4936 TempDescriptor temp=fm.getTag(i);
4937 int offset=i+objectparams.numPrimitives();
4938 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
4941 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
4942 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
4943 } else output.println(") {");
4946 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
4947 output.println("/* FlatFlagActionNode */");
4950 /* Process tag changes */
4951 Relation tagsettable=new Relation();
4952 Relation tagcleartable=new Relation();
4954 Iterator tagsit=ffan.getTempTagPairs();
4955 while (tagsit.hasNext()) {
4956 TempTagPair ttp=(TempTagPair) tagsit.next();
4957 TempDescriptor objtmp=ttp.getTemp();
4958 TagDescriptor tag=ttp.getTag();
4959 TempDescriptor tagtmp=ttp.getTagTemp();
4960 boolean tagstatus=ffan.getTagChange(ttp);
4962 tagsettable.put(objtmp, tagtmp);
4964 tagcleartable.put(objtmp, tagtmp);
4969 Hashtable flagandtable=new Hashtable();
4970 Hashtable flagortable=new Hashtable();
4972 /* Process flag changes */
4973 Iterator flagsit=ffan.getTempFlagPairs();
4974 while(flagsit.hasNext()) {
4975 TempFlagPair tfp=(TempFlagPair)flagsit.next();
4976 TempDescriptor temp=tfp.getTemp();
4977 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
4978 FlagDescriptor flag=tfp.getFlag();
4980 //Newly allocate objects that don't set any flags case
4981 if (flagortable.containsKey(temp)) {
4985 flagortable.put(temp,new Integer(mask));
4987 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
4988 boolean flagstatus=ffan.getFlagChange(tfp);
4991 if (flagortable.containsKey(temp)) {
4992 mask=((Integer)flagortable.get(temp)).intValue();
4995 flagortable.put(temp,new Integer(mask));
4997 int mask=0xFFFFFFFF;
4998 if (flagandtable.containsKey(temp)) {
4999 mask=((Integer)flagandtable.get(temp)).intValue();
5001 mask&=(0xFFFFFFFF^flagid);
5002 flagandtable.put(temp,new Integer(mask));
5008 HashSet flagtagset=new HashSet();
5009 flagtagset.addAll(flagortable.keySet());
5010 flagtagset.addAll(flagandtable.keySet());
5011 flagtagset.addAll(tagsettable.keySet());
5012 flagtagset.addAll(tagcleartable.keySet());
5014 Iterator ftit=flagtagset.iterator();
5015 while(ftit.hasNext()) {
5016 TempDescriptor temp=(TempDescriptor)ftit.next();
5019 Set tagtmps=tagcleartable.get(temp);
5020 if (tagtmps!=null) {
5021 Iterator tagit=tagtmps.iterator();
5022 while(tagit.hasNext()) {
5023 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5024 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5025 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5027 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5031 tagtmps=tagsettable.get(temp);
5032 if (tagtmps!=null) {
5033 Iterator tagit=tagtmps.iterator();
5034 while(tagit.hasNext()) {
5035 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5036 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5037 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5039 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
5044 int andmask=0xFFFFFFF;
5046 if (flagortable.containsKey(temp))
5047 ormask=((Integer)flagortable.get(temp)).intValue();
5048 if (flagandtable.containsKey(temp))
5049 andmask=((Integer)flagandtable.get(temp)).intValue();
5050 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
5051 generateObjectDistribute(ffan, fm, lb, temp, output);
5055 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
5056 PrintWriter output, int ormask, int andmask) {
5057 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
5058 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5060 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5064 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
5065 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
5068 void generateOptionalHeader(PrintWriter headers) {
5071 headers.println("#include \"task.h\"\n\n");
5072 headers.println("#ifndef _OPTIONAL_STRUCT_");
5073 headers.println("#define _OPTIONAL_STRUCT_");
5075 //STRUCT PREDICATEMEMBER
5076 headers.println("struct predicatemember{");
5077 headers.println("int type;");
5078 headers.println("int numdnfterms;");
5079 headers.println("int * flags;");
5080 headers.println("int numtags;");
5081 headers.println("int * tags;\n};\n\n");
5083 //STRUCT OPTIONALTASKDESCRIPTOR
5084 headers.println("struct optionaltaskdescriptor{");
5085 headers.println("struct taskdescriptor * task;");
5086 headers.println("int index;");
5087 headers.println("int numenterflags;");
5088 headers.println("int * enterflags;");
5089 headers.println("int numpredicatemembers;");
5090 headers.println("struct predicatemember ** predicatememberarray;");
5091 headers.println("};\n\n");
5093 //STRUCT TASKFAILURE
5094 headers.println("struct taskfailure {");
5095 headers.println("struct taskdescriptor * task;");
5096 headers.println("int index;");
5097 headers.println("int numoptionaltaskdescriptors;");
5098 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5100 //STRUCT FSANALYSISWRAPPER
5101 headers.println("struct fsanalysiswrapper{");
5102 headers.println("int flags;");
5103 headers.println("int numtags;");
5104 headers.println("int * tags;");
5105 headers.println("int numtaskfailures;");
5106 headers.println("struct taskfailure ** taskfailurearray;");
5107 headers.println("int numoptionaltaskdescriptors;");
5108 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5110 //STRUCT CLASSANALYSISWRAPPER
5111 headers.println("struct classanalysiswrapper{");
5112 headers.println("int type;");
5113 headers.println("int numotd;");
5114 headers.println("struct optionaltaskdescriptor ** otdarray;");
5115 headers.println("int numfsanalysiswrappers;");
5116 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
5118 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
5120 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
5121 while(taskit.hasNext()) {
5122 TaskDescriptor td=(TaskDescriptor)taskit.next();
5123 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
5128 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
5129 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
5130 int predicateindex = 0;
5131 //iterate through the classes concerned by the predicate
5132 Set c_vard = predicate.vardescriptors;
5133 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
5136 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
5137 VarDescriptor vard = (VarDescriptor)vard_it.next();
5138 TypeDescriptor typed = vard.getType();
5140 //generate for flags
5141 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
5142 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5144 if (fen_hashset!=null) {
5145 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
5146 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
5148 DNFFlag dflag=fen.getDNF();
5149 numberterms+=dflag.size();
5151 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
5153 for(int j=0; j<dflag.size(); j++) {
5155 output.println(",");
5156 Vector term=dflag.get(j);
5159 for(int k=0; k<term.size(); k++) {
5160 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
5161 FlagDescriptor fd=dfa.getFlag();
5162 boolean negated=dfa.getNegated();
5163 int flagid=1<<((Integer)flags.get(fd)).intValue();
5168 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
5173 output.println("};\n");
5176 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
5177 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5180 for(int j=0; j<tagel.numTags(); j++) {
5182 output.println(",");
5183 TempDescriptor tmp=tagel.getTemp(j);
5184 if (!slotnumber.containsKey(tmp)) {
5185 Integer slotint=new Integer(current_slot++);
5186 slotnumber.put(tmp,slotint);
5188 int slot=slotnumber.get(tmp).intValue();
5189 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
5191 numtags = tagel.numTags();
5193 output.println("};");
5195 //store the result into a predicatemember struct
5196 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5197 output.println("/*type*/"+typed.getClassDesc().getId()+",");
5198 output.println("/* number of dnf terms */"+numberterms+",");
5199 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5200 output.println("/* number of tag */"+numtags+",");
5201 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5202 output.println("};\n");
5207 //generate an array that stores the entire predicate
5208 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5209 for( int j = 0; j<predicateindex; j++) {
5210 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5211 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5213 output.println("};\n");
5214 return predicateindex;
5218 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
5219 generateOptionalHeader(headers);
5221 output.println("#include \"optionalstruct.h\"\n\n");
5222 output.println("#include \"stdlib.h\"\n");
5224 HashSet processedcd = new HashSet();
5226 Enumeration e = safeexecution.keys();
5227 while (e.hasMoreElements()) {
5230 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
5231 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
5233 //Generate the struct of optionals
5234 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5235 numotd = c_otd.size();
5236 if(maxotd<numotd) maxotd = numotd;
5237 if( !c_otd.isEmpty() ) {
5238 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5239 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5241 //generate the int arrays for the predicate
5242 Predicate predicate = otd.predicate;
5243 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
5244 TreeSet<Integer> fsset=new TreeSet<Integer>();
5245 //iterate through possible FSes corresponding to
5246 //the state when entering
5248 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
5249 FlagState fs = (FlagState)fses.next();
5251 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5252 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5253 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5256 fsset.add(new Integer(flagid));
5257 //tag information not needed because tag
5258 //changes are not tolerated.
5261 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5262 boolean needcomma=false;
5263 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
5266 output.println(it.next());
5269 output.println("};\n");
5272 //generate optionaltaskdescriptor that actually
5273 //includes exit fses, predicate and the task
5275 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5276 output.println("&task_"+otd.td.getSafeSymbol()+",");
5277 output.println("/*index*/"+otd.getIndex()+",");
5278 output.println("/*number of enter flags*/"+fsset.size()+",");
5279 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5280 output.println("/*number of members */"+predicateindex+",");
5281 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5282 output.println("};\n");
5286 // if there are no optionals, there is no need to build the rest of the struct
5288 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
5289 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5290 if( !c_otd.isEmpty() ) {
5291 boolean needcomma=false;
5292 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5293 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5295 output.println(",");
5297 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5300 output.println("};\n");
5302 //get all the possible flagstates reachable by an object
5303 Hashtable hashtbtemp = safeexecution.get(cdtemp);
5305 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
5306 fsts.addAll(hashtbtemp.keySet());
5307 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
5308 FlagState fs = (FlagState)fsit.next();
5311 //get the set of OptionalTaskDescriptors corresponding
5312 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
5313 //iterate through the OptionalTaskDescriptors and
5314 //store the pointers to the optionals struct (see on
5315 //top) into an array
5317 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
5318 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
5319 OptionalTaskDescriptor mm = mos.next();
5321 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
5323 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5326 output.println("};\n");
5328 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
5331 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5332 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5333 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5337 //process tag information
5340 boolean first = true;
5341 Enumeration tag_enum = fs.getTags();
5342 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5343 while(tag_enum.hasMoreElements()) {
5345 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
5349 output.println(", ");
5350 output.println("/*tagid*/"+state.getTagId(tagd));
5352 output.println("};");
5354 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
5355 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5356 TaskIndex ti=itti.next();
5360 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
5362 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
5363 boolean needcomma=false;
5364 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
5365 OptionalTaskDescriptor otd=otdit.next();
5369 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5371 output.println("};");
5373 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
5374 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
5375 output.print(ti.getIndex()+", ");
5376 output.print(otdset.size()+", ");
5377 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
5378 output.println("};");
5381 tiset=sa.getTaskIndex(fs);
5382 boolean needcomma=false;
5384 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5385 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5386 TaskIndex ti=itti.next();
5387 if (ti.isRuntime()) {
5394 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
5396 output.println("};\n");
5398 //Store the result in fsanalysiswrapper
5400 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
5401 output.println("/*flag*/"+flagid+",");
5402 output.println("/* number of tags*/"+tagcounter+",");
5403 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5404 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
5405 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5406 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
5407 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
5408 output.println("};\n");
5412 //Build the array of fsanalysiswrappers
5413 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
5414 boolean needcomma=false;
5415 for(int i = 0; i<fscounter; i++) {
5416 if (needcomma) output.print(",");
5417 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
5420 output.println("};");
5422 //Build the classanalysiswrapper referring to the previous array
5423 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
5424 output.println("/*type*/"+cdtemp.getId()+",");
5425 output.println("/*numotd*/"+numotd+",");
5426 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
5427 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
5428 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
5429 processedcd.add(cdtemp);
5432 //build an array containing every classes for which code has been build
5433 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
5434 for(int i=0; i<state.numClasses(); i++) {
5435 ClassDescriptor cn=cdarray[i];
5438 if ((cn != null) && (processedcd.contains(cn)))
5439 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
5441 output.print("NULL");
5443 output.println("};");
5445 output.println("#define MAXOTD "+maxotd);
5446 headers.println("#endif");
5449 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
5450 Relation r=new Relation();
5451 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
5452 OptionalTaskDescriptor otd=otdit.next();
5453 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
5457 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
5458 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
5459 Set s=r.get(it.next());
5460 for(Iterator it2=s.iterator(); it2.hasNext();) {
5461 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
5469 protected void outputTransCode(PrintWriter output) {
5472 private int calculateSizeOfSESEParamList(FlatSESEEnterNode fsen){
5474 Set<TempDescriptor> tdSet=new HashSet<TempDescriptor>();
5476 for (Iterator iterator = fsen.getInVarSet().iterator(); iterator.hasNext();) {
5477 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5478 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5479 tdSet.add(tempDescriptor);
5483 for (Iterator iterator = fsen.getOutVarSet().iterator(); iterator.hasNext();) {
5484 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5485 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5486 tdSet.add(tempDescriptor);
5490 return tdSet.size();
5493 private String calculateSizeOfSESEParamSize(FlatSESEEnterNode fsen){
5494 HashMap <String,Integer> map=new HashMap();
5495 HashSet <TempDescriptor> processed=new HashSet<TempDescriptor>();
5498 // space for all in and out set primitives
5499 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
5500 inSetAndOutSet.addAll( fsen.getInVarSet() );
5501 inSetAndOutSet.addAll( fsen.getOutVarSet() );
5503 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
5505 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
5506 while( itr.hasNext() ) {
5507 TempDescriptor temp = itr.next();
5508 TypeDescriptor type = temp.getType();
5509 if( !type.isPtr() ) {
5510 inSetAndOutSetPrims.add( temp );
5514 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
5515 while( itrPrims.hasNext() ) {
5516 TempDescriptor temp = itrPrims.next();
5517 TypeDescriptor type = temp.getType();
5518 if(type.isPrimitive()){
5519 Integer count=map.get(type.getSymbol());
5521 count=new Integer(1);
5522 map.put(type.getSymbol(), count);
5524 map.put(type.getSymbol(), new Integer(count.intValue()+1));
5529 Set<String> keySet=map.keySet();
5530 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
5531 String key = (String) iterator.next();
5532 rtr+="+sizeof("+key+")*"+map.get(key);
5537 private int calculatePrevSESECount(FlatSESEEnterNode fsen){
5541 Iterator<TempDescriptor>itrDynInVars = fsen.getDynamicInVarSet().iterator();
5542 while( itrDynInVars.hasNext() ) {
5543 TempDescriptor dynInVar = itrDynInVars.next();
5547 // in-set source tracking
5548 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
5549 while( itrStaticInVarSrcs.hasNext() ) {
5550 SESEandAgePair srcPair = itrStaticInVarSrcs.next();