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;
14 import Analysis.TaskStateAnalysis.FlagState;
15 import Analysis.TaskStateAnalysis.FlagComparator;
16 import Analysis.TaskStateAnalysis.OptionalTaskDescriptor;
17 import Analysis.TaskStateAnalysis.Predicate;
18 import Analysis.TaskStateAnalysis.SafetyAnalysis;
19 import Analysis.TaskStateAnalysis.TaskIndex;
20 import Analysis.Locality.LocalityAnalysis;
21 import Analysis.Locality.LocalityBinding;
22 import Analysis.Locality.DiscoverConflicts;
23 import Analysis.Locality.DCWrapper;
24 import Analysis.Locality.DelayComputation;
25 import Analysis.Locality.BranchAnalysis;
26 import Analysis.CallGraph.CallGraph;
27 import Analysis.Disjoint.AllocSite;
28 import Analysis.Disjoint.Effect;
29 import Analysis.Disjoint.ReachGraph;
30 import Analysis.Disjoint.Taint;
31 import Analysis.OoOJava.OoOJavaAnalysis;
32 import Analysis.Prefetch.*;
33 import Analysis.Loops.WriteBarrier;
34 import Analysis.Loops.GlobalFieldType;
35 import Analysis.Locality.TypeAnalysis;
36 import Analysis.MLP.ConflictGraph;
37 import Analysis.MLP.ConflictNode;
38 import Analysis.MLP.MLPAnalysis;
39 import Analysis.MLP.ParentChildConflictsMap;
40 import Analysis.MLP.SESELock;
41 import Analysis.MLP.SESEWaitingQueue;
42 import Analysis.MLP.VariableSourceToken;
43 import Analysis.MLP.VSTWrapper;
44 import Analysis.MLP.CodePlan;
45 import Analysis.MLP.SESEandAgePair;
46 import Analysis.MLP.WaitingElement;
48 public class BuildCode {
51 Hashtable paramstable;
56 String localsprefix="___locals___";
57 String localsprefixaddr="&"+localsprefix;
58 String localsprefixderef=localsprefix+".";
59 String fcrevert="___fcrevert___";
60 String paramsprefix="___params___";
61 String oidstr="___nextobject___";
62 String nextobjstr="___nextobject___";
63 String localcopystr="___localcopy___";
64 public static boolean GENERATEPRECISEGC=false;
65 public static String PREFIX="";
66 public static String arraytype="ArrayObject";
67 public static int flagcount = 0;
70 protected int maxtaskparams=0;
71 private int maxcount=0;
72 ClassDescriptor[] cdarray;
73 TypeDescriptor[] arraytable;
74 LocalityAnalysis locality;
75 Hashtable<LocalityBinding, TempDescriptor> reverttable;
76 Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>> backuptable;
81 String maxTaskRecSizeStr="__maxTaskRecSize___";
82 String mlperrstr = "if(status != 0) { "+
83 "sprintf(errmsg, \"MLP error at %s:%d\", __FILE__, __LINE__); "+
84 "perror(errmsg); exit(-1); }";
85 boolean nonSESEpass=true;
86 RuntimeConflictResolver rcr = null;
89 DiscoverConflicts recorddc;
94 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa) {
95 this(st, temptovar, typeutil, null, sa, pa, null, null);
98 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
99 this(st, temptovar, typeutil, null, sa, pa, mlpa, oooa);
102 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
103 this(st, temptovar, typeutil, locality, null, pa, mlpa, oooa);
106 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
112 callgraph=new CallGraph(state);
114 oidstr="___objlocation___";
115 this.temptovar=temptovar;
116 paramstable=new Hashtable();
117 tempstable=new Hashtable();
118 fieldorder=new Hashtable();
119 flagorder=new Hashtable();
120 this.typeutil=typeutil;
121 virtualcalls=new Virtual(state,locality);
122 if (locality!=null) {
123 this.locality=locality;
124 this.reverttable=new Hashtable<LocalityBinding, TempDescriptor>();
125 this.backuptable=new Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>>();
126 this.wb=new WriteBarrier(locality, st);
128 if (state.SINGLETM&&state.DCOPTS) {
129 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
130 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
131 this.dc=new DiscoverConflicts(locality, st, typeanalysis, gft);
134 if (state.DELAYCOMP) {
135 //TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
136 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
137 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
138 delaycomp=new DCWrapper(locality, st, typeanalysis, gft);
139 dc=delaycomp.getConflicts();
140 recorddc=new DiscoverConflicts(locality, st, typeanalysis, delaycomp.getCannotDelayMap(), true, true, null);
141 recorddc.doAnalysis();
145 /** The buildCode method outputs C code for all the methods. The Flat
146 * versions of the methods must already be generated and stored in
147 * the State object. */
148 PrintWriter outsandbox=null;
150 public void buildCode() {
151 /* Create output streams to write to */
152 PrintWriter outclassdefs=null;
153 PrintWriter outstructs=null;
154 PrintWriter outrepairstructs=null;
155 PrintWriter outmethodheader=null;
156 PrintWriter outmethod=null;
157 PrintWriter outvirtual=null;
158 PrintWriter outtask=null;
159 PrintWriter outtaskdefs=null;
160 PrintWriter outoptionalarrays=null;
161 PrintWriter optionalheaders=null;
162 PrintWriter outglobaldefs=null;
166 outsandbox=new PrintWriter(new FileOutputStream(PREFIX+"sandboxdefs.c"), true);
168 outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
169 outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
170 outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
172 // TODO add version for normal Java later
173 outglobaldefs=new PrintWriter(new FileOutputStream(PREFIX+"globaldefs.h"), true);
175 outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
176 outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
178 outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
179 outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
180 if (state.OPTIONAL) {
181 outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
182 optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
185 if (state.structfile!=null) {
186 outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
188 } catch (Exception e) {
193 /* Build the virtual dispatch tables */
194 buildVirtualTables(outvirtual);
196 /* Tag the methods that are invoked by static blocks */
197 tagMethodInvokedByStaticBlock();
199 /* Output includes */
200 outmethodheader.println("#ifndef METHODHEADERS_H");
201 outmethodheader.println("#define METHODHEADERS_H");
202 outmethodheader.println("#include \"structdefs.h\"");
204 outmethodheader.println("#include \"dstm.h\"");
206 outmethodheader.println("#include \"sandbox.h\"");
208 if (state.EVENTMONITOR) {
209 outmethodheader.println("#include \"monitor.h\"");
211 if (state.SINGLETM) {
212 outmethodheader.println("#include \"tm.h\"");
213 outmethodheader.println("#include \"delaycomp.h\"");
214 outmethodheader.println("#include \"inlinestm.h\"");
216 if (state.ABORTREADERS) {
217 outmethodheader.println("#include \"abortreaders.h\"");
218 outmethodheader.println("#include <setjmp.h>");
220 if (state.MLP || state.OOOJAVA) {
221 outmethodheader.println("#include <stdlib.h>");
222 outmethodheader.println("#include <stdio.h>");
223 outmethodheader.println("#include <string.h>");
224 outmethodheader.println("#include \"mlp_runtime.h\"");
225 outmethodheader.println("#include \"psemaphore.h\"");
226 outmethodheader.println("#include \"memPool.h\"");
229 outmethodheader.println("#include \"rcr_runtime.h\"");
232 // spit out a global to inform all worker threads with
233 // the maximum size is for any task record
234 outmethodheader.println("extern int "+maxTaskRecSizeStr+";");
237 /* Output Structures */
238 outputStructs(outstructs);
240 // Output the C class declarations
241 // These could mutually reference each other
244 // TODO add version for normal Java later
245 outglobaldefs.println("#ifndef __GLOBALDEF_H_");
246 outglobaldefs.println("#define __GLOBALDEF_H_");
247 outglobaldefs.println("");
248 outglobaldefs.println("struct global_defs_t {");
251 outclassdefs.println("#ifndef __CLASSDEF_H_");
252 outclassdefs.println("#define __CLASSDEF_H_");
253 outputClassDeclarations(outclassdefs, outglobaldefs);
255 // Output function prototypes and structures for parameters
256 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
257 while(it.hasNext()) {
258 ClassDescriptor cn=(ClassDescriptor)it.next();
259 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader, outglobaldefs);
261 outclassdefs.println("#endif");
262 outclassdefs.close();
264 // TODO add version for normal Java later
265 outglobaldefs.println("};");
266 outglobaldefs.println("");
267 outglobaldefs.println("extern struct global_defs_t * global_defs_p;");
268 outglobaldefs.println("#endif");
269 outglobaldefs.flush();
270 outglobaldefs.close();
274 /* Map flags to integers */
275 /* The runtime keeps track of flags using these integers */
276 it=state.getClassSymbolTable().getDescriptorsIterator();
277 while(it.hasNext()) {
278 ClassDescriptor cn=(ClassDescriptor)it.next();
282 generateTaskStructs(outstructs, outmethodheader);
284 /* Outputs generic task structures if this is a task
286 outputTaskTypes(outtask);
289 if( state.MLP || state.OOOJAVA) {
290 // have to initialize some SESE compiler data before
291 // analyzing normal methods, which must happen before
292 // generating SESE internal code
294 Iterator<FlatSESEEnterNode> seseit;
296 seseit=mlpa.getAllSESEs().iterator();
298 seseit=oooa.getAllSESEs().iterator();
301 //TODO signal the object that will report errors
304 rcr = new RuntimeConflictResolver(PREFIX, oooa, state);
305 rcr.setGlobalEffects(oooa.getDisjointAnalysis().getEffectsAnalysis().getAllEffects());
306 } catch (FileNotFoundException e) {
307 System.out.println("Runtime Conflict Resolver could not create output file.");
312 while(seseit.hasNext()){
313 FlatSESEEnterNode fsen = seseit.next();
314 initializeSESE( fsen );
318 /* Build the actual methods */
319 outputMethods(outmethod);
321 // Output function prototypes and structures for SESE's and code
322 if( state.MLP || state.OOOJAVA ) {
324 // spit out a global to inform all worker threads with
325 // the maximum size is for any task record
326 outmethod.println("int "+maxTaskRecSizeStr+" = 0;");
328 // used to differentiate, during code generation, whether we are
329 // passing over SESE body code, or non-SESE code
332 // first generate code for each sese's internals
333 Iterator<FlatSESEEnterNode> seseit;
335 seseit=mlpa.getAllSESEs().iterator();
337 seseit=oooa.getAllSESEs().iterator();
340 while(seseit.hasNext()) {
341 FlatSESEEnterNode fsen = seseit.next();
342 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
345 // then write the invokeSESE switch to decouple scheduler
346 // from having to do unique details of sese invocation
347 generateSESEinvocationMethod(outmethodheader, outmethod);
351 /* Output code for tasks */
352 outputTaskCode(outtaskdefs, outmethod);
354 /* Record maximum number of task parameters */
355 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
356 } else if (state.main!=null) {
357 /* Generate main method */
358 outputMainMethod(outmethod);
361 /* Generate information for task with optional parameters */
362 if (state.TASK&&state.OPTIONAL) {
363 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
364 outoptionalarrays.close();
367 /* Output structure definitions for repair tool */
368 if (state.structfile!=null) {
369 buildRepairStructs(outrepairstructs);
370 outrepairstructs.close();
374 outmethodheader.println("#endif");
375 outmethodheader.close();
377 outstructs.println("#endif");
381 System.out.println("Runtime Conflict Resolver Done.");
385 /* This method goes though the call graph and tag those methods that are
386 * invoked inside static blocks
388 protected void tagMethodInvokedByStaticBlock() {
390 Iterator it_sclasses = this.state.getSClassSymbolTable().getDescriptorsIterator();
391 MethodDescriptor current_md=null;
392 HashSet tovisit=new HashSet();
393 HashSet visited=new HashSet();
395 while(it_sclasses.hasNext()) {
396 ClassDescriptor cd = (ClassDescriptor)it_sclasses.next();
397 MethodDescriptor md = (MethodDescriptor)cd.getMethodTable().get("staticblocks");
403 while(!tovisit.isEmpty()) {
404 current_md=(MethodDescriptor)tovisit.iterator().next();
405 tovisit.remove(current_md);
406 visited.add(current_md);
407 Iterator it_callee = this.callgraph.getCalleeSet(current_md).iterator();
408 while(it_callee.hasNext()) {
409 Descriptor d = (Descriptor)it_callee.next();
410 if(d instanceof MethodDescriptor) {
411 if(!visited.contains(d)) {
412 ((MethodDescriptor)d).setIsInvokedByStatic(true);
418 } // TODO for normal Java version
421 /* This code generates code for each static block and static field
423 protected void outputStaticBlocks(PrintWriter outmethod) {
424 // execute all the static blocks and all the static field initializations
428 /* This code generates code to create a Class object for each class for
431 protected void outputClassObjects(PrintWriter outmethod) {
432 // for each class, initialize its Class object
434 SymbolTable ctbl = this.state.getClassSymbolTable();
435 Iterator it_classes = ctbl.getDescriptorsIterator();
436 while(it_classes.hasNext()) {
437 ClassDescriptor t_cd = (ClassDescriptor)it_classes.next();
438 outmethod.println(" {");
439 outmethod.println(" global_defs_p->"+t_cd.getSafeSymbol()+"classobj.type="+t_cd.getId()+";");
440 outmethod.println(" initlock((struct ___Object___ *)(&(global_defs_p->"+t_cd.getSafeSymbol()+"classobj)));");
441 outmethod.println(" }");
443 } // else TODO normal java version
446 /* This code just generates the main C method for java programs.
447 * The main C method packs up the arguments into a string array
448 * and passes it to the java main method. */
450 protected void outputMainMethod(PrintWriter outmethod) {
451 outmethod.println("int main(int argc, const char *argv[]) {");
452 outmethod.println(" int i;");
454 outputStaticBlocks(outmethod);
455 outputClassObjects(outmethod);
457 if (state.MLP || state.OOOJAVA) {
459 // do a calculation to determine which task record
460 // is the largest, store that as a global value for
461 // allocating records
462 Iterator<FlatSESEEnterNode> seseit;
464 seseit=mlpa.getAllSESEs().iterator();
466 seseit=oooa.getAllSESEs().iterator();
468 while(seseit.hasNext()){
469 FlatSESEEnterNode fsen = seseit.next();
470 outmethod.println("if( sizeof( "+fsen.getSESErecordName()+
471 " ) > "+maxTaskRecSizeStr+
472 " ) { "+maxTaskRecSizeStr+
473 " = sizeof( "+fsen.getSESErecordName()+
477 outmethod.println(" runningSESE = NULL;");
479 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
481 //initializes data structures needed for the RCR traverser
482 if(state.RCR && rcr != null) {
483 outmethod.println(" initializeStructsRCR();");
484 outmethod.println(" createAndFillMasterHashStructureArray();");
489 if (state.DSMRECOVERYSTATS) {
490 outmethod.println("#ifdef RECOVERYSTATS \n");
491 outmethod.println("handle();\n");
492 outmethod.println("#endif\n");
494 outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
495 outmethod.println("handle();\n");
496 outmethod.println("#endif\n");
500 if (state.THREAD||state.DSM||state.SINGLETM) {
501 outmethod.println("initializethreads();");
504 outmethod.println("if (dstmStartup(argv[1])) {");
505 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
506 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
508 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
511 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
512 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
514 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
518 outmethod.println(" for(i=2;i<argc;i++) {");
520 outmethod.println(" for(i=1;i<argc;i++) {");
521 outmethod.println(" int length=strlen(argv[i]);");
522 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
523 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
525 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
528 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
530 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
531 outmethod.println(" }");
533 MethodDescriptor md=typeutil.getMain();
534 ClassDescriptor cd=typeutil.getMainClass();
536 outmethod.println(" {");
537 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
538 if (state.DSM||state.SINGLETM) {
539 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
541 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
542 outmethod.println("1, NULL,"+"stringarray};");
543 if (state.DSM||state.SINGLETM)
544 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
546 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
548 if (state.DSM||state.SINGLETM)
549 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
551 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
553 outmethod.println(" }");
556 outmethod.println("}");
559 if (state.THREAD||state.DSM||state.SINGLETM) {
560 outmethod.println("pthread_mutex_lock(&gclistlock);");
561 outmethod.println("threadcount--;");
562 outmethod.println("pthread_cond_signal(&gccond);");
563 outmethod.println("pthread_mutex_unlock(&gclistlock);");
566 if (state.DSM||state.SINGLETM) {
567 //outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
568 outmethod.println("#if defined(TRANSSTATS) \n");
569 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
570 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
571 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
572 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
574 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
575 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
576 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
577 outmethod.println("printf(\"ndirtyCacheObj= %d\\n\", ndirtyCacheObj);");
578 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
579 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
580 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
581 outmethod.println("printf(\"totalObjSize= %d\\n\", totalObjSize);");
582 outmethod.println("printf(\"sendRemoteReq= %d\\n\", sendRemoteReq);");
583 outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
584 } else if (state.SINGLETM) {
585 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
586 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
587 outmethod.println("#ifdef STMSTATS\n");
588 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
589 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
590 outmethod.println("}\n");
591 outmethod.println("#endif\n");
592 outmethod.println("fflush(stdout);");
594 outmethod.println("#endif\n");
597 if (state.EVENTMONITOR) {
598 outmethod.println("dumpdata();");
601 if (state.THREAD||state.SINGLETM)
602 outmethod.println("pthread_exit(NULL);");
604 if (state.MLP || state.OOOJAVA ) {
605 outmethod.println(" workScheduleBegin();");
608 outmethod.println("}");
611 /* This method outputs code for each task. */
613 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
614 /* Compile task based program */
615 outtaskdefs.println("#include \"task.h\"");
616 outtaskdefs.println("#include \"methodheaders.h\"");
617 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
618 while(taskit.hasNext()) {
619 TaskDescriptor td=(TaskDescriptor)taskit.next();
620 FlatMethod fm=state.getMethodFlat(td);
621 generateFlatMethod(fm, null, outmethod);
622 generateTaskDescriptor(outtaskdefs, fm, td);
625 //Output task descriptors
626 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
627 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
629 while(taskit.hasNext()) {
630 TaskDescriptor td=(TaskDescriptor)taskit.next();
634 outtaskdefs.println(",");
635 outtaskdefs.print("&task_"+td.getSafeSymbol());
637 outtaskdefs.println("};");
639 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
642 /* This method outputs most of the methods.c file. This includes
643 * some standard includes and then an array with the sizes of
644 * objets and array that stores supertype and then the code for
645 * the Java methods.. */
647 protected void outputMethods(PrintWriter outmethod) {
648 outmethod.println("#include \"methodheaders.h\"");
649 outmethod.println("#include \"virtualtable.h\"");
650 outmethod.println("#include \"runtime.h\"");
652 // always include: compiler directives will leave out
653 // instrumentation when option is not set
654 outmethod.println("#include \"coreprof/coreprof.h\"");
657 outmethod.println("#include \"sandboxdefs.c\"");
660 outmethod.println("#include \"addPrefetchEnhance.h\"");
661 outmethod.println("#include \"localobjects.h\"");
663 if (state.FASTCHECK) {
664 outmethod.println("#include \"localobjects.h\"");
666 if(state.MULTICORE) {
668 outmethod.println("#include \"task.h\"");
670 outmethod.println("#include \"multicoreruntime.h\"");
671 outmethod.println("#include \"runtime_arch.h\"");
673 if (state.THREAD||state.DSM||state.SINGLETM) {
674 outmethod.println("#include <thread.h>");
677 outmethod.println("#include \"thread.h\"");
679 if (state.main!=null) {
680 outmethod.println("#include <string.h>");
682 if (state.CONSCHECK) {
683 outmethod.println("#include \"checkers.h\"");
685 if (state.MLP || state.OOOJAVA ) {
686 outmethod.println("#include <stdlib.h>");
687 outmethod.println("#include <stdio.h>");
688 outmethod.println("#include \"mlp_runtime.h\"");
689 outmethod.println("#include \"psemaphore.h\"");
692 outmethod.println("#include \"trqueue.h\"");
693 outmethod.println("#include \"RuntimeConflictResolver.h\"");
694 outmethod.println("#include \"rcr_runtime.h\"");
695 outmethod.println("#include \"hashStructure.h\"");
700 // TODO add version for normal Java later
701 outmethod.println("struct global_defs_t * global_defs_p;");
703 //Store the sizes of classes & array elements
704 generateSizeArray(outmethod);
706 //Store table of supertypes
707 generateSuperTypeTable(outmethod);
709 //Store the layout of classes
710 generateLayoutStructs(outmethod);
712 /* Generate code for methods */
713 if (state.DSM||state.SINGLETM) {
714 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
715 LocalityBinding lb=lbit.next();
716 MethodDescriptor md=lb.getMethod();
717 FlatMethod fm=state.getMethodFlat(md);
719 if (!md.getModifiers().isNative()) {
720 generateFlatMethod(fm, lb, outmethod);
721 //System.out.println("fm= " + fm + " md= " + md);
725 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
726 while(classit.hasNext()) {
727 ClassDescriptor cn=(ClassDescriptor)classit.next();
728 Iterator methodit=cn.getMethods();
729 while(methodit.hasNext()) {
730 /* Classify parameters */
731 MethodDescriptor md=(MethodDescriptor)methodit.next();
732 FlatMethod fm=state.getMethodFlat(md);
733 if (!md.getModifiers().isNative()) {
734 generateFlatMethod(fm, null, outmethod);
741 protected void outputStructs(PrintWriter outstructs) {
742 outstructs.println("#ifndef STRUCTDEFS_H");
743 outstructs.println("#define STRUCTDEFS_H");
744 outstructs.println("#include \"classdefs.h\"");
745 outstructs.println("#ifndef INTPTR");
746 outstructs.println("#ifdef BIT64");
747 outstructs.println("#define INTPTR long");
748 outstructs.println("#else");
749 outstructs.println("#define INTPTR int");
750 outstructs.println("#endif");
751 outstructs.println("#endif");
752 if( state.MLP || state.OOOJAVA ) {
753 outstructs.println("#include \"mlp_runtime.h\"");
754 outstructs.println("#include \"psemaphore.h\"");
757 outstructs.println("#include \"rcr_runtime.h\"");
761 /* Output #defines that the runtime uses to determine type
762 * numbers for various objects it needs */
763 outstructs.println("#define MAXCOUNT "+maxcount);
764 if (state.DSM||state.SINGLETM) {
765 LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
767 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
769 else if (state.SINGLETM) {
770 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
772 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
776 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
778 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
779 else if( state.SINGLETM)
780 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
781 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
784 outstructs.println("#define STRINGARRAYTYPE "+
785 (state.getArrayNumber(
786 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
788 outstructs.println("#define OBJECTARRAYTYPE "+
789 (state.getArrayNumber(
790 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
793 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
794 outstructs.println("#define CHARARRAYTYPE "+
795 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
797 outstructs.println("#define BYTEARRAYTYPE "+
798 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
800 outstructs.println("#define BYTEARRAYARRAYTYPE "+
801 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
803 outstructs.println("#define NUMCLASSES "+state.numClasses());
804 int totalClassSize = state.numClasses() + state.numArrays();
805 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
807 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
808 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
809 outstructs.println("#define TAGARRAYTYPE "+
810 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
814 protected void outputClassDeclarations(PrintWriter outclassdefs, PrintWriter outglobaldefs) {
815 if (state.THREAD||state.DSM||state.SINGLETM)
816 outclassdefs.println("#include <pthread.h>");
817 outclassdefs.println("#ifndef INTPTR");
818 outclassdefs.println("#ifdef BIT64");
819 outclassdefs.println("#define INTPTR long");
820 outclassdefs.println("#else");
821 outclassdefs.println("#define INTPTR int");
822 outclassdefs.println("#endif");
823 outclassdefs.println("#endif");
825 outclassdefs.println("#include \"optionalstruct.h\"");
826 outclassdefs.println("struct "+arraytype+";");
827 /* Start by declaring all structs */
828 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
829 while(it.hasNext()) {
830 ClassDescriptor cn=(ClassDescriptor)it.next();
831 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
834 // TODO add version for normal Java later
835 if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
836 // this class has static fields/blocks, need to add a global flag to
837 // indicate if its static fields have been initialized and/or if its
838 // static blocks have been executed
839 outglobaldefs.println(" int "+cn.getSafeSymbol()+"static_block_exe_flag;");
842 // for each class, create a global object
843 outglobaldefs.println(" struct Class "+cn.getSafeSymbol()+"classobj;");
846 outclassdefs.println("");
847 //Print out definition for array type
848 outclassdefs.println("struct "+arraytype+" {");
849 outclassdefs.println(" int type;");
850 if(state.MLP || state.OOOJAVA ){
851 outclassdefs.println(" int oid;");
852 outclassdefs.println(" int allocsite;");
854 if (state.EVENTMONITOR) {
855 outclassdefs.println(" int objuid;");
858 outclassdefs.println(" pthread_t tid;");
859 outclassdefs.println(" void * lockentry;");
860 outclassdefs.println(" int lockcount;");
863 outclassdefs.println(" int mutex;");
864 outclassdefs.println(" int objlock;");
865 if(state.MULTICOREGC) {
866 outclassdefs.println(" int marked;");
870 outclassdefs.println(" int flag;");
871 if(!state.MULTICORE) {
872 outclassdefs.println(" void * flagptr;");
874 outclassdefs.println(" int version;");
875 outclassdefs.println(" int * lock;"); // lock entry for this obj
876 outclassdefs.println(" int mutex;");
877 outclassdefs.println(" int lockcount;");
878 if(state.MULTICOREGC) {
879 outclassdefs.println(" int marked;");
883 outclassdefs.println(" int numfses;");
884 outclassdefs.println(" int * fses;");
887 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs, outglobaldefs);
889 if (state.STMARRAY) {
890 outclassdefs.println(" int lowindex;");
891 outclassdefs.println(" int highindex;");
894 outclassdefs.println(" int paddingforarray;");
895 if (state.DUALVIEW) {
896 outclassdefs.println(" int arrayversion;");
899 outclassdefs.println(" int ___length___;");
900 outclassdefs.println("};\n");
903 // TODO add version for normal Java later
904 outclassdefs.println("");
905 //Print out definition for Class type
906 outclassdefs.println("struct Class {");
907 outclassdefs.println(" int type;");
908 if(state.MLP || state.OOOJAVA ){
909 outclassdefs.println(" int oid;");
910 outclassdefs.println(" int allocsite;");
912 if (state.EVENTMONITOR) {
913 outclassdefs.println(" int objuid;");
916 outclassdefs.println(" pthread_t tid;");
917 outclassdefs.println(" void * lockentry;");
918 outclassdefs.println(" int lockcount;");
921 outclassdefs.println(" int mutex;");
922 outclassdefs.println(" int objlock;");
923 if(state.MULTICOREGC) {
924 outclassdefs.println(" int marked;");
928 outclassdefs.println(" int flag;");
929 if(!state.MULTICORE) {
930 outclassdefs.println(" void * flagptr;");
932 outclassdefs.println(" int version;");
933 outclassdefs.println(" int * lock;"); // lock entry for this obj
934 outclassdefs.println(" int mutex;");
935 outclassdefs.println(" int lockcount;");
936 if(state.MULTICOREGC) {
937 outclassdefs.println(" int marked;");
941 outclassdefs.println(" int numfses;");
942 outclassdefs.println(" int * fses;");
945 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs, outglobaldefs);
946 outclassdefs.println("};\n");
949 outclassdefs.println("");
950 outclassdefs.println("extern int classsize[];");
951 outclassdefs.println("extern int hasflags[];");
952 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
953 outclassdefs.println("extern int supertypes[];");
955 // TODO add version for normal Java later
956 outclassdefs.println("#include \"globaldefs.h\"");
958 outclassdefs.println("");
961 /** Prints out definitions for generic task structures */
963 private void outputTaskTypes(PrintWriter outtask) {
964 outtask.println("#ifndef _TASK_H");
965 outtask.println("#define _TASK_H");
966 outtask.println("struct parameterdescriptor {");
967 outtask.println("int type;");
968 outtask.println("int numberterms;");
969 outtask.println("int *intarray;");
970 outtask.println("void * queue;");
971 outtask.println("int numbertags;");
972 outtask.println("int *tagarray;");
973 outtask.println("};");
975 outtask.println("struct taskdescriptor {");
976 outtask.println("void * taskptr;");
977 outtask.println("int numParameters;");
978 outtask.println(" int numTotal;");
979 outtask.println("struct parameterdescriptor **descriptorarray;");
980 outtask.println("char * name;");
981 outtask.println("};");
982 outtask.println("extern struct taskdescriptor * taskarray[];");
983 outtask.println("extern numtasks;");
984 outtask.println("#endif");
988 private void buildRepairStructs(PrintWriter outrepairstructs) {
989 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
990 while(classit.hasNext()) {
991 ClassDescriptor cn=(ClassDescriptor)classit.next();
992 outrepairstructs.println("structure "+cn.getSymbol()+" {");
993 outrepairstructs.println(" int __type__;");
995 outrepairstructs.println(" int __flag__;");
996 if(!state.MULTICORE) {
997 outrepairstructs.println(" int __flagptr__;");
1000 printRepairStruct(cn, outrepairstructs);
1001 outrepairstructs.println("}\n");
1004 for(int i=0; i<state.numArrays(); i++) {
1005 TypeDescriptor tdarray=arraytable[i];
1006 TypeDescriptor tdelement=tdarray.dereference();
1007 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
1008 outrepairstructs.println(" int __type__;");
1009 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
1010 outrepairstructs.println(" int length;");
1012 // Need to add support to repair tool for this
1013 if (tdelement.isClass()||tdelement.isArray())
1014 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
1016 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
1018 outrepairstructs.println("}\n");
1022 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
1023 ClassDescriptor sp=cn.getSuperDesc();
1025 printRepairStruct(sp, output);
1027 Vector fields=(Vector)fieldorder.get(cn);
1029 for(int i=0; i<fields.size(); i++) {
1030 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1031 if (fd.getType().isArray()) {
1032 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
1033 } else if (fd.getType().isClass())
1034 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
1035 else if (fd.getType().isFloat())
1036 output.println(" int "+fd.getSymbol()+"; /* really float */");
1038 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
1042 /** This method outputs TaskDescriptor information */
1043 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
1044 for (int i=0; i<task.numParameters(); i++) {
1045 VarDescriptor param_var=task.getParameter(i);
1046 TypeDescriptor param_type=task.getParamType(i);
1047 FlagExpressionNode param_flag=task.getFlag(param_var);
1048 TagExpressionList param_tag=task.getTag(param_var);
1051 if (param_flag==null) {
1052 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
1053 output.println("0x0, 0x0 };");
1056 DNFFlag dflag=param_flag.getDNF();
1057 dnfterms=dflag.size();
1059 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
1060 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
1061 for(int j=0; j<dflag.size(); j++) {
1063 output.println(",");
1064 Vector term=dflag.get(j);
1067 for(int k=0; k<term.size(); k++) {
1068 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
1069 FlagDescriptor fd=dfa.getFlag();
1070 boolean negated=dfa.getNegated();
1071 int flagid=1<<((Integer)flags.get(fd)).intValue();
1076 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
1078 output.println("};");
1081 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
1082 //BUG...added next line to fix, test with any task program
1083 if (param_tag!=null)
1084 for(int j=0; j<param_tag.numTags(); j++) {
1086 output.println(",");
1087 /* for each tag we need */
1088 /* which slot it is */
1089 /* what type it is */
1090 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
1091 TempDescriptor tmp=param_tag.getTemp(j);
1092 int slot=fm.getTagInt(tmp);
1093 output.println(slot+", "+state.getTagId(tvd.getTag()));
1095 output.println("};");
1097 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
1098 output.println("/* type */"+param_type.getClassDesc().getId()+",");
1099 output.println("/* number of DNF terms */"+dnfterms+",");
1100 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
1101 output.println("0,");
1102 //BUG, added next line to fix and else statement...test
1103 //with any task program
1104 if (param_tag!=null)
1105 output.println("/* number of tags */"+param_tag.numTags()+",");
1107 output.println("/* number of tags */ 0,");
1108 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
1109 output.println("};");
1113 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
1114 for (int i=0; i<task.numParameters(); i++) {
1116 output.println(",");
1117 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
1119 output.println("};");
1121 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
1122 output.println("&"+task.getSafeSymbol()+",");
1123 output.println("/* number of parameters */" +task.numParameters() + ",");
1124 int numtotal=task.numParameters()+fm.numTags();
1125 output.println("/* number total parameters */" +numtotal + ",");
1126 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
1127 output.println("\""+task.getSymbol()+"\"");
1128 output.println("};");
1132 /** The buildVirtualTables method outputs the virtual dispatch
1133 * tables for methods. */
1135 protected void buildVirtualTables(PrintWriter outvirtual) {
1136 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
1137 while(classit.hasNext()) {
1138 ClassDescriptor cd=(ClassDescriptor)classit.next();
1139 if (virtualcalls.getMethodCount(cd)>maxcount)
1140 maxcount=virtualcalls.getMethodCount(cd);
1142 MethodDescriptor[][] virtualtable=null;
1143 LocalityBinding[][] lbvirtualtable=null;
1144 if (state.DSM||state.SINGLETM)
1145 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
1147 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
1149 /* Fill in virtual table */
1150 classit=state.getClassSymbolTable().getDescriptorsIterator();
1151 while(classit.hasNext()) {
1152 ClassDescriptor cd=(ClassDescriptor)classit.next();
1153 if(cd.isInterface()) {
1156 if (state.DSM||state.SINGLETM)
1157 fillinRow(cd, lbvirtualtable, cd.getId());
1159 fillinRow(cd, virtualtable, cd.getId());
1162 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
1163 Iterator arrayit=state.getArrayIterator();
1164 while(arrayit.hasNext()) {
1165 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1166 int id=state.getArrayNumber(td);
1167 if (state.DSM||state.SINGLETM)
1168 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
1170 fillinRow(objectcd, virtualtable, id+state.numClasses());
1173 outvirtual.print("void * virtualtable[]={");
1174 boolean needcomma=false;
1175 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
1176 for(int j=0; j<maxcount; j++) {
1178 outvirtual.print(", ");
1179 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
1180 LocalityBinding lb=lbvirtualtable[i][j];
1181 MethodDescriptor md=lb.getMethod();
1182 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
1183 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
1184 MethodDescriptor md=virtualtable[i][j];
1185 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
1187 outvirtual.print("0");
1191 outvirtual.println("");
1193 outvirtual.println("};");
1197 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
1198 /* Get inherited methods */
1199 if (cd.getSuperDesc()!=null)
1200 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
1202 // TODO add version for normal Java later
1203 Iterator it_sifs = cd.getSuperInterfaces();
1204 while(it_sifs.hasNext()) {
1205 ClassDescriptor superif = (ClassDescriptor)it_sifs.next();
1206 fillinRow(superif, virtualtable, rownum);
1209 /* Override them with our methods */
1210 for(Iterator it=cd.getMethods(); it.hasNext();) {
1211 MethodDescriptor md=(MethodDescriptor)it.next();
1212 if (md.isStatic()||md.getReturnType()==null)
1214 int methodnum=virtualcalls.getMethodNumber(md);
1215 virtualtable[rownum][methodnum]=md;
1219 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
1220 /* Get inherited methods */
1221 if (cd.getSuperDesc()!=null)
1222 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
1223 /* Override them with our methods */
1224 if (locality.getClassBindings(cd)!=null)
1225 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
1226 LocalityBinding lb=lbit.next();
1227 MethodDescriptor md=lb.getMethod();
1228 //Is the method static or a constructor
1229 if (md.isStatic()||md.getReturnType()==null)
1231 int methodnum=virtualcalls.getLocalityNumber(lb);
1232 virtualtable[rownum][methodnum]=lb;
1236 /** Generate array that contains the sizes of class objects. The
1237 * object allocation functions in the runtime use this
1240 private void generateSizeArray(PrintWriter outclassdefs) {
1241 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
1242 outclassdefs.print("#ifdef TRANSSTATS \n");
1243 outclassdefs.print("extern int numTransAbort;\n");
1244 outclassdefs.print("extern int numTransCommit;\n");
1245 outclassdefs.print("extern int nSoftAbort;\n");
1247 outclassdefs.print("extern int nchashSearch;\n");
1248 outclassdefs.print("extern int nmhashSearch;\n");
1249 outclassdefs.print("extern int nprehashSearch;\n");
1250 outclassdefs.print("extern int ndirtyCacheObj;\n");
1251 outclassdefs.print("extern int nRemoteSend;\n");
1252 outclassdefs.print("extern int sendRemoteReq;\n");
1253 outclassdefs.print("extern int getResponse;\n");
1254 outclassdefs.print("extern int bytesSent;\n");
1255 outclassdefs.print("extern int bytesRecv;\n");
1256 outclassdefs.print("extern int totalObjSize;\n");
1257 outclassdefs.print("extern void handle();\n");
1258 } else if (state.SINGLETM) {
1259 outclassdefs.println("extern int nSoftAbortAbort;");
1260 outclassdefs.println("extern int nSoftAbortCommit;");
1261 outclassdefs.println("#ifdef STMSTATS\n");
1262 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
1263 outclassdefs.println("#endif\n");
1265 outclassdefs.print("#endif\n");
1267 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
1268 if(this.state.MLP || state.OOOJAVA ){
1269 outclassdefs.print("extern __thread int oid;\n");
1270 outclassdefs.print("extern int oidIncrement;\n");
1273 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1274 cdarray=new ClassDescriptor[state.numClasses()];
1276 while(it.hasNext()) {
1277 ClassDescriptor cd=(ClassDescriptor)it.next();
1278 if(!cd.isInterface()) {
1279 cdarray[cd.getId()]=cd;
1283 arraytable=new TypeDescriptor[state.numArrays()];
1285 Iterator arrayit=state.getArrayIterator();
1286 while(arrayit.hasNext()) {
1287 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1288 int id=state.getArrayNumber(td);
1294 /* Print out types */
1295 outclassdefs.println("/* ");
1296 for(int i=0; i<state.numClasses(); i++) {
1297 ClassDescriptor cd=cdarray[i];
1299 outclassdefs.println("NULL " + i);
1301 outclassdefs.println(cd +" "+i);
1305 for(int i=0; i<state.numArrays(); i++) {
1306 TypeDescriptor arraytd=arraytable[i];
1307 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
1310 outclassdefs.println("*/");
1313 outclassdefs.print("int classsize[]={");
1315 boolean needcomma=false;
1316 for(int i=0; i<state.numClasses(); i++) {
1318 outclassdefs.print(", ");
1320 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1322 outclassdefs.print("0");
1328 for(int i=0; i<state.numArrays(); i++) {
1330 outclassdefs.print(", ");
1331 TypeDescriptor tdelement=arraytable[i].dereference();
1332 if (tdelement.isArray()||tdelement.isClass())
1333 outclassdefs.print("sizeof(void *)");
1335 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1339 outclassdefs.println("};");
1341 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1343 outclassdefs.print("int typearray[]={");
1344 for(int i=0; i<state.numClasses(); i++) {
1345 ClassDescriptor cd=cdarray[i];
1346 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1348 outclassdefs.print(", ");
1350 outclassdefs.print("-1");
1352 outclassdefs.print(supercd.getId());
1356 for(int i=0; i<state.numArrays(); i++) {
1357 TypeDescriptor arraytd=arraytable[i];
1358 ClassDescriptor arraycd=arraytd.getClassDesc();
1359 if (arraycd==null) {
1361 outclassdefs.print(", ");
1362 outclassdefs.print(objectclass.getId());
1366 ClassDescriptor cd=arraycd.getSuperDesc();
1369 TypeDescriptor supertd=new TypeDescriptor(cd);
1370 supertd.setArrayCount(arraytd.getArrayCount());
1371 type=state.getArrayNumber(supertd);
1373 type+=state.numClasses();
1376 cd=cd.getSuperDesc();
1379 outclassdefs.print(", ");
1380 outclassdefs.print(type);
1384 outclassdefs.println("};");
1389 outclassdefs.print("int typearray2[]={");
1390 for(int i=0; i<state.numArrays(); i++) {
1391 TypeDescriptor arraytd=arraytable[i];
1392 ClassDescriptor arraycd=arraytd.getClassDesc();
1393 if (arraycd==null) {
1395 outclassdefs.print(", ");
1396 outclassdefs.print("-1");
1400 ClassDescriptor cd=arraycd.getSuperDesc();
1401 int level=arraytd.getArrayCount()-1;
1403 for(; level>0; level--) {
1404 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1405 supertd.setArrayCount(level);
1406 type=state.getArrayNumber(supertd);
1408 type+=state.numClasses();
1413 outclassdefs.print(", ");
1414 outclassdefs.print(type);
1418 outclassdefs.println("};");
1421 /** Constructs params and temp objects for each method or task.
1422 * These objects tell the compiler which temps need to be
1425 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1426 MethodDescriptor md=fm.getMethod();
1427 TaskDescriptor task=fm.getTask();
1428 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1429 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1431 paramstable.put(lb, objectparams);
1432 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1433 } else if (md!=null)
1434 paramstable.put(md, objectparams);
1436 paramstable.put(task, objectparams);
1438 for(int i=0; i<fm.numParameters(); i++) {
1439 TempDescriptor temp=fm.getParameter(i);
1440 TypeDescriptor type=temp.getType();
1441 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1442 objectparams.addPtr(temp);
1444 objectparams.addPrim(temp);
1445 if(lb!=null&&saveset.contains(temp)) {
1446 backuptable.get(lb).put(temp, temp.createNew());
1450 for(int i=0; i<fm.numTags(); i++) {
1451 TempDescriptor temp=fm.getTag(i);
1452 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1453 objectparams.addPtr(temp);
1455 objectparams.addPrim(temp);
1458 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1460 tempstable.put(lb, objecttemps);
1462 tempstable.put(md, objecttemps);
1464 tempstable.put(task, objecttemps);
1466 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1467 FlatNode fn=(FlatNode)nodeit.next();
1468 TempDescriptor[] writes=fn.writesTemps();
1469 for(int i=0; i<writes.length; i++) {
1470 TempDescriptor temp=writes[i];
1471 TypeDescriptor type=temp.getType();
1472 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1473 objecttemps.addPtr(temp);
1475 objecttemps.addPrim(temp);
1476 if(lb!=null&&saveset.contains(temp)&&
1477 !backuptable.get(lb).containsKey(temp))
1478 backuptable.get(lb).put(temp, temp.createNew());
1482 /* Create backup temps */
1484 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1485 TempDescriptor tmp=tmpit.next();
1486 TypeDescriptor type=tmp.getType();
1487 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1488 objecttemps.addPtr(tmp);
1490 objecttemps.addPrim(tmp);
1492 /* Create temp to hold revert table */
1493 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1494 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1495 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1496 objecttemps.addPtr(reverttmp);
1498 objecttemps.addPrim(reverttmp);
1499 reverttable.put(lb, reverttmp);
1504 /** This method outputs the following information about classes
1506 * (1) For classes, what are the locations of pointers.
1507 * (2) For arrays, does the array contain pointers or primitives.
1508 * (3) For classes, does the class contain flags.
1511 private void generateLayoutStructs(PrintWriter output) {
1512 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1513 while(it.hasNext()) {
1514 ClassDescriptor cn=(ClassDescriptor)it.next();
1515 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1516 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1518 while(allit.hasNext()) {
1519 FieldDescriptor fd=(FieldDescriptor)allit.next();
1520 TypeDescriptor type=fd.getType();
1521 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1526 output.print(count);
1527 allit=cn.getFieldTable().getAllDescriptorsIterator();
1528 while(allit.hasNext()) {
1529 FieldDescriptor fd=(FieldDescriptor)allit.next();
1530 TypeDescriptor type=fd.getType();
1531 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1534 output.println(",");
1535 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1538 output.println("};");
1540 output.println("unsigned INTPTR * pointerarray[]={");
1541 boolean needcomma=false;
1542 for(int i=0; i<state.numClasses(); i++) {
1543 ClassDescriptor cn=cdarray[i];
1545 output.println(",");
1548 output.print(cn.getSafeSymbol()+"_pointers");
1550 output.print("NULL");
1554 for(int i=0; i<state.numArrays(); i++) {
1556 output.println(", ");
1557 TypeDescriptor tdelement=arraytable[i].dereference();
1558 if (tdelement.isArray()||tdelement.isClass())
1559 output.print("((unsigned INTPTR *)1)");
1565 output.println("};");
1567 output.println("int hasflags[]={");
1568 for(int i=0; i<state.numClasses(); i++) {
1569 ClassDescriptor cn=cdarray[i];
1571 output.println(", ");
1573 if ((cn != null) && (cn.hasFlags()))
1578 output.println("};");
1581 /** Print out table to give us supertypes */
1582 private void generateSuperTypeTable(PrintWriter output) {
1583 output.println("int supertypes[]={");
1584 boolean needcomma=false;
1585 for(int i=0; i<state.numClasses(); i++) {
1586 ClassDescriptor cn=cdarray[i];
1588 output.println(",");
1590 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1591 ClassDescriptor cdsuper=cn.getSuperDesc();
1592 output.print(cdsuper.getId());
1596 output.println("};");
1599 /** Force consistent field ordering between inherited classes. */
1601 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout, PrintWriter globaldefout) {
1603 ClassDescriptor sp=cn.getSuperDesc();
1605 printClassStruct(sp, classdefout, globaldefout);
1607 if (!fieldorder.containsKey(cn)) {
1608 Vector fields=new Vector();
1609 fieldorder.put(cn,fields);
1610 Vector fieldvec=cn.getFieldVec();
1611 for(int i=0;i<fieldvec.size();i++) {
1612 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1613 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1617 Vector fields=(Vector)fieldorder.get(cn);
1619 for(int i=0; i<fields.size(); i++) {
1620 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1621 if (fd.getType().isClass()||fd.getType().isArray())
1622 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1623 else if ((state.MGC) && (fd.isStatic())) {
1624 // TODO add version for normal Java later
1626 if(fd.isVolatile()) {
1627 globaldefout.println(" volatile "+fd.getType().getSafeSymbol()+ " "+cn.getSafeSymbol()+fd.getSafeSymbol()+";");
1629 globaldefout.println(" "+fd.getType().getSafeSymbol()+ " "+cn.getSafeSymbol()+fd.getSafeSymbol()+";");
1631 classdefout.println(" "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1632 } else if ((state.MGC) && (fd.isVolatile())) {
1633 // TODO add version for normal Java later
1635 globaldefout.println(" volatile "+fd.getType().getSafeSymbol()+ " "+cn.getSafeSymbol()+fd.getSafeSymbol()+";");
1636 classdefout.println(" "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1638 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1643 /* Map flags to integers consistently between inherited
1646 protected void mapFlags(ClassDescriptor cn) {
1647 ClassDescriptor sp=cn.getSuperDesc();
1651 if (!flagorder.containsKey(cn)) {
1652 Hashtable flags=new Hashtable();
1653 flagorder.put(cn,flags);
1655 Hashtable superflags=(Hashtable)flagorder.get(sp);
1656 Iterator superflagit=superflags.keySet().iterator();
1657 while(superflagit.hasNext()) {
1658 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1659 Integer number=(Integer)superflags.get(fd);
1660 flags.put(fd, number);
1661 if ((number.intValue()+1)>max)
1662 max=number.intValue()+1;
1666 Iterator flagit=cn.getFlags();
1667 while(flagit.hasNext()) {
1668 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1669 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1670 flags.put(fd, new Integer(max++));
1676 /** This function outputs (1) structures that parameters are
1677 * passed in (when PRECISE GC is enabled) and (2) function
1678 * prototypes for the methods */
1680 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout, PrintWriter globaldefout) {
1681 /* Output class structure */
1682 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1683 classdefout.println(" int type;");
1684 if(state.MLP || state.OOOJAVA){
1685 classdefout.println(" int oid;");
1686 classdefout.println(" int allocsite;");
1688 if (state.EVENTMONITOR) {
1689 classdefout.println(" int objuid;");
1692 classdefout.println(" pthread_t tid;");
1693 classdefout.println(" void * lockentry;");
1694 classdefout.println(" int lockcount;");
1697 classdefout.println(" int mutex;");
1698 classdefout.println(" int objlock;");
1699 if(state.MULTICOREGC) {
1700 classdefout.println(" int marked;");
1704 classdefout.println(" int flag;");
1705 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1706 classdefout.println(" void * flagptr;");
1707 } else if (state.MULTICORE) {
1708 classdefout.println(" int version;");
1709 classdefout.println(" int * lock;"); // lock entry for this obj
1710 classdefout.println(" int mutex;");
1711 classdefout.println(" int lockcount;");
1712 if(state.MULTICOREGC) {
1713 classdefout.println(" int marked;");
1716 if (state.OPTIONAL) {
1717 classdefout.println(" int numfses;");
1718 classdefout.println(" int * fses;");
1721 printClassStruct(cn, classdefout, globaldefout);
1722 classdefout.println("};\n");
1724 if (state.DSM||state.SINGLETM) {
1725 /* Cycle through LocalityBindings */
1726 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1727 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1729 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1730 LocalityBinding lb=lbit.next();
1731 MethodDescriptor md=lb.getMethod();
1732 if (md.getModifiers().isNative()) {
1733 //make sure we only print a native method once
1734 if (nativemethods.contains(md)) {
1735 FlatMethod fm=state.getMethodFlat(md);
1736 generateTempStructs(fm, lb);
1739 nativemethods.add(md);
1741 generateMethod(cn, md, lb, headersout, output);
1744 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1745 MethodDescriptor md=(MethodDescriptor)methodit.next();
1746 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1747 //Need to build param structure for library code
1748 FlatMethod fm=state.getMethodFlat(md);
1749 generateTempStructs(fm, null);
1750 generateMethodParam(cn, md, null, output);
1755 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1756 MethodDescriptor md=(MethodDescriptor)methodit.next();
1757 generateMethod(cn, md, null, headersout, output);
1761 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1762 /* Output parameter structure */
1763 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1764 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1765 if ((state.DSM||state.SINGLETM)&&lb!=null)
1766 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1768 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1769 output.println(" int size;");
1770 output.println(" void * next;");
1771 for(int i=0; i<objectparams.numPointers(); i++) {
1772 TempDescriptor temp=objectparams.getPointer(i);
1773 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1775 output.println("};\n");
1779 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1780 FlatMethod fm=state.getMethodFlat(md);
1781 generateTempStructs(fm, lb);
1783 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1784 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1786 generateMethodParam(cn, md, lb, output);
1788 /* Output temp structure */
1789 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1790 if (state.DSM||state.SINGLETM)
1791 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1793 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1794 output.println(" int size;");
1795 output.println(" void * next;");
1796 for(int i=0; i<objecttemps.numPointers(); i++) {
1797 TempDescriptor temp=objecttemps.getPointer(i);
1798 if (temp.getType().isNull())
1799 output.println(" void * "+temp.getSafeSymbol()+";");
1801 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1803 output.println("};\n");
1806 /********* Output method declaration ***********/
1807 if (state.DSM||state.SINGLETM) {
1808 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1810 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1812 /* First the return type */
1813 if (md.getReturnType()!=null) {
1814 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1815 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1817 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1819 //catch the constructor case
1820 headersout.print("void ");
1822 /* Next the method name */
1823 if (state.DSM||state.SINGLETM) {
1824 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1826 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1828 boolean printcomma=false;
1829 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1830 if (state.DSM||state.SINGLETM) {
1831 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1833 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1837 /* Output parameter list*/
1838 for(int i=0; i<objectparams.numPrimitives(); i++) {
1839 TempDescriptor temp=objectparams.getPrimitive(i);
1841 headersout.print(", ");
1843 if (temp.getType().isClass()||temp.getType().isArray())
1844 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1846 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1848 headersout.println(");\n");
1852 /** This function outputs (1) structures that parameters are
1853 * passed in (when PRECISE GC is enabled) and (2) function
1854 * prototypes for the tasks */
1856 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1857 /* Cycle through tasks */
1858 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1860 while(taskit.hasNext()) {
1861 /* Classify parameters */
1862 TaskDescriptor task=(TaskDescriptor)taskit.next();
1863 FlatMethod fm=state.getMethodFlat(task);
1864 generateTempStructs(fm, null);
1866 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1867 TempObject objecttemps=(TempObject) tempstable.get(task);
1869 /* Output parameter structure */
1870 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1871 output.println("struct "+task.getSafeSymbol()+"_params {");
1872 output.println(" int size;");
1873 output.println(" void * next;");
1874 for(int i=0; i<objectparams.numPointers(); i++) {
1875 TempDescriptor temp=objectparams.getPointer(i);
1876 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1879 output.println("};\n");
1880 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1881 maxtaskparams=objectparams.numPointers()+fm.numTags();
1885 /* Output temp structure */
1886 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1887 output.println("struct "+task.getSafeSymbol()+"_locals {");
1888 output.println(" int size;");
1889 output.println(" void * next;");
1890 for(int i=0; i<objecttemps.numPointers(); i++) {
1891 TempDescriptor temp=objecttemps.getPointer(i);
1892 if (temp.getType().isNull())
1893 output.println(" void * "+temp.getSafeSymbol()+";");
1894 else if(temp.getType().isTag())
1895 output.println(" struct "+
1896 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1898 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1900 output.println("};\n");
1903 /* Output task declaration */
1904 headersout.print("void " + task.getSafeSymbol()+"(");
1906 boolean printcomma=false;
1907 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1908 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1910 headersout.print("void * parameterarray[]");
1911 headersout.println(");\n");
1915 /***** Generate code for FlatMethod fm. *****/
1917 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1918 static int atomicmethodcount=0;
1921 BranchAnalysis branchanalysis;
1922 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1923 if (State.PRINTFLAT)
1924 System.out.println(fm.printMethod());
1925 MethodDescriptor md=fm.getMethod();
1926 TaskDescriptor task=fm.getTask();
1927 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1928 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1930 HashSet<AtomicRecord> arset=null;
1931 branchanalysis=null;
1933 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1935 if (atomicmethodmap==null)
1936 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1938 //fix these so we get right strings for local variables
1939 localsprefixaddr=localsprefix;
1940 localsprefixderef=localsprefix+"->";
1941 arset=new HashSet<AtomicRecord>();
1943 //build branchanalysis
1944 branchanalysis=new BranchAnalysis(locality, lb, delaycomp.getNotReady(lb), delaycomp.livecode(lb), state);
1946 //Generate commit methods here
1947 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1948 FlatNode fn=fnit.next();
1949 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1950 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
1951 delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
1952 //We have an atomic enter
1953 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1954 Set<FlatNode> exitset=faen.getExits();
1956 String methodname=md.getSymbol()+(atomicmethodcount++);
1957 AtomicRecord ar=new AtomicRecord();
1961 atomicmethodmap.put(faen, ar);
1963 //build data structure declaration
1964 output.println("struct atomicprimitives_"+methodname+" {");
1966 Set<FlatNode> recordset=delaycomp.livecode(lb);
1967 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1968 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1969 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1971 ar.reallivein=new HashSet(liveinto);
1973 ar.liveoutvirtualread=liveoutvirtualread;
1976 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1977 TempDescriptor tmp=it.next();
1978 //remove the pointers
1979 if (tmp.getType().isPtr()) {
1982 //let's print it here
1983 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1986 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1987 TempDescriptor tmp=it.next();
1988 //remove the pointers
1989 if (tmp.getType().isPtr()) {
1991 } else if (!liveinto.contains(tmp)) {
1992 //let's print it here
1993 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1996 output.println("};");
1998 //print out method name
1999 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) {");
2000 //build code for commit method
2002 //first define local primitives
2003 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
2004 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
2005 TempDescriptor tmp=tmpit.next();
2006 if (!tmp.getType().isPtr()) {
2007 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
2008 //read from live into set
2009 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
2012 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
2016 //turn off write barrier generation
2018 state.SINGLETM=false;
2019 generateCode(faen, fm, lb, exitset, output, false);
2020 state.SINGLETM=true;
2021 //turn on write barrier generation
2023 output.println("}\n\n");
2027 //redefine these back to normal
2029 localsprefixaddr="&"+localsprefix;
2030 localsprefixderef=localsprefix+".";
2032 generateHeader(fm, lb, md!=null ? md : task,output);
2033 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2035 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2036 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
2037 AtomicRecord ar=arit.next();
2038 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
2042 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2043 if (md!=null&&(state.DSM||state.SINGLETM))
2044 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2045 else if (md!=null&&!(state.DSM||state.SINGLETM))
2046 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2048 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
2049 output.print(objecttemp.numPointers()+",");
2050 output.print(paramsprefix);
2051 for(int j=0; j<objecttemp.numPointers(); j++)
2052 output.print(", NULL");
2053 output.println("};");
2056 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2057 TempDescriptor td=objecttemp.getPrimitive(i);
2058 TypeDescriptor type=td.getType();
2060 output.println(" void * "+td.getSafeSymbol()+";");
2061 else if (type.isClass()||type.isArray())
2062 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2064 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2068 if( state.MLP || state.OOOJAVA ) {
2069 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
2070 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
2071 if( (state.MLP && callerSESEplaceholder != mlpa.getMainSESE()) ||
2072 (state.OOOJAVA && callerSESEplaceholder != oooa.getMainSESE())
2074 // declare variables for naming static SESE's
2075 output.println(" /* static SESE names */");
2076 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
2077 while( pItr.hasNext() ) {
2078 SESEandAgePair pair = pItr.next();
2079 output.println(" void* "+pair+" = NULL;");
2082 // declare variables for tracking dynamic sources
2083 output.println(" /* dynamic variable sources */");
2084 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
2085 while( dynSrcItr.hasNext() ) {
2086 TempDescriptor dynSrcVar = dynSrcItr.next();
2087 output.println(" SESEcommon* "+dynSrcVar+"_srcSESE = NULL;");
2088 output.println(" INTPTR "+dynSrcVar+"_srcOffset = 0x1;");
2093 // set up related allocation sites's waiting queues
2096 ConflictGraph graph = null;
2097 graph = mlpa.getConflictGraphResults().get(fm);
2098 if (graph != null && graph.hasConflictEdge()) {
2099 output.println(" /* set up waiting queues */");
2100 output.println(" int numMemoryQueue=0;");
2101 output.println(" int memoryQueueItemID=0;");
2102 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
2104 System.out.println("#lockSet="+lockSet.hashCode());
2105 System.out.println("lockset="+lockSet);
2106 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
2107 SESELock seseLock = (SESELock) iterator.next();
2108 System.out.println("id="+seseLock.getID());
2109 System.out.println("#="+seseLock);
2111 System.out.println("size="+lockSet.size());
2112 if (lockSet.size() > 0) {
2113 output.println(" numMemoryQueue=" + lockSet.size() + ";");
2114 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
2115 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2120 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
2121 if(callerSESEplaceholder!= oooa.getMainSESE()){
2122 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(callerSESEplaceholder);
2123 if (graph != null && graph.hasConflictEdge()) {
2124 output.println(" // set up waiting queues ");
2125 output.println(" int numMemoryQueue=0;");
2126 output.println(" int memoryQueueItemID=0;");
2127 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
2128 System.out.println("#lockSet="+lockSet.hashCode());
2129 System.out.println("lockset="+lockSet);
2130 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
2131 Analysis.OoOJava.SESELock seseLock = (Analysis.OoOJava.SESELock) iterator.next();
2132 System.out.println("id="+seseLock.getID());
2133 System.out.println("#="+seseLock);
2135 System.out.println("size="+lockSet.size());
2136 if (lockSet.size() > 0) {
2137 output.println(" numMemoryQueue=" + lockSet.size() + ";");
2138 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
2139 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2149 /* Check to see if we need to do a GC if this is a
2150 * multi-threaded program...*/
2152 if (((state.MLP||state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
2153 || this.state.MULTICOREGC) {
2154 //Don't bother if we aren't in recursive methods...The loops case will catch it
2155 if (callgraph.getAllMethods(md).contains(md)) {
2156 if (state.DSM&&lb.isAtomic())
2157 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
2158 else if (this.state.MULTICOREGC) {
2159 output.println("if(gcflag) gc("+localsprefixaddr+");");
2161 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2167 // TODO add version for normal Java later
2168 if(fm.getMethod().isStaticBlock()) {
2169 // a static block, check if it has been executed
2170 output.println(" if(global_defs_p->" + cn.getSafeSymbol()+"static_block_exe_flag != 0) {");
2171 output.println(" return;");
2172 output.println(" }");
2175 if((!fm.getMethod().isStaticBlock()) && (fm.getMethod().getReturnType() == null) && (cn != null)){
2176 // is a constructor, check and output initialization of the static fields
2177 // here does not initialize the static fields of the class, instead it
2178 // redirect the corresponding fields in the object to the global_defs_p
2179 Vector fields=(Vector)fieldorder.get(cn);
2181 for(int i=0; i<fields.size(); i++) {
2182 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
2185 output.println(generateTemp(fm,fm.getParameter(0),lb)+"->"+fd.getSafeSymbol()+"=&(global_defs_p->"+cn.getSafeSymbol()+fd.getSafeSymbol()+");");
2191 generateCode(fm.getNext(0), fm, lb, null, output, true);
2193 output.println("}\n\n");
2197 protected void initializeSESE( FlatSESEEnterNode fsen ) {
2199 FlatMethod fm = fsen.getfmEnclosing();
2200 MethodDescriptor md = fm.getMethod();
2201 ClassDescriptor cn = md.getClassDesc();
2204 // Creates bogus method descriptor to index into tables
2205 Modifiers modBogus = new Modifiers();
2206 MethodDescriptor mdBogus =
2207 new MethodDescriptor( modBogus,
2208 new TypeDescriptor( TypeDescriptor.VOID ),
2209 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
2212 mdBogus.setClassDesc( fsen.getcdEnclosing() );
2213 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
2214 fsen.setfmBogus( fmBogus );
2215 fsen.setmdBogus( mdBogus );
2217 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
2218 inSetAndOutSet.addAll( fsen.getInVarSet() );
2219 inSetAndOutSet.addAll( fsen.getOutVarSet() );
2221 // Build paramsobj for bogus method descriptor
2222 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
2223 paramstable.put( mdBogus, objectparams );
2225 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
2226 while( itr.hasNext() ) {
2227 TempDescriptor temp = itr.next();
2228 TypeDescriptor type = temp.getType();
2229 if( type.isPtr() ) {
2230 objectparams.addPtr( temp );
2232 objectparams.addPrim( temp );
2236 // Build normal temp object for bogus method descriptor
2237 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
2238 tempstable.put( mdBogus, objecttemps );
2240 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
2241 FlatNode fn = (FlatNode)nodeit.next();
2242 TempDescriptor[] writes = fn.writesTemps();
2244 for( int i = 0; i < writes.length; i++ ) {
2245 TempDescriptor temp = writes[i];
2246 TypeDescriptor type = temp.getType();
2248 if( type.isPtr() ) {
2249 objecttemps.addPtr( temp );
2251 objecttemps.addPrim( temp );
2257 // used when generating the specific SESE record struct
2258 // to remember the FIRST field name of sese records
2259 // that the current SESE depends on--we need to know the
2260 // offset to the first one for garbage collection
2261 protected void addingDepRecField( FlatSESEEnterNode fsen,
2263 if( fsen.getFirstDepRecField() == null ) {
2264 fsen.setFirstDepRecField( field );
2266 fsen.incNumDepRecs();
2269 protected void generateMethodSESE(FlatSESEEnterNode fsen,
2271 PrintWriter outputStructs,
2272 PrintWriter outputMethHead,
2273 PrintWriter outputMethods
2276 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
2277 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
2279 // generate locals structure
2280 outputStructs.println("struct "+
2281 fsen.getcdEnclosing().getSafeSymbol()+
2282 fsen.getmdBogus().getSafeSymbol()+"_"+
2283 fsen.getmdBogus().getSafeMethodDescriptor()+
2285 outputStructs.println(" int size;");
2286 outputStructs.println(" void * next;");
2287 for(int i=0; i<objecttemps.numPointers(); i++) {
2288 TempDescriptor temp=objecttemps.getPointer(i);
2290 if (temp.getType().isNull())
2291 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
2293 outputStructs.println(" struct "+
2294 temp.getType().getSafeSymbol()+" * "+
2295 temp.getSafeSymbol()+";");
2297 outputStructs.println("};\n");
2300 // divide in-set and out-set into objects and primitives to prep
2301 // for the record generation just below
2302 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
2303 inSetAndOutSet.addAll( fsen.getInVarSet() );
2304 inSetAndOutSet.addAll( fsen.getOutVarSet() );
2306 Set<TempDescriptor> inSetAndOutSetObjs = new HashSet<TempDescriptor>();
2307 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
2309 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
2310 while( itr.hasNext() ) {
2311 TempDescriptor temp = itr.next();
2312 TypeDescriptor type = temp.getType();
2313 if( type.isPtr() ) {
2314 inSetAndOutSetObjs.add( temp );
2316 inSetAndOutSetPrims.add( temp );
2321 // generate the SESE record structure
2322 outputStructs.println(fsen.getSESErecordName()+" {");
2324 // data common to any SESE, and it must be placed first so
2325 // a module that doesn't know what kind of SESE record this
2326 // is can cast the pointer to a common struct
2327 outputStructs.println(" SESEcommon common;");
2329 // then garbage list stuff
2330 outputStructs.println(" /* next is in-set and out-set objects that look like a garbage list */");
2331 outputStructs.println(" int size;");
2332 outputStructs.println(" void * next;");
2334 // I think that the set of TempDescriptors inSetAndOutSetObjs
2335 // calculated above should match the pointer object params
2336 // used in the following code, but let's just leave the working
2337 // implementation unless there is actually a problem...
2339 Vector<TempDescriptor> inset=fsen.getInVarsForDynamicCoarseConflictResolution();
2340 for(int i=0; i<inset.size();i++) {
2341 TempDescriptor temp=inset.get(i);
2342 if (temp.getType().isNull())
2343 outputStructs.println(" void * "+temp.getSafeSymbol()+
2344 "; /* in-or-out-set obj in gl */");
2346 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+
2347 temp.getSafeSymbol()+"; /* in-or-out-set obj in gl */");
2350 for(int i=0; i<objectparams.numPointers(); i++) {
2351 TempDescriptor temp=objectparams.getPointer(i);
2352 if (!inset.contains(temp)) {
2353 if (temp.getType().isNull())
2354 outputStructs.println(" void * "+temp.getSafeSymbol()+
2355 "; /* in-or-out-set obj in gl */");
2357 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+
2358 temp.getSafeSymbol()+"; /* in-or-out-set obj in gl */");
2362 outputStructs.println(" /* next is primitives for in-set and out-set and dynamic tracking */");
2364 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
2365 while( itrPrims.hasNext() ) {
2366 TempDescriptor temp = itrPrims.next();
2367 TypeDescriptor type = temp.getType();
2368 if(type.isPrimitive()){
2369 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+"; /* in-set or out-set primitive */");
2373 // note that the sese record pointer will be added below, just primitive part of tracking here
2374 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
2375 while( itrDynInVars.hasNext() ) {
2376 TempDescriptor dynInVar = itrDynInVars.next();
2377 outputStructs.println(" INTPTR "+dynInVar+"_srcOffset; /* dynamic tracking primitive */");
2381 outputStructs.println(" /* everything after this should be pointers to an SESE record */" );
2383 // other half of info for dynamic tracking, the SESE record pointer
2384 itrDynInVars = fsen.getDynamicInVarSet().iterator();
2385 while( itrDynInVars.hasNext() ) {
2386 TempDescriptor dynInVar = itrDynInVars.next();
2387 String depRecField = dynInVar+"_srcSESE";
2388 outputStructs.println(" SESEcommon* "+depRecField+";");
2389 addingDepRecField( fsen, depRecField );
2392 // statically known sese sources are record pointers, too
2393 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
2394 while( itrStaticInVarSrcs.hasNext() ) {
2395 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
2396 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
2397 addingDepRecField(fsen, srcPair.toString());
2401 if (inset.size()!=0)
2402 outputStructs.println("struct rcrRecord rcrRecords["+inset.size()+"];");
2405 if( fsen.getFirstDepRecField() != null ) {
2406 outputStructs.println(" /* compiler believes first dependent SESE record field above is: "+
2407 fsen.getFirstDepRecField()+" */" );
2409 outputStructs.println("};\n");
2412 // write method declaration to header file
2413 outputMethHead.print("void ");
2414 outputMethHead.print(fsen.getSESEmethodName()+"(");
2415 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
2416 outputMethHead.println(");\n");
2419 generateFlatMethodSESE( fsen.getfmBogus(),
2420 fsen.getcdEnclosing(),
2426 private void generateFlatMethodSESE(FlatMethod fm,
2428 FlatSESEEnterNode fsen,
2429 FlatSESEExitNode seseExit,
2433 MethodDescriptor md=fm.getMethod();
2435 output.print("void ");
2436 output.print(fsen.getSESEmethodName()+"(");
2437 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
2438 output.println("){\n");
2441 TempObject objecttemp=(TempObject) tempstable.get(md);
2443 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2444 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2445 output.print(objecttemp.numPointers()+",");
2446 output.print("&(((SESEcommon*)(___params___))[1])");
2447 for(int j=0; j<objecttemp.numPointers(); j++)
2448 output.print(", NULL");
2449 output.println("};");
2452 output.println(" /* regular local primitives */");
2453 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2454 TempDescriptor td=objecttemp.getPrimitive(i);
2455 TypeDescriptor type=td.getType();
2457 output.println(" void * "+td.getSafeSymbol()+";");
2458 else if (type.isClass()||type.isArray())
2459 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2461 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2465 // declare variables for naming static SESE's
2466 output.println(" /* static SESE names */");
2467 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
2468 while( pItr.hasNext() ) {
2469 SESEandAgePair pair = pItr.next();
2470 output.println(" SESEcommon* "+pair+" = NULL;");
2473 // declare variables for tracking dynamic sources
2474 output.println(" /* dynamic variable sources */");
2475 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
2476 while( dynSrcItr.hasNext() ) {
2477 TempDescriptor dynSrcVar = dynSrcItr.next();
2478 output.println(" SESEcommon* "+dynSrcVar+"_srcSESE = NULL;");
2479 output.println(" INTPTR "+dynSrcVar+"_srcOffset = 0x1;");
2482 // declare local temps for in-set primitives, and if it is
2483 // a ready-source variable, get the value from the record
2484 output.println(" /* local temps for in-set primitives */");
2485 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2486 while( itrInSet.hasNext() ) {
2487 TempDescriptor temp = itrInSet.next();
2488 TypeDescriptor type = temp.getType();
2489 if( !type.isPtr() ) {
2490 if( fsen.getReadyInVarSet().contains( temp ) ) {
2491 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2493 output.println(" "+type+" "+temp+";");
2498 // declare local temps for out-set primitives if its not already
2499 // in the in-set, and it's value will get written so no problem
2500 output.println(" /* local temp for out-set prim, not already in the in-set */");
2501 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2502 while( itrOutSet.hasNext() ) {
2503 TempDescriptor temp = itrOutSet.next();
2504 TypeDescriptor type = temp.getType();
2505 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2506 output.println(" "+type+" "+temp+";");
2511 // initialize thread-local var to a the task's record, which is fused
2512 // with the param list
2513 output.println(" ");
2514 output.println(" // code of this task's body should use this to access the running task record");
2515 output.println(" runningSESE = &(___params___->common);");
2516 output.println(" childSESE = 0;");
2517 output.println(" ");
2519 // setup memory queue
2522 output.println(" // set up memory queues ");
2523 output.println(" int numMemoryQueue=0;");
2524 output.println(" int memoryQueueItemID=0;");
2525 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(fsen);
2526 if (graph != null && graph.hasConflictEdge()) {
2527 output.println(" {");
2528 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
2529 System.out.println("#lockSet="+lockSet);
2530 if (lockSet.size() > 0) {
2531 output.println(" numMemoryQueue=" + lockSet.size() + ";");
2532 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
2533 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2536 output.println(" }");
2539 output.println(" // set up memory queues ");
2540 output.println(" int numMemoryQueue=0;");
2541 output.println(" int memoryQueueItemID=0;");
2542 ConflictGraph graph = null;
2543 graph = mlpa.getConflictGraphResults().get(fsen);
2544 if (graph != null && graph.hasConflictEdge()) {
2545 output.println(" {");
2546 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
2548 System.out.println("#lockSet="+lockSet);
2550 if (lockSet.size() > 0) {
2551 output.println(" numMemoryQueue=" + lockSet.size() + "; ");
2552 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
2553 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2556 output.println(" }");
2561 // set up a task's mem pool to recycle the allocation of children tasks
2562 // don't bother if the task never has children (a leaf task)
2563 output.println( "#ifndef OOO_DISABLE_TASKMEMPOOL" );
2564 if( !fsen.getIsLeafSESE() ) {
2565 output.println(" runningSESE->taskRecordMemPool = poolcreate( "+
2566 maxTaskRecSizeStr+", freshTaskRecordInitializer );");
2567 if (state.RCR && !rcr.hasEmptyTraversers(fsen)) {
2568 output.println(" createTR();");
2569 output.println(" runningSESE->allHashStructures=TRqueue->allHashStructures;");
2572 // make it clear we purposefully did not initialize this
2573 output.println(" runningSESE->taskRecordMemPool = (MemPool*)0x7;");
2575 output.println( "#endif // OOO_DISABLE_TASKMEMPOOL" );
2578 // copy in-set into place, ready vars were already
2579 // copied when the SESE was issued
2580 Iterator<TempDescriptor> tempItr;
2582 // static vars are from a known SESE
2583 output.println(" // copy variables from static sources");
2584 tempItr = fsen.getStaticInVarSet().iterator();
2585 while( tempItr.hasNext() ) {
2586 TempDescriptor temp = tempItr.next();
2587 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2588 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2589 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2590 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2593 output.println(" // decrement references to static sources");
2594 for( Iterator<SESEandAgePair> pairItr = fsen.getStaticInVarSrcs().iterator(); pairItr.hasNext(); ) {
2595 SESEandAgePair srcPair = pairItr.next();
2596 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
2597 output.println(" {");
2598 output.println(" SESEcommon* src = &("+paramsprefix+"->"+srcPair+"->common);");
2599 output.println(" RELEASE_REFERENCE_TO( src );");
2600 output.println(" }");
2601 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
2605 // dynamic vars come from an SESE and src
2606 output.println(" // copy variables from dynamic sources");
2607 tempItr = fsen.getDynamicInVarSet().iterator();
2608 while( tempItr.hasNext() ) {
2609 TempDescriptor temp = tempItr.next();
2610 TypeDescriptor type = temp.getType();
2612 // go grab it from the SESE source
2613 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2616 if( type.isNull() ) {
2618 } else if( type.isClass() || type.isArray() ) {
2619 typeStr = "struct "+type.getSafeSymbol()+"*";
2621 typeStr = type.getSafeSymbol();
2624 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2625 " = *(("+typeStr+"*) ((void*)"+
2626 paramsprefix+"->"+temp+"_srcSESE + "+
2627 paramsprefix+"->"+temp+"_srcOffset));");
2629 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
2630 output.println(" SESEcommon* src = "+paramsprefix+"->"+temp+"_srcSESE;");
2631 output.println(" RELEASE_REFERENCE_TO( src );");
2632 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
2634 // or if the source was our parent, its already in our record to grab
2635 output.println(" } else {");
2636 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2637 " = "+paramsprefix+"->"+temp+";");
2638 output.println(" }");
2641 // Check to see if we need to do a GC if this is a
2642 // multi-threaded program...
2643 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2644 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2645 //Don't bother if we aren't in recursive methods...The loops case will catch it
2646 // if (callgraph.getAllMethods(md).contains(md)) {
2647 // if(this.state.MULTICOREGC) {
2648 // output.println("if(gcflag) gc("+localsprefixaddr+");");
2650 // output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2655 if( state.COREPROF ) {
2656 output.println("#ifdef CP_EVENTID_TASKEXECUTE");
2657 output.println(" CP_LOGEVENT( CP_EVENTID_TASKEXECUTE, CP_EVENTTYPE_BEGIN );");
2658 output.println("#endif");
2661 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2662 exitset.add(seseExit);
2663 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2664 output.println("}\n\n");
2669 // when a new mlp thread is created for an issued SESE, it is started
2670 // by running this method which blocks on a cond variable until
2671 // it is allowed to transition to execute. Then a case statement
2672 // allows it to invoke the method with the proper SESE body, and after
2673 // exiting the SESE method, executes proper SESE exit code before the
2674 // thread can be destroyed
2675 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2676 PrintWriter outmethod
2679 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2680 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2681 outmethod.println( " int status;");
2682 outmethod.println( " char errmsg[128];");
2684 // generate a case for each SESE class that can be invoked
2685 outmethod.println( " switch( ((SESEcommon*)seseRecord)->classID ) {");
2686 outmethod.println( " ");
2687 Iterator<FlatSESEEnterNode> seseit;
2689 seseit=mlpa.getAllSESEs().iterator();
2691 seseit=oooa.getAllSESEs().iterator();
2693 while(seseit.hasNext()){
2694 FlatSESEEnterNode fsen = seseit.next();
2696 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2697 outmethod.println( " case "+fsen.getIdentifier()+":");
2698 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2700 if( (state.MLP && fsen.equals( mlpa.getMainSESE() )) ||
2701 (state.OOOJAVA && fsen.equals( oooa.getMainSESE() ))
2703 outmethod.println( " workScheduleExit();");
2706 outmethod.println( " break;");
2707 outmethod.println( "");
2710 // default case should never be taken, error out
2711 outmethod.println( " default:");
2712 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2713 outmethod.println( " exit(-30);");
2714 outmethod.println( " break;");
2715 outmethod.println( " }");
2716 outmethod.println( " return NULL;");
2717 outmethod.println( "}\n\n");
2721 protected void generateCode(FlatNode first,
2724 Set<FlatNode> stopset,
2726 boolean firstpass) {
2728 /* Assign labels to FlatNode's if necessary.*/
2730 Hashtable<FlatNode, Integer> nodetolabel;
2732 if (state.DELAYCOMP&&!firstpass)
2733 nodetolabel=dcassignLabels(first, stopset);
2735 nodetolabel=assignLabels(first, stopset);
2737 Set<FlatNode> storeset=null;
2738 HashSet<FlatNode> genset=null;
2739 HashSet<FlatNode> refset=null;
2740 Set<FlatNode> unionset=null;
2742 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2743 storeset=delaycomp.livecode(lb);
2744 genset=new HashSet<FlatNode>();
2745 if (state.STMARRAY&&!state.DUALVIEW) {
2746 refset=new HashSet<FlatNode>();
2747 refset.addAll(delaycomp.getDeref(lb));
2748 refset.removeAll(delaycomp.getCannotDelay(lb));
2749 refset.removeAll(delaycomp.getOther(lb));
2752 genset.addAll(delaycomp.getCannotDelay(lb));
2753 genset.addAll(delaycomp.getOther(lb));
2755 genset.addAll(delaycomp.getNotReady(lb));
2756 if (state.STMARRAY&&!state.DUALVIEW) {
2757 genset.removeAll(refset);
2760 unionset=new HashSet<FlatNode>();
2761 unionset.addAll(storeset);
2762 unionset.addAll(genset);
2763 if (state.STMARRAY&&!state.DUALVIEW)
2764 unionset.addAll(refset);
2767 /* Do the actual code generation */
2768 FlatNode current_node=null;
2769 HashSet tovisit=new HashSet();
2770 HashSet visited=new HashSet();
2772 tovisit.add(first.getNext(0));
2775 while(current_node!=null||!tovisit.isEmpty()) {
2776 if (current_node==null) {
2777 current_node=(FlatNode)tovisit.iterator().next();
2778 tovisit.remove(current_node);
2779 } else if (tovisit.contains(current_node)) {
2780 tovisit.remove(current_node);
2782 visited.add(current_node);
2783 if (nodetolabel.containsKey(current_node)) {
2784 output.println("L"+nodetolabel.get(current_node)+":");
2786 if (state.INSTRUCTIONFAILURE) {
2787 if (state.THREAD||state.DSM||state.SINGLETM) {
2788 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2790 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2792 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2794 if (!state.DELAYCOMP||firstpass) {
2795 generateFlatNode(fm, lb, current_node, output);
2797 //store primitive variables in out set
2798 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2799 Set<TempDescriptor> liveout=ar.liveout;
2800 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2801 TempDescriptor tmp=tmpit.next();
2802 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2805 if ((state.MLP || state.OOOJAVA) && stopset!=null) {
2806 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2807 assert current_node instanceof FlatSESEExitNode;
2808 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2809 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2810 assert fsen.getFlatExit().equals( fsxn );
2811 assert fsxn.getFlatEnter().equals( fsen );
2813 if (current_node.kind()!=FKind.FlatReturnNode) {
2815 // TODO add version for normal Java later
2816 if((fm.getMethod() != null) && (fm.getMethod().isStaticBlock())) {
2817 // a static block, check if it has been executed
2818 output.println(" global_defs_p->" + fm.getMethod().getClassDesc().getSafeSymbol()+"static_block_exe_flag = 1;");
2822 output.println(" return;");
2825 } else if(current_node.numNext()==1) {
2827 if ((state.MLP|| state.OOOJAVA) &&
2828 current_node.kind()==FKind.FlatSESEEnterNode &&
2829 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2831 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2832 generateFlatNode(fm, lb, current_node, output);
2833 nextnode=fsen.getFlatExit().getNext(0);
2834 } else if (state.DELAYCOMP) {
2835 boolean specialprimitive=false;
2836 //skip literals...no need to add extra overhead
2837 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2838 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2839 if (!typedesc.isClass()&&!typedesc.isArray()) {
2840 specialprimitive=true;
2844 if (genset==null||genset.contains(current_node)||specialprimitive)
2845 generateFlatNode(fm, lb, current_node, output);
2846 if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2847 //need to acquire lock
2848 handleArrayDeref(fm, lb, current_node, output, firstpass);
2850 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2851 TempDescriptor wrtmp=current_node.writesTemps()[0];
2853 //need to store value written by previous node
2854 if (wrtmp.getType().isPtr()) {
2855 //only lock the objects that may actually need locking
2856 if (recorddc.getNeedTrans(lb, current_node)&&
2857 (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2858 wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2859 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2861 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2864 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2867 //need to read value read by previous node
2868 if (wrtmp.getType().isPtr()) {
2869 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2871 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");
2875 nextnode=current_node.getNext(0);
2878 generateFlatNode(fm, lb, current_node, output);
2879 nextnode=current_node.getNext(0);
2881 if (visited.contains(nextnode)) {
2882 output.println("goto L"+nodetolabel.get(nextnode)+";");
2885 current_node=nextnode;
2886 } else if (current_node.numNext()==2) {
2888 if (state.DELAYCOMP) {
2889 boolean computeside=false;
2891 //need to record which way it should go
2892 if (genset==null||genset.contains(current_node)) {
2893 if (storeset!=null&&storeset.contains(current_node)) {
2894 //need to store which way branch goes
2895 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2897 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2899 //which side to execute
2903 if (genset.contains(current_node)) {
2904 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2905 } else if (storeset.contains(current_node)) {
2907 branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2909 //which side to execute
2914 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2916 if (leftset.size()==0)
2918 if (visited.contains(current_node.getNext(branch))) {
2919 //already visited -- build jump
2920 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2923 current_node=current_node.getNext(branch);
2926 if (!visited.contains(current_node.getNext(1)))
2927 tovisit.add(current_node.getNext(1));
2928 if (visited.contains(current_node.getNext(0))) {
2929 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2932 current_node=current_node.getNext(0);
2936 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2937 if (!visited.contains(current_node.getNext(1)))
2938 tovisit.add(current_node.getNext(1));
2939 if (visited.contains(current_node.getNext(0))) {
2940 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2943 current_node=current_node.getNext(0);
2945 } else throw new Error();
2949 protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2950 if (fn.kind()==FKind.FlatSetElementNode) {
2951 FlatSetElementNode fsen=(FlatSetElementNode) fn;
2952 String dst=generateTemp(fm, fsen.getDst(), lb);
2953 String src=generateTemp(fm, fsen.getSrc(), lb);
2954 String index=generateTemp(fm, fsen.getIndex(), lb);
2955 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2957 if (elementtype.isArray()||elementtype.isClass())
2960 type=elementtype.getSafeSymbol()+" ";
2962 output.println("STOREARRAY("+dst+","+index+","+type+")");
2964 output.println("{");
2965 output.println(" struct ArrayObject *array;");
2966 output.println(" int index;");
2967 output.println(" RESTOREARRAY(array,index);");
2968 output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2969 output.println("}");
2971 } else if (fn.kind()==FKind.FlatElementNode) {
2972 FlatElementNode fen=(FlatElementNode) fn;
2973 String src=generateTemp(fm, fen.getSrc(), lb);
2974 String index=generateTemp(fm, fen.getIndex(), lb);
2975 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2976 String dst=generateTemp(fm, fen.getDst(), lb);
2978 if (elementtype.isArray()||elementtype.isClass())
2981 type=elementtype.getSafeSymbol()+" ";
2983 output.println("STOREARRAY("+src+","+index+","+type+")");
2985 output.println("{");
2986 output.println(" struct ArrayObject *array;");
2987 output.println(" int index;");
2988 output.println(" RESTOREARRAY(array,index);");
2989 output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2990 output.println("}");
2994 /** Special label assignment for delaycomputation */
2995 protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2996 HashSet tovisit=new HashSet();
2997 HashSet visited=new HashSet();
2999 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
3001 //Label targets of branches
3002 Set<FlatNode> targets=branchanalysis.getTargets();
3003 for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
3004 nodetolabel.put(it.next(), new Integer(labelindex++));
3009 /*Assign labels first. A node needs a label if the previous
3010 * node has two exits or this node is a join point. */
3012 while(!tovisit.isEmpty()) {
3013 FlatNode fn=(FlatNode)tovisit.iterator().next();
3018 if(lastset!=null&&lastset.contains(fn)) {
3019 // if last is not null and matches, don't go
3020 // any further for assigning labels
3024 for(int i=0; i<fn.numNext(); i++) {
3025 FlatNode nn=fn.getNext(i);
3028 //1) Edge >1 of node
3029 nodetolabel.put(nn,new Integer(labelindex++));
3031 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
3035 nodetolabel.put(nn,new Integer(labelindex++));
3043 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
3044 return assignLabels(first, null);
3047 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
3048 HashSet tovisit=new HashSet();
3049 HashSet visited=new HashSet();
3051 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
3054 /*Assign labels first. A node needs a label if the previous
3055 * node has two exits or this node is a join point. */
3057 while(!tovisit.isEmpty()) {
3058 FlatNode fn=(FlatNode)tovisit.iterator().next();
3063 if(lastset!=null&&lastset.contains(fn)) {
3064 // if last is not null and matches, don't go
3065 // any further for assigning labels
3069 for(int i=0; i<fn.numNext(); i++) {
3070 FlatNode nn=fn.getNext(i);
3073 //1) Edge >1 of node
3074 nodetolabel.put(nn,new Integer(labelindex++));
3076 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
3080 nodetolabel.put(nn,new Integer(labelindex++));
3088 /** Generate text string that corresponds to the TempDescriptor td. */
3089 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
3090 MethodDescriptor md=fm.getMethod();
3091 TaskDescriptor task=fm.getTask();
3092 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
3094 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
3095 return td.getSafeSymbol();
3098 if (objecttemps.isLocalPtr(td)) {
3099 return localsprefixderef+td.getSafeSymbol();
3102 if (objecttemps.isParamPtr(td)) {
3103 return paramsprefix+"->"+td.getSafeSymbol();
3110 void stallMEMRCR(FlatMethod fm, FlatNode fn, Set<Analysis.OoOJava.WaitingElement> waitingElementSet, PrintWriter output) {
3111 output.println("// stall on parent's stall sites ");
3112 output.println(" {");
3113 output.println(" REntry* rentry;");
3114 output.println(" // stallrecord sometimes is used as a task record for instance ");
3115 output.println(" // when you call RELEASE_REFERENCE_TO on a stall record.");
3116 output.println(" // so the parent field must be initialized.");
3117 output.println(" SESEstall * stallrecord=(SESEstall *) poolalloc(runningSESE->taskRecordMemPool);");
3118 output.println(" stallrecord->common.parent=runningSESE;");
3119 output.println(" stallrecord->common.unresolvedDependencies=10000;");
3120 output.println(" stallrecord->common.rcrstatus=1;");
3121 output.println(" stallrecord->common.offsetToParamRecords=(INTPTR) & (((SESEstall *)0)->rcrRecords);");
3122 output.println(" stallrecord->common.refCount = 10003;");
3123 output.println(" int localCount=10000;");
3124 output.println(" stallrecord->rcrRecords[0].index=0;");
3125 output.println(" stallrecord->rcrRecords[0].flag=0;");
3126 output.println(" stallrecord->rcrRecords[0].next=NULL;");
3127 output.println(" stallrecord->common.parentsStallSem=&runningSESEstallSem;");
3128 output.println(" psem_reset( &runningSESEstallSem);");
3129 output.println(" stallrecord->tag=runningSESEstallSem.tag;");
3131 TempDescriptor stalltd=null;
3132 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
3133 Analysis.OoOJava.WaitingElement waitingElement =(Analysis.OoOJava.WaitingElement) iterator.next();
3134 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
3135 output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray["
3136 + waitingElement.getQueueID() + "]," + waitingElement.getStatus()
3137 + ", (SESEcommon *) stallrecord, 1LL);");
3139 throw new Error("Fine-grained conflict: This should not happen in RCR");
3141 output.println(" rentry->queue=runningSESE->memoryQueueArray["
3142 + waitingElement.getQueueID() + "];");
3143 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["
3144 + waitingElement.getQueueID() + "],rentry)==NOTREADY) {");
3145 output.println(" localCount--;");
3146 output.println(" }");
3147 output.println("#if defined(RCR)&&!defined(OOO_DISABLE_TASKMEMPOOL)");
3148 output.println(" else poolfreeinto(runningSESE->memoryQueueArray["+waitingElement.getQueueID()+"]->rentrypool, rentry);");
3149 output.println("#endif");
3150 if (stalltd==null) {
3151 stalltd=waitingElement.getTempDesc();
3152 } else if (stalltd!=waitingElement.getTempDesc()) {
3153 throw new Error("Multiple temp descriptors at stall site"+stalltd+"!="+waitingElement.getTempDesc());
3157 //did all of the course grained stuff
3158 output.println(" if(!atomic_sub_and_test(localCount, &(stallrecord->common.unresolvedDependencies))) {");
3159 //have to do fine-grained work also
3160 output.println(" stallrecord->___obj___=(struct ___Object___ *)"
3161 + generateTemp(fm, stalltd, null) + ";");
3162 output.println(" stallrecord->common.classID=-"
3163 + rcr.getTraverserID(stalltd, fn) + ";");
3165 output.println(" enqueueTR(TRqueue, (void *)stallrecord);");
3167 if (state.COREPROF) {
3168 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3170 .println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3171 output.println("#endif");
3174 output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );");
3176 if (state.COREPROF) {
3177 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3179 .println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3180 output.println("#endif");
3183 output.println(" } else {");//exit if condition
3184 //release traversers reference if we didn't use traverser
3185 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL");
3186 output.println(" RELEASE_REFERENCE_TO((SESEcommon *)stallrecord);");
3187 output.println("#endif");
3188 output.println(" }");
3189 //release our reference to stall record
3190 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL");
3191 output.println(" RELEASE_REFERENCE_TO((SESEcommon *)stallrecord);");
3192 output.println("#endif");
3193 output.println(" }");//exit block
3196 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
3198 // insert pre-node actions from the code plan
3199 if( state.MLP|| state.OOOJAVA ) {
3203 cp = mlpa.getCodePlan( fn );
3205 cp = oooa.getCodePlan(fn);
3210 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
3212 // for each sese and age pair that this parent statement
3213 // must stall on, take that child's stall semaphore, the
3214 // copying of values comes after the statement
3215 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
3216 while( vstItr.hasNext() ) {
3217 VariableSourceToken vst = vstItr.next();
3219 SESEandAgePair pair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
3221 output.println(" {");
3222 output.println(" "+pair.getSESE().getSESErecordName()+"* child = ("+
3223 pair.getSESE().getSESErecordName()+"*) "+pair+";");
3225 output.println(" SESEcommon* childCom = (SESEcommon*) "+pair+";");
3227 if( state.COREPROF ) {
3228 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
3229 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
3230 output.println("#endif");
3233 output.println(" pthread_mutex_lock( &(childCom->lock) );");
3234 output.println(" if( childCom->doneExecuting == FALSE ) {");
3235 output.println(" psem_reset( &runningSESEstallSem );");
3236 output.println(" childCom->parentsStallSem = &runningSESEstallSem;");
3237 output.println(" pthread_mutex_unlock( &(childCom->lock) );");
3238 output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );");
3239 output.println(" } else {");
3240 output.println(" pthread_mutex_unlock( &(childCom->lock) );");
3241 output.println(" }");
3243 // copy things we might have stalled for
3244 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
3245 while( tdItr.hasNext() ) {
3246 TempDescriptor td = tdItr.next();
3247 FlatMethod fmContext;
3248 if( currentSESE.getIsCallerSESEplaceholder() ) {
3249 fmContext = currentSESE.getfmEnclosing();
3251 fmContext = currentSESE.getfmBogus();
3253 output.println(" "+generateTemp( fmContext, td, null )+
3254 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
3257 if( state.COREPROF ) {
3258 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
3259 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
3260 output.println("#endif");
3263 output.println(" }");
3266 // for each variable with a dynamic source, stall just for that variable
3267 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
3268 while( dynItr.hasNext() ) {
3269 TempDescriptor dynVar = dynItr.next();
3271 // only stall if the dynamic source is not yourself, denoted by src==NULL
3272 // otherwise the dynamic write nodes will have the local var up-to-date
3273 output.println(" {");
3274 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
3276 output.println(" SESEcommon* childCom = (SESEcommon*) "+dynVar+"_srcSESE;");
3278 if( state.COREPROF ) {
3279 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
3280 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
3281 output.println("#endif");
3284 output.println(" pthread_mutex_lock( &(childCom->lock) );");
3285 output.println(" if( childCom->doneExecuting == FALSE ) {");
3286 output.println(" psem_reset( &runningSESEstallSem );");
3287 output.println(" childCom->parentsStallSem = &runningSESEstallSem;");
3288 output.println(" pthread_mutex_unlock( &(childCom->lock) );");
3289 output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );");
3290 output.println(" } else {");
3291 output.println(" pthread_mutex_unlock( &(childCom->lock) );");
3292 output.println(" }");
3294 FlatMethod fmContext;
3295 if( currentSESE.getIsCallerSESEplaceholder() ) {
3296 fmContext = currentSESE.getfmEnclosing();
3298 fmContext = currentSESE.getfmBogus();
3301 TypeDescriptor type = dynVar.getType();
3303 if( type.isNull() ) {
3305 } else if( type.isClass() || type.isArray() ) {
3306 typeStr = "struct "+type.getSafeSymbol()+"*";
3308 typeStr = type.getSafeSymbol();
3311 output.println(" "+generateTemp( fmContext, dynVar, null )+
3312 " = *(("+typeStr+"*) ((void*)"+
3313 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
3315 if( state.COREPROF ) {
3316 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
3317 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
3318 output.println("#endif");
3321 output.println(" }");
3322 output.println(" }");
3325 // for each assignment of a variable to rhs that has a dynamic source,
3326 // copy the dynamic sources
3327 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
3328 while( dynAssignItr.hasNext() ) {
3329 Map.Entry me = (Map.Entry) dynAssignItr.next();
3330 TempDescriptor lhs = (TempDescriptor) me.getKey();
3331 TempDescriptor rhs = (TempDescriptor) me.getValue();
3333 output.println(" {");
3334 output.println(" SESEcommon* oldSrc = "+lhs+"_srcSESE;");
3336 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
3337 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
3339 // no matter what we did above, track reference count of whatever
3340 // this variable pointed to, do release last in case we're just
3341 // copying the same value in because 1->2->1 is safe but ref count
3342 // 1->0->1 has a window where it looks like it should be free'd
3343 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3344 output.println(" if( "+rhs+"_srcSESE != NULL ) {");
3345 output.println(" ADD_REFERENCE_TO( "+rhs+"_srcSESE );");
3346 output.println(" }");
3347 output.println(" if( oldSrc != NULL ) {");
3348 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
3349 output.println(" }");
3350 output.println(" }");
3351 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
3354 // for each lhs that is dynamic from a non-dynamic source, set the
3355 // dynamic source vars to the current SESE
3356 dynItr = cp.getDynAssignCurr().iterator();
3357 while( dynItr.hasNext() ) {
3358 TempDescriptor dynVar = dynItr.next();
3359 assert currentSESE.getDynamicVarSet().contains( dynVar );
3361 // first release a reference to current record
3362 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3363 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
3364 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
3365 output.println(" }");
3366 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
3368 output.println(" "+dynVar+"_srcSESE = NULL;");
3372 // handling stall site
3373 if (state.OOOJAVA) {
3375 // assumes that there is only one parent, but it is possible that
3376 // currentSESE has more than one so we need to generate
3377 // conditional case for each parent case
3378 Analysis.OoOJava.ConflictGraph graph = null;
3379 if(currentSESE.getSESEParent().size()>0){
3380 graph = oooa.getConflictGraph(currentSESE.getSESEParent().iterator().next());
3382 // Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(currentSESE);
3384 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
3385 Set<Analysis.OoOJava.WaitingElement> waitingElementSet = graph.getStallSiteWaitingElementSet(fn, seseLockSet);
3387 if (waitingElementSet.size() > 0) {
3389 stallMEMRCR(fm, fn, waitingElementSet, output);
3391 output.println("// stall on parent's stall sites ");
3392 output.println(" {");
3393 output.println(" REntry* rentry;");
3395 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
3396 Analysis.OoOJava.WaitingElement waitingElement =
3397 (Analysis.OoOJava.WaitingElement) iterator.next();
3398 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
3399 output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray["
3400 + waitingElement.getQueueID() + "]," + waitingElement.getStatus()
3401 + ", runningSESE);");
3403 output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["
3404 + waitingElement.getQueueID() + "]," + waitingElement.getStatus()
3405 + ", runningSESE, (void*)&"
3406 + generateTemp(fm, waitingElement.getTempDesc(), lb) + ");");
3408 output.println(" rentry->parentStallSem=&runningSESEstallSem;");
3409 output.println(" psem_reset( &runningSESEstallSem);");
3410 output.println(" rentry->tag=runningSESEstallSem.tag;");
3411 output.println(" rentry->queue=runningSESE->memoryQueueArray["
3412 + waitingElement.getQueueID() + "];");
3413 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["
3414 + waitingElement.getQueueID() + "],rentry)==NOTREADY){");
3415 if (state.COREPROF) {
3416 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3418 .println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3419 output.println("#endif");
3422 output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );");
3424 if (state.COREPROF) {
3425 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3427 .println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3428 output.println("#endif");
3430 output.println(" } ");
3432 output.println(" }");
3437 ParentChildConflictsMap conflictsMap = mlpa.getConflictsResults().get(fn);
3438 if (conflictsMap != null) {
3439 Set<Long> allocSet = conflictsMap.getAllocationSiteIDSetofStallSite();
3440 if (allocSet.size() > 0) {
3441 FlatNode enclosingFlatNode=null;
3442 if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
3443 enclosingFlatNode=currentSESE.getfmEnclosing();
3445 enclosingFlatNode=currentSESE;
3447 ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
3448 HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
3449 Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
3451 if(waitingElementSet.size()>0){
3452 output.println("// stall on parent's stall sites ");
3453 output.println(" {");
3454 output.println(" REntry* rentry;");
3456 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
3457 WaitingElement waitingElement = (WaitingElement) iterator.next();
3459 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3460 // HERE! a parent might conflict with a child
3461 output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "],"+ waitingElement.getStatus()+ ", runningSESE);");
3463 output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "],"+ waitingElement.getStatus()+ ", runningSESE, (void*)&___locals___."+ waitingElement.getDynID() + ");");
3465 output.println(" rentry->parentStallSem=&runningSESEstallSem;");
3466 output.println(" psem_reset( &runningSESEstallSem);");
3467 output.println(" rentry->tag=runningSESEstallSem.tag;");
3468 output.println(" rentry->queue=runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3469 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+"],rentry)==NOTREADY) {");
3470 if( state.COREPROF ) {
3471 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3472 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3473 output.println("#endif");
3475 output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );");
3476 if( state.COREPROF ) {
3477 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3478 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3479 output.println("#endif");
3481 output.println(" } ");
3483 output.println(" }");
3492 case FKind.FlatAtomicEnterNode:
3493 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
3496 case FKind.FlatAtomicExitNode:
3497 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
3500 case FKind.FlatInstanceOfNode:
3501 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
3504 case FKind.FlatSESEEnterNode:
3505 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
3508 case FKind.FlatSESEExitNode:
3509 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
3512 case FKind.FlatWriteDynamicVarNode:
3513 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
3516 case FKind.FlatGlobalConvNode:
3517 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
3520 case FKind.FlatTagDeclaration:
3521 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
3524 case FKind.FlatCall:
3525 generateFlatCall(fm, lb, (FlatCall) fn,output);
3528 case FKind.FlatFieldNode:
3529 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
3532 case FKind.FlatElementNode:
3533 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
3536 case FKind.FlatSetElementNode:
3537 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
3540 case FKind.FlatSetFieldNode:
3541 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
3545 generateFlatNew(fm, lb, (FlatNew) fn,output);
3548 case FKind.FlatOpNode:
3549 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
3552 case FKind.FlatCastNode:
3553 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
3556 case FKind.FlatLiteralNode:
3557 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
3560 case FKind.FlatReturnNode:
3561 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
3565 output.println("/* nop */");
3568 case FKind.FlatGenReachNode:
3569 // this node is just for generating a reach graph
3570 // in disjointness analysis at a particular program point
3573 case FKind.FlatExit:
3574 output.println("/* exit */");
3577 case FKind.FlatBackEdge:
3578 if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3579 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3581 if(state.DSM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3582 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3584 if (((state.MLP|| state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
3585 || (this.state.MULTICOREGC)) {
3586 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
3587 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
3588 } else if(this.state.MULTICOREGC) {
3589 output.println("if (gcflag) gc("+localsprefixaddr+");");
3591 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3594 output.println("/* nop */");
3597 case FKind.FlatCheckNode:
3598 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
3601 case FKind.FlatFlagActionNode:
3602 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
3605 case FKind.FlatPrefetchNode:
3606 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
3609 case FKind.FlatOffsetNode:
3610 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
3617 // insert post-node actions from the code-plan
3620 CodePlan cp = mlpa.getCodePlan( fn );
3628 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
3629 output.println("/* FlatOffsetNode */");
3630 FieldDescriptor fd=fofn.getField();
3631 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
3632 output.println("/* offset */");
3635 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
3636 if (state.PREFETCH) {
3637 Vector oids = new Vector();
3638 Vector fieldoffset = new Vector();
3639 Vector endoffset = new Vector();
3640 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
3641 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
3642 PrefetchPair pp = (PrefetchPair) it.next();
3643 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
3644 /* Find prefetches that can generate oid */
3645 if(statusbase == LocalityAnalysis.GLOBAL) {
3646 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
3648 } else if (statusbase == LocalityAnalysis.LOCAL) {
3649 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
3656 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
3657 output.println("{");
3658 output.println("/* prefetch */");
3659 output.println("/* prefetchid_" + fpn.siteid + " */");
3660 output.println("void * prefptr;");
3661 output.println("int tmpindex;");
3663 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
3664 /*Create C code for oid array */
3665 output.print(" unsigned int oidarray_[] = {");
3666 boolean needcomma=false;
3667 for (Iterator it = oids.iterator(); it.hasNext();) {
3670 output.print(it.next());
3673 output.println("};");
3675 /*Create C code for endoffset values */
3676 output.print(" unsigned short endoffsetarry_[] = {");
3678 for (Iterator it = endoffset.iterator(); it.hasNext();) {
3681 output.print(it.next());
3684 output.println("};");
3686 /*Create C code for Field Offset Values */
3687 output.print(" short fieldarry_[] = {");
3689 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
3692 output.print(it.next());
3695 output.println("};");
3696 /* make the prefetch call to Runtime */
3697 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
3698 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
3699 output.println(" }");
3700 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
3701 output.println(" } else {");
3702 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
3703 output.println(" }");
3704 output.println("}");
3708 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
3709 short offsetcount = 0;
3713 } else if (localbase) {
3714 for(; breakindex<pp.desc.size(); breakindex++) {
3715 Descriptor desc=pp.getDescAt(breakindex);
3716 if (desc instanceof FieldDescriptor) {
3717 FieldDescriptor fd=(FieldDescriptor)desc;
3718 if (fd.isGlobal()) {
3726 if (breakindex>pp.desc.size()) //all local
3729 TypeDescriptor lasttype=pp.base.getType();
3730 String basestr=generateTemp(fm, pp.base, lb);
3732 boolean maybenull=fm.getMethod().isStatic()||
3733 !pp.base.equals(fm.getParameter(0));
3735 for(int i=0; i<breakindex; i++) {
3736 String indexcheck="";
3738 Descriptor desc=pp.getDescAt(i);
3739 if (desc instanceof FieldDescriptor) {
3740 FieldDescriptor fd=(FieldDescriptor)desc;
3742 if (!teststr.equals(""))
3744 teststr+="((prefptr="+basestr+")!=NULL)";
3745 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3747 basestr=basestr+"->"+fd.getSafeSymbol();
3750 lasttype=fd.getType();
3752 IndexDescriptor id=(IndexDescriptor)desc;
3753 indexcheck="((tmpindex=";
3754 for(int j=0; j<id.tddesc.size(); j++) {
3755 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3757 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3759 if (!teststr.equals(""))
3761 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3762 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3764 lasttype=lasttype.dereference();
3769 if (teststr.equals("")) {
3770 oid="((unsigned int)"+basestr+")";
3772 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3776 for(int i = breakindex; i < pp.desc.size(); i++) {
3777 String newfieldoffset;
3778 Object desc = pp.getDescAt(i);
3779 if(desc instanceof FieldDescriptor) {
3780 FieldDescriptor fd=(FieldDescriptor)desc;
3781 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3782 lasttype=fd.getType();
3784 newfieldoffset = "";
3785 IndexDescriptor id=(IndexDescriptor)desc;
3786 for(int j = 0; j < id.tddesc.size(); j++) {
3787 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3789 newfieldoffset += id.offset.toString();
3790 lasttype=lasttype.dereference();
3792 fieldoffset.add(newfieldoffset);
3795 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3796 base+=pp.desc.size()-breakindex;
3797 endoffset.add(new Short((short)base));
3802 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3803 if (lb!=fgcn.getLocality())
3805 /* Have to generate flat globalconv */
3806 if (fgcn.getMakePtr()) {
3808 //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3809 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3811 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3812 //need to do translation
3813 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3814 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3815 if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3816 output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3818 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3822 /* Need to convert to OID */
3823 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3824 if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3825 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3827 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3833 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3835 if (fion.getType().isArray()) {
3836 type=state.getArrayNumber(fion.getType())+state.numClasses();
3838 type=fion.getType().getClassDesc().getId();
3841 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3842 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3844 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3847 int sandboxcounter=0;
3848 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3849 /* Check to see if we need to generate code for this atomic */
3850 if (locality==null) {
3851 if (GENERATEPRECISEGC) {
3852 output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3853 output.println("stopforgc((struct garbagelist *) &___locals___);");
3854 output.println("pthread_mutex_lock(&atomiclock);");
3855 output.println("restartaftergc();");
3856 output.println("}");
3858 output.println("pthread_mutex_lock(&atomiclock);");
3863 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3867 if (state.SANDBOX) {
3868 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3869 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3872 if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3873 AtomicRecord ar=atomicmethodmap.get(faen);
3875 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3876 TempDescriptor tmp=tmpit.next();
3877 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3880 //copy outs that depend on path
3881 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3882 TempDescriptor tmp=tmpit.next();
3883 if (!ar.livein.contains(tmp))
3884 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3888 /* Backup the temps. */
3889 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3890 TempDescriptor tmp=tmpit.next();
3891 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3894 output.println("goto transstart"+faen.getIdentifier()+";");
3896 /******* Print code to retry aborted transaction *******/
3897 output.println("transretry"+faen.getIdentifier()+":");
3900 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3901 TempDescriptor tmp=tmpit.next();
3902 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3906 /********* Need to revert local object store ********/
3907 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3909 output.println("while ("+revertptr+") {");
3910 output.println("struct ___Object___ * tmpptr;");
3911 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3912 output.println("REVERT_OBJ("+revertptr+");");
3913 output.println(revertptr+"=tmpptr;");
3914 output.println("}");
3916 /******* Tell the runtime to start the transaction *******/
3918 output.println("transstart"+faen.getIdentifier()+":");
3919 if (state.SANDBOX) {
3920 output.println("transaction_check_counter=*counter_reset_pointer;");
3923 output.println("transStart();");
3925 if (state.ABORTREADERS||state.SANDBOX) {
3927 output.println("abortenabled=1;");
3928 output.println("if (_setjmp(aborttrans)) {");
3929 output.println(" goto transretry"+faen.getIdentifier()+"; }");
3933 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3934 /* Check to see if we need to generate code for this atomic */
3935 if (locality==null) {
3936 output.println("pthread_mutex_unlock(&atomiclock);");
3939 if (locality.getAtomic(lb).get(faen).intValue()>0)
3941 //store the revert list before we lose the transaction object
3944 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3945 output.println(revertptr+"=revertlist;");
3946 output.println("if (transCommit()) {");
3947 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3948 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3949 output.println("} else {");
3950 /* Need to commit local object store */
3951 output.println("while ("+revertptr+") {");
3952 output.println("struct ___Object___ * tmpptr;");
3953 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3954 output.println("COMMIT_OBJ("+revertptr+");");
3955 output.println(revertptr+"=tmpptr;");
3956 output.println("}");
3957 output.println("}");
3961 if (!state.DELAYCOMP) {
3963 output.println("if (transCommit()) {");
3964 /* Transaction aborts if it returns true */
3965 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3966 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3967 output.println("}");
3969 if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
3970 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3971 output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3973 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3974 TempDescriptor tmp=tmpit.next();
3975 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3977 } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3978 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3980 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3981 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3982 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3983 output.println("}");
3985 output.println("else {");
3986 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3987 TempDescriptor tmp=tmpit.next();
3988 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3990 output.println("}");
3992 output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3993 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3994 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3995 output.println("}");
4000 public void generateFlatSESEEnterNode( FlatMethod fm,
4002 FlatSESEEnterNode fsen,
4003 PrintWriter output) {
4004 // if MLP flag is off, okay that SESE nodes are in IR graph,
4005 // just skip over them and code generates exactly the same
4006 if( !(state.MLP || state.OOOJAVA) ) {
4009 // there may be an SESE in an unreachable method, skip over
4010 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
4011 (state.OOOJAVA && !oooa.getAllSESEs().contains(fsen))
4016 // also, if we have encountered a placeholder, just skip it
4017 if( fsen.getIsCallerSESEplaceholder() ) {
4021 output.println(" {");
4023 if( state.COREPROF ) {
4024 output.println("#ifdef CP_EVENTID_TASKDISPATCH");
4025 output.println(" CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_BEGIN );");
4026 output.println("#endif");
4030 // before doing anything, lock your own record and increment the running children
4031 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4032 (state.OOOJAVA && fsen != oooa.getMainSESE())
4034 output.println(" childSESE++;");
4037 // allocate the space for this record
4038 output.println( "#ifndef OOO_DISABLE_TASKMEMPOOL" );
4040 output.println( "#ifdef CP_EVENTID_POOLALLOC");
4041 output.println( " CP_LOGEVENT( CP_EVENTID_POOLALLOC, CP_EVENTTYPE_BEGIN );");
4042 output.println( "#endif");
4043 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4044 (state.OOOJAVA && fsen != oooa.getMainSESE())
4047 fsen.getSESErecordName()+"* seseToIssue = ("+
4048 fsen.getSESErecordName()+"*) poolalloc( runningSESE->taskRecordMemPool );");
4049 output.println(" CHECK_RECORD( seseToIssue );");
4052 fsen.getSESErecordName()+"* seseToIssue = ("+
4053 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
4054 fsen.getSESErecordName()+" ) );");
4056 output.println( "#ifdef CP_EVENTID_POOLALLOC");
4057 output.println( " CP_LOGEVENT( CP_EVENTID_POOLALLOC, CP_EVENTTYPE_END );");
4058 output.println( "#endif");
4060 output.println( "#else // OOO_DISABLE_TASKMEMPOOL" );
4062 fsen.getSESErecordName()+"* seseToIssue = ("+
4063 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
4064 fsen.getSESErecordName()+" ) );");
4065 output.println( "#endif // OOO_DISABLE_TASKMEMPOOL" );
4068 // set up the SESE in-set and out-set objects, which look
4069 // like a garbage list
4070 output.println(" struct garbagelist * gl= (struct garbagelist *)&(((SESEcommon*)(seseToIssue))[1]);");
4071 output.println(" gl->size="+calculateSizeOfSESEParamList(fsen)+";");
4072 output.println(" gl->next = NULL;");
4073 output.println(" seseToIssue->common.rentryIdx=0;");
4076 //flag the SESE status as 1...it will be reset
4077 output.println(" seseToIssue->common.rcrstatus=1;");
4080 // there are pointers to SESE records the newly-issued SESE
4081 // will use to get values it depends on them for--how many
4082 // are there, and what is the offset from the total SESE
4083 // record to the first dependent record pointer?
4084 output.println(" seseToIssue->common.numDependentSESErecords="+
4085 fsen.getNumDepRecs()+";");
4087 // we only need this (and it will only compile) when the number of dependent
4088 // SESE records is non-zero
4089 if( fsen.getFirstDepRecField() != null ) {
4090 output.println(" seseToIssue->common.offsetToDepSESErecords=(INTPTR)sizeof("+
4091 fsen.getSESErecordName()+") - (INTPTR)&((("+
4092 fsen.getSESErecordName()+"*)0)->"+fsen.getFirstDepRecField()+");"
4096 if (state.RCR&&fsen.getInVarsForDynamicCoarseConflictResolution().size()>0) {
4097 output.println(" seseToIssue->common.offsetToParamRecords=(INTPTR) & ((("+fsen.getSESErecordName()+"*)0)->rcrRecords);");
4100 // fill in common data
4101 output.println(" int localCount=0;");
4102 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
4103 output.println(" seseToIssue->common.unresolvedDependencies = 10000;");
4104 output.println(" seseToIssue->common.parentsStallSem = NULL;");
4105 output.println(" initQueue(&seseToIssue->common.forwardList);");
4106 output.println(" seseToIssue->common.doneExecuting = FALSE;");
4107 output.println(" seseToIssue->common.numRunningChildren = 0;");
4108 output.println( "#ifdef OOO_DISABLE_TASKMEMPOOL" );
4109 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
4110 output.println("#endif");
4111 output.println(" seseToIssue->common.parent = runningSESE;");
4112 // start with refCount = 2, one being the count that the child itself
4113 // will decrement when it retires, to say it is done using its own
4114 // record, and the other count is for the parent that will remember
4115 // the static name of this new child below
4117 // if we're using RCR, ref count is 3 because the traverser has
4119 if( fsen != oooa.getMainSESE() && fsen.getInVarsForDynamicCoarseConflictResolution().size()>0){
4120 output.println(" seseToIssue->common.refCount = 10003;");
4122 output.println(" seseToIssue->common.refCount = 10002;");
4124 output.println(" int refCount=10000;");
4126 output.println(" seseToIssue->common.refCount = 2;");
4129 // all READY in-vars should be copied now and be done with it
4130 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
4131 while( tempItr.hasNext() ) {
4132 TempDescriptor temp = tempItr.next();
4134 // when we are issuing the main SESE or an SESE with placeholder
4135 // caller SESE as parent, generate temp child child's eclosing method,
4136 // otherwise use the parent's enclosing method as the context
4137 boolean useParentContext = false;
4139 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4140 (state.OOOJAVA && fsen != oooa.getMainSESE())
4142 assert fsen.getParent() != null;
4143 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
4144 useParentContext = true;
4148 if( useParentContext ) {
4149 output.println(" seseToIssue->"+temp+" = "+
4150 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
4152 output.println(" seseToIssue->"+temp+" = "+
4153 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
4157 // before potentially adding this SESE to other forwarding lists,
4159 output.println( "#ifdef OOO_DISABLE_TASKMEMPOOL" );
4160 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
4161 output.println("#endif");
4163 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4164 (state.OOOJAVA && fsen != oooa.getMainSESE())
4166 // count up outstanding dependencies, static first, then dynamic
4167 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
4168 while( staticSrcsItr.hasNext() ) {
4169 SESEandAgePair srcPair = staticSrcsItr.next();
4170 output.println(" {");
4171 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
4172 output.println(" pthread_mutex_lock( &(src->lock) );");
4174 output.println(" if( !src->doneExecuting ) {");
4175 output.println(" addNewItem( &src->forwardList, seseToIssue );");
4176 output.println(" ++(localCount);");
4177 output.println(" }");
4178 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4179 output.println(" ADD_REFERENCE_TO( src );");
4180 output.println("#endif" );
4181 output.println(" pthread_mutex_unlock( &(src->lock) );");
4182 output.println(" }");
4184 // whether or not it is an outstanding dependency, make sure
4185 // to pass the static name to the child's record
4186 output.println(" seseToIssue->"+srcPair+" = "+
4187 "("+srcPair.getSESE().getSESErecordName()+"*)"+
4191 // dynamic sources might already be accounted for in the static list,
4192 // so only add them to forwarding lists if they're not already there
4193 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
4194 while( dynVarsItr.hasNext() ) {
4195 TempDescriptor dynInVar = dynVarsItr.next();
4196 output.println(" {");
4197 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
4199 // the dynamic source is NULL if it comes from your own space--you can't pass
4200 // the address off to the new child, because you're not done executing and
4201 // might change the variable, so copy it right now
4202 output.println(" if( src != NULL ) {");
4203 output.println(" pthread_mutex_lock( &(src->lock) );");
4207 output.println(" if( isEmpty( &src->forwardList ) ||");
4208 output.println(" seseToIssue != peekItem( &src->forwardList ) ) {");
4209 output.println(" if( !src->doneExecuting ) {");
4210 output.println(" addNewItem( &src->forwardList, seseToIssue );");
4211 output.println(" ++(localCount);");
4212 output.println(" }");
4213 output.println(" }");
4214 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4215 output.println(" ADD_REFERENCE_TO( src );");
4216 output.println("#endif" );
4217 output.println(" pthread_mutex_unlock( &(src->lock) );");
4218 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
4219 output.println(" } else {");
4221 boolean useParentContext = false;
4222 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4223 (state.OOOJAVA && fsen != oooa.getMainSESE())
4225 assert fsen.getParent() != null;
4226 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
4227 useParentContext = true;
4230 if( useParentContext ) {
4231 output.println(" seseToIssue->"+dynInVar+" = "+
4232 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
4234 output.println(" seseToIssue->"+dynInVar+" = "+
4235 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
4238 output.println(" }");
4239 output.println(" }");
4241 // even if the value is already copied, make sure your NULL source
4242 // gets passed so child knows it already has the dynamic value
4243 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
4249 // maintain pointers for finding dynamic SESE
4250 // instances from static names
4251 SESEandAgePair pairNewest = new SESEandAgePair( fsen, 0 );
4252 SESEandAgePair pairOldest = new SESEandAgePair( fsen, fsen.getOldestAgeToTrack() );
4253 if( fsen.getParent() != null &&
4254 fsen.getParent().getNeededStaticNames().contains( pairNewest )
4256 output.println(" {");
4257 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4258 output.println(" SESEcommon* oldest = "+pairOldest+";");
4259 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4261 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
4262 SESEandAgePair pair1 = new SESEandAgePair( fsen, i );
4263 SESEandAgePair pair2 = new SESEandAgePair( fsen, i-1 );
4264 output.println(" "+pair1+" = "+pair2+";");
4266 output.println(" "+pairNewest+" = &(seseToIssue->common);");
4268 // no need to add a reference to whatever is the newest record, because
4269 // we initialized seseToIssue->refCount to *2*
4270 // but release a reference to whatever was the oldest BEFORE the shift
4271 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4272 output.println(" if( oldest != NULL ) {");
4273 output.println(" RELEASE_REFERENCE_TO( oldest );");
4274 output.println(" }");
4275 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4276 output.println(" }");
4279 if( state.COREPROF ) {
4280 output.println("#ifdef CP_EVENTID_PREPAREMEMQ");
4281 output.println(" CP_LOGEVENT( CP_EVENTID_PREPAREMEMQ, CP_EVENTTYPE_BEGIN );");
4282 output.println("#endif");
4287 // count up memory conflict dependencies,
4289 dispatchMEMRC(fm, lb, fsen, output);
4290 } else if(state.OOOJAVA){
4292 // assumes that there is only one parent, but it is possible that
4293 // currentSESE has more than one so we need to generate
4294 // conditional case for each parent case
4295 assert fsen.getSESEParent().size()>0;
4296 FlatSESEEnterNode parent = fsen.getSESEParent().iterator().next();
4297 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(parent);
4298 if (graph != null && graph.hasConflictEdge()) {
4299 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
4301 output.println(" //add memory queue element");
4302 Analysis.OoOJava.SESEWaitingQueue seseWaitingQueue=
4303 graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet);
4304 if(seseWaitingQueue.getWaitingElementSize()>0) {
4305 output.println(" {");
4306 output.println(" REntry* rentry=NULL;");
4307 output.println(" INTPTR* pointer=NULL;");
4308 output.println(" seseToIssue->common.rentryIdx=0;");
4310 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
4311 for (Iterator iterator = queueIDSet.iterator(); iterator.hasNext();) {
4312 Integer key = (Integer) iterator.next();
4313 int queueID=key.intValue();
4314 Set<Analysis.OoOJava.WaitingElement> waitingQueueSet =
4315 seseWaitingQueue.getWaitingElementSet(queueID);
4316 int enqueueType=seseWaitingQueue.getType(queueID);
4317 if(enqueueType==SESEWaitingQueue.EXCEPTION) {
4318 output.println(" INITIALIZEBUF(runningSESE->memoryQueueArray[" + queueID+ "]);");
4320 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2.hasNext();) {
4321 Analysis.OoOJava.WaitingElement waitingElement
4322 = (Analysis.OoOJava.WaitingElement) iterator2.next();
4323 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
4324 output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
4325 + waitingElement.getStatus()
4326 + ", &(seseToIssue->common));");
4328 TempDescriptor td = waitingElement.getTempDesc();
4329 // decide whether waiting element is dynamic or static
4330 if (fsen.getDynamicInVarSet().contains(td)) {
4331 // dynamic in-var case
4332 output.println(" pointer=seseToIssue->"
4333 + waitingElement.getDynID()
4334 + "_srcSESE+seseToIssue->"
4335 + waitingElement.getDynID()
4337 output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
4338 + waitingElement.getStatus()
4339 + ", &(seseToIssue->common), pointer );");
4340 } else if (fsen.getStaticInVarSet().contains(td)) {
4341 // static in-var case
4342 VariableSourceToken vst = fsen.getStaticInVarSrc(td);
4345 String srcId = "SESE_" + vst.getSESE().getPrettyIdentifier()
4346 + vst.getSESE().getIdentifier()
4347 + "_" + vst.getAge();
4348 output.println(" pointer=(void*)&seseToIssue->"
4354 output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
4355 + waitingElement.getStatus()
4356 + ", &(seseToIssue->common), pointer );");
4359 output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
4360 + waitingElement.getStatus()
4361 + ", &(seseToIssue->common), (void*)&seseToIssue->"
4362 + waitingElement.getDynID()
4366 output.println(" rentry->queue=runningSESE->memoryQueueArray["
4367 + waitingElement.getQueueID()
4370 if(enqueueType==SESEWaitingQueue.NORMAL){
4371 output.println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4372 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["
4373 + waitingElement.getQueueID()
4374 + "],rentry)==NOTREADY) {");
4375 output.println(" localCount++;");
4376 output.println(" }");
4378 output.println(" ADDRENTRYTOBUF(runningSESE->memoryQueueArray[" + waitingElement.getQueueID() + "],rentry);");
4381 if(enqueueType!=SESEWaitingQueue.NORMAL){
4382 output.println(" localCount+=RESOLVEBUF(runningSESE->memoryQueueArray["
4383 + queueID+ "],&seseToIssue->common);");
4386 output.println(" }");
4391 ConflictGraph graph = null;
4392 FlatSESEEnterNode parent = fsen.getParent();
4393 if (parent != null) {
4394 if (parent.isCallerSESEplaceholder) {
4395 graph = mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
4397 graph = mlpa.getConflictGraphResults().get(parent);
4400 if (graph != null && graph.hasConflictEdge()) {
4401 HashSet<SESELock> seseLockSet = mlpa.getConflictGraphLockMap()
4404 output.println(" //add memory queue element");
4405 SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(fsen.getIdentifier(),
4407 if(seseWaitingQueue.getWaitingElementSize()>0){
4408 output.println(" {");
4409 output.println(" REntry* rentry=NULL;");
4410 output.println(" INTPTR* pointer=NULL;");
4411 output.println(" seseToIssue->common.rentryIdx=0;");
4413 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
4414 for (Iterator iterator = queueIDSet.iterator(); iterator
4416 Integer key = (Integer) iterator.next();
4417 int queueID=key.intValue();
4418 Set<WaitingElement> waitingQueueSet = seseWaitingQueue.getWaitingElementSet(queueID);
4419 int enqueueType=seseWaitingQueue.getType(queueID);
4420 if(enqueueType==SESEWaitingQueue.EXCEPTION){
4421 output.println(" INITIALIZEBUF(runningSESE->memoryQueueArray["
4424 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2
4426 WaitingElement waitingElement = (WaitingElement) iterator2
4428 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
4429 output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
4430 + waitingElement.getStatus()
4431 + ", &(seseToIssue->common));");
4433 TempDescriptor td = waitingElement
4435 // decide whether waiting element is dynamic or
4437 if (fsen.getDynamicInVarSet().contains(td)) {
4438 // dynamic in-var case
4439 output.println(" pointer=seseToIssue->"
4440 + waitingElement.getDynID()
4441 + "_srcSESE+seseToIssue->"
4442 + waitingElement.getDynID()
4445 .println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
4448 + ", &(seseToIssue->common), pointer );");
4449 } else if (fsen.getStaticInVarSet()
4451 // static in-var case
4452 VariableSourceToken vst = fsen
4453 .getStaticInVarSrc(td);
4456 String srcId = "SESE_"
4458 .getPrettyIdentifier()
4459 + vst.getSESE().getIdentifier()
4460 + "_" + vst.getAge();
4462 .println(" pointer=(void*)&seseToIssue->"
4469 .println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
4472 + ", &(seseToIssue->common), pointer );");
4477 .println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
4480 + ", &(seseToIssue->common), (void*)&seseToIssue->"
4481 + waitingElement.getDynID()
4486 .println(" rentry->queue=runningSESE->memoryQueueArray["
4487 + waitingElement.getQueueID()
4490 if(enqueueType==SESEWaitingQueue.NORMAL){
4492 .println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4494 .println(" if(ADDRENTRY(runningSESE->memoryQueueArray["
4495 + waitingElement.getQueueID()
4496 + "],rentry)==NOTREADY){");
4497 output.println(" ++(localCount);");
4498 output.println(" } ");
4501 .println(" ADDRENTRYTOBUF(runningSESE->memoryQueueArray["
4502 + waitingElement.getQueueID()
4506 if(enqueueType!=SESEWaitingQueue.NORMAL){
4507 output.println(" localCount+=RESOLVEBUF(runningSESE->memoryQueueArray["
4508 + queueID+ "],&seseToIssue->common);");
4511 output.println(" }");
4518 if( state.COREPROF ) {
4519 output.println("#ifdef CP_EVENTID_PREPAREMEMQ");
4520 output.println(" CP_LOGEVENT( CP_EVENTID_PREPAREMEMQ, CP_EVENTTYPE_END );");
4521 output.println("#endif");
4524 // Enqueue Task Record
4526 if( fsen != oooa.getMainSESE() && fsen.getInVarsForDynamicCoarseConflictResolution().size()>0){
4527 output.println(" enqueueTR(TRqueue, (void *)seseToIssue);");
4531 // if there were no outstanding dependencies, issue here
4532 output.println(" if( atomic_sub_and_test(10000-localCount,&(seseToIssue->common.unresolvedDependencies) ) ) {");
4533 output.println(" workScheduleSubmit( (void*)seseToIssue );");
4534 output.println(" }");
4538 if( state.COREPROF ) {
4539 output.println("#ifdef CP_EVENTID_TASKDISPATCH");
4540 output.println(" CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_END );");
4541 output.println("#endif");
4544 output.println(" }");
4548 void dispatchMEMRC(FlatMethod fm, LocalityBinding lb, FlatSESEEnterNode fsen, PrintWriter output) {
4550 // assumes that there is only one parent, but it is possible that
4551 // currentSESE has more than one so we need to generate
4552 // conditional case for each parent case
4553 assert fsen.getSESEParent().size()>0;
4554 FlatSESEEnterNode parent = fsen.getSESEParent().iterator().next();
4555 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(parent);
4556 if (graph != null && graph.hasConflictEdge()) {
4557 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
4558 Analysis.OoOJava.SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet);
4559 if(seseWaitingQueue.getWaitingElementSize()>0) {
4560 output.println(" {");
4561 output.println(" REntry* rentry=NULL;");
4562 output.println(" INTPTR* pointer=NULL;");
4563 output.println(" seseToIssue->common.rentryIdx=0;");
4564 Vector<TempDescriptor> invars=fsen.getInVarsForDynamicCoarseConflictResolution();
4565 System.out.println(fm.getMethod()+"["+invars+"]");
4567 Vector<Long> queuetovar=new Vector<Long>();
4569 for(int i=0;i<invars.size();i++) {
4570 TempDescriptor td=invars.get(i);
4571 Set<Analysis.OoOJava.WaitingElement> weset=seseWaitingQueue.getWaitingElementSet(td);
4573 Set<Integer> queueSet=new HashSet<Integer>();
4574 for (Iterator iterator = weset.iterator(); iterator.hasNext();) {
4575 Analysis.OoOJava.WaitingElement we = (Analysis.OoOJava.WaitingElement) iterator.next();
4576 Integer queueID=new Integer( we.getQueueID());
4577 if(!queueSet.contains(queueID)){
4579 queueSet.add(queueID);
4582 output.println(" seseToIssue->rcrRecords["+i+"].flag="+numqueues+";");
4583 output.println(" seseToIssue->rcrRecords["+i+"].index=0;");
4584 output.println(" seseToIssue->rcrRecords["+i+"].next=NULL;");
4585 output.println(" int dispCount"+i+"=0;");
4587 for (Iterator<Analysis.OoOJava.WaitingElement> wtit = weset.iterator(); wtit.hasNext();) {
4588 Analysis.OoOJava.WaitingElement waitingElement = wtit.next();
4589 int queueID = waitingElement.getQueueID();
4590 if (queueID >= queuetovar.size())
4591 queuetovar.setSize(queueID + 1);
4592 Long l = queuetovar.get(queueID);
4593 long val = (l != null) ? l.longValue() : 0;
4594 val = val | (1 << i);
4595 queuetovar.set(queueID, new Long(val));
4599 HashSet generatedqueueentry=new HashSet();
4600 for(int i=0;i<invars.size();i++) {
4601 TempDescriptor td=invars.get(i);
4602 Set<Analysis.OoOJava.WaitingElement> weset=seseWaitingQueue.getWaitingElementSet(td);
4603 for(Iterator<Analysis.OoOJava.WaitingElement> wtit=weset.iterator();wtit.hasNext();) {
4604 Analysis.OoOJava.WaitingElement waitingElement=wtit.next();
4605 int queueID=waitingElement.getQueueID();
4607 if(waitingElement.isBogus()){
4611 if (generatedqueueentry.contains(queueID))
4614 generatedqueueentry.add(queueID);
4616 assert(waitingElement.getStatus()>=ConflictNode.COARSE);
4617 long mask=queuetovar.get(queueID);
4618 output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "]," + waitingElement.getStatus() + ", &(seseToIssue->common), "+mask+"LL);");
4619 output.println(" rentry->count=2;");
4620 output.println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4621 output.println(" rentry->queue=runningSESE->memoryQueueArray[" + waitingElement.getQueueID()+"];");
4623 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "],rentry)==READY) {");
4624 for(int j=0;mask!=0;j++) {
4626 output.println(" dispCount"+j+"++;");
4629 output.println(" } else ");
4630 output.println(" refCount--;");
4634 if (fsen.getDynamicInVarSet().contains(td)) {
4635 // dynamic in-var case
4636 //output.println(" pointer=seseToIssue->" + waitingElement.getDynID()+ "_srcSESE+seseToIssue->"+ waitingElement.getDynID()+ "_srcOffset;");
4637 //output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", &(seseToIssue->common), pointer );");
4640 for(int i=0;i<invars.size();i++) {
4641 output.println(" if(!dispCount"+i+" || !atomic_sub_and_test(dispCount"+i+",&(seseToIssue->rcrRecords["+i+"].flag)))");
4642 output.println(" localCount++;");
4644 output.println(" }");
4647 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL");
4648 output.println(" RELEASE_REFERENCES_TO((SESEcommon *)seseToIssue, refCount);");
4649 output.println("#endif");
4652 public void generateFlatSESEExitNode( FlatMethod fm,
4654 FlatSESEExitNode fsexn,
4655 PrintWriter output) {
4657 // if MLP flag is off, okay that SESE nodes are in IR graph,
4658 // just skip over them and code generates exactly the same
4659 if( ! (state.MLP || state.OOOJAVA) ) {
4663 // get the enter node for this exit that has meta data embedded
4664 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
4666 // there may be an SESE in an unreachable method, skip over
4667 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
4668 (state.OOOJAVA && !oooa.getAllSESEs().contains( fsen ))
4673 // also, if we have encountered a placeholder, just jump it
4674 if( fsen.getIsCallerSESEplaceholder() ) {
4678 if( state.COREPROF ) {
4679 output.println("#ifdef CP_EVENTID_TASKEXECUTE");
4680 output.println(" CP_LOGEVENT( CP_EVENTID_TASKEXECUTE, CP_EVENTTYPE_END );");
4681 output.println("#endif");
4684 output.println(" /* SESE exiting */");
4686 if( state.COREPROF ) {
4687 output.println("#ifdef CP_EVENTID_TASKRETIRE");
4688 output.println(" CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_BEGIN );");
4689 output.println("#endif");
4693 // this SESE cannot be done until all of its children are done
4694 // so grab your own lock with the condition variable for watching
4695 // that the number of your running children is greater than zero
4696 output.println(" atomic_add(childSESE, &runningSESE->numRunningChildren);");
4697 output.println(" pthread_mutex_lock( &(runningSESE->lock) );");
4698 output.println(" if( runningSESE->numRunningChildren > 0 ) {");
4699 output.println(" stopforgc( (struct garbagelist *)&___locals___ );");
4700 output.println(" do {");
4701 output.println(" pthread_cond_wait( &(runningSESE->runningChildrenCond), &(runningSESE->lock) );");
4702 output.println(" } while( runningSESE->numRunningChildren > 0 );");
4703 output.println(" restartaftergc();");
4704 output.println(" }");
4707 // copy out-set from local temps into the sese record
4708 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
4709 while( itr.hasNext() ) {
4710 TempDescriptor temp = itr.next();
4712 // only have to do this for primitives non-arrays
4714 temp.getType().isPrimitive() && !temp.getType().isArray()
4720 // have to determine the context enclosing this sese
4721 boolean useParentContext = false;
4723 if( (state.MLP &&fsen != mlpa.getMainSESE()) ||
4724 (state.OOOJAVA &&fsen != oooa.getMainSESE())
4726 assert fsen.getParent() != null;
4727 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
4728 useParentContext = true;
4733 if( useParentContext ) {
4734 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
4736 from = generateTemp( fsen.getfmEnclosing(), temp, null );
4739 output.println(" "+paramsprefix+
4740 "->"+temp.getSafeSymbol()+
4744 // mark yourself done, your task data is now read-only
4745 output.println(" runningSESE->doneExecuting = TRUE;");
4747 // if parent is stalling on you, let them know you're done
4748 if( (state.MLP && fsexn.getFlatEnter() != mlpa.getMainSESE()) ||
4749 (state.OOOJAVA && fsexn.getFlatEnter() != oooa.getMainSESE())
4751 output.println(" if( runningSESE->parentsStallSem != NULL ) {");
4752 output.println(" psem_give( runningSESE->parentsStallSem );");
4753 output.println(" }");
4756 output.println(" pthread_mutex_unlock( &(runningSESE->lock) );");
4758 // decrement dependency count for all SESE's on your forwarding list
4761 output.println(" while( !isEmpty( &runningSESE->forwardList ) ) {");
4762 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( &runningSESE->forwardList );");
4766 output.println(" if(consumer->rentryIdx>0){");
4767 output.println(" // resolved null pointer");
4768 output.println(" int idx;");
4769 output.println(" for(idx=0;idx<consumer->rentryIdx;idx++){");
4770 output.println(" resolvePointer(consumer->rentryArray[idx]);");
4771 output.println(" }");
4772 output.println(" }");
4775 output.println(" if( atomic_sub_and_test( 1, &(consumer->unresolvedDependencies) ) ){");
4776 output.println(" workScheduleSubmit( (void*)consumer );");
4777 output.println(" }");
4778 output.println(" }");
4781 // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
4782 if((state.MLP && fsen != mlpa.getMainSESE()) ||
4783 (state.OOOJAVA && fsen != oooa.getMainSESE())) {
4785 output.println(" /* check memory dependency*/");
4786 output.println(" {");
4787 output.println(" int idx;");
4788 output.println(" for(idx=0;idx<___params___->common.rentryIdx;idx++){");
4789 output.println(" REntry* re=___params___->common.rentryArray[idx];");
4790 output.println(" RETIRERENTRY(re->queue,re);");
4791 output.println(" }");
4792 output.println(" }");
4795 Vector<TempDescriptor> inset=fsen.getInVarsForDynamicCoarseConflictResolution();
4796 if (state.RCR && inset.size() > 0) {
4797 /* Make sure the running SESE is finished */
4798 output.println(" if (unlikely(runningSESE->rcrstatus!=0)) {");
4799 output.println(" if(CAS(&runningSESE->rcrstatus,1,0)==2) {");
4800 output.println(" while(runningSESE->rcrstatus) {");
4801 output.println(" BARRIER();");
4802 output.println(" sched_yield();");
4803 output.println(" }");
4804 output.println(" }");
4805 output.println(" }");
4806 output.println("{");
4807 output.println(" int idx,idx2;");
4809 output.println(" struct rcrRecord *rec;");
4811 .println(" struct Hashtable_rcr ** hashstruct=runningSESE->parent->allHashStructures;");
4813 for (int i = 0; i < inset.size(); i++) {
4814 output.println(" rec=&" + paramsprefix + "->rcrRecords[" + i + "];");
4815 output.println(" while(rec!=NULL) {");
4816 output.println(" for(idx2=0;idx2<rec->index;idx2++) {");
4818 int weaklyConnectedComponentIndex = rcr.getWeakID(inset.get(i), fsen);
4820 output.println(" rcr_RETIREHASHTABLE(hashstruct[" + weaklyConnectedComponentIndex
4821 + "],&(___params___->common), rec->array[idx2], (BinItem_rcr *) rec->ptrarray[idx2]);");
4823 output.println(" }");// exit idx2 for loop
4824 output.println(" rec=rec->next;");
4825 output.println(" }");// exit rec while loop
4827 output.println("}");
4831 // a task has variables to track static/dynamic instances
4832 // that serve as sources, release the parent's ref of each
4833 // non-null var of these types
4834 output.println(" // releasing static SESEs");
4835 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4836 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
4837 while( pItr.hasNext() ) {
4838 SESEandAgePair pair = pItr.next();
4839 output.println(" if( "+pair+" != NULL ) {");
4840 output.println(" RELEASE_REFERENCE_TO( "+pair+" );");
4841 output.println(" }");
4843 output.println(" // releasing dynamic variable sources");
4844 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
4845 while( dynSrcItr.hasNext() ) {
4846 TempDescriptor dynSrcVar = dynSrcItr.next();
4847 output.println(" if( "+dynSrcVar+"_srcSESE != NULL ) {");
4848 output.println(" RELEASE_REFERENCE_TO( "+dynSrcVar+"_srcSESE );");
4849 output.println(" }");
4851 // destroy this task's mempool if it is not a leaf task
4852 if( !fsen.getIsLeafSESE() ) {
4853 output.println(" pooldestroy( runningSESE->taskRecordMemPool );");
4854 if (state.RCR && fsen.getInVarsForDynamicCoarseConflictResolution().size() > 0 ) {
4855 output.println(" returnTR();");
4858 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4861 output.println("{");
4862 output.println("SESEcommon *myparent=runningSESE->parent;");
4864 // if this is not the Main sese (which has no parent) then return
4865 // THIS task's record to the PARENT'S task record pool, and only if
4866 // the reference count is now zero
4867 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4868 (state.OOOJAVA && fsen != oooa.getMainSESE())
4870 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4871 output.println(" RELEASE_REFERENCE_TO( runningSESE );");
4872 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4874 // the main task has no parent, just free its record
4875 output.println(" mlpFreeSESErecord( runningSESE );");
4879 // last of all, decrement your parent's number of running children
4880 output.println(" if( myparent != NULL ) {");
4881 output.println(" if( atomic_sub_and_test( 1, &(myparent->numRunningChildren) ) ) {");
4882 output.println(" pthread_mutex_lock ( &(myparent->lock) );");
4883 output.println(" pthread_cond_signal ( &(myparent->runningChildrenCond) );");
4884 output.println(" pthread_mutex_unlock( &(myparent->lock) );");
4885 output.println(" }");
4886 output.println(" }");
4888 output.println("}");
4890 // as this thread is wrapping up the task, make sure the thread-local var
4891 // for the currently running task record references an invalid task
4892 output.println(" runningSESE = (SESEcommon*) 0x1;");
4894 if( state.COREPROF ) {
4895 output.println("#ifdef CP_EVENTID_TASKRETIRE");
4896 output.println(" CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_END );");
4897 output.println("#endif");
4901 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
4903 FlatWriteDynamicVarNode fwdvn,
4906 if( !(state.MLP || state.OOOJAVA) ) {
4907 // should node should not be in an IR graph if the
4908 // MLP flag is not set
4909 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
4912 Hashtable<TempDescriptor, VSTWrapper> writeDynamic = fwdvn.getVar2src();
4914 assert writeDynamic != null;
4916 Iterator wdItr = writeDynamic.entrySet().iterator();
4917 while( wdItr.hasNext() ) {
4918 Map.Entry me = (Map.Entry) wdItr.next();
4919 TempDescriptor refVar = (TempDescriptor) me.getKey();
4920 VSTWrapper vstW = (VSTWrapper) me.getValue();
4921 VariableSourceToken vst = vstW.vst;
4923 output.println(" {");
4924 output.println(" SESEcommon* oldSrc = "+refVar+"_srcSESE;");
4927 // if there is no given source, this variable is ready so
4928 // mark src pointer NULL to signify that the var is up-to-date
4929 output.println(" "+refVar+"_srcSESE = NULL;");
4931 // otherwise we track where it will come from
4932 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
4933 output.println(" "+refVar+"_srcSESE = "+instance+";");
4934 output.println(" "+refVar+"_srcOffset = (INTPTR) &((("+
4935 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
4938 // no matter what we did above, track reference count of whatever
4939 // this variable pointed to, do release last in case we're just
4940 // copying the same value in because 1->2->1 is safe but ref count
4941 // 1->0->1 has a window where it looks like it should be free'd
4942 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4943 output.println(" if( "+refVar+"_srcSESE != NULL ) {");
4944 output.println(" ADD_REFERENCE_TO( "+refVar+"_srcSESE );");
4945 output.println(" }");
4946 output.println(" if( oldSrc != NULL ) {");
4947 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
4948 output.println(" }");
4949 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4951 output.println(" }");
4956 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
4957 if (state.CONSCHECK) {
4958 String specname=fcn.getSpec();
4959 String varname="repairstate___";
4960 output.println("{");
4961 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
4963 TempDescriptor[] temps=fcn.getTemps();
4964 String[] vars=fcn.getVars();
4965 for(int i=0; i<temps.length; i++) {
4966 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
4969 output.println("if (doanalysis"+specname+"("+varname+")) {");
4970 output.println("free"+specname+"_state("+varname+");");
4971 output.println("} else {");
4972 output.println("/* Bad invariant */");
4973 output.println("free"+specname+"_state("+varname+");");
4974 output.println("abort_task();");
4975 output.println("}");
4976 output.println("}");
4980 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
4982 MethodDescriptor md=fc.getMethod();
4983 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
4984 ClassDescriptor cn=md.getClassDesc();
4986 // if the called method is a static block or a static method or a constructor
4987 // need to check if it can be invoked inside some static block
4989 // TODO add version for normal Java later
4990 if((md.isStatic() || md.isStaticBlock() || md.isConstructor()) &&
4991 ((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic()))) {
4992 if(!md.isInvokedByStatic()) {
4993 System.err.println("Error: a method that is invoked inside a static block is not tagged!");
4995 // is a static block or is invoked in some static block
4996 ClassDescriptor cd = fm.getMethod().getClassDesc();
4998 // the same class, do nothing
4999 // TODO may want to invoke static field initialization here
5001 if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
5002 // need to check if the class' static fields have been initialized and/or
5003 // its static blocks have been executed
5004 output.println("#ifdef MGC_STATIC_INIT_CHECK");
5005 output.println("if(global_defs_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
5006 if(cn.getNumStaticFields() != 0) {
5007 // TODO add static field initialization here
5009 if(cn.getNumStaticBlocks() != 0) {
5010 MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
5011 output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
5013 output.println(" global_defs_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
5015 output.println("}");
5016 output.println("#endif // MGC_STATIC_INIT_CHECK");
5022 output.println("{");
5023 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5025 LocalityBinding fclb=locality.getBinding(lb, fc);
5026 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
5028 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
5029 output.print(objectparams.numPointers());
5030 output.print(", "+localsprefixaddr);
5031 if (md.getThis()!=null) {
5033 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
5035 if (fc.getThis()!=null&&md.getThis()==null) {
5036 System.out.println("WARNING!!!!!!!!!!!!");
5037 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
5041 for(int i=0; i<fc.numArgs(); i++) {
5042 Descriptor var=md.getParameter(i);
5043 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
5044 if (objectparams.isParamPtr(paramtemp)) {
5045 TempDescriptor targ=fc.getArg(i);
5047 TypeDescriptor td=md.getParamType(i);
5049 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
5051 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
5054 output.println("};");
5059 if (fc.getReturnTemp()!=null)
5060 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
5062 /* Do we need to do virtual dispatch? */
5063 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
5066 LocalityBinding fclb=locality.getBinding(lb, fc);
5067 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
5069 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
5074 if (md.getReturnType().isClass()||md.getReturnType().isArray())
5075 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
5077 output.print(md.getReturnType().getSafeSymbol()+" ");
5078 output.print("(*)(");
5080 boolean printcomma=false;
5081 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5083 LocalityBinding fclb=locality.getBinding(lb, fc);
5084 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
5086 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
5090 for(int i=0; i<objectparams.numPrimitives(); i++) {
5091 TempDescriptor temp=objectparams.getPrimitive(i);
5095 if (temp.getType().isClass()||temp.getType().isArray())
5096 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
5098 output.print(temp.getType().getSafeSymbol());
5103 LocalityBinding fclb=locality.getBinding(lb, fc);
5104 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
5106 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
5110 boolean needcomma=false;
5111 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5112 output.print("&__parameterlist__");
5116 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
5117 if (fc.getThis()!=null) {
5118 TypeDescriptor ptd=null;
5119 if(md.getThis() != null) {
5120 ptd = md.getThis().getType();
5122 ptd = fc.getThis().getType();
5126 if (ptd.isClass()&&!ptd.isArray())
5127 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
5128 output.print(generateTemp(fm,fc.getThis(),lb));
5133 for(int i=0; i<fc.numArgs(); i++) {
5134 Descriptor var=md.getParameter(i);
5135 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
5136 if (objectparams.isParamPrim(paramtemp)) {
5137 TempDescriptor targ=fc.getArg(i);
5141 TypeDescriptor ptd=md.getParamType(i);
5142 if (ptd.isClass()&&!ptd.isArray())
5143 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
5144 output.print(generateTemp(fm, targ,lb));
5148 output.println(");");
5149 output.println(" }");
5152 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
5153 Set subclasses=typeutil.getSubClasses(thiscd);
5154 if (subclasses==null)
5156 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
5157 ClassDescriptor cd=(ClassDescriptor)classit.next();
5158 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
5159 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
5160 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
5161 if (md.matches(matchmd))
5168 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
5169 if (state.SINGLETM) {
5170 //single machine transactional memory case
5171 String field=ffn.getField().getSafeSymbol();
5172 String src=generateTemp(fm, ffn.getSrc(),lb);
5173 String dst=generateTemp(fm, ffn.getDst(),lb);
5175 output.println(dst+"="+ src +"->"+field+ ";");
5176 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
5177 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
5178 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
5179 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
5180 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
5181 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
5182 if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
5183 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
5185 output.println("TRANSREADRD("+dst+", "+dst+");");
5188 } else if (state.DSM) {
5189 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
5190 if (status==LocalityAnalysis.GLOBAL) {
5191 String field=ffn.getField().getSafeSymbol();
5192 String src=generateTemp(fm, ffn.getSrc(),lb);
5193 String dst=generateTemp(fm, ffn.getDst(),lb);
5195 if (ffn.getField().getType().isPtr()) {
5197 //TODO: Uncomment this when we have runtime support
5198 //if (ffn.getSrc()==ffn.getDst()) {
5199 //output.println("{");
5200 //output.println("void * temp="+src+";");
5201 //output.println("if (temp&0x1) {");
5202 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
5203 //output.println(src+"->"+field+"="+temp+";");
5204 //output.println("}");
5205 //output.println(dst+"=temp;");
5206 //output.println("}");
5208 output.println(dst+"="+ src +"->"+field+ ";");
5209 //output.println("if ("+dst+"&0x1) {");
5210 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
5211 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
5212 //output.println(src+"->"+field+"="+src+"->"+field+";");
5213 //output.println("}");
5216 output.println(dst+"="+ src+"->"+field+";");
5218 } else if (status==LocalityAnalysis.LOCAL) {
5219 if (ffn.getField().getType().isPtr()&&
5220 ffn.getField().isGlobal()) {
5221 String field=ffn.getField().getSafeSymbol();
5222 String src=generateTemp(fm, ffn.getSrc(),lb);
5223 String dst=generateTemp(fm, ffn.getDst(),lb);
5224 output.println(dst+"="+ src +"->"+field+ ";");
5225 if (locality.getAtomic(lb).get(ffn).intValue()>0)
5226 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
5227 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
5229 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
5230 } else if (status==LocalityAnalysis.EITHER) {
5231 //Code is reading from a null pointer
5232 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
5233 output.println("#ifndef RAW");
5234 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
5235 output.println("#endif");
5236 //This should throw a suitable null pointer error
5237 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
5239 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
5241 // DEBUG if(!ffn.getDst().getType().isPrimitive()){
5242 // DEBUG output.println("within((void*)"+generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+");");
5245 // TODO add version for normal Java later
5246 if(ffn.getField().isStatic()) {
5248 if((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())) {
5249 // is a static block or is invoked in some static block
5250 ClassDescriptor cd = fm.getMethod().getClassDesc();
5251 ClassDescriptor cn = ffn.getSrc().getType().getClassDesc();
5253 // the same class, do nothing
5254 // TODO may want to invoke static field initialization here
5256 if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
5257 // need to check if the class' static fields have been initialized and/or
5258 // its static blocks have been executed
5259 output.println("#ifdef MGC_STATIC_INIT_CHECK");
5260 output.println("if(global_defs_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
5261 if(cn.getNumStaticFields() != 0) {
5262 // TODO add static field initialization here
5264 if(cn.getNumStaticBlocks() != 0) {
5265 MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
5266 output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
5268 output.println(" global_defs_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
5270 output.println("}");
5271 output.println("#endif // MGC_STATIC_INIT_CHECK");
5275 // redirect to the global_defs_p structure
5276 if(ffn.getSrc().getType().isStatic()) {
5277 // reference to the static field with Class name
5278 output.println(generateTemp(fm, ffn.getDst(),lb)+"=global_defs_p->"+ ffn.getSrc().getType().getClassDesc().getSafeSymbol()+ffn.getField().getSafeSymbol()+";");
5280 output.println(generateTemp(fm, ffn.getDst(),lb)+"=*"+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
5282 //output.println(generateTemp(fm, ffn.getDst(),lb)+"=global_defs_p->"+ffn.getSrc().getType().getClassDesc().getSafeSymbol()+"->"+ ffn.getField().getSafeSymbol()+";");
5284 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
5287 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
5293 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
5294 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
5295 throw new Error("Can't set array length");
5296 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
5297 //Single Machine Transaction Case
5298 boolean srcptr=fsfn.getSrc().getType().isPtr();
5299 String src=generateTemp(fm,fsfn.getSrc(),lb);
5300 String dst=generateTemp(fm,fsfn.getDst(),lb);
5301 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
5302 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
5303 output.println("{");
5304 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
5305 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
5306 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
5308 output.println("INTPTR srcoid=(INTPTR)"+src+";");
5311 if (wb.needBarrier(fsfn)&&
5312 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
5313 if (state.EVENTMONITOR) {
5314 output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
5316 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
5318 if (srcptr&!fsfn.getSrc().getType().isNull()) {
5319 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
5320 output.println("}");
5322 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
5324 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
5325 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
5326 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
5327 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
5329 String src=generateTemp(fm,fsfn.getSrc(),lb);
5330 String dst=generateTemp(fm,fsfn.getDst(),lb);
5332 output.println("{");
5333 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
5335 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
5338 if (wb.needBarrier(fsfn))
5339 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
5341 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
5343 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
5344 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
5345 /** Check if we need to copy */
5346 output.println("if(!"+dst+"->"+localcopystr+") {");
5347 /* Link object into list */
5348 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5349 output.println(revertptr+"=revertlist;");
5350 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
5351 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
5353 output.println("COPY_OBJ("+dst+");");
5354 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
5355 output.println("revertlist=(struct ___Object___ *)"+dst+";");
5356 output.println("}");
5358 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
5360 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
5361 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
5362 //writing to a null...bad
5363 output.println("if ("+dst+") {");
5364 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
5366 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
5368 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
5371 output.println("}");
5374 if (state.FASTCHECK) {
5375 String dst=generateTemp(fm, fsfn.getDst(),lb);
5376 output.println("if(!"+dst+"->"+localcopystr+") {");
5377 /* Link object into list */
5378 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
5379 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
5381 output.println("COPY_OBJ("+dst+");");
5382 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
5383 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
5384 output.println("}");
5387 // DEBUG if(!fsfn.getField().getType().isPrimitive()){
5388 // DEBUG output.println("within((void*)"+generateTemp(fm,fsfn.getSrc(),lb)+");");
5391 // TODO add version for normal Java later
5392 if(fsfn.getField().isStatic()) {
5394 if((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())) {
5395 // is a static block or is invoked in some static block
5396 ClassDescriptor cd = fm.getMethod().getClassDesc();
5397 ClassDescriptor cn = fsfn.getDst().getType().getClassDesc();
5399 // the same class, do nothing
5400 // TODO may want to invoke static field initialization here
5402 if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
5403 // need to check if the class' static fields have been initialized and/or
5404 // its static blocks have been executed
5405 output.println("#ifdef MGC_STATIC_INIT_CHECK");
5406 output.println("if(global_defs_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
5407 if(cn.getNumStaticFields() != 0) {
5408 // TODO add static field initialization here
5410 if(cn.getNumStaticBlocks() != 0) {
5411 MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
5412 output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
5414 output.println(" global_defs_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
5416 output.println("}");
5417 output.println("#endif // MGC_STATIC_INIT_CHECK");
5421 // redirect to the global_defs_p structure
5422 if(fsfn.getDst().getType().isStatic()) {
5423 // reference to the static field with Class name
5424 output.println("global_defs_p->" + fsfn.getDst().getType().getClassDesc().getSafeSymbol() + fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
5426 output.println("*"+generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
5429 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
5432 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
5437 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
5438 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
5441 if (elementtype.isArray()||elementtype.isClass())
5444 type=elementtype.getSafeSymbol()+" ";
5446 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
5447 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
5448 output.println("failedboundschk();");
5450 if (state.SINGLETM) {
5451 //Single machine transaction case
5452 String dst=generateTemp(fm, fen.getDst(),lb);
5453 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))) {
5454 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
5456 output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
5459 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
5460 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
5461 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
5462 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
5463 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
5464 if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
5465 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
5467 output.println("TRANSREADRD("+dst+", "+dst+");");
5470 } else if (state.DSM) {
5471 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
5472 if (status==LocalityAnalysis.GLOBAL) {
5473 String dst=generateTemp(fm, fen.getDst(),lb);
5474 if (elementtype.isPtr()) {
5475 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
5476 //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
5477 output.println("TRANSREAD("+dst+", "+dst+");");
5479 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
5481 } else if (status==LocalityAnalysis.LOCAL) {
5482 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
5483 } else if (status==LocalityAnalysis.EITHER) {
5484 //Code is reading from a null pointer
5485 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
5486 output.println("#ifndef RAW");
5487 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
5488 output.println("#endif");
5489 //This should throw a suitable null pointer error
5490 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
5492 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
5494 // DEBUG output.println("within((void*)"+generateTemp(fm,fen.getSrc(),lb)+");");
5495 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
5499 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
5500 //TODO: need dynamic check to make sure this assignment is actually legal
5501 //Because Object[] could actually be something more specific...ie. Integer[]
5503 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
5506 if (elementtype.isArray()||elementtype.isClass())
5509 type=elementtype.getSafeSymbol()+" ";
5511 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
5512 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
5513 output.println("failedboundschk();");
5516 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
5517 //Transaction set element case
5518 if (wb.needBarrier(fsen)&&
5519 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
5520 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
5522 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
5523 output.println("{");
5524 String src=generateTemp(fm, fsen.getSrc(), lb);
5525 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
5526 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
5527 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
5529 output.println("INTPTR srcoid=(INTPTR)"+src+";");
5531 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
5532 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
5534 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
5536 output.println("}");
5538 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
5539 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
5541 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
5544 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
5545 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
5546 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
5547 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
5548 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
5549 boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
5552 if (wb.needBarrier(fsen))
5553 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
5554 } else if (dstlocal) {
5555 /** Check if we need to copy */
5556 String dst=generateTemp(fm, fsen.getDst(),lb);
5557 output.println("if(!"+dst+"->"+localcopystr+") {");
5558 /* Link object into list */
5559 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5560 output.println(revertptr+"=revertlist;");
5561 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
5562 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
5564 output.println("COPY_OBJ("+dst+");");
5565 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
5566 output.println("revertlist=(struct ___Object___ *)"+dst+";");
5567 output.println("}");
5569 System.out.println("Node: "+fsen);
5570 System.out.println(lb);
5571 System.out.println("statusdst="+statusdst);
5572 System.out.println(fm.printMethod());
5573 throw new Error("Unknown array type");
5576 output.println("{");
5577 String src=generateTemp(fm, fsen.getSrc(), lb);
5578 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
5579 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
5580 output.println("}");
5582 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
5585 if (state.FASTCHECK) {
5586 String dst=generateTemp(fm, fsen.getDst(),lb);
5587 output.println("if(!"+dst+"->"+localcopystr+") {");
5588 /* Link object into list */
5589 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
5590 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
5592 output.println("COPY_OBJ("+dst+");");
5593 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
5594 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
5595 output.println("}");
5597 // DEBUG output.println("within((void*)"+generateTemp(fm,fsen.getDst(),lb)+");");
5598 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
5602 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
5603 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
5604 //Stash pointer in case of GC
5605 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5606 output.println(revertptr+"=revertlist;");
5608 if (state.SINGLETM) {
5609 if (fn.getType().isArray()) {
5610 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
5611 if (locality.getAtomic(lb).get(fn).intValue()>0) {
5612 //inside transaction
5613 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5615 //outside transaction
5616 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5619 if (locality.getAtomic(lb).get(fn).intValue()>0) {
5620 //inside transaction
5621 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
5623 //outside transaction
5624 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
5627 } else if (fn.getType().isArray()) {
5628 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
5629 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
5630 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5631 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5632 if(this.state.MLP || state.OOOJAVA){
5633 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray_mlp("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
5634 output.println(" oid += oidIncrement;");
5636 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5639 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5642 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
5643 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
5644 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5645 if (this.state.MLP || state.OOOJAVA){
5646 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new_mlp("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
5647 output.println(" oid += oidIncrement;");
5649 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
5652 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
5655 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
5656 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5657 String dst=generateTemp(fm,fn.getDst(),lb);
5658 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
5659 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
5660 output.println("revertlist=(struct ___Object___ *)"+dst+";");
5662 if (state.FASTCHECK) {
5663 String dst=generateTemp(fm,fn.getDst(),lb);
5664 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
5665 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
5666 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
5670 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
5671 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5672 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
5674 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
5678 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
5679 if (fon.getRight()!=null) {
5680 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
5681 if (fon.getLeft().getType().isLong())
5682 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
5684 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
5686 } else if (dc!=null) {
5687 output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
5688 if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
5689 output.print("(void *)");
5690 if (dc.getNeedLeftSrcTrans(lb, fon))
5691 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
5693 output.print(generateTemp(fm, fon.getLeft(),lb));
5694 output.print(")"+fon.getOp().toString()+"(");
5695 if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
5696 output.print("(void *)");
5697 if (dc.getNeedRightSrcTrans(lb, fon))
5698 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
5700 output.println(generateTemp(fm,fon.getRight(),lb)+");");
5702 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
5703 } else if (fon.getOp().getOp()==Operation.ASSIGN)
5704 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
5705 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
5706 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
5707 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
5708 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
5709 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
5710 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
5711 else if (fon.getOp().getOp()==Operation.COMP)
5712 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
5713 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
5714 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
5716 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
5719 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
5720 /* TODO: Do type check here */
5721 if (fcn.getType().isArray()) {
5722 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
5723 } else if (fcn.getType().isClass())
5724 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
5726 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
5729 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
5730 if (fln.getValue()==null)
5731 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
5732 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
5733 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5734 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
5735 //Stash pointer in case of GC
5736 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5737 output.println(revertptr+"=revertlist;");
5739 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
5740 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
5741 //Stash pointer in case of GC
5742 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5743 output.println("revertlist="+revertptr+";");
5746 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
5748 } else if (fln.getType().isBoolean()) {
5749 if (((Boolean)fln.getValue()).booleanValue())
5750 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
5752 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
5753 } else if (fln.getType().isChar()) {
5754 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
5755 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
5756 } else if (fln.getType().isLong()) {
5757 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
5759 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
5762 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
5764 // TODO add version for normal Java later
5765 if((fm.getMethod() != null) && (fm.getMethod().isStaticBlock())) {
5766 // a static block, check if it has been executed
5767 output.println(" global_defs_p->" + fm.getMethod().getClassDesc().getSafeSymbol()+"static_block_exe_flag = 1;");
5771 if (frn.getReturnTemp()!=null) {
5772 if (frn.getReturnTemp().getType().isPtr())
5773 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
5775 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
5777 output.println("return;");
5781 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
5784 //only record if this group has more than one exit
5785 if (branchanalysis.numJumps(fcb)>1) {
5786 left=branchanalysis.jumpValue(fcb, 0);
5787 right=branchanalysis.jumpValue(fcb, 1);
5789 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
5791 output.println("STOREBRANCH("+right+");");
5792 output.println("goto "+label+";");
5793 output.println("}");
5795 output.println("STOREBRANCH("+left+");");
5798 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
5799 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
5802 /** This method generates header information for the method or
5803 * task referenced by the Descriptor des. */
5804 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
5805 generateHeader(fm, lb, des, output, false);
5808 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
5810 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
5811 MethodDescriptor md=null;
5812 TaskDescriptor task=null;
5813 if (des instanceof MethodDescriptor)
5814 md=(MethodDescriptor) des;
5816 task=(TaskDescriptor) des;
5818 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
5820 if (md!=null&&md.getReturnType()!=null) {
5821 if (md.getReturnType().isClass()||md.getReturnType().isArray())
5822 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
5824 output.print(md.getReturnType().getSafeSymbol()+" ");
5826 //catch the constructor case
5827 output.print("void ");
5829 if (state.DSM||state.SINGLETM) {
5830 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5832 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5834 output.print(task.getSafeSymbol()+"(");
5836 boolean printcomma=false;
5837 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5839 if (state.DSM||state.SINGLETM) {
5840 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5842 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5844 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
5850 for(int i=0; i<objectparams.numPrimitives(); i++) {
5851 TempDescriptor temp=objectparams.getPrimitive(i);
5855 if (temp.getType().isClass()||temp.getType().isArray())
5856 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
5858 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
5860 output.println(") {");
5861 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
5862 /* Imprecise Task */
5863 output.println("void * parameterarray[]) {");
5864 /* Unpack variables */
5865 for(int i=0; i<objectparams.numPrimitives(); i++) {
5866 TempDescriptor temp=objectparams.getPrimitive(i);
5867 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
5869 for(int i=0; i<fm.numTags(); i++) {
5870 TempDescriptor temp=fm.getTag(i);
5871 int offset=i+objectparams.numPrimitives();
5872 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
5875 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
5876 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
5877 } else output.println(") {");
5880 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
5881 output.println("/* FlatFlagActionNode */");
5884 /* Process tag changes */
5885 Relation tagsettable=new Relation();
5886 Relation tagcleartable=new Relation();
5888 Iterator tagsit=ffan.getTempTagPairs();
5889 while (tagsit.hasNext()) {
5890 TempTagPair ttp=(TempTagPair) tagsit.next();
5891 TempDescriptor objtmp=ttp.getTemp();
5892 TagDescriptor tag=ttp.getTag();
5893 TempDescriptor tagtmp=ttp.getTagTemp();
5894 boolean tagstatus=ffan.getTagChange(ttp);
5896 tagsettable.put(objtmp, tagtmp);
5898 tagcleartable.put(objtmp, tagtmp);
5903 Hashtable flagandtable=new Hashtable();
5904 Hashtable flagortable=new Hashtable();
5906 /* Process flag changes */
5907 Iterator flagsit=ffan.getTempFlagPairs();
5908 while(flagsit.hasNext()) {
5909 TempFlagPair tfp=(TempFlagPair)flagsit.next();
5910 TempDescriptor temp=tfp.getTemp();
5911 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
5912 FlagDescriptor flag=tfp.getFlag();
5914 //Newly allocate objects that don't set any flags case
5915 if (flagortable.containsKey(temp)) {
5919 flagortable.put(temp,new Integer(mask));
5921 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
5922 boolean flagstatus=ffan.getFlagChange(tfp);
5925 if (flagortable.containsKey(temp)) {
5926 mask=((Integer)flagortable.get(temp)).intValue();
5929 flagortable.put(temp,new Integer(mask));
5931 int mask=0xFFFFFFFF;
5932 if (flagandtable.containsKey(temp)) {
5933 mask=((Integer)flagandtable.get(temp)).intValue();
5935 mask&=(0xFFFFFFFF^flagid);
5936 flagandtable.put(temp,new Integer(mask));
5942 HashSet flagtagset=new HashSet();
5943 flagtagset.addAll(flagortable.keySet());
5944 flagtagset.addAll(flagandtable.keySet());
5945 flagtagset.addAll(tagsettable.keySet());
5946 flagtagset.addAll(tagcleartable.keySet());
5948 Iterator ftit=flagtagset.iterator();
5949 while(ftit.hasNext()) {
5950 TempDescriptor temp=(TempDescriptor)ftit.next();
5953 Set tagtmps=tagcleartable.get(temp);
5954 if (tagtmps!=null) {
5955 Iterator tagit=tagtmps.iterator();
5956 while(tagit.hasNext()) {
5957 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5958 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5959 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5961 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5965 tagtmps=tagsettable.get(temp);
5966 if (tagtmps!=null) {
5967 Iterator tagit=tagtmps.iterator();
5968 while(tagit.hasNext()) {
5969 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5970 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5971 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5973 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
5978 int andmask=0xFFFFFFF;
5980 if (flagortable.containsKey(temp))
5981 ormask=((Integer)flagortable.get(temp)).intValue();
5982 if (flagandtable.containsKey(temp))
5983 andmask=((Integer)flagandtable.get(temp)).intValue();
5984 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
5985 generateObjectDistribute(ffan, fm, lb, temp, output);
5989 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
5990 PrintWriter output, int ormask, int andmask) {
5991 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
5992 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5994 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5998 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
5999 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
6002 void generateOptionalHeader(PrintWriter headers) {
6005 headers.println("#include \"task.h\"\n\n");
6006 headers.println("#ifndef _OPTIONAL_STRUCT_");
6007 headers.println("#define _OPTIONAL_STRUCT_");
6009 //STRUCT PREDICATEMEMBER
6010 headers.println("struct predicatemember{");
6011 headers.println("int type;");
6012 headers.println("int numdnfterms;");
6013 headers.println("int * flags;");
6014 headers.println("int numtags;");
6015 headers.println("int * tags;\n};\n\n");
6017 //STRUCT OPTIONALTASKDESCRIPTOR
6018 headers.println("struct optionaltaskdescriptor{");
6019 headers.println("struct taskdescriptor * task;");
6020 headers.println("int index;");
6021 headers.println("int numenterflags;");
6022 headers.println("int * enterflags;");
6023 headers.println("int numpredicatemembers;");
6024 headers.println("struct predicatemember ** predicatememberarray;");
6025 headers.println("};\n\n");
6027 //STRUCT TASKFAILURE
6028 headers.println("struct taskfailure {");
6029 headers.println("struct taskdescriptor * task;");
6030 headers.println("int index;");
6031 headers.println("int numoptionaltaskdescriptors;");
6032 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
6034 //STRUCT FSANALYSISWRAPPER
6035 headers.println("struct fsanalysiswrapper{");
6036 headers.println("int flags;");
6037 headers.println("int numtags;");
6038 headers.println("int * tags;");
6039 headers.println("int numtaskfailures;");
6040 headers.println("struct taskfailure ** taskfailurearray;");
6041 headers.println("int numoptionaltaskdescriptors;");
6042 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
6044 //STRUCT CLASSANALYSISWRAPPER
6045 headers.println("struct classanalysiswrapper{");
6046 headers.println("int type;");
6047 headers.println("int numotd;");
6048 headers.println("struct optionaltaskdescriptor ** otdarray;");
6049 headers.println("int numfsanalysiswrappers;");
6050 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
6052 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
6054 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
6055 while(taskit.hasNext()) {
6056 TaskDescriptor td=(TaskDescriptor)taskit.next();
6057 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
6062 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
6063 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
6064 int predicateindex = 0;
6065 //iterate through the classes concerned by the predicate
6066 Set c_vard = predicate.vardescriptors;
6067 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
6070 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
6071 VarDescriptor vard = (VarDescriptor)vard_it.next();
6072 TypeDescriptor typed = vard.getType();
6074 //generate for flags
6075 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
6076 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
6078 if (fen_hashset!=null) {
6079 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
6080 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
6082 DNFFlag dflag=fen.getDNF();
6083 numberterms+=dflag.size();
6085 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
6087 for(int j=0; j<dflag.size(); j++) {
6089 output.println(",");
6090 Vector term=dflag.get(j);
6093 for(int k=0; k<term.size(); k++) {
6094 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
6095 FlagDescriptor fd=dfa.getFlag();
6096 boolean negated=dfa.getNegated();
6097 int flagid=1<<((Integer)flags.get(fd)).intValue();
6102 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
6107 output.println("};\n");
6110 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
6111 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
6114 for(int j=0; j<tagel.numTags(); j++) {
6116 output.println(",");
6117 TempDescriptor tmp=tagel.getTemp(j);
6118 if (!slotnumber.containsKey(tmp)) {
6119 Integer slotint=new Integer(current_slot++);
6120 slotnumber.put(tmp,slotint);
6122 int slot=slotnumber.get(tmp).intValue();
6123 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
6125 numtags = tagel.numTags();
6127 output.println("};");
6129 //store the result into a predicatemember struct
6130 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
6131 output.println("/*type*/"+typed.getClassDesc().getId()+",");
6132 output.println("/* number of dnf terms */"+numberterms+",");
6133 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
6134 output.println("/* number of tag */"+numtags+",");
6135 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
6136 output.println("};\n");
6141 //generate an array that stores the entire predicate
6142 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
6143 for( int j = 0; j<predicateindex; j++) {
6144 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
6145 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
6147 output.println("};\n");
6148 return predicateindex;
6152 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
6153 generateOptionalHeader(headers);
6155 output.println("#include \"optionalstruct.h\"\n\n");
6156 output.println("#include \"stdlib.h\"\n");
6158 HashSet processedcd = new HashSet();
6160 Enumeration e = safeexecution.keys();
6161 while (e.hasMoreElements()) {
6164 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
6165 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
6167 //Generate the struct of optionals
6168 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
6169 numotd = c_otd.size();
6170 if(maxotd<numotd) maxotd = numotd;
6171 if( !c_otd.isEmpty() ) {
6172 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
6173 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
6175 //generate the int arrays for the predicate
6176 Predicate predicate = otd.predicate;
6177 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
6178 TreeSet<Integer> fsset=new TreeSet<Integer>();
6179 //iterate through possible FSes corresponding to
6180 //the state when entering
6182 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
6183 FlagState fs = (FlagState)fses.next();
6185 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
6186 FlagDescriptor flagd = (FlagDescriptor)flags.next();
6187 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
6190 fsset.add(new Integer(flagid));
6191 //tag information not needed because tag
6192 //changes are not tolerated.
6195 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
6196 boolean needcomma=false;
6197 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
6200 output.println(it.next());
6203 output.println("};\n");
6206 //generate optionaltaskdescriptor that actually
6207 //includes exit fses, predicate and the task
6209 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
6210 output.println("&task_"+otd.td.getSafeSymbol()+",");
6211 output.println("/*index*/"+otd.getIndex()+",");
6212 output.println("/*number of enter flags*/"+fsset.size()+",");
6213 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
6214 output.println("/*number of members */"+predicateindex+",");
6215 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
6216 output.println("};\n");
6220 // if there are no optionals, there is no need to build the rest of the struct
6222 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
6223 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
6224 if( !c_otd.isEmpty() ) {
6225 boolean needcomma=false;
6226 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
6227 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
6229 output.println(",");
6231 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
6234 output.println("};\n");
6236 //get all the possible flagstates reachable by an object
6237 Hashtable hashtbtemp = safeexecution.get(cdtemp);
6239 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
6240 fsts.addAll(hashtbtemp.keySet());
6241 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
6242 FlagState fs = (FlagState)fsit.next();
6245 //get the set of OptionalTaskDescriptors corresponding
6246 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
6247 //iterate through the OptionalTaskDescriptors and
6248 //store the pointers to the optionals struct (see on
6249 //top) into an array
6251 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
6252 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
6253 OptionalTaskDescriptor mm = mos.next();
6255 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
6257 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
6260 output.println("};\n");
6262 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
6265 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
6266 FlagDescriptor flagd = (FlagDescriptor)flags.next();
6267 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
6271 //process tag information
6274 boolean first = true;
6275 Enumeration tag_enum = fs.getTags();
6276 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
6277 while(tag_enum.hasMoreElements()) {
6279 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
6283 output.println(", ");
6284 output.println("/*tagid*/"+state.getTagId(tagd));
6286 output.println("};");
6288 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
6289 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
6290 TaskIndex ti=itti.next();
6294 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
6296 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
6297 boolean needcomma=false;
6298 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
6299 OptionalTaskDescriptor otd=otdit.next();
6303 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
6305 output.println("};");
6307 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
6308 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
6309 output.print(ti.getIndex()+", ");
6310 output.print(otdset.size()+", ");
6311 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
6312 output.println("};");
6315 tiset=sa.getTaskIndex(fs);
6316 boolean needcomma=false;
6318 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
6319 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
6320 TaskIndex ti=itti.next();
6321 if (ti.isRuntime()) {
6328 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
6330 output.println("};\n");
6332 //Store the result in fsanalysiswrapper
6334 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
6335 output.println("/*flag*/"+flagid+",");
6336 output.println("/* number of tags*/"+tagcounter+",");
6337 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
6338 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
6339 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
6340 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
6341 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
6342 output.println("};\n");
6346 //Build the array of fsanalysiswrappers
6347 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
6348 boolean needcomma=false;
6349 for(int i = 0; i<fscounter; i++) {
6350 if (needcomma) output.print(",");
6351 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
6354 output.println("};");
6356 //Build the classanalysiswrapper referring to the previous array
6357 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
6358 output.println("/*type*/"+cdtemp.getId()+",");
6359 output.println("/*numotd*/"+numotd+",");
6360 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
6361 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
6362 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
6363 processedcd.add(cdtemp);
6366 //build an array containing every classes for which code has been build
6367 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
6368 for(int i=0; i<state.numClasses(); i++) {
6369 ClassDescriptor cn=cdarray[i];
6372 if ((cn != null) && (processedcd.contains(cn)))
6373 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
6375 output.print("NULL");
6377 output.println("};");
6379 output.println("#define MAXOTD "+maxotd);
6380 headers.println("#endif");
6383 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
6384 Relation r=new Relation();
6385 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
6386 OptionalTaskDescriptor otd=otdit.next();
6387 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
6391 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
6392 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
6393 Set s=r.get(it.next());
6394 for(Iterator it2=s.iterator(); it2.hasNext();) {
6395 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
6403 protected void outputTransCode(PrintWriter output) {
6406 private int calculateSizeOfSESEParamList(FlatSESEEnterNode fsen){
6408 Set<TempDescriptor> tdSet=new HashSet<TempDescriptor>();
6410 for (Iterator iterator = fsen.getInVarSet().iterator(); iterator.hasNext();) {
6411 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
6412 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
6413 tdSet.add(tempDescriptor);
6417 for (Iterator iterator = fsen.getOutVarSet().iterator(); iterator.hasNext();) {
6418 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
6419 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
6420 tdSet.add(tempDescriptor);
6424 return tdSet.size();
6427 private String calculateSizeOfSESEParamSize(FlatSESEEnterNode fsen){
6428 HashMap <String,Integer> map=new HashMap();
6429 HashSet <TempDescriptor> processed=new HashSet<TempDescriptor>();
6432 // space for all in and out set primitives
6433 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
6434 inSetAndOutSet.addAll( fsen.getInVarSet() );
6435 inSetAndOutSet.addAll( fsen.getOutVarSet() );
6437 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
6439 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
6440 while( itr.hasNext() ) {
6441 TempDescriptor temp = itr.next();
6442 TypeDescriptor type = temp.getType();
6443 if( !type.isPtr() ) {
6444 inSetAndOutSetPrims.add( temp );
6448 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
6449 while( itrPrims.hasNext() ) {
6450 TempDescriptor temp = itrPrims.next();
6451 TypeDescriptor type = temp.getType();
6452 if(type.isPrimitive()){
6453 Integer count=map.get(type.getSymbol());
6455 count=new Integer(1);
6456 map.put(type.getSymbol(), count);
6458 map.put(type.getSymbol(), new Integer(count.intValue()+1));
6463 Set<String> keySet=map.keySet();
6464 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
6465 String key = (String) iterator.next();
6466 rtr+="+sizeof("+key+")*"+map.get(key);