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);
171 outglobaldefs=new PrintWriter(new FileOutputStream(PREFIX+"globaldefs.h"), true);
172 outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
173 outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
175 outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
176 outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
177 if (state.OPTIONAL) {
178 outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
179 optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
182 if (state.structfile!=null) {
183 outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
185 } catch (Exception e) {
190 /* Build the virtual dispatch tables */
191 buildVirtualTables(outvirtual);
193 /* Tag the methods that are invoked by static blocks */
194 tagMethodInvokedByStaticBlock();
196 /* Output includes */
197 outmethodheader.println("#ifndef METHODHEADERS_H");
198 outmethodheader.println("#define METHODHEADERS_H");
199 outmethodheader.println("#include \"structdefs.h\"");
201 outmethodheader.println("#include \"dstm.h\"");
203 outmethodheader.println("#include \"sandbox.h\"");
205 if (state.EVENTMONITOR) {
206 outmethodheader.println("#include \"monitor.h\"");
208 if (state.SINGLETM) {
209 outmethodheader.println("#include \"tm.h\"");
210 outmethodheader.println("#include \"delaycomp.h\"");
211 outmethodheader.println("#include \"inlinestm.h\"");
213 if (state.ABORTREADERS) {
214 outmethodheader.println("#include \"abortreaders.h\"");
215 outmethodheader.println("#include <setjmp.h>");
217 if (state.MLP || state.OOOJAVA) {
218 outmethodheader.println("#include <stdlib.h>");
219 outmethodheader.println("#include <stdio.h>");
220 outmethodheader.println("#include <string.h>");
221 outmethodheader.println("#include \"mlp_runtime.h\"");
222 outmethodheader.println("#include \"psemaphore.h\"");
223 outmethodheader.println("#include \"memPool.h\"");
226 outmethodheader.println("#include \"rcr_runtime.h\"");
228 // spit out a global to inform all worker threads with
229 // the maximum size is for any task record
230 outmethodheader.println("extern int "+maxTaskRecSizeStr+";");
233 /* Output Structures */
234 outputStructs(outstructs);
236 // Output the C class declarations
237 // These could mutually reference each other
239 outglobaldefs.println("#ifndef __GLOBALDEF_H_");
240 outglobaldefs.println("#define __GLOBALDEF_H_");
241 outglobaldefs.println("");
242 outglobaldefs.println("struct global_defs_t {");
244 outclassdefs.println("#ifndef __CLASSDEF_H_");
245 outclassdefs.println("#define __CLASSDEF_H_");
246 outputClassDeclarations(outclassdefs, outglobaldefs);
248 // Output function prototypes and structures for parameters
249 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
250 while(it.hasNext()) {
251 ClassDescriptor cn=(ClassDescriptor)it.next();
252 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader, outglobaldefs);
254 outclassdefs.println("#endif");
255 outclassdefs.close();
256 outglobaldefs.println("};");
257 outglobaldefs.println("");
258 outglobaldefs.println("extern struct global_defs_t * global_defs_p;");
259 outglobaldefs.println("#endif");
260 outglobaldefs.flush();
261 outglobaldefs.close();
264 /* Map flags to integers */
265 /* The runtime keeps track of flags using these integers */
266 it=state.getClassSymbolTable().getDescriptorsIterator();
267 while(it.hasNext()) {
268 ClassDescriptor cn=(ClassDescriptor)it.next();
272 generateTaskStructs(outstructs, outmethodheader);
274 /* Outputs generic task structures if this is a task
276 outputTaskTypes(outtask);
279 if( state.MLP || state.OOOJAVA) {
280 // have to initialize some SESE compiler data before
281 // analyzing normal methods, which must happen before
282 // generating SESE internal code
284 Iterator<FlatSESEEnterNode> seseit;
286 seseit=mlpa.getAllSESEs().iterator();
288 seseit=oooa.getAllSESEs().iterator();
291 //TODO signal the object that will report errors
294 rcr = new RuntimeConflictResolver(PREFIX, oooa);
295 rcr.setGlobalEffects(oooa.getDisjointAnalysis().getEffectsAnalysis().getAllEffects());
296 } catch (FileNotFoundException e) {
297 System.out.println("Runtime Conflict Resolver could not create output file.");
302 while(seseit.hasNext()){
303 FlatSESEEnterNode fsen = seseit.next();
304 initializeSESE( fsen );
308 /* Build the actual methods */
309 outputMethods(outmethod);
311 // Output function prototypes and structures for SESE's and code
312 if( state.MLP || state.OOOJAVA ) {
314 // spit out a global to inform all worker threads with
315 // the maximum size is for any task record
316 outmethod.println("int "+maxTaskRecSizeStr+" = 0;");
318 // used to differentiate, during code generation, whether we are
319 // passing over SESE body code, or non-SESE code
322 // first generate code for each sese's internals
323 Iterator<FlatSESEEnterNode> seseit;
325 seseit=mlpa.getAllSESEs().iterator();
327 seseit=oooa.getAllSESEs().iterator();
330 while(seseit.hasNext()) {
331 FlatSESEEnterNode fsen = seseit.next();
332 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
335 // then write the invokeSESE switch to decouple scheduler
336 // from having to do unique details of sese invocation
337 generateSESEinvocationMethod(outmethodheader, outmethod);
341 /* Output code for tasks */
342 outputTaskCode(outtaskdefs, outmethod);
344 /* Record maximum number of task parameters */
345 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
346 } else if (state.main!=null) {
347 /* Generate main method */
348 outputMainMethod(outmethod);
351 /* Generate information for task with optional parameters */
352 if (state.TASK&&state.OPTIONAL) {
353 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
354 outoptionalarrays.close();
357 /* Output structure definitions for repair tool */
358 if (state.structfile!=null) {
359 buildRepairStructs(outrepairstructs);
360 outrepairstructs.close();
364 outmethodheader.println("#endif");
365 outmethodheader.close();
367 outstructs.println("#endif");
371 System.out.println("Runtime Conflict Resolver Done.");
375 /* This method goes though the call graph and tag those methods that are
376 * invoked inside static blocks
378 protected void tagMethodInvokedByStaticBlock() {
379 Iterator it_sclasses = this.state.getSClassSymbolTable().getDescriptorsIterator();
380 MethodDescriptor current_md=null;
381 HashSet tovisit=new HashSet();
382 HashSet visited=new HashSet();
384 while(it_sclasses.hasNext()) {
385 ClassDescriptor cd = (ClassDescriptor)it_sclasses.next();
386 MethodDescriptor md = (MethodDescriptor)cd.getMethodTable().get("staticblocks");
390 while(!tovisit.isEmpty()) {
391 current_md=(MethodDescriptor)tovisit.iterator().next();
392 tovisit.remove(current_md);
393 visited.add(current_md);
394 Iterator it_callee = this.callgraph.getCalleeSet(current_md).iterator();
395 while(it_callee.hasNext()) {
396 Descriptor d = (Descriptor)it_callee.next();
397 if(d instanceof MethodDescriptor) {
398 if(!visited.contains(d)) {
399 ((MethodDescriptor)d).setIsInvokedByStatic(true);
407 /* This code generates code for each static block and static field
409 protected void outputStaticBlocks(PrintWriter outmethod) {
410 // execute all the static blocks and all the static field initializations
414 /* This code just generates the main C method for java programs.
415 * The main C method packs up the arguments into a string array
416 * and passes it to the java main method. */
418 protected void outputMainMethod(PrintWriter outmethod) {
419 outmethod.println("int main(int argc, const char *argv[]) {");
420 outmethod.println(" int i;");
422 outputStaticBlocks(outmethod);
424 if (state.MLP || state.OOOJAVA) {
426 // do a calculation to determine which task record
427 // is the largest, store that as a global value for
428 // allocating records
429 Iterator<FlatSESEEnterNode> seseit;
431 seseit=mlpa.getAllSESEs().iterator();
433 seseit=oooa.getAllSESEs().iterator();
435 while(seseit.hasNext()){
436 FlatSESEEnterNode fsen = seseit.next();
437 outmethod.println("if( sizeof( "+fsen.getSESErecordName()+
438 " ) > "+maxTaskRecSizeStr+
439 " ) { "+maxTaskRecSizeStr+
440 " = sizeof( "+fsen.getSESErecordName()+
444 outmethod.println(" runningSESE = NULL;");
446 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
448 //initializes data structures needed for the RCR traverser
449 if(state.RCR && rcr != null) {
450 outmethod.println(" initializeStructsRCR();");
455 if (state.DSMRECOVERYSTATS) {
456 outmethod.println("#ifdef RECOVERYSTATS \n");
457 outmethod.println("handle();\n");
458 outmethod.println("#endif\n");
460 outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
461 outmethod.println("handle();\n");
462 outmethod.println("#endif\n");
466 if (state.THREAD||state.DSM||state.SINGLETM) {
467 outmethod.println("initializethreads();");
470 outmethod.println("if (dstmStartup(argv[1])) {");
471 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
472 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
474 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
477 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
478 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
480 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
484 outmethod.println(" for(i=2;i<argc;i++) {");
486 outmethod.println(" for(i=1;i<argc;i++) {");
487 outmethod.println(" int length=strlen(argv[i]);");
488 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
489 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
491 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
494 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
496 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
497 outmethod.println(" }");
499 MethodDescriptor md=typeutil.getMain();
500 ClassDescriptor cd=typeutil.getMainClass();
502 outmethod.println(" {");
503 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
504 if (state.DSM||state.SINGLETM) {
505 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
507 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
508 outmethod.println("1, NULL,"+"stringarray};");
509 if (state.DSM||state.SINGLETM)
510 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
512 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
514 if (state.DSM||state.SINGLETM)
515 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
517 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
519 outmethod.println(" }");
522 outmethod.println("}");
525 if (state.THREAD||state.DSM||state.SINGLETM) {
526 outmethod.println("pthread_mutex_lock(&gclistlock);");
527 outmethod.println("threadcount--;");
528 outmethod.println("pthread_cond_signal(&gccond);");
529 outmethod.println("pthread_mutex_unlock(&gclistlock);");
532 if (state.DSM||state.SINGLETM) {
533 //outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
534 outmethod.println("#if defined(TRANSSTATS) \n");
535 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
536 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
537 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
538 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
540 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
541 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
542 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
543 outmethod.println("printf(\"ndirtyCacheObj= %d\\n\", ndirtyCacheObj);");
544 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
545 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
546 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
547 outmethod.println("printf(\"totalObjSize= %d\\n\", totalObjSize);");
548 outmethod.println("printf(\"sendRemoteReq= %d\\n\", sendRemoteReq);");
549 outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
550 } else if (state.SINGLETM) {
551 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
552 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
553 outmethod.println("#ifdef STMSTATS\n");
554 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
555 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
556 outmethod.println("}\n");
557 outmethod.println("#endif\n");
558 outmethod.println("fflush(stdout);");
560 outmethod.println("#endif\n");
563 if (state.EVENTMONITOR) {
564 outmethod.println("dumpdata();");
567 if (state.THREAD||state.SINGLETM)
568 outmethod.println("pthread_exit(NULL);");
570 if (state.MLP || state.OOOJAVA ) {
571 outmethod.println(" workScheduleBegin();");
574 outmethod.println("}");
577 /* This method outputs code for each task. */
579 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
580 /* Compile task based program */
581 outtaskdefs.println("#include \"task.h\"");
582 outtaskdefs.println("#include \"methodheaders.h\"");
583 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
584 while(taskit.hasNext()) {
585 TaskDescriptor td=(TaskDescriptor)taskit.next();
586 FlatMethod fm=state.getMethodFlat(td);
587 generateFlatMethod(fm, null, outmethod);
588 generateTaskDescriptor(outtaskdefs, fm, td);
591 //Output task descriptors
592 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
593 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
595 while(taskit.hasNext()) {
596 TaskDescriptor td=(TaskDescriptor)taskit.next();
600 outtaskdefs.println(",");
601 outtaskdefs.print("&task_"+td.getSafeSymbol());
603 outtaskdefs.println("};");
605 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
608 /* This method outputs most of the methods.c file. This includes
609 * some standard includes and then an array with the sizes of
610 * objets and array that stores supertype and then the code for
611 * the Java methods.. */
613 protected void outputMethods(PrintWriter outmethod) {
614 outmethod.println("#include \"methodheaders.h\"");
615 outmethod.println("#include \"virtualtable.h\"");
616 outmethod.println("#include \"runtime.h\"");
618 // always include: compiler directives will leave out
619 // instrumentation when option is not set
620 outmethod.println("#include \"coreprof/coreprof.h\"");
623 outmethod.println("#include \"sandboxdefs.c\"");
626 outmethod.println("#include \"addPrefetchEnhance.h\"");
627 outmethod.println("#include \"localobjects.h\"");
629 if (state.FASTCHECK) {
630 outmethod.println("#include \"localobjects.h\"");
632 if(state.MULTICORE) {
634 outmethod.println("#include \"task.h\"");
636 outmethod.println("#include \"multicoreruntime.h\"");
637 outmethod.println("#include \"runtime_arch.h\"");
639 if (state.THREAD||state.DSM||state.SINGLETM)
640 outmethod.println("#include <thread.h>");
641 if (state.main!=null) {
642 outmethod.println("#include <string.h>");
644 if (state.CONSCHECK) {
645 outmethod.println("#include \"checkers.h\"");
647 if (state.MLP || state.OOOJAVA ) {
648 outmethod.println("#include <stdlib.h>");
649 outmethod.println("#include <stdio.h>");
650 outmethod.println("#include \"mlp_runtime.h\"");
651 outmethod.println("#include \"psemaphore.h\"");
654 outmethod.println("#include \"trqueue.h\"");
655 outmethod.println("#include \"RuntimeConflictResolver.h\"");
656 outmethod.println("#include \"rcr_runtime.h\"");
660 outmethod.println("struct global_defs_t * global_defs_p;");
661 //Store the sizes of classes & array elements
662 generateSizeArray(outmethod);
664 //Store table of supertypes
665 generateSuperTypeTable(outmethod);
667 //Store the layout of classes
668 generateLayoutStructs(outmethod);
670 /* Generate code for methods */
671 if (state.DSM||state.SINGLETM) {
672 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
673 LocalityBinding lb=lbit.next();
674 MethodDescriptor md=lb.getMethod();
675 FlatMethod fm=state.getMethodFlat(md);
677 if (!md.getModifiers().isNative()) {
678 generateFlatMethod(fm, lb, outmethod);
679 //System.out.println("fm= " + fm + " md= " + md);
683 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
684 while(classit.hasNext()) {
685 ClassDescriptor cn=(ClassDescriptor)classit.next();
686 Iterator methodit=cn.getMethods();
687 while(methodit.hasNext()) {
688 /* Classify parameters */
689 MethodDescriptor md=(MethodDescriptor)methodit.next();
690 FlatMethod fm=state.getMethodFlat(md);
691 if (!md.getModifiers().isNative()) {
692 generateFlatMethod(fm, null, outmethod);
699 protected void outputStructs(PrintWriter outstructs) {
700 outstructs.println("#ifndef STRUCTDEFS_H");
701 outstructs.println("#define STRUCTDEFS_H");
702 outstructs.println("#include \"classdefs.h\"");
703 outstructs.println("#ifndef INTPTR");
704 outstructs.println("#ifdef BIT64");
705 outstructs.println("#define INTPTR long");
706 outstructs.println("#else");
707 outstructs.println("#define INTPTR int");
708 outstructs.println("#endif");
709 outstructs.println("#endif");
710 if( state.MLP || state.OOOJAVA ) {
711 outstructs.println("#include \"mlp_runtime.h\"");
712 outstructs.println("#include \"psemaphore.h\"");
715 outstructs.println("#include \"rcr_runtime.h\"");
719 /* Output #defines that the runtime uses to determine type
720 * numbers for various objects it needs */
721 outstructs.println("#define MAXCOUNT "+maxcount);
722 if (state.DSM||state.SINGLETM) {
723 LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
725 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
727 else if (state.SINGLETM) {
728 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
730 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
734 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
736 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
737 else if( state.SINGLETM)
738 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
739 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
742 outstructs.println("#define STRINGARRAYTYPE "+
743 (state.getArrayNumber(
744 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
746 outstructs.println("#define OBJECTARRAYTYPE "+
747 (state.getArrayNumber(
748 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
751 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
752 outstructs.println("#define CHARARRAYTYPE "+
753 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
755 outstructs.println("#define BYTEARRAYTYPE "+
756 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
758 outstructs.println("#define BYTEARRAYARRAYTYPE "+
759 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
761 outstructs.println("#define NUMCLASSES "+state.numClasses());
762 int totalClassSize = state.numClasses() + state.numArrays();
763 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
765 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
766 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
767 outstructs.println("#define TAGARRAYTYPE "+
768 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
772 protected void outputClassDeclarations(PrintWriter outclassdefs, PrintWriter outglobaldefs) {
773 if (state.THREAD||state.DSM||state.SINGLETM)
774 outclassdefs.println("#include <pthread.h>");
775 outclassdefs.println("#ifndef INTPTR");
776 outclassdefs.println("#ifdef BIT64");
777 outclassdefs.println("#define INTPTR long");
778 outclassdefs.println("#else");
779 outclassdefs.println("#define INTPTR int");
780 outclassdefs.println("#endif");
781 outclassdefs.println("#endif");
783 outclassdefs.println("#include \"optionalstruct.h\"");
784 outclassdefs.println("struct "+arraytype+";");
785 /* Start by declaring all structs */
786 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
787 while(it.hasNext()) {
788 ClassDescriptor cn=(ClassDescriptor)it.next();
789 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
791 outclassdefs.println("");
792 //Print out definition for array type
793 outclassdefs.println("struct "+arraytype+" {");
794 outclassdefs.println(" int type;");
795 if(state.MLP || state.OOOJAVA ){
796 outclassdefs.println(" int oid;");
797 outclassdefs.println(" int allocsite;");
799 if (state.EVENTMONITOR) {
800 outclassdefs.println(" int objuid;");
803 outclassdefs.println(" pthread_t tid;");
804 outclassdefs.println(" void * lockentry;");
805 outclassdefs.println(" int lockcount;");
808 outclassdefs.println(" int mutex;");
809 outclassdefs.println(" int objlock;");
810 if(state.MULTICOREGC) {
811 outclassdefs.println(" int marked;");
815 outclassdefs.println(" int flag;");
816 if(!state.MULTICORE) {
817 outclassdefs.println(" void * flagptr;");
819 outclassdefs.println(" int version;");
820 outclassdefs.println(" int * lock;"); // lock entry for this obj
821 outclassdefs.println(" int mutex;");
822 outclassdefs.println(" int lockcount;");
823 if(state.MULTICOREGC) {
824 outclassdefs.println(" int marked;");
828 outclassdefs.println(" int numfses;");
829 outclassdefs.println(" int * fses;");
832 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs, outglobaldefs);
834 if (state.STMARRAY) {
835 outclassdefs.println(" int lowindex;");
836 outclassdefs.println(" int highindex;");
839 outclassdefs.println(" int paddingforarray;");
840 if (state.DUALVIEW) {
841 outclassdefs.println(" int arrayversion;");
844 outclassdefs.println(" int ___length___;");
845 outclassdefs.println("};\n");
846 outclassdefs.println("extern int classsize[];");
847 outclassdefs.println("extern int hasflags[];");
848 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
849 outclassdefs.println("extern int supertypes[];");
850 outclassdefs.println("#include \"globaldefs.h\"");
851 outclassdefs.println("");
854 /** Prints out definitions for generic task structures */
856 private void outputTaskTypes(PrintWriter outtask) {
857 outtask.println("#ifndef _TASK_H");
858 outtask.println("#define _TASK_H");
859 outtask.println("struct parameterdescriptor {");
860 outtask.println("int type;");
861 outtask.println("int numberterms;");
862 outtask.println("int *intarray;");
863 outtask.println("void * queue;");
864 outtask.println("int numbertags;");
865 outtask.println("int *tagarray;");
866 outtask.println("};");
868 outtask.println("struct taskdescriptor {");
869 outtask.println("void * taskptr;");
870 outtask.println("int numParameters;");
871 outtask.println(" int numTotal;");
872 outtask.println("struct parameterdescriptor **descriptorarray;");
873 outtask.println("char * name;");
874 outtask.println("};");
875 outtask.println("extern struct taskdescriptor * taskarray[];");
876 outtask.println("extern numtasks;");
877 outtask.println("#endif");
881 private void buildRepairStructs(PrintWriter outrepairstructs) {
882 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
883 while(classit.hasNext()) {
884 ClassDescriptor cn=(ClassDescriptor)classit.next();
885 outrepairstructs.println("structure "+cn.getSymbol()+" {");
886 outrepairstructs.println(" int __type__;");
888 outrepairstructs.println(" int __flag__;");
889 if(!state.MULTICORE) {
890 outrepairstructs.println(" int __flagptr__;");
893 printRepairStruct(cn, outrepairstructs);
894 outrepairstructs.println("}\n");
897 for(int i=0; i<state.numArrays(); i++) {
898 TypeDescriptor tdarray=arraytable[i];
899 TypeDescriptor tdelement=tdarray.dereference();
900 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
901 outrepairstructs.println(" int __type__;");
902 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
903 outrepairstructs.println(" int length;");
905 // Need to add support to repair tool for this
906 if (tdelement.isClass()||tdelement.isArray())
907 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
909 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
911 outrepairstructs.println("}\n");
915 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
916 ClassDescriptor sp=cn.getSuperDesc();
918 printRepairStruct(sp, output);
920 Vector fields=(Vector)fieldorder.get(cn);
922 for(int i=0; i<fields.size(); i++) {
923 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
924 if (fd.getType().isArray()) {
925 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
926 } else if (fd.getType().isClass())
927 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
928 else if (fd.getType().isFloat())
929 output.println(" int "+fd.getSymbol()+"; /* really float */");
931 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
935 /** This method outputs TaskDescriptor information */
936 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
937 for (int i=0; i<task.numParameters(); i++) {
938 VarDescriptor param_var=task.getParameter(i);
939 TypeDescriptor param_type=task.getParamType(i);
940 FlagExpressionNode param_flag=task.getFlag(param_var);
941 TagExpressionList param_tag=task.getTag(param_var);
944 if (param_flag==null) {
945 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
946 output.println("0x0, 0x0 };");
949 DNFFlag dflag=param_flag.getDNF();
950 dnfterms=dflag.size();
952 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
953 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
954 for(int j=0; j<dflag.size(); j++) {
957 Vector term=dflag.get(j);
960 for(int k=0; k<term.size(); k++) {
961 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
962 FlagDescriptor fd=dfa.getFlag();
963 boolean negated=dfa.getNegated();
964 int flagid=1<<((Integer)flags.get(fd)).intValue();
969 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
971 output.println("};");
974 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
975 //BUG...added next line to fix, test with any task program
977 for(int j=0; j<param_tag.numTags(); j++) {
980 /* for each tag we need */
981 /* which slot it is */
982 /* what type it is */
983 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
984 TempDescriptor tmp=param_tag.getTemp(j);
985 int slot=fm.getTagInt(tmp);
986 output.println(slot+", "+state.getTagId(tvd.getTag()));
988 output.println("};");
990 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
991 output.println("/* type */"+param_type.getClassDesc().getId()+",");
992 output.println("/* number of DNF terms */"+dnfterms+",");
993 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
994 output.println("0,");
995 //BUG, added next line to fix and else statement...test
996 //with any task program
998 output.println("/* number of tags */"+param_tag.numTags()+",");
1000 output.println("/* number of tags */ 0,");
1001 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
1002 output.println("};");
1006 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
1007 for (int i=0; i<task.numParameters(); i++) {
1009 output.println(",");
1010 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
1012 output.println("};");
1014 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
1015 output.println("&"+task.getSafeSymbol()+",");
1016 output.println("/* number of parameters */" +task.numParameters() + ",");
1017 int numtotal=task.numParameters()+fm.numTags();
1018 output.println("/* number total parameters */" +numtotal + ",");
1019 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
1020 output.println("\""+task.getSymbol()+"\"");
1021 output.println("};");
1025 /** The buildVirtualTables method outputs the virtual dispatch
1026 * tables for methods. */
1028 protected void buildVirtualTables(PrintWriter outvirtual) {
1029 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
1030 while(classit.hasNext()) {
1031 ClassDescriptor cd=(ClassDescriptor)classit.next();
1032 if (virtualcalls.getMethodCount(cd)>maxcount)
1033 maxcount=virtualcalls.getMethodCount(cd);
1035 MethodDescriptor[][] virtualtable=null;
1036 LocalityBinding[][] lbvirtualtable=null;
1037 if (state.DSM||state.SINGLETM)
1038 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
1040 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
1042 /* Fill in virtual table */
1043 classit=state.getClassSymbolTable().getDescriptorsIterator();
1044 while(classit.hasNext()) {
1045 ClassDescriptor cd=(ClassDescriptor)classit.next();
1046 if (state.DSM||state.SINGLETM)
1047 fillinRow(cd, lbvirtualtable, cd.getId());
1049 fillinRow(cd, virtualtable, cd.getId());
1052 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
1053 Iterator arrayit=state.getArrayIterator();
1054 while(arrayit.hasNext()) {
1055 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1056 int id=state.getArrayNumber(td);
1057 if (state.DSM||state.SINGLETM)
1058 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
1060 fillinRow(objectcd, virtualtable, id+state.numClasses());
1063 outvirtual.print("void * virtualtable[]={");
1064 boolean needcomma=false;
1065 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
1066 for(int j=0; j<maxcount; j++) {
1068 outvirtual.print(", ");
1069 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
1070 LocalityBinding lb=lbvirtualtable[i][j];
1071 MethodDescriptor md=lb.getMethod();
1072 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
1073 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
1074 MethodDescriptor md=virtualtable[i][j];
1075 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
1077 outvirtual.print("0");
1081 outvirtual.println("");
1083 outvirtual.println("};");
1087 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
1088 /* Get inherited methods */
1089 if (cd.getSuperDesc()!=null)
1090 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
1091 /* Override them with our methods */
1092 for(Iterator it=cd.getMethods(); it.hasNext();) {
1093 MethodDescriptor md=(MethodDescriptor)it.next();
1094 if (md.isStatic()||md.getReturnType()==null)
1096 int methodnum=virtualcalls.getMethodNumber(md);
1097 virtualtable[rownum][methodnum]=md;
1101 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
1102 /* Get inherited methods */
1103 if (cd.getSuperDesc()!=null)
1104 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
1105 /* Override them with our methods */
1106 if (locality.getClassBindings(cd)!=null)
1107 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
1108 LocalityBinding lb=lbit.next();
1109 MethodDescriptor md=lb.getMethod();
1110 //Is the method static or a constructor
1111 if (md.isStatic()||md.getReturnType()==null)
1113 int methodnum=virtualcalls.getLocalityNumber(lb);
1114 virtualtable[rownum][methodnum]=lb;
1118 /** Generate array that contains the sizes of class objects. The
1119 * object allocation functions in the runtime use this
1122 private void generateSizeArray(PrintWriter outclassdefs) {
1123 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
1124 outclassdefs.print("#ifdef TRANSSTATS \n");
1125 outclassdefs.print("extern int numTransAbort;\n");
1126 outclassdefs.print("extern int numTransCommit;\n");
1127 outclassdefs.print("extern int nSoftAbort;\n");
1129 outclassdefs.print("extern int nchashSearch;\n");
1130 outclassdefs.print("extern int nmhashSearch;\n");
1131 outclassdefs.print("extern int nprehashSearch;\n");
1132 outclassdefs.print("extern int ndirtyCacheObj;\n");
1133 outclassdefs.print("extern int nRemoteSend;\n");
1134 outclassdefs.print("extern int sendRemoteReq;\n");
1135 outclassdefs.print("extern int getResponse;\n");
1136 outclassdefs.print("extern int bytesSent;\n");
1137 outclassdefs.print("extern int bytesRecv;\n");
1138 outclassdefs.print("extern int totalObjSize;\n");
1139 outclassdefs.print("extern void handle();\n");
1140 } else if (state.SINGLETM) {
1141 outclassdefs.println("extern int nSoftAbortAbort;");
1142 outclassdefs.println("extern int nSoftAbortCommit;");
1143 outclassdefs.println("#ifdef STMSTATS\n");
1144 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
1145 outclassdefs.println("#endif\n");
1147 outclassdefs.print("#endif\n");
1149 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
1150 if(this.state.MLP || state.OOOJAVA ){
1151 outclassdefs.print("extern __thread int oid;\n");
1152 outclassdefs.print("extern int numWorkers;\n");
1155 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1156 cdarray=new ClassDescriptor[state.numClasses()];
1158 while(it.hasNext()) {
1159 ClassDescriptor cd=(ClassDescriptor)it.next();
1160 cdarray[cd.getId()]=cd;
1163 arraytable=new TypeDescriptor[state.numArrays()];
1165 Iterator arrayit=state.getArrayIterator();
1166 while(arrayit.hasNext()) {
1167 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1168 int id=state.getArrayNumber(td);
1174 /* Print out types */
1175 outclassdefs.println("/* ");
1176 for(int i=0; i<state.numClasses(); i++) {
1177 ClassDescriptor cd=cdarray[i];
1179 outclassdefs.println("NULL " + i);
1181 outclassdefs.println(cd +" "+i);
1185 for(int i=0; i<state.numArrays(); i++) {
1186 TypeDescriptor arraytd=arraytable[i];
1187 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
1190 outclassdefs.println("*/");
1193 outclassdefs.print("int classsize[]={");
1195 boolean needcomma=false;
1196 for(int i=0; i<state.numClasses(); i++) {
1198 outclassdefs.print(", ");
1200 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1202 outclassdefs.print("0");
1208 for(int i=0; i<state.numArrays(); i++) {
1210 outclassdefs.print(", ");
1211 TypeDescriptor tdelement=arraytable[i].dereference();
1212 if (tdelement.isArray()||tdelement.isClass())
1213 outclassdefs.print("sizeof(void *)");
1215 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1219 outclassdefs.println("};");
1221 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1223 outclassdefs.print("int typearray[]={");
1224 for(int i=0; i<state.numClasses(); i++) {
1225 ClassDescriptor cd=cdarray[i];
1226 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1228 outclassdefs.print(", ");
1230 outclassdefs.print("-1");
1232 outclassdefs.print(supercd.getId());
1236 for(int i=0; i<state.numArrays(); i++) {
1237 TypeDescriptor arraytd=arraytable[i];
1238 ClassDescriptor arraycd=arraytd.getClassDesc();
1239 if (arraycd==null) {
1241 outclassdefs.print(", ");
1242 outclassdefs.print(objectclass.getId());
1246 ClassDescriptor cd=arraycd.getSuperDesc();
1249 TypeDescriptor supertd=new TypeDescriptor(cd);
1250 supertd.setArrayCount(arraytd.getArrayCount());
1251 type=state.getArrayNumber(supertd);
1253 type+=state.numClasses();
1256 cd=cd.getSuperDesc();
1259 outclassdefs.print(", ");
1260 outclassdefs.print(type);
1264 outclassdefs.println("};");
1269 outclassdefs.print("int typearray2[]={");
1270 for(int i=0; i<state.numArrays(); i++) {
1271 TypeDescriptor arraytd=arraytable[i];
1272 ClassDescriptor arraycd=arraytd.getClassDesc();
1273 if (arraycd==null) {
1275 outclassdefs.print(", ");
1276 outclassdefs.print("-1");
1280 ClassDescriptor cd=arraycd.getSuperDesc();
1281 int level=arraytd.getArrayCount()-1;
1283 for(; level>0; level--) {
1284 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1285 supertd.setArrayCount(level);
1286 type=state.getArrayNumber(supertd);
1288 type+=state.numClasses();
1293 outclassdefs.print(", ");
1294 outclassdefs.print(type);
1298 outclassdefs.println("};");
1301 /** Constructs params and temp objects for each method or task.
1302 * These objects tell the compiler which temps need to be
1305 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1306 MethodDescriptor md=fm.getMethod();
1307 TaskDescriptor task=fm.getTask();
1308 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1309 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1311 paramstable.put(lb, objectparams);
1312 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1313 } else if (md!=null)
1314 paramstable.put(md, objectparams);
1316 paramstable.put(task, objectparams);
1318 for(int i=0; i<fm.numParameters(); i++) {
1319 TempDescriptor temp=fm.getParameter(i);
1320 TypeDescriptor type=temp.getType();
1321 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1322 objectparams.addPtr(temp);
1324 objectparams.addPrim(temp);
1325 if(lb!=null&&saveset.contains(temp)) {
1326 backuptable.get(lb).put(temp, temp.createNew());
1330 for(int i=0; i<fm.numTags(); i++) {
1331 TempDescriptor temp=fm.getTag(i);
1332 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1333 objectparams.addPtr(temp);
1335 objectparams.addPrim(temp);
1338 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1340 tempstable.put(lb, objecttemps);
1342 tempstable.put(md, objecttemps);
1344 tempstable.put(task, objecttemps);
1346 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1347 FlatNode fn=(FlatNode)nodeit.next();
1348 TempDescriptor[] writes=fn.writesTemps();
1349 for(int i=0; i<writes.length; i++) {
1350 TempDescriptor temp=writes[i];
1351 TypeDescriptor type=temp.getType();
1352 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1353 objecttemps.addPtr(temp);
1355 objecttemps.addPrim(temp);
1356 if(lb!=null&&saveset.contains(temp)&&
1357 !backuptable.get(lb).containsKey(temp))
1358 backuptable.get(lb).put(temp, temp.createNew());
1362 /* Create backup temps */
1364 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1365 TempDescriptor tmp=tmpit.next();
1366 TypeDescriptor type=tmp.getType();
1367 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1368 objecttemps.addPtr(tmp);
1370 objecttemps.addPrim(tmp);
1372 /* Create temp to hold revert table */
1373 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1374 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1375 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1376 objecttemps.addPtr(reverttmp);
1378 objecttemps.addPrim(reverttmp);
1379 reverttable.put(lb, reverttmp);
1384 /** This method outputs the following information about classes
1386 * (1) For classes, what are the locations of pointers.
1387 * (2) For arrays, does the array contain pointers or primitives.
1388 * (3) For classes, does the class contain flags.
1391 private void generateLayoutStructs(PrintWriter output) {
1392 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1393 while(it.hasNext()) {
1394 ClassDescriptor cn=(ClassDescriptor)it.next();
1395 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1396 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1398 while(allit.hasNext()) {
1399 FieldDescriptor fd=(FieldDescriptor)allit.next();
1400 TypeDescriptor type=fd.getType();
1401 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1406 output.print(count);
1407 allit=cn.getFieldTable().getAllDescriptorsIterator();
1408 while(allit.hasNext()) {
1409 FieldDescriptor fd=(FieldDescriptor)allit.next();
1410 TypeDescriptor type=fd.getType();
1411 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1414 output.println(",");
1415 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1418 output.println("};");
1420 output.println("unsigned INTPTR * pointerarray[]={");
1421 boolean needcomma=false;
1422 for(int i=0; i<state.numClasses(); i++) {
1423 ClassDescriptor cn=cdarray[i];
1425 output.println(",");
1428 output.print(cn.getSafeSymbol()+"_pointers");
1430 output.print("NULL");
1434 for(int i=0; i<state.numArrays(); i++) {
1436 output.println(", ");
1437 TypeDescriptor tdelement=arraytable[i].dereference();
1438 if (tdelement.isArray()||tdelement.isClass())
1439 output.print("((unsigned INTPTR *)1)");
1445 output.println("};");
1447 output.println("int hasflags[]={");
1448 for(int i=0; i<state.numClasses(); i++) {
1449 ClassDescriptor cn=cdarray[i];
1451 output.println(", ");
1453 if ((cn != null) && (cn.hasFlags()))
1458 output.println("};");
1461 /** Print out table to give us supertypes */
1462 private void generateSuperTypeTable(PrintWriter output) {
1463 output.println("int supertypes[]={");
1464 boolean needcomma=false;
1465 for(int i=0; i<state.numClasses(); i++) {
1466 ClassDescriptor cn=cdarray[i];
1468 output.println(",");
1470 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1471 ClassDescriptor cdsuper=cn.getSuperDesc();
1472 output.print(cdsuper.getId());
1476 output.println("};");
1479 /** Force consistent field ordering between inherited classes. */
1481 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout, PrintWriter globaldefout) {
1483 ClassDescriptor sp=cn.getSuperDesc();
1485 printClassStruct(sp, classdefout, globaldefout);
1487 if (!fieldorder.containsKey(cn)) {
1488 Vector fields=new Vector();
1489 fieldorder.put(cn,fields);
1490 Vector fieldvec=cn.getFieldVec();
1491 for(int i=0;i<fieldvec.size();i++) {
1492 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1493 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1497 Vector fields=(Vector)fieldorder.get(cn);
1499 if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
1500 // this class has static fields/blocks, need to add a global flag to
1501 // indicate if its static fields have been initialized and/or if its
1502 // static blocks have been executed
1503 globaldefout.println(" int "+cn.getSafeSymbol()+"static_block_exe_flag;");
1506 for(int i=0; i<fields.size(); i++) {
1507 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1508 if (fd.getType().isClass()||fd.getType().isArray())
1509 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1510 else if(fd.isStatic()) {
1512 globaldefout.println(" "+fd.getType().getSafeSymbol()+ " "+cn.getSafeSymbol()+fd.getSafeSymbol()+";");
1513 classdefout.println(" "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1515 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1520 /* Map flags to integers consistently between inherited
1523 protected void mapFlags(ClassDescriptor cn) {
1524 ClassDescriptor sp=cn.getSuperDesc();
1528 if (!flagorder.containsKey(cn)) {
1529 Hashtable flags=new Hashtable();
1530 flagorder.put(cn,flags);
1532 Hashtable superflags=(Hashtable)flagorder.get(sp);
1533 Iterator superflagit=superflags.keySet().iterator();
1534 while(superflagit.hasNext()) {
1535 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1536 Integer number=(Integer)superflags.get(fd);
1537 flags.put(fd, number);
1538 if ((number.intValue()+1)>max)
1539 max=number.intValue()+1;
1543 Iterator flagit=cn.getFlags();
1544 while(flagit.hasNext()) {
1545 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1546 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1547 flags.put(fd, new Integer(max++));
1553 /** This function outputs (1) structures that parameters are
1554 * passed in (when PRECISE GC is enabled) and (2) function
1555 * prototypes for the methods */
1557 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout, PrintWriter globaldefout) {
1558 /* Output class structure */
1559 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1560 classdefout.println(" int type;");
1561 if(state.MLP || state.OOOJAVA){
1562 classdefout.println(" int oid;");
1563 classdefout.println(" int allocsite;");
1565 if (state.EVENTMONITOR) {
1566 classdefout.println(" int objuid;");
1569 classdefout.println(" pthread_t tid;");
1570 classdefout.println(" void * lockentry;");
1571 classdefout.println(" int lockcount;");
1574 classdefout.println(" int mutex;");
1575 classdefout.println(" int objlock;");
1576 if(state.MULTICOREGC) {
1577 classdefout.println(" int marked;");
1581 classdefout.println(" int flag;");
1582 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1583 classdefout.println(" void * flagptr;");
1584 } else if (state.MULTICORE) {
1585 classdefout.println(" int version;");
1586 classdefout.println(" int * lock;"); // lock entry for this obj
1587 classdefout.println(" int mutex;");
1588 classdefout.println(" int lockcount;");
1589 if(state.MULTICOREGC) {
1590 classdefout.println(" int marked;");
1593 if (state.OPTIONAL) {
1594 classdefout.println(" int numfses;");
1595 classdefout.println(" int * fses;");
1598 printClassStruct(cn, classdefout, globaldefout);
1599 classdefout.println("};\n");
1601 if (state.DSM||state.SINGLETM) {
1602 /* Cycle through LocalityBindings */
1603 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1604 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1606 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1607 LocalityBinding lb=lbit.next();
1608 MethodDescriptor md=lb.getMethod();
1609 if (md.getModifiers().isNative()) {
1610 //make sure we only print a native method once
1611 if (nativemethods.contains(md)) {
1612 FlatMethod fm=state.getMethodFlat(md);
1613 generateTempStructs(fm, lb);
1616 nativemethods.add(md);
1618 generateMethod(cn, md, lb, headersout, output);
1621 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1622 MethodDescriptor md=(MethodDescriptor)methodit.next();
1623 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1624 //Need to build param structure for library code
1625 FlatMethod fm=state.getMethodFlat(md);
1626 generateTempStructs(fm, null);
1627 generateMethodParam(cn, md, null, output);
1632 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1633 MethodDescriptor md=(MethodDescriptor)methodit.next();
1634 generateMethod(cn, md, null, headersout, output);
1638 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1639 /* Output parameter structure */
1640 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1641 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1642 if ((state.DSM||state.SINGLETM)&&lb!=null)
1643 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1645 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1646 output.println(" int size;");
1647 output.println(" void * next;");
1648 for(int i=0; i<objectparams.numPointers(); i++) {
1649 TempDescriptor temp=objectparams.getPointer(i);
1650 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1652 output.println("};\n");
1656 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1657 FlatMethod fm=state.getMethodFlat(md);
1658 generateTempStructs(fm, lb);
1660 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1661 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1663 generateMethodParam(cn, md, lb, output);
1665 /* Output temp structure */
1666 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1667 if (state.DSM||state.SINGLETM)
1668 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1670 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1671 output.println(" int size;");
1672 output.println(" void * next;");
1673 for(int i=0; i<objecttemps.numPointers(); i++) {
1674 TempDescriptor temp=objecttemps.getPointer(i);
1675 if (temp.getType().isNull())
1676 output.println(" void * "+temp.getSafeSymbol()+";");
1678 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1680 output.println("};\n");
1683 /********* Output method declaration ***********/
1684 if (state.DSM||state.SINGLETM) {
1685 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1687 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1689 /* First the return type */
1690 if (md.getReturnType()!=null) {
1691 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1692 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1694 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1696 //catch the constructor case
1697 headersout.print("void ");
1699 /* Next the method name */
1700 if (state.DSM||state.SINGLETM) {
1701 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1703 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1705 boolean printcomma=false;
1706 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1707 if (state.DSM||state.SINGLETM) {
1708 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1710 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1714 /* Output parameter list*/
1715 for(int i=0; i<objectparams.numPrimitives(); i++) {
1716 TempDescriptor temp=objectparams.getPrimitive(i);
1718 headersout.print(", ");
1720 if (temp.getType().isClass()||temp.getType().isArray())
1721 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1723 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1725 headersout.println(");\n");
1729 /** This function outputs (1) structures that parameters are
1730 * passed in (when PRECISE GC is enabled) and (2) function
1731 * prototypes for the tasks */
1733 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1734 /* Cycle through tasks */
1735 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1737 while(taskit.hasNext()) {
1738 /* Classify parameters */
1739 TaskDescriptor task=(TaskDescriptor)taskit.next();
1740 FlatMethod fm=state.getMethodFlat(task);
1741 generateTempStructs(fm, null);
1743 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1744 TempObject objecttemps=(TempObject) tempstable.get(task);
1746 /* Output parameter structure */
1747 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1748 output.println("struct "+task.getSafeSymbol()+"_params {");
1749 output.println(" int size;");
1750 output.println(" void * next;");
1751 for(int i=0; i<objectparams.numPointers(); i++) {
1752 TempDescriptor temp=objectparams.getPointer(i);
1753 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1756 output.println("};\n");
1757 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1758 maxtaskparams=objectparams.numPointers()+fm.numTags();
1762 /* Output temp structure */
1763 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1764 output.println("struct "+task.getSafeSymbol()+"_locals {");
1765 output.println(" int size;");
1766 output.println(" void * next;");
1767 for(int i=0; i<objecttemps.numPointers(); i++) {
1768 TempDescriptor temp=objecttemps.getPointer(i);
1769 if (temp.getType().isNull())
1770 output.println(" void * "+temp.getSafeSymbol()+";");
1771 else if(temp.getType().isTag())
1772 output.println(" struct "+
1773 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1775 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1777 output.println("};\n");
1780 /* Output task declaration */
1781 headersout.print("void " + task.getSafeSymbol()+"(");
1783 boolean printcomma=false;
1784 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1785 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1787 headersout.print("void * parameterarray[]");
1788 headersout.println(");\n");
1792 /***** Generate code for FlatMethod fm. *****/
1794 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1795 static int atomicmethodcount=0;
1798 BranchAnalysis branchanalysis;
1799 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1800 if (State.PRINTFLAT)
1801 System.out.println(fm.printMethod());
1802 MethodDescriptor md=fm.getMethod();
1803 TaskDescriptor task=fm.getTask();
1804 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1805 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1807 HashSet<AtomicRecord> arset=null;
1808 branchanalysis=null;
1810 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1812 if (atomicmethodmap==null)
1813 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1815 //fix these so we get right strings for local variables
1816 localsprefixaddr=localsprefix;
1817 localsprefixderef=localsprefix+"->";
1818 arset=new HashSet<AtomicRecord>();
1820 //build branchanalysis
1821 branchanalysis=new BranchAnalysis(locality, lb, delaycomp.getNotReady(lb), delaycomp.livecode(lb), state);
1823 //Generate commit methods here
1824 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1825 FlatNode fn=fnit.next();
1826 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1827 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
1828 delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
1829 //We have an atomic enter
1830 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1831 Set<FlatNode> exitset=faen.getExits();
1833 String methodname=md.getSymbol()+(atomicmethodcount++);
1834 AtomicRecord ar=new AtomicRecord();
1838 atomicmethodmap.put(faen, ar);
1840 //build data structure declaration
1841 output.println("struct atomicprimitives_"+methodname+" {");
1843 Set<FlatNode> recordset=delaycomp.livecode(lb);
1844 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1845 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1846 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1848 ar.reallivein=new HashSet(liveinto);
1850 ar.liveoutvirtualread=liveoutvirtualread;
1853 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1854 TempDescriptor tmp=it.next();
1855 //remove the pointers
1856 if (tmp.getType().isPtr()) {
1859 //let's print it here
1860 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1863 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1864 TempDescriptor tmp=it.next();
1865 //remove the pointers
1866 if (tmp.getType().isPtr()) {
1868 } else if (!liveinto.contains(tmp)) {
1869 //let's print it here
1870 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1873 output.println("};");
1875 //print out method name
1876 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) {");
1877 //build code for commit method
1879 //first define local primitives
1880 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1881 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1882 TempDescriptor tmp=tmpit.next();
1883 if (!tmp.getType().isPtr()) {
1884 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1885 //read from live into set
1886 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1889 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1893 //turn off write barrier generation
1895 state.SINGLETM=false;
1896 generateCode(faen, fm, lb, exitset, output, false);
1897 state.SINGLETM=true;
1898 //turn on write barrier generation
1900 output.println("}\n\n");
1904 //redefine these back to normal
1906 localsprefixaddr="&"+localsprefix;
1907 localsprefixderef=localsprefix+".";
1909 generateHeader(fm, lb, md!=null ? md : task,output);
1910 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1912 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1913 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1914 AtomicRecord ar=arit.next();
1915 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1919 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1920 if (md!=null&&(state.DSM||state.SINGLETM))
1921 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1922 else if (md!=null&&!(state.DSM||state.SINGLETM))
1923 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1925 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1926 output.print(objecttemp.numPointers()+",");
1927 output.print(paramsprefix);
1928 for(int j=0; j<objecttemp.numPointers(); j++)
1929 output.print(", NULL");
1930 output.println("};");
1933 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1934 TempDescriptor td=objecttemp.getPrimitive(i);
1935 TypeDescriptor type=td.getType();
1937 output.println(" void * "+td.getSafeSymbol()+";");
1938 else if (type.isClass()||type.isArray())
1939 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1941 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1945 if( state.MLP || state.OOOJAVA ) {
1946 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1947 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1948 if( (state.MLP && callerSESEplaceholder != mlpa.getMainSESE()) ||
1949 (state.OOOJAVA && callerSESEplaceholder != oooa.getMainSESE())
1951 // declare variables for naming static SESE's
1952 output.println(" /* static SESE names */");
1953 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1954 while( pItr.hasNext() ) {
1955 SESEandAgePair pair = pItr.next();
1956 output.println(" void* "+pair+" = NULL;");
1959 // declare variables for tracking dynamic sources
1960 output.println(" /* dynamic variable sources */");
1961 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1962 while( dynSrcItr.hasNext() ) {
1963 TempDescriptor dynSrcVar = dynSrcItr.next();
1964 output.println(" SESEcommon* "+dynSrcVar+"_srcSESE = NULL;");
1965 output.println(" INTPTR "+dynSrcVar+"_srcOffset = 0x1;");
1970 // set up related allocation sites's waiting queues
1973 ConflictGraph graph = null;
1974 graph = mlpa.getConflictGraphResults().get(fm);
1975 if (graph != null && graph.hasConflictEdge()) {
1976 output.println(" /* set up waiting queues */");
1977 output.println(" int numMemoryQueue=0;");
1978 output.println(" int memoryQueueItemID=0;");
1979 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
1981 System.out.println("#lockSet="+lockSet.hashCode());
1982 System.out.println("lockset="+lockSet);
1983 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1984 SESELock seseLock = (SESELock) iterator.next();
1985 System.out.println("id="+seseLock.getID());
1986 System.out.println("#="+seseLock);
1988 System.out.println("size="+lockSet.size());
1989 if (lockSet.size() > 0) {
1990 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1991 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
1992 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1997 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1998 if(callerSESEplaceholder!= oooa.getMainSESE()){
1999 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(callerSESEplaceholder);
2000 if (graph != null && graph.hasConflictEdge()) {
2001 output.println(" // set up waiting queues ");
2002 output.println(" int numMemoryQueue=0;");
2003 output.println(" int memoryQueueItemID=0;");
2004 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
2005 System.out.println("#lockSet="+lockSet.hashCode());
2006 System.out.println("lockset="+lockSet);
2007 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
2008 Analysis.OoOJava.SESELock seseLock = (Analysis.OoOJava.SESELock) iterator.next();
2009 System.out.println("id="+seseLock.getID());
2010 System.out.println("#="+seseLock);
2012 System.out.println("size="+lockSet.size());
2013 if (lockSet.size() > 0) {
2014 output.println(" numMemoryQueue=" + lockSet.size() + ";");
2015 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
2016 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2026 /* Check to see if we need to do a GC if this is a
2027 * multi-threaded program...*/
2029 if (((state.MLP||state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
2030 || this.state.MULTICOREGC) {
2031 //Don't bother if we aren't in recursive methods...The loops case will catch it
2032 if (callgraph.getAllMethods(md).contains(md)) {
2033 if (state.DSM&&lb.isAtomic())
2034 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
2035 else if (this.state.MULTICOREGC) {
2036 output.println("if(gcflag) gc("+localsprefixaddr+");");
2038 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2043 if(fm.getMethod().isStaticBlock()) {
2044 // a static block, check if it has been executed
2045 output.println(" if(global_defs_p->" + cn.getSafeSymbol()+"static_block_exe_flag != 0) {");
2046 output.println(" return;");
2047 output.println(" }");
2050 if((!fm.getMethod().isStaticBlock()) && (fm.getMethod().getReturnType() == null) && (cn != null)){
2051 // is a constructor, check and output initialization of the static fields
2052 // here does not initialize the static fields of the class, instead it
2053 // redirect the corresponding fields in the object to the global_defs_p
2054 Vector fields=(Vector)fieldorder.get(cn);
2056 for(int i=0; i<fields.size(); i++) {
2057 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
2060 output.println(generateTemp(fm,fm.getParameter(0),lb)+"->"+fd.getSafeSymbol()+"=&(global_defs_p->"+cn.getSafeSymbol()+fd.getSafeSymbol()+");");
2065 generateCode(fm.getNext(0), fm, lb, null, output, true);
2067 output.println("}\n\n");
2071 protected void initializeSESE( FlatSESEEnterNode fsen ) {
2073 FlatMethod fm = fsen.getfmEnclosing();
2074 MethodDescriptor md = fm.getMethod();
2075 ClassDescriptor cn = md.getClassDesc();
2078 // Creates bogus method descriptor to index into tables
2079 Modifiers modBogus = new Modifiers();
2080 MethodDescriptor mdBogus =
2081 new MethodDescriptor( modBogus,
2082 new TypeDescriptor( TypeDescriptor.VOID ),
2083 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
2086 mdBogus.setClassDesc( fsen.getcdEnclosing() );
2087 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
2088 fsen.setfmBogus( fmBogus );
2089 fsen.setmdBogus( mdBogus );
2091 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
2092 inSetAndOutSet.addAll( fsen.getInVarSet() );
2093 inSetAndOutSet.addAll( fsen.getOutVarSet() );
2095 // Build paramsobj for bogus method descriptor
2096 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
2097 paramstable.put( mdBogus, objectparams );
2099 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
2100 while( itr.hasNext() ) {
2101 TempDescriptor temp = itr.next();
2102 TypeDescriptor type = temp.getType();
2103 if( type.isPtr() ) {
2104 objectparams.addPtr( temp );
2106 objectparams.addPrim( temp );
2110 // Build normal temp object for bogus method descriptor
2111 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
2112 tempstable.put( mdBogus, objecttemps );
2114 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
2115 FlatNode fn = (FlatNode)nodeit.next();
2116 TempDescriptor[] writes = fn.writesTemps();
2118 for( int i = 0; i < writes.length; i++ ) {
2119 TempDescriptor temp = writes[i];
2120 TypeDescriptor type = temp.getType();
2122 if( type.isPtr() ) {
2123 objecttemps.addPtr( temp );
2125 objecttemps.addPrim( temp );
2131 // used when generating the specific SESE record struct
2132 // to remember the FIRST field name of sese records
2133 // that the current SESE depends on--we need to know the
2134 // offset to the first one for garbage collection
2135 protected void addingDepRecField( FlatSESEEnterNode fsen,
2137 if( fsen.getFirstDepRecField() == null ) {
2138 fsen.setFirstDepRecField( field );
2140 fsen.incNumDepRecs();
2143 protected void generateMethodSESE(FlatSESEEnterNode fsen,
2145 PrintWriter outputStructs,
2146 PrintWriter outputMethHead,
2147 PrintWriter outputMethods
2150 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
2151 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
2153 // generate locals structure
2154 outputStructs.println("struct "+
2155 fsen.getcdEnclosing().getSafeSymbol()+
2156 fsen.getmdBogus().getSafeSymbol()+"_"+
2157 fsen.getmdBogus().getSafeMethodDescriptor()+
2159 outputStructs.println(" int size;");
2160 outputStructs.println(" void * next;");
2161 for(int i=0; i<objecttemps.numPointers(); i++) {
2162 TempDescriptor temp=objecttemps.getPointer(i);
2164 if (temp.getType().isNull())
2165 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
2167 outputStructs.println(" struct "+
2168 temp.getType().getSafeSymbol()+" * "+
2169 temp.getSafeSymbol()+";");
2171 outputStructs.println("};\n");
2174 // divide in-set and out-set into objects and primitives to prep
2175 // for the record generation just below
2176 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
2177 inSetAndOutSet.addAll( fsen.getInVarSet() );
2178 inSetAndOutSet.addAll( fsen.getOutVarSet() );
2180 Set<TempDescriptor> inSetAndOutSetObjs = new HashSet<TempDescriptor>();
2181 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
2183 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
2184 while( itr.hasNext() ) {
2185 TempDescriptor temp = itr.next();
2186 TypeDescriptor type = temp.getType();
2187 if( type.isPtr() ) {
2188 inSetAndOutSetObjs.add( temp );
2190 inSetAndOutSetPrims.add( temp );
2195 // generate the SESE record structure
2196 outputStructs.println(fsen.getSESErecordName()+" {");
2198 // data common to any SESE, and it must be placed first so
2199 // a module that doesn't know what kind of SESE record this
2200 // is can cast the pointer to a common struct
2201 outputStructs.println(" SESEcommon common;");
2203 // then garbage list stuff
2204 outputStructs.println(" /* next is in-set and out-set objects that look like a garbage list */");
2205 outputStructs.println(" int size;");
2206 outputStructs.println(" void * next;");
2208 // I think that the set of TempDescriptors inSetAndOutSetObjs
2209 // calculated above should match the pointer object params
2210 // used in the following code, but let's just leave the working
2211 // implementation unless there is actually a problem...
2213 Vector<TempDescriptor> inset=fsen.getInVarsForDynamicCoarseConflictResolution();
2214 for(int i=0; i<inset.size();i++) {
2215 TempDescriptor temp=inset.get(i);
2216 if (temp.getType().isNull())
2217 outputStructs.println(" void * "+temp.getSafeSymbol()+
2218 "; /* in-or-out-set obj in gl */");
2220 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+
2221 temp.getSafeSymbol()+"; /* in-or-out-set obj in gl */");
2224 for(int i=0; i<objectparams.numPointers(); i++) {
2225 TempDescriptor temp=objectparams.getPointer(i);
2226 if (!inset.contains(temp)) {
2227 if (temp.getType().isNull())
2228 outputStructs.println(" void * "+temp.getSafeSymbol()+
2229 "; /* in-or-out-set obj in gl */");
2231 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+
2232 temp.getSafeSymbol()+"; /* in-or-out-set obj in gl */");
2236 outputStructs.println(" /* next is primitives for in-set and out-set and dynamic tracking */");
2238 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
2239 while( itrPrims.hasNext() ) {
2240 TempDescriptor temp = itrPrims.next();
2241 TypeDescriptor type = temp.getType();
2242 if(type.isPrimitive()){
2243 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+"; /* in-set or out-set primitive */");
2247 // note that the sese record pointer will be added below, just primitive part of tracking here
2248 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
2249 while( itrDynInVars.hasNext() ) {
2250 TempDescriptor dynInVar = itrDynInVars.next();
2251 outputStructs.println(" INTPTR "+dynInVar+"_srcOffset; /* dynamic tracking primitive */");
2255 outputStructs.println(" /* everything after this should be pointers to an SESE record */" );
2257 // other half of info for dynamic tracking, the SESE record pointer
2258 itrDynInVars = fsen.getDynamicInVarSet().iterator();
2259 while( itrDynInVars.hasNext() ) {
2260 TempDescriptor dynInVar = itrDynInVars.next();
2261 String depRecField = dynInVar+"_srcSESE";
2262 outputStructs.println(" SESEcommon* "+depRecField+";");
2263 addingDepRecField( fsen, depRecField );
2266 // statically known sese sources are record pointers, too
2267 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
2268 while( itrStaticInVarSrcs.hasNext() ) {
2269 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
2270 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
2271 addingDepRecField(fsen, srcPair.toString());
2275 if (inset.size()!=0)
2276 outputStructs.println("struct rcrRecord rcrRecords["+inset.size()+"];");
2279 if( fsen.getFirstDepRecField() != null ) {
2280 outputStructs.println(" /* compiler believes first dependent SESE record field above is: "+
2281 fsen.getFirstDepRecField()+" */" );
2283 outputStructs.println("};\n");
2286 // write method declaration to header file
2287 outputMethHead.print("void ");
2288 outputMethHead.print(fsen.getSESEmethodName()+"(");
2289 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
2290 outputMethHead.println(");\n");
2293 generateFlatMethodSESE( fsen.getfmBogus(),
2294 fsen.getcdEnclosing(),
2300 private void generateFlatMethodSESE(FlatMethod fm,
2302 FlatSESEEnterNode fsen,
2303 FlatSESEExitNode seseExit,
2307 MethodDescriptor md=fm.getMethod();
2309 output.print("void ");
2310 output.print(fsen.getSESEmethodName()+"(");
2311 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
2312 output.println("){\n");
2315 TempObject objecttemp=(TempObject) tempstable.get(md);
2317 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2318 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2319 output.print(objecttemp.numPointers()+",");
2320 output.print("&(((SESEcommon*)(___params___))[1])");
2321 for(int j=0; j<objecttemp.numPointers(); j++)
2322 output.print(", NULL");
2323 output.println("};");
2326 output.println(" /* regular local primitives */");
2327 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2328 TempDescriptor td=objecttemp.getPrimitive(i);
2329 TypeDescriptor type=td.getType();
2331 output.println(" void * "+td.getSafeSymbol()+";");
2332 else if (type.isClass()||type.isArray())
2333 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2335 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2339 // declare variables for naming static SESE's
2340 output.println(" /* static SESE names */");
2341 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
2342 while( pItr.hasNext() ) {
2343 SESEandAgePair pair = pItr.next();
2344 output.println(" SESEcommon* "+pair+" = NULL;");
2347 // declare variables for tracking dynamic sources
2348 output.println(" /* dynamic variable sources */");
2349 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
2350 while( dynSrcItr.hasNext() ) {
2351 TempDescriptor dynSrcVar = dynSrcItr.next();
2352 output.println(" SESEcommon* "+dynSrcVar+"_srcSESE = NULL;");
2353 output.println(" INTPTR "+dynSrcVar+"_srcOffset = 0x1;");
2356 // declare local temps for in-set primitives, and if it is
2357 // a ready-source variable, get the value from the record
2358 output.println(" /* local temps for in-set primitives */");
2359 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2360 while( itrInSet.hasNext() ) {
2361 TempDescriptor temp = itrInSet.next();
2362 TypeDescriptor type = temp.getType();
2363 if( !type.isPtr() ) {
2364 if( fsen.getReadyInVarSet().contains( temp ) ) {
2365 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2367 output.println(" "+type+" "+temp+";");
2372 // declare local temps for out-set primitives if its not already
2373 // in the in-set, and it's value will get written so no problem
2374 output.println(" /* local temp for out-set prim, not already in the in-set */");
2375 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2376 while( itrOutSet.hasNext() ) {
2377 TempDescriptor temp = itrOutSet.next();
2378 TypeDescriptor type = temp.getType();
2379 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2380 output.println(" "+type+" "+temp+";");
2385 // initialize thread-local var to a the task's record, which is fused
2386 // with the param list
2387 output.println(" ");
2388 output.println(" // code of this task's body should use this to access the running task record");
2389 output.println(" runningSESE = &(___params___->common);");
2390 output.println(" ");
2392 // setup memory queue
2395 output.println(" // set up memory queues ");
2396 output.println(" int numMemoryQueue=0;");
2397 output.println(" int memoryQueueItemID=0;");
2398 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(fsen);
2399 if (graph != null && graph.hasConflictEdge()) {
2400 output.println(" {");
2401 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
2402 System.out.println("#lockSet="+lockSet);
2403 if (lockSet.size() > 0) {
2404 output.println(" numMemoryQueue=" + lockSet.size() + ";");
2405 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
2406 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2409 output.println(" }");
2412 output.println(" // set up memory queues ");
2413 output.println(" int numMemoryQueue=0;");
2414 output.println(" int memoryQueueItemID=0;");
2415 ConflictGraph graph = null;
2416 graph = mlpa.getConflictGraphResults().get(fsen);
2417 if (graph != null && graph.hasConflictEdge()) {
2418 output.println(" {");
2419 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
2421 System.out.println("#lockSet="+lockSet);
2423 if (lockSet.size() > 0) {
2424 output.println(" numMemoryQueue=" + lockSet.size() + "; ");
2425 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
2426 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2429 output.println(" }");
2434 // set up a task's mem pool to recycle the allocation of children tasks
2435 // don't bother if the task never has children (a leaf task)
2436 output.println( "#ifndef OOO_DISABLE_TASKMEMPOOL" );
2437 if( !fsen.getIsLeafSESE() ) {
2438 output.println(" runningSESE->taskRecordMemPool = poolcreate( "+
2439 maxTaskRecSizeStr+" );");
2441 // make it clear we purposefully did not initialize this
2442 output.println(" runningSESE->taskRecordMemPool = (MemPool*)0x1;");
2444 output.println( "#endif // OOO_DISABLE_TASKMEMPOOL" );
2447 // copy in-set into place, ready vars were already
2448 // copied when the SESE was issued
2449 Iterator<TempDescriptor> tempItr;
2451 // static vars are from a known SESE
2452 output.println(" // copy variables from static sources");
2453 tempItr = fsen.getStaticInVarSet().iterator();
2454 while( tempItr.hasNext() ) {
2455 TempDescriptor temp = tempItr.next();
2456 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2457 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2458 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2459 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2462 output.println(" // decrement references to static sources");
2463 for( Iterator<SESEandAgePair> pairItr = fsen.getStaticInVarSrcs().iterator(); pairItr.hasNext(); ) {
2464 SESEandAgePair srcPair = pairItr.next();
2465 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
2466 output.println(" {");
2467 output.println(" SESEcommon* src = &("+paramsprefix+"->"+srcPair+"->common);");
2468 output.println(" RELEASE_REFERENCE_TO( src );");
2469 output.println(" }");
2470 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
2474 // dynamic vars come from an SESE and src
2475 output.println(" // copy variables from dynamic sources");
2476 tempItr = fsen.getDynamicInVarSet().iterator();
2477 while( tempItr.hasNext() ) {
2478 TempDescriptor temp = tempItr.next();
2479 TypeDescriptor type = temp.getType();
2481 // go grab it from the SESE source
2482 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2485 if( type.isNull() ) {
2487 } else if( type.isClass() || type.isArray() ) {
2488 typeStr = "struct "+type.getSafeSymbol()+"*";
2490 typeStr = type.getSafeSymbol();
2493 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2494 " = *(("+typeStr+"*) ((void*)"+
2495 paramsprefix+"->"+temp+"_srcSESE + "+
2496 paramsprefix+"->"+temp+"_srcOffset));");
2498 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
2499 output.println(" SESEcommon* src = "+paramsprefix+"->"+temp+"_srcSESE;");
2500 output.println(" RELEASE_REFERENCE_TO( src );");
2501 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
2503 // or if the source was our parent, its already in our record to grab
2504 output.println(" } else {");
2505 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2506 " = "+paramsprefix+"->"+temp+";");
2507 output.println(" }");
2510 // Check to see if we need to do a GC if this is a
2511 // multi-threaded program...
2512 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2513 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2514 //Don't bother if we aren't in recursive methods...The loops case will catch it
2515 // if (callgraph.getAllMethods(md).contains(md)) {
2516 // if(this.state.MULTICOREGC) {
2517 // output.println("if(gcflag) gc("+localsprefixaddr+");");
2519 // output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2524 if( state.COREPROF ) {
2525 output.println("#ifdef CP_EVENTID_TASKEXECUTE");
2526 output.println(" CP_LOGEVENT( CP_EVENTID_TASKEXECUTE, CP_EVENTTYPE_BEGIN );");
2527 output.println("#endif");
2530 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2531 exitset.add(seseExit);
2532 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2533 output.println("}\n\n");
2538 // when a new mlp thread is created for an issued SESE, it is started
2539 // by running this method which blocks on a cond variable until
2540 // it is allowed to transition to execute. Then a case statement
2541 // allows it to invoke the method with the proper SESE body, and after
2542 // exiting the SESE method, executes proper SESE exit code before the
2543 // thread can be destroyed
2544 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2545 PrintWriter outmethod
2548 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2549 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2550 outmethod.println( " int status;");
2551 outmethod.println( " char errmsg[128];");
2553 // generate a case for each SESE class that can be invoked
2554 outmethod.println( " switch( *((int*)seseRecord) ) {");
2555 outmethod.println( " ");
2556 Iterator<FlatSESEEnterNode> seseit;
2558 seseit=mlpa.getAllSESEs().iterator();
2560 seseit=oooa.getAllSESEs().iterator();
2562 while(seseit.hasNext()){
2563 FlatSESEEnterNode fsen = seseit.next();
2565 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2566 outmethod.println( " case "+fsen.getIdentifier()+":");
2567 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2569 if( (state.MLP && fsen.equals( mlpa.getMainSESE() )) ||
2570 (state.OOOJAVA && fsen.equals( oooa.getMainSESE() ))
2572 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2573 outmethod.println( " CP_EXIT();");
2574 outmethod.println( " CP_DUMP();");
2575 outmethod.println( " workScheduleExit();");
2576 outmethod.println( " exit( 0 );");
2579 outmethod.println( " break;");
2580 outmethod.println( "");
2583 // default case should never be taken, error out
2584 outmethod.println( " default:");
2585 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2586 outmethod.println( " exit(-30);");
2587 outmethod.println( " break;");
2588 outmethod.println( " }");
2589 outmethod.println( " return NULL;");
2590 outmethod.println( "}\n\n");
2594 protected void generateCode(FlatNode first,
2597 Set<FlatNode> stopset,
2599 boolean firstpass) {
2601 /* Assign labels to FlatNode's if necessary.*/
2603 Hashtable<FlatNode, Integer> nodetolabel;
2605 if (state.DELAYCOMP&&!firstpass)
2606 nodetolabel=dcassignLabels(first, stopset);
2608 nodetolabel=assignLabels(first, stopset);
2610 Set<FlatNode> storeset=null;
2611 HashSet<FlatNode> genset=null;
2612 HashSet<FlatNode> refset=null;
2613 Set<FlatNode> unionset=null;
2615 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2616 storeset=delaycomp.livecode(lb);
2617 genset=new HashSet<FlatNode>();
2618 if (state.STMARRAY&&!state.DUALVIEW) {
2619 refset=new HashSet<FlatNode>();
2620 refset.addAll(delaycomp.getDeref(lb));
2621 refset.removeAll(delaycomp.getCannotDelay(lb));
2622 refset.removeAll(delaycomp.getOther(lb));
2625 genset.addAll(delaycomp.getCannotDelay(lb));
2626 genset.addAll(delaycomp.getOther(lb));
2628 genset.addAll(delaycomp.getNotReady(lb));
2629 if (state.STMARRAY&&!state.DUALVIEW) {
2630 genset.removeAll(refset);
2633 unionset=new HashSet<FlatNode>();
2634 unionset.addAll(storeset);
2635 unionset.addAll(genset);
2636 if (state.STMARRAY&&!state.DUALVIEW)
2637 unionset.addAll(refset);
2640 /* Do the actual code generation */
2641 FlatNode current_node=null;
2642 HashSet tovisit=new HashSet();
2643 HashSet visited=new HashSet();
2645 tovisit.add(first.getNext(0));
2648 while(current_node!=null||!tovisit.isEmpty()) {
2649 if (current_node==null) {
2650 current_node=(FlatNode)tovisit.iterator().next();
2651 tovisit.remove(current_node);
2652 } else if (tovisit.contains(current_node)) {
2653 tovisit.remove(current_node);
2655 visited.add(current_node);
2656 if (nodetolabel.containsKey(current_node)) {
2657 output.println("L"+nodetolabel.get(current_node)+":");
2659 if (state.INSTRUCTIONFAILURE) {
2660 if (state.THREAD||state.DSM||state.SINGLETM) {
2661 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2663 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2665 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2667 if (!state.DELAYCOMP||firstpass) {
2668 generateFlatNode(fm, lb, current_node, output);
2670 //store primitive variables in out set
2671 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2672 Set<TempDescriptor> liveout=ar.liveout;
2673 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2674 TempDescriptor tmp=tmpit.next();
2675 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2678 if ((state.MLP || state.OOOJAVA) && stopset!=null) {
2679 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2680 assert current_node instanceof FlatSESEExitNode;
2681 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2682 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2683 assert fsen.getFlatExit().equals( fsxn );
2684 assert fsxn.getFlatEnter().equals( fsen );
2686 if (current_node.kind()!=FKind.FlatReturnNode) {
2687 if((fm.getMethod() != null) && (fm.getMethod().isStaticBlock())) {
2688 // a static block, check if it has been executed
2689 output.println(" global_defs_p->" + fm.getMethod().getClassDesc().getSafeSymbol()+"static_block_exe_flag = 1;");
2692 output.println(" return;");
2695 } else if(current_node.numNext()==1) {
2697 if ((state.MLP|| state.OOOJAVA) &&
2698 current_node.kind()==FKind.FlatSESEEnterNode &&
2699 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2701 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2702 generateFlatNode(fm, lb, current_node, output);
2703 nextnode=fsen.getFlatExit().getNext(0);
2704 } else if (state.DELAYCOMP) {
2705 boolean specialprimitive=false;
2706 //skip literals...no need to add extra overhead
2707 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2708 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2709 if (!typedesc.isClass()&&!typedesc.isArray()) {
2710 specialprimitive=true;
2714 if (genset==null||genset.contains(current_node)||specialprimitive)
2715 generateFlatNode(fm, lb, current_node, output);
2716 if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2717 //need to acquire lock
2718 handleArrayDeref(fm, lb, current_node, output, firstpass);
2720 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2721 TempDescriptor wrtmp=current_node.writesTemps()[0];
2723 //need to store value written by previous node
2724 if (wrtmp.getType().isPtr()) {
2725 //only lock the objects that may actually need locking
2726 if (recorddc.getNeedTrans(lb, current_node)&&
2727 (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2728 wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2729 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2731 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2734 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2737 //need to read value read by previous node
2738 if (wrtmp.getType().isPtr()) {
2739 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2741 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");
2745 nextnode=current_node.getNext(0);
2748 generateFlatNode(fm, lb, current_node, output);
2749 nextnode=current_node.getNext(0);
2751 if (visited.contains(nextnode)) {
2752 output.println("goto L"+nodetolabel.get(nextnode)+";");
2755 current_node=nextnode;
2756 } else if (current_node.numNext()==2) {
2758 if (state.DELAYCOMP) {
2759 boolean computeside=false;
2761 //need to record which way it should go
2762 if (genset==null||genset.contains(current_node)) {
2763 if (storeset!=null&&storeset.contains(current_node)) {
2764 //need to store which way branch goes
2765 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2767 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2769 //which side to execute
2773 if (genset.contains(current_node)) {
2774 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2775 } else if (storeset.contains(current_node)) {
2777 branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2779 //which side to execute
2784 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2786 if (leftset.size()==0)
2788 if (visited.contains(current_node.getNext(branch))) {
2789 //already visited -- build jump
2790 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2793 current_node=current_node.getNext(branch);
2796 if (!visited.contains(current_node.getNext(1)))
2797 tovisit.add(current_node.getNext(1));
2798 if (visited.contains(current_node.getNext(0))) {
2799 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2802 current_node=current_node.getNext(0);
2806 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2807 if (!visited.contains(current_node.getNext(1)))
2808 tovisit.add(current_node.getNext(1));
2809 if (visited.contains(current_node.getNext(0))) {
2810 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2813 current_node=current_node.getNext(0);
2815 } else throw new Error();
2819 protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2820 if (fn.kind()==FKind.FlatSetElementNode) {
2821 FlatSetElementNode fsen=(FlatSetElementNode) fn;
2822 String dst=generateTemp(fm, fsen.getDst(), lb);
2823 String src=generateTemp(fm, fsen.getSrc(), lb);
2824 String index=generateTemp(fm, fsen.getIndex(), lb);
2825 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2827 if (elementtype.isArray()||elementtype.isClass())
2830 type=elementtype.getSafeSymbol()+" ";
2832 output.println("STOREARRAY("+dst+","+index+","+type+")");
2834 output.println("{");
2835 output.println(" struct ArrayObject *array;");
2836 output.println(" int index;");
2837 output.println(" RESTOREARRAY(array,index);");
2838 output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2839 output.println("}");
2841 } else if (fn.kind()==FKind.FlatElementNode) {
2842 FlatElementNode fen=(FlatElementNode) fn;
2843 String src=generateTemp(fm, fen.getSrc(), lb);
2844 String index=generateTemp(fm, fen.getIndex(), lb);
2845 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2846 String dst=generateTemp(fm, fen.getDst(), lb);
2848 if (elementtype.isArray()||elementtype.isClass())
2851 type=elementtype.getSafeSymbol()+" ";
2853 output.println("STOREARRAY("+src+","+index+","+type+")");
2855 output.println("{");
2856 output.println(" struct ArrayObject *array;");
2857 output.println(" int index;");
2858 output.println(" RESTOREARRAY(array,index);");
2859 output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2860 output.println("}");
2864 /** Special label assignment for delaycomputation */
2865 protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2866 HashSet tovisit=new HashSet();
2867 HashSet visited=new HashSet();
2869 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2871 //Label targets of branches
2872 Set<FlatNode> targets=branchanalysis.getTargets();
2873 for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2874 nodetolabel.put(it.next(), new Integer(labelindex++));
2879 /*Assign labels first. A node needs a label if the previous
2880 * node has two exits or this node is a join point. */
2882 while(!tovisit.isEmpty()) {
2883 FlatNode fn=(FlatNode)tovisit.iterator().next();
2888 if(lastset!=null&&lastset.contains(fn)) {
2889 // if last is not null and matches, don't go
2890 // any further for assigning labels
2894 for(int i=0; i<fn.numNext(); i++) {
2895 FlatNode nn=fn.getNext(i);
2898 //1) Edge >1 of node
2899 nodetolabel.put(nn,new Integer(labelindex++));
2901 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2905 nodetolabel.put(nn,new Integer(labelindex++));
2913 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2914 return assignLabels(first, null);
2917 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2918 HashSet tovisit=new HashSet();
2919 HashSet visited=new HashSet();
2921 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2924 /*Assign labels first. A node needs a label if the previous
2925 * node has two exits or this node is a join point. */
2927 while(!tovisit.isEmpty()) {
2928 FlatNode fn=(FlatNode)tovisit.iterator().next();
2933 if(lastset!=null&&lastset.contains(fn)) {
2934 // if last is not null and matches, don't go
2935 // any further for assigning labels
2939 for(int i=0; i<fn.numNext(); i++) {
2940 FlatNode nn=fn.getNext(i);
2943 //1) Edge >1 of node
2944 nodetolabel.put(nn,new Integer(labelindex++));
2946 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2950 nodetolabel.put(nn,new Integer(labelindex++));
2958 /** Generate text string that corresponds to the TempDescriptor td. */
2959 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2960 MethodDescriptor md=fm.getMethod();
2961 TaskDescriptor task=fm.getTask();
2962 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2964 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2965 return td.getSafeSymbol();
2968 if (objecttemps.isLocalPtr(td)) {
2969 return localsprefixderef+td.getSafeSymbol();
2972 if (objecttemps.isParamPtr(td)) {
2973 return paramsprefix+"->"+td.getSafeSymbol();
2979 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2981 // insert pre-node actions from the code plan
2982 if( state.MLP|| state.OOOJAVA ) {
2986 cp = mlpa.getCodePlan( fn );
2988 cp = oooa.getCodePlan(fn);
2993 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2995 // for each sese and age pair that this parent statement
2996 // must stall on, take that child's stall semaphore, the
2997 // copying of values comes after the statement
2998 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2999 while( vstItr.hasNext() ) {
3000 VariableSourceToken vst = vstItr.next();
3002 SESEandAgePair pair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
3004 output.println(" {");
3005 output.println(" "+pair.getSESE().getSESErecordName()+"* child = ("+
3006 pair.getSESE().getSESErecordName()+"*) "+pair+";");
3008 output.println(" SESEcommon* childCom = (SESEcommon*) "+pair+";");
3010 if( state.COREPROF ) {
3011 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
3012 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
3013 output.println("#endif");
3016 output.println(" pthread_mutex_lock( &(childCom->lock) );");
3017 output.println(" if( childCom->doneExecuting == FALSE ) {");
3018 output.println(" psem_reset( &runningSESEstallSem );");
3019 output.println(" childCom->parentsStallSem = &runningSESEstallSem;");
3020 output.println(" pthread_mutex_unlock( &(childCom->lock) );");
3021 output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );");
3022 output.println(" } else {");
3023 output.println(" pthread_mutex_unlock( &(childCom->lock) );");
3024 output.println(" }");
3026 // copy things we might have stalled for
3027 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
3028 while( tdItr.hasNext() ) {
3029 TempDescriptor td = tdItr.next();
3030 FlatMethod fmContext;
3031 if( currentSESE.getIsCallerSESEplaceholder() ) {
3032 fmContext = currentSESE.getfmEnclosing();
3034 fmContext = currentSESE.getfmBogus();
3036 output.println(" "+generateTemp( fmContext, td, null )+
3037 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
3040 if( state.COREPROF ) {
3041 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
3042 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
3043 output.println("#endif");
3046 output.println(" }");
3049 // for each variable with a dynamic source, stall just for that variable
3050 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
3051 while( dynItr.hasNext() ) {
3052 TempDescriptor dynVar = dynItr.next();
3054 // only stall if the dynamic source is not yourself, denoted by src==NULL
3055 // otherwise the dynamic write nodes will have the local var up-to-date
3056 output.println(" {");
3057 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
3059 output.println(" SESEcommon* childCom = (SESEcommon*) "+dynVar+"_srcSESE;");
3061 if( state.COREPROF ) {
3062 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
3063 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
3064 output.println("#endif");
3067 output.println(" pthread_mutex_lock( &(childCom->lock) );");
3068 output.println(" if( childCom->doneExecuting == FALSE ) {");
3069 output.println(" psem_reset( &runningSESEstallSem );");
3070 output.println(" childCom->parentsStallSem = &runningSESEstallSem;");
3071 output.println(" pthread_mutex_unlock( &(childCom->lock) );");
3072 output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );");
3073 output.println(" } else {");
3074 output.println(" pthread_mutex_unlock( &(childCom->lock) );");
3075 output.println(" }");
3077 FlatMethod fmContext;
3078 if( currentSESE.getIsCallerSESEplaceholder() ) {
3079 fmContext = currentSESE.getfmEnclosing();
3081 fmContext = currentSESE.getfmBogus();
3084 TypeDescriptor type = dynVar.getType();
3086 if( type.isNull() ) {
3088 } else if( type.isClass() || type.isArray() ) {
3089 typeStr = "struct "+type.getSafeSymbol()+"*";
3091 typeStr = type.getSafeSymbol();
3094 output.println(" "+generateTemp( fmContext, dynVar, null )+
3095 " = *(("+typeStr+"*) ((void*)"+
3096 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
3098 if( state.COREPROF ) {
3099 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
3100 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
3101 output.println("#endif");
3104 output.println(" }");
3105 output.println(" }");
3108 // for each assignment of a variable to rhs that has a dynamic source,
3109 // copy the dynamic sources
3110 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
3111 while( dynAssignItr.hasNext() ) {
3112 Map.Entry me = (Map.Entry) dynAssignItr.next();
3113 TempDescriptor lhs = (TempDescriptor) me.getKey();
3114 TempDescriptor rhs = (TempDescriptor) me.getValue();
3116 output.println(" {");
3117 output.println(" SESEcommon* oldSrc = "+lhs+"_srcSESE;");
3119 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
3120 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
3122 // no matter what we did above, track reference count of whatever
3123 // this variable pointed to, do release last in case we're just
3124 // copying the same value in because 1->2->1 is safe but ref count
3125 // 1->0->1 has a window where it looks like it should be free'd
3126 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3127 output.println(" if( "+rhs+"_srcSESE != NULL ) {");
3128 output.println(" ADD_REFERENCE_TO( "+rhs+"_srcSESE );");
3129 output.println(" }");
3130 output.println(" if( oldSrc != NULL ) {");
3131 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
3132 output.println(" }");
3133 output.println(" }");
3134 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
3137 // for each lhs that is dynamic from a non-dynamic source, set the
3138 // dynamic source vars to the current SESE
3139 dynItr = cp.getDynAssignCurr().iterator();
3140 while( dynItr.hasNext() ) {
3141 TempDescriptor dynVar = dynItr.next();
3142 assert currentSESE.getDynamicVarSet().contains( dynVar );
3144 // first release a reference to current record
3145 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3146 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
3147 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
3148 output.println(" }");
3149 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
3151 output.println(" "+dynVar+"_srcSESE = NULL;");
3155 // handling stall site
3156 if (state.OOOJAVA) {
3157 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(currentSESE);
3159 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
3160 Set<Analysis.OoOJava.WaitingElement> waitingElementSet =
3161 graph.getStallSiteWaitingElementSet(fn, seseLockSet);
3163 if(waitingElementSet.size()>0){
3164 output.println("// stall on parent's stall sites ");
3165 output.println(" {");
3166 output.println(" REntry* rentry;");
3168 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
3169 Analysis.OoOJava.WaitingElement waitingElement = (Analysis.OoOJava.WaitingElement) iterator.next();
3170 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3171 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", runningSESE);");
3173 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", runningSESE, (void*)&" +generateTemp(fm,waitingElement.getTempDesc(),lb)+ ");");
3175 output.println(" psem_init( &(rentry->parentStallSem) );");
3176 output.println(" rentry->queue=runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3177 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()
3178 + "],rentry)==NOTREADY){");
3179 if( state.COREPROF ) {
3180 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3181 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3182 output.println("#endif");
3184 output.println(" psem_take( &(rentry->parentStallSem), (struct garbagelist *)&___locals___ );");
3185 if( state.COREPROF ) {
3186 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3187 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3188 output.println("#endif");
3190 output.println(" } ");
3193 output.println(" "+rcr.getTraverserInvocation(waitingElement.getTempDesc(),
3194 generateTemp(fm, waitingElement.getTempDesc(), null), fn));
3197 output.println(" }");
3201 ParentChildConflictsMap conflictsMap = mlpa.getConflictsResults().get(fn);
3202 if (conflictsMap != null) {
3203 Set<Long> allocSet = conflictsMap.getAllocationSiteIDSetofStallSite();
3204 if (allocSet.size() > 0) {
3205 FlatNode enclosingFlatNode=null;
3206 if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
3207 enclosingFlatNode=currentSESE.getfmEnclosing();
3209 enclosingFlatNode=currentSESE;
3211 ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
3212 HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
3213 Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
3215 if(waitingElementSet.size()>0){
3216 output.println("// stall on parent's stall sites ");
3217 output.println(" {");
3218 output.println(" REntry* rentry;");
3220 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
3221 WaitingElement waitingElement = (WaitingElement) iterator.next();
3223 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3224 // HERE! a parent might conflict with a child
3225 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", runningSESE);");
3227 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", runningSESE, (void*)&___locals___."+ waitingElement.getDynID() + ");");
3229 output.println(" psem_init( &(rentry->parentStallSem) );");
3230 output.println(" rentry->queue=runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3232 .println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()
3233 + "],rentry)==NOTREADY){");
3234 if( state.COREPROF ) {
3235 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3236 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3237 output.println("#endif");
3239 output.println(" psem_take( &(rentry->parentStallSem), (struct garbagelist *)&___locals___ );");
3240 if( state.COREPROF ) {
3241 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3242 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3243 output.println("#endif");
3245 output.println(" } ");
3247 output.println(" }");
3256 case FKind.FlatAtomicEnterNode:
3257 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
3260 case FKind.FlatAtomicExitNode:
3261 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
3264 case FKind.FlatInstanceOfNode:
3265 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
3268 case FKind.FlatSESEEnterNode:
3269 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
3272 case FKind.FlatSESEExitNode:
3273 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
3276 case FKind.FlatWriteDynamicVarNode:
3277 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
3280 case FKind.FlatGlobalConvNode:
3281 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
3284 case FKind.FlatTagDeclaration:
3285 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
3288 case FKind.FlatCall:
3289 generateFlatCall(fm, lb, (FlatCall) fn,output);
3292 case FKind.FlatFieldNode:
3293 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
3296 case FKind.FlatElementNode:
3297 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
3300 case FKind.FlatSetElementNode:
3301 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
3304 case FKind.FlatSetFieldNode:
3305 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
3309 generateFlatNew(fm, lb, (FlatNew) fn,output);
3312 case FKind.FlatOpNode:
3313 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
3316 case FKind.FlatCastNode:
3317 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
3320 case FKind.FlatLiteralNode:
3321 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
3324 case FKind.FlatReturnNode:
3325 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
3329 output.println("/* nop */");
3332 case FKind.FlatGenReachNode:
3333 // this node is just for generating a reach graph
3334 // in disjointness analysis at a particular program point
3337 case FKind.FlatExit:
3338 output.println("/* exit */");
3341 case FKind.FlatBackEdge:
3342 if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3343 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3345 if(state.DSM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3346 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3348 if (((state.MLP|| state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
3349 || (this.state.MULTICOREGC)) {
3350 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
3351 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
3352 } else if(this.state.MULTICOREGC) {
3353 output.println("if (gcflag) gc("+localsprefixaddr+");");
3355 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3358 output.println("/* nop */");
3361 case FKind.FlatCheckNode:
3362 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
3365 case FKind.FlatFlagActionNode:
3366 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
3369 case FKind.FlatPrefetchNode:
3370 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
3373 case FKind.FlatOffsetNode:
3374 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
3381 // insert post-node actions from the code-plan
3384 CodePlan cp = mlpa.getCodePlan( fn );
3392 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
3393 output.println("/* FlatOffsetNode */");
3394 FieldDescriptor fd=fofn.getField();
3395 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
3396 output.println("/* offset */");
3399 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
3400 if (state.PREFETCH) {
3401 Vector oids = new Vector();
3402 Vector fieldoffset = new Vector();
3403 Vector endoffset = new Vector();
3404 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
3405 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
3406 PrefetchPair pp = (PrefetchPair) it.next();
3407 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
3408 /* Find prefetches that can generate oid */
3409 if(statusbase == LocalityAnalysis.GLOBAL) {
3410 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
3412 } else if (statusbase == LocalityAnalysis.LOCAL) {
3413 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
3420 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
3421 output.println("{");
3422 output.println("/* prefetch */");
3423 output.println("/* prefetchid_" + fpn.siteid + " */");
3424 output.println("void * prefptr;");
3425 output.println("int tmpindex;");
3427 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
3428 /*Create C code for oid array */
3429 output.print(" unsigned int oidarray_[] = {");
3430 boolean needcomma=false;
3431 for (Iterator it = oids.iterator(); it.hasNext();) {
3434 output.print(it.next());
3437 output.println("};");
3439 /*Create C code for endoffset values */
3440 output.print(" unsigned short endoffsetarry_[] = {");
3442 for (Iterator it = endoffset.iterator(); it.hasNext();) {
3445 output.print(it.next());
3448 output.println("};");
3450 /*Create C code for Field Offset Values */
3451 output.print(" short fieldarry_[] = {");
3453 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
3456 output.print(it.next());
3459 output.println("};");
3460 /* make the prefetch call to Runtime */
3461 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
3462 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
3463 output.println(" }");
3464 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
3465 output.println(" } else {");
3466 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
3467 output.println(" }");
3468 output.println("}");
3472 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
3473 short offsetcount = 0;
3477 } else if (localbase) {
3478 for(; breakindex<pp.desc.size(); breakindex++) {
3479 Descriptor desc=pp.getDescAt(breakindex);
3480 if (desc instanceof FieldDescriptor) {
3481 FieldDescriptor fd=(FieldDescriptor)desc;
3482 if (fd.isGlobal()) {
3490 if (breakindex>pp.desc.size()) //all local
3493 TypeDescriptor lasttype=pp.base.getType();
3494 String basestr=generateTemp(fm, pp.base, lb);
3496 boolean maybenull=fm.getMethod().isStatic()||
3497 !pp.base.equals(fm.getParameter(0));
3499 for(int i=0; i<breakindex; i++) {
3500 String indexcheck="";
3502 Descriptor desc=pp.getDescAt(i);
3503 if (desc instanceof FieldDescriptor) {
3504 FieldDescriptor fd=(FieldDescriptor)desc;
3506 if (!teststr.equals(""))
3508 teststr+="((prefptr="+basestr+")!=NULL)";
3509 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3511 basestr=basestr+"->"+fd.getSafeSymbol();
3514 lasttype=fd.getType();
3516 IndexDescriptor id=(IndexDescriptor)desc;
3517 indexcheck="((tmpindex=";
3518 for(int j=0; j<id.tddesc.size(); j++) {
3519 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3521 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3523 if (!teststr.equals(""))
3525 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3526 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3528 lasttype=lasttype.dereference();
3533 if (teststr.equals("")) {
3534 oid="((unsigned int)"+basestr+")";
3536 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3540 for(int i = breakindex; i < pp.desc.size(); i++) {
3541 String newfieldoffset;
3542 Object desc = pp.getDescAt(i);
3543 if(desc instanceof FieldDescriptor) {
3544 FieldDescriptor fd=(FieldDescriptor)desc;
3545 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3546 lasttype=fd.getType();
3548 newfieldoffset = "";
3549 IndexDescriptor id=(IndexDescriptor)desc;
3550 for(int j = 0; j < id.tddesc.size(); j++) {
3551 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3553 newfieldoffset += id.offset.toString();
3554 lasttype=lasttype.dereference();
3556 fieldoffset.add(newfieldoffset);
3559 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3560 base+=pp.desc.size()-breakindex;
3561 endoffset.add(new Short((short)base));
3566 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3567 if (lb!=fgcn.getLocality())
3569 /* Have to generate flat globalconv */
3570 if (fgcn.getMakePtr()) {
3572 //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3573 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3575 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3576 //need to do translation
3577 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3578 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3579 if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3580 output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3582 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3586 /* Need to convert to OID */
3587 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3588 if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3589 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3591 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3597 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3599 if (fion.getType().isArray()) {
3600 type=state.getArrayNumber(fion.getType())+state.numClasses();
3602 type=fion.getType().getClassDesc().getId();
3605 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3606 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3608 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3611 int sandboxcounter=0;
3612 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3613 /* Check to see if we need to generate code for this atomic */
3614 if (locality==null) {
3615 if (GENERATEPRECISEGC) {
3616 output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3617 output.println("stopforgc((struct garbagelist *) &___locals___);");
3618 output.println("pthread_mutex_lock(&atomiclock);");
3619 output.println("restartaftergc();");
3620 output.println("}");
3622 output.println("pthread_mutex_lock(&atomiclock);");
3627 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3631 if (state.SANDBOX) {
3632 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3633 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3636 if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3637 AtomicRecord ar=atomicmethodmap.get(faen);
3639 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3640 TempDescriptor tmp=tmpit.next();
3641 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3644 //copy outs that depend on path
3645 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3646 TempDescriptor tmp=tmpit.next();
3647 if (!ar.livein.contains(tmp))
3648 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3652 /* Backup the temps. */
3653 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3654 TempDescriptor tmp=tmpit.next();
3655 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3658 output.println("goto transstart"+faen.getIdentifier()+";");
3660 /******* Print code to retry aborted transaction *******/
3661 output.println("transretry"+faen.getIdentifier()+":");
3664 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3665 TempDescriptor tmp=tmpit.next();
3666 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3670 /********* Need to revert local object store ********/
3671 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3673 output.println("while ("+revertptr+") {");
3674 output.println("struct ___Object___ * tmpptr;");
3675 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3676 output.println("REVERT_OBJ("+revertptr+");");
3677 output.println(revertptr+"=tmpptr;");
3678 output.println("}");
3680 /******* Tell the runtime to start the transaction *******/
3682 output.println("transstart"+faen.getIdentifier()+":");
3683 if (state.SANDBOX) {
3684 output.println("transaction_check_counter=*counter_reset_pointer;");
3687 output.println("transStart();");
3689 if (state.ABORTREADERS||state.SANDBOX) {
3691 output.println("abortenabled=1;");
3692 output.println("if (_setjmp(aborttrans)) {");
3693 output.println(" goto transretry"+faen.getIdentifier()+"; }");
3697 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3698 /* Check to see if we need to generate code for this atomic */
3699 if (locality==null) {
3700 output.println("pthread_mutex_unlock(&atomiclock);");
3703 if (locality.getAtomic(lb).get(faen).intValue()>0)
3705 //store the revert list before we lose the transaction object
3708 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3709 output.println(revertptr+"=revertlist;");
3710 output.println("if (transCommit()) {");
3711 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3712 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3713 output.println("} else {");
3714 /* Need to commit local object store */
3715 output.println("while ("+revertptr+") {");
3716 output.println("struct ___Object___ * tmpptr;");
3717 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3718 output.println("COMMIT_OBJ("+revertptr+");");
3719 output.println(revertptr+"=tmpptr;");
3720 output.println("}");
3721 output.println("}");
3725 if (!state.DELAYCOMP) {
3727 output.println("if (transCommit()) {");
3728 /* Transaction aborts if it returns true */
3729 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3730 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3731 output.println("}");
3733 if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
3734 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3735 output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3737 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3738 TempDescriptor tmp=tmpit.next();
3739 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3741 } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3742 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3744 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3745 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3746 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3747 output.println("}");
3749 output.println("else {");
3750 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3751 TempDescriptor tmp=tmpit.next();
3752 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3754 output.println("}");
3756 output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3757 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3758 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3759 output.println("}");
3764 public void generateFlatSESEEnterNode( FlatMethod fm,
3766 FlatSESEEnterNode fsen,
3767 PrintWriter output) {
3768 // if MLP flag is off, okay that SESE nodes are in IR graph,
3769 // just skip over them and code generates exactly the same
3770 if( !(state.MLP || state.OOOJAVA) ) {
3773 // there may be an SESE in an unreachable method, skip over
3774 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
3775 (state.OOOJAVA && !oooa.getAllSESEs().contains(fsen))
3780 // also, if we have encountered a placeholder, just skip it
3781 if( fsen.getIsCallerSESEplaceholder() ) {
3785 output.println(" {");
3787 if( state.COREPROF ) {
3788 output.println("#ifdef CP_EVENTID_TASKDISPATCH");
3789 output.println(" CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_BEGIN );");
3790 output.println("#endif");
3794 // before doing anything, lock your own record and increment the running children
3795 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3796 (state.OOOJAVA && fsen != oooa.getMainSESE())
3798 output.println(" atomic_inc(&(runningSESE->numRunningChildren));");
3801 // allocate the space for this record
3802 output.println( "#ifndef OOO_DISABLE_TASKMEMPOOL" );
3804 output.println( "#ifdef CP_EVENTID_POOLALLOC");
3805 output.println( " CP_LOGEVENT( CP_EVENTID_POOLALLOC, CP_EVENTTYPE_BEGIN );");
3806 output.println( "#endif");
3807 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3808 (state.OOOJAVA && fsen != oooa.getMainSESE())
3811 fsen.getSESErecordName()+"* seseToIssue = ("+
3812 fsen.getSESErecordName()+"*) poolalloc( runningSESE->taskRecordMemPool );");
3815 fsen.getSESErecordName()+"* seseToIssue = ("+
3816 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3817 fsen.getSESErecordName()+" ) );");
3819 output.println( "#ifdef CP_EVENTID_POOLALLOC");
3820 output.println( " CP_LOGEVENT( CP_EVENTID_POOLALLOC, CP_EVENTTYPE_END );");
3821 output.println( "#endif");
3823 output.println( "#else // OOO_DISABLE_TASKMEMPOOL" );
3825 fsen.getSESErecordName()+"* seseToIssue = ("+
3826 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3827 fsen.getSESErecordName()+" ) );");
3828 output.println( "#endif // OOO_DISABLE_TASKMEMPOOL" );
3831 // set up the SESE in-set and out-set objects, which look
3832 // like a garbage list
3833 output.println(" struct garbagelist * gl= (struct garbagelist *)&(((SESEcommon*)(seseToIssue))[1]);");
3834 output.println(" gl->size="+calculateSizeOfSESEParamList(fsen)+";");
3835 output.println(" gl->next = NULL;");
3837 // there are pointers to SESE records the newly-issued SESE
3838 // will use to get values it depends on them for--how many
3839 // are there, and what is the offset from the total SESE
3840 // record to the first dependent record pointer?
3841 output.println(" seseToIssue->common.numDependentSESErecords="+
3842 fsen.getNumDepRecs()+";");
3844 // we only need this (and it will only compile) when the number of dependent
3845 // SESE records is non-zero
3846 if( fsen.getFirstDepRecField() != null ) {
3847 output.println(" seseToIssue->common.offsetToDepSESErecords=(INTPTR)sizeof("+
3848 fsen.getSESErecordName()+") - (INTPTR)&((("+
3849 fsen.getSESErecordName()+"*)0)->"+fsen.getFirstDepRecField()+");"
3853 if (state.RCR&&fsen.getInVarsForDynamicCoarseConflictResolution().size()>0) {
3854 output.println(" seseToIssue->common.offsetToParamRecords=(INTPTR)sizeof("+fsen.getSESErecordName()+") - (INTPTR) & ((("+fsen.getSESErecordName()+"*)0)->rcrRecords);");
3857 // fill in common data
3858 output.println(" int localCount=0;");
3859 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3860 output.println(" seseToIssue->common.parentsStallSem = NULL;");
3861 output.println(" seseToIssue->common.forwardList = createQueue();");
3862 output.println(" seseToIssue->common.unresolvedDependencies = 10000;");
3863 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3864 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3865 output.println(" seseToIssue->common.numRunningChildren = 0;");
3866 output.println(" seseToIssue->common.parent = runningSESE;");
3867 // start with refCount = 2, one being the count that the child itself
3868 // will decrement when it retires, to say it is done using its own
3869 // record, and the other count is for the parent that will remember
3870 // the static name of this new child below
3871 output.println(" seseToIssue->common.refCount = 2;");
3873 // all READY in-vars should be copied now and be done with it
3874 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3875 while( tempItr.hasNext() ) {
3876 TempDescriptor temp = tempItr.next();
3878 // when we are issuing the main SESE or an SESE with placeholder
3879 // caller SESE as parent, generate temp child child's eclosing method,
3880 // otherwise use the parent's enclosing method as the context
3881 boolean useParentContext = false;
3883 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3884 (state.OOOJAVA && fsen != oooa.getMainSESE())
3886 assert fsen.getParent() != null;
3887 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3888 useParentContext = true;
3892 if( useParentContext ) {
3893 output.println(" seseToIssue->"+temp+" = "+
3894 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3896 output.println(" seseToIssue->"+temp+" = "+
3897 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3901 // before potentially adding this SESE to other forwarding lists,
3903 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3906 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3907 (state.OOOJAVA && fsen != oooa.getMainSESE())
3909 // count up outstanding dependencies, static first, then dynamic
3910 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3911 while( staticSrcsItr.hasNext() ) {
3912 SESEandAgePair srcPair = staticSrcsItr.next();
3913 output.println(" {");
3914 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3915 output.println(" pthread_mutex_lock( &(src->lock) );");
3917 output.println(" if( !src->doneExecuting ) {");
3918 output.println(" addNewItem( src->forwardList, seseToIssue );");
3919 output.println(" ++(localCount);");
3920 output.println(" }");
3921 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3922 output.println(" ADD_REFERENCE_TO( src );");
3923 output.println("#endif" );
3924 output.println(" pthread_mutex_unlock( &(src->lock) );");
3925 output.println(" }");
3927 // whether or not it is an outstanding dependency, make sure
3928 // to pass the static name to the child's record
3929 output.println(" seseToIssue->"+srcPair+" = "+
3930 "("+srcPair.getSESE().getSESErecordName()+"*)"+
3934 // dynamic sources might already be accounted for in the static list,
3935 // so only add them to forwarding lists if they're not already there
3936 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3937 while( dynVarsItr.hasNext() ) {
3938 TempDescriptor dynInVar = dynVarsItr.next();
3939 output.println(" {");
3940 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3942 // the dynamic source is NULL if it comes from your own space--you can't pass
3943 // the address off to the new child, because you're not done executing and
3944 // might change the variable, so copy it right now
3945 output.println(" if( src != NULL ) {");
3946 output.println(" pthread_mutex_lock( &(src->lock) );");
3950 output.println(" if( isEmpty( src->forwardList ) ||");
3951 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3952 output.println(" if( !src->doneExecuting ) {");
3953 output.println(" addNewItem( src->forwardList, seseToIssue );");
3954 output.println(" ++(localCount);");
3955 output.println(" }");
3956 output.println(" }");
3957 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3958 output.println(" ADD_REFERENCE_TO( src );");
3959 output.println("#endif" );
3960 output.println(" pthread_mutex_unlock( &(src->lock) );");
3961 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3962 output.println(" } else {");
3964 boolean useParentContext = false;
3965 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3966 (state.OOOJAVA && fsen != oooa.getMainSESE())
3968 assert fsen.getParent() != null;
3969 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3970 useParentContext = true;
3973 if( useParentContext ) {
3974 output.println(" seseToIssue->"+dynInVar+" = "+
3975 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3977 output.println(" seseToIssue->"+dynInVar+" = "+
3978 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3981 output.println(" }");
3982 output.println(" }");
3984 // even if the value is already copied, make sure your NULL source
3985 // gets passed so child knows it already has the dynamic value
3986 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3992 // maintain pointers for finding dynamic SESE
3993 // instances from static names
3994 SESEandAgePair pairNewest = new SESEandAgePair( fsen, 0 );
3995 SESEandAgePair pairOldest = new SESEandAgePair( fsen, fsen.getOldestAgeToTrack() );
3996 if( fsen.getParent() != null &&
3997 fsen.getParent().getNeededStaticNames().contains( pairNewest )
3999 output.println(" {");
4000 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4001 output.println(" SESEcommon* oldest = "+pairOldest+";");
4002 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4004 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
4005 SESEandAgePair pair1 = new SESEandAgePair( fsen, i );
4006 SESEandAgePair pair2 = new SESEandAgePair( fsen, i-1 );
4007 output.println(" "+pair1+" = "+pair2+";");
4009 output.println(" "+pairNewest+" = &(seseToIssue->common);");
4011 // no need to add a reference to whatever is the newest record, because
4012 // we initialized seseToIssue->refCount to *2*
4013 // but release a reference to whatever was the oldest BEFORE the shift
4014 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4015 output.println(" if( oldest != NULL ) {");
4016 output.println(" RELEASE_REFERENCE_TO( oldest );");
4017 output.println(" }");
4018 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4019 output.println(" }");
4024 if( state.COREPROF ) {
4025 output.println("#ifdef CP_EVENTID_PREPAREMEMQ");
4026 output.println(" CP_LOGEVENT( CP_EVENTID_PREPAREMEMQ, CP_EVENTTYPE_BEGIN );");
4027 output.println("#endif");
4032 // count up memory conflict dependencies,
4034 dispatchMEMRC(fm, lb, fsen, output);
4035 } else if(state.OOOJAVA){
4036 FlatSESEEnterNode parent = fsen.getParent();
4037 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(parent);
4038 if (graph != null && graph.hasConflictEdge()) {
4039 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
4041 output.println(" //add memory queue element");
4042 Analysis.OoOJava.SESEWaitingQueue seseWaitingQueue=
4043 graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet);
4044 if(seseWaitingQueue.getWaitingElementSize()>0) {
4045 output.println(" {");
4046 output.println(" REntry* rentry=NULL;");
4047 output.println(" INTPTR* pointer=NULL;");
4048 output.println(" seseToIssue->common.rentryIdx=0;");
4050 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
4051 for (Iterator iterator = queueIDSet.iterator(); iterator.hasNext();) {
4052 Integer key = (Integer) iterator.next();
4053 int queueID=key.intValue();
4054 Set<Analysis.OoOJava.WaitingElement> waitingQueueSet =
4055 seseWaitingQueue.getWaitingElementSet(queueID);
4056 int enqueueType=seseWaitingQueue.getType(queueID);
4057 if(enqueueType==SESEWaitingQueue.EXCEPTION) {
4058 output.println(" INITIALIZEBUF(runningSESE->memoryQueueArray[" + queueID+ "]);");
4060 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2.hasNext();) {
4061 Analysis.OoOJava.WaitingElement waitingElement
4062 = (Analysis.OoOJava.WaitingElement) iterator2.next();
4063 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
4064 output.println(" rentry=mlpCreateREntry("
4065 + waitingElement.getStatus()
4066 + ", &(seseToIssue->common));");
4068 TempDescriptor td = waitingElement.getTempDesc();
4069 // decide whether waiting element is dynamic or static
4070 if (fsen.getDynamicInVarSet().contains(td)) {
4071 // dynamic in-var case
4072 output.println(" pointer=seseToIssue->"
4073 + waitingElement.getDynID()
4074 + "_srcSESE+seseToIssue->"
4075 + waitingElement.getDynID()
4077 output.println(" rentry=mlpCreateFineREntry("
4078 + waitingElement.getStatus()
4079 + ", &(seseToIssue->common), pointer );");
4080 } else if (fsen.getStaticInVarSet().contains(td)) {
4081 // static in-var case
4082 VariableSourceToken vst = fsen.getStaticInVarSrc(td);
4085 String srcId = "SESE_" + vst.getSESE().getPrettyIdentifier()
4086 + vst.getSESE().getIdentifier()
4087 + "_" + vst.getAge();
4088 output.println(" pointer=(void*)&seseToIssue->"
4094 output.println(" rentry=mlpCreateFineREntry("
4095 + waitingElement.getStatus()
4096 + ", &(seseToIssue->common), pointer );");
4099 output.println(" rentry=mlpCreateFineREntry("
4100 + waitingElement.getStatus()
4101 + ", &(seseToIssue->common), (void*)&seseToIssue->"
4102 + waitingElement.getDynID()
4106 output.println(" rentry->queue=runningSESE->memoryQueueArray["
4107 + waitingElement.getQueueID()
4110 if(enqueueType==SESEWaitingQueue.NORMAL){
4111 output.println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4112 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["
4113 + waitingElement.getQueueID()
4114 + "],rentry)==NOTREADY) {");
4115 output.println(" localCount++;");
4116 output.println(" }");
4118 output.println(" ADDRENTRYTOBUF(runningSESE->memoryQueueArray[" + waitingElement.getQueueID() + "],rentry);");
4121 if(enqueueType!=SESEWaitingQueue.NORMAL){
4122 output.println(" localCount+=RESOLVEBUF(runningSESE->memoryQueueArray["
4123 + queueID+ "],&seseToIssue->common);");
4126 output.println(" }");
4131 ConflictGraph graph = null;
4132 FlatSESEEnterNode parent = fsen.getParent();
4133 if (parent != null) {
4134 if (parent.isCallerSESEplaceholder) {
4135 graph = mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
4137 graph = mlpa.getConflictGraphResults().get(parent);
4140 if (graph != null && graph.hasConflictEdge()) {
4141 HashSet<SESELock> seseLockSet = mlpa.getConflictGraphLockMap()
4144 output.println(" //add memory queue element");
4145 SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(fsen.getIdentifier(),
4147 if(seseWaitingQueue.getWaitingElementSize()>0){
4148 output.println(" {");
4149 output.println(" REntry* rentry=NULL;");
4150 output.println(" INTPTR* pointer=NULL;");
4151 output.println(" seseToIssue->common.rentryIdx=0;");
4153 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
4154 for (Iterator iterator = queueIDSet.iterator(); iterator
4156 Integer key = (Integer) iterator.next();
4157 int queueID=key.intValue();
4158 Set<WaitingElement> waitingQueueSet = seseWaitingQueue.getWaitingElementSet(queueID);
4159 int enqueueType=seseWaitingQueue.getType(queueID);
4160 if(enqueueType==SESEWaitingQueue.EXCEPTION){
4161 output.println(" INITIALIZEBUF(runningSESE->memoryQueueArray["
4164 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2
4166 WaitingElement waitingElement = (WaitingElement) iterator2
4168 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
4169 output.println(" rentry=mlpCreateREntry("
4170 + waitingElement.getStatus()
4171 + ", &(seseToIssue->common));");
4173 TempDescriptor td = waitingElement
4175 // decide whether waiting element is dynamic or
4177 if (fsen.getDynamicInVarSet().contains(td)) {
4178 // dynamic in-var case
4179 output.println(" pointer=seseToIssue->"
4180 + waitingElement.getDynID()
4181 + "_srcSESE+seseToIssue->"
4182 + waitingElement.getDynID()
4185 .println(" rentry=mlpCreateFineREntry("
4188 + ", &(seseToIssue->common), pointer );");
4189 } else if (fsen.getStaticInVarSet()
4191 // static in-var case
4192 VariableSourceToken vst = fsen
4193 .getStaticInVarSrc(td);
4196 String srcId = "SESE_"
4198 .getPrettyIdentifier()
4199 + vst.getSESE().getIdentifier()
4200 + "_" + vst.getAge();
4202 .println(" pointer=(void*)&seseToIssue->"
4209 .println(" rentry=mlpCreateFineREntry("
4212 + ", &(seseToIssue->common), pointer );");
4217 .println(" rentry=mlpCreateFineREntry("
4220 + ", &(seseToIssue->common), (void*)&seseToIssue->"
4221 + waitingElement.getDynID()
4226 .println(" rentry->queue=runningSESE->memoryQueueArray["
4227 + waitingElement.getQueueID()
4230 if(enqueueType==SESEWaitingQueue.NORMAL){
4232 .println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4234 .println(" if(ADDRENTRY(runningSESE->memoryQueueArray["
4235 + waitingElement.getQueueID()
4236 + "],rentry)==NOTREADY){");
4237 output.println(" ++(localCount);");
4238 output.println(" } ");
4241 .println(" ADDRENTRYTOBUF(runningSESE->memoryQueueArray["
4242 + waitingElement.getQueueID()
4246 if(enqueueType!=SESEWaitingQueue.NORMAL){
4247 output.println(" localCount+=RESOLVEBUF(runningSESE->memoryQueueArray["
4248 + queueID+ "],&seseToIssue->common);");
4251 output.println(" }");
4258 if( state.COREPROF ) {
4259 output.println("#ifdef CP_EVENTID_PREPAREMEMQ");
4260 output.println(" CP_LOGEVENT( CP_EVENTID_PREPAREMEMQ, CP_EVENTTYPE_END );");
4261 output.println("#endif");
4264 // Enqueue Task Record
4266 output.println(" enqueueTR(TRqueue, (void *)seseToIssue);");
4269 // if there were no outstanding dependencies, issue here
4270 output.println(" if( atomic_sub_and_test(10000-localCount,&(seseToIssue->common.unresolvedDependencies) ) ) {");
4271 output.println(" workScheduleSubmit( (void*)seseToIssue );");
4272 output.println(" }");
4276 if( state.COREPROF ) {
4277 output.println("#ifdef CP_EVENTID_TASKDISPATCH");
4278 output.println(" CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_END );");
4279 output.println("#endif");
4282 output.println(" }");
4286 void dispatchMEMRC(FlatMethod fm, LocalityBinding lb, FlatSESEEnterNode fsen, PrintWriter output) {
4287 FlatSESEEnterNode parent = fsen.getParent();
4288 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(parent);
4289 if (graph != null && graph.hasConflictEdge()) {
4290 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
4291 Analysis.OoOJava.SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet);
4292 if(seseWaitingQueue.getWaitingElementSize()>0) {
4293 output.println(" {");
4294 output.println(" REntry* rentry=NULL;");
4295 output.println(" INTPTR* pointer=NULL;");
4296 output.println(" seseToIssue->common.rentryIdx=0;");
4297 output.println(" int dispCount;");
4298 Vector<TempDescriptor> invars=fsen.getInVarsForDynamicCoarseConflictResolution();
4299 for(int i=0;i<invars.size();i++) {
4300 TempDescriptor td=invars.get(i);
4301 Set<Analysis.OoOJava.WaitingElement> weset=seseWaitingQueue.getWaitingElementSet(td);
4302 int numqueues=weset.size();
4303 output.println(" seseToIssue->rcrRecords["+i+"].flag="+numqueues+";");
4304 output.println(" dispCount=0;");
4305 for(Iterator<Analysis.OoOJava.WaitingElement> wtit=weset.iterator();wtit.hasNext();) {
4306 Analysis.OoOJava.WaitingElement waitingElement=wtit.next();
4307 int queueID=waitingElement.getQueueID();
4308 assert(waitingElement.getStatus()>=ConflictNode.COARSE);
4309 output.println(" rentry=mlpCreateREntry(" + waitingElement.getStatus() + ", &(seseToIssue->common));");
4310 output.println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4311 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "],rentry)==READY) {");
4312 output.println(" dispCount++;");
4313 output.println(" }");
4315 output.println(" if(!dispCount || !atomic_sub_and_test(dispCount,&(seseToIssue->rcrRecords["+i+"].flag)))");
4316 output.println(" localCount++;");
4317 if (fsen.getDynamicInVarSet().contains(td)) {
4318 // dynamic in-var case
4319 //output.println(" pointer=seseToIssue->" + waitingElement.getDynID()+ "_srcSESE+seseToIssue->"+ waitingElement.getDynID()+ "_srcOffset;");
4320 //output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", &(seseToIssue->common), pointer );");
4323 output.println(" }");
4328 public void generateFlatSESEExitNode( FlatMethod fm,
4330 FlatSESEExitNode fsexn,
4331 PrintWriter output) {
4333 // if MLP flag is off, okay that SESE nodes are in IR graph,
4334 // just skip over them and code generates exactly the same
4335 if( ! (state.MLP || state.OOOJAVA) ) {
4339 // get the enter node for this exit that has meta data embedded
4340 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
4342 // there may be an SESE in an unreachable method, skip over
4343 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
4344 (state.OOOJAVA && !oooa.getAllSESEs().contains( fsen ))
4349 // also, if we have encountered a placeholder, just jump it
4350 if( fsen.getIsCallerSESEplaceholder() ) {
4354 if( state.COREPROF ) {
4355 output.println("#ifdef CP_EVENTID_TASKEXECUTE");
4356 output.println(" CP_LOGEVENT( CP_EVENTID_TASKEXECUTE, CP_EVENTTYPE_END );");
4357 output.println("#endif");
4360 output.println(" /* SESE exiting */");
4362 if( state.COREPROF ) {
4363 output.println("#ifdef CP_EVENTID_TASKRETIRE");
4364 output.println(" CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_BEGIN );");
4365 output.println("#endif");
4369 // this SESE cannot be done until all of its children are done
4370 // so grab your own lock with the condition variable for watching
4371 // that the number of your running children is greater than zero
4372 output.println(" pthread_mutex_lock( &(runningSESE->lock) );");
4373 output.println(" if( runningSESE->numRunningChildren > 0 ) {");
4374 output.println(" stopforgc( (struct garbagelist *)&___locals___ );");
4375 output.println(" do {");
4376 output.println(" pthread_cond_wait( &(runningSESE->runningChildrenCond), &(runningSESE->lock) );");
4377 output.println(" } while( runningSESE->numRunningChildren > 0 );");
4378 output.println(" restartaftergc();");
4379 output.println(" }");
4382 // copy out-set from local temps into the sese record
4383 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
4384 while( itr.hasNext() ) {
4385 TempDescriptor temp = itr.next();
4387 // only have to do this for primitives non-arrays
4389 temp.getType().isPrimitive() && !temp.getType().isArray()
4395 // have to determine the context enclosing this sese
4396 boolean useParentContext = false;
4398 if( (state.MLP &&fsen != mlpa.getMainSESE()) ||
4399 (state.OOOJAVA &&fsen != oooa.getMainSESE())
4401 assert fsen.getParent() != null;
4402 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
4403 useParentContext = true;
4408 if( useParentContext ) {
4409 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
4411 from = generateTemp( fsen.getfmEnclosing(), temp, null );
4414 output.println(" "+paramsprefix+
4415 "->"+temp.getSafeSymbol()+
4419 // mark yourself done, your task data is now read-only
4420 output.println(" runningSESE->doneExecuting = TRUE;");
4422 // if parent is stalling on you, let them know you're done
4423 if( (state.MLP && fsexn.getFlatEnter() != mlpa.getMainSESE()) ||
4424 (state.OOOJAVA && fsexn.getFlatEnter() != oooa.getMainSESE())
4426 output.println(" if( runningSESE->parentsStallSem != NULL ) {");
4427 output.println(" psem_give( runningSESE->parentsStallSem );");
4428 output.println(" }");
4431 output.println(" pthread_mutex_unlock( &(runningSESE->lock) );");
4433 // decrement dependency count for all SESE's on your forwarding list
4436 output.println(" while( !isEmpty( runningSESE->forwardList ) ) {");
4437 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( runningSESE->forwardList );");
4440 output.println(" if(consumer->rentryIdx>0){");
4441 output.println(" // resolved null pointer");
4442 output.println(" int idx;");
4443 output.println(" for(idx=0;idx<consumer->rentryIdx;idx++){");
4444 output.println(" resolvePointer(consumer->rentryArray[idx]);");
4445 output.println(" }");
4446 output.println(" }");
4449 output.println(" if( atomic_sub_and_test( 1, &(consumer->unresolvedDependencies) ) ){");
4450 output.println(" workScheduleSubmit( (void*)consumer );");
4451 output.println(" }");
4452 output.println(" }");
4456 // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
4457 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4458 (state.OOOJAVA && fsen != oooa.getMainSESE())
4462 output.println(" /* check memory dependency*/");
4463 output.println(" {");
4464 output.println(" int idx;");
4465 output.println(" for(idx=0;idx<___params___->common.rentryIdx;idx++){");
4466 output.println(" REntry* re=___params___->common.rentryArray[idx];");
4467 output.println(" RETIRERENTRY(re->queue,re);");
4468 output.println(" }");
4469 output.println(" }");
4474 // last of all, decrement your parent's number of running children
4475 output.println(" if( runningSESE->parent != NULL ) {");
4476 output.println(" if( atomic_sub_and_test( 1, &(runningSESE->parent->numRunningChildren) ) ) {");
4477 output.println(" pthread_mutex_lock ( &(runningSESE->parent->lock) );");
4478 output.println(" pthread_cond_signal ( &(runningSESE->parent->runningChildrenCond) );");
4479 output.println(" pthread_mutex_unlock( &(runningSESE->parent->lock) );");
4480 output.println(" }");
4481 output.println(" }");
4483 // a task has variables to track static/dynamic instances
4484 // that serve as sources, release the parent's ref of each
4485 // non-null var of these types
4486 output.println(" // releasing static SESEs");
4487 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4488 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
4489 while( pItr.hasNext() ) {
4490 SESEandAgePair pair = pItr.next();
4491 output.println(" if( "+pair+" != NULL ) {");
4492 output.println(" RELEASE_REFERENCE_TO( "+pair+" );");
4493 output.println(" }");
4495 output.println(" // releasing dynamic variable sources");
4496 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
4497 while( dynSrcItr.hasNext() ) {
4498 TempDescriptor dynSrcVar = dynSrcItr.next();
4499 output.println(" if( "+dynSrcVar+"_srcSESE != NULL ) {");
4500 output.println(" RELEASE_REFERENCE_TO( "+dynSrcVar+"_srcSESE );");
4501 output.println(" }");
4503 // destroy this task's mempool if it is not a leaf task
4504 if( !fsen.getIsLeafSESE() ) {
4505 output.println(" pooldestroy( runningSESE->taskRecordMemPool );");
4507 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4510 // if this is not the Main sese (which has no parent) then return
4511 // THIS task's record to the PARENT'S task record pool, and only if
4512 // the reference count is now zero
4513 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4514 (state.OOOJAVA && fsen != oooa.getMainSESE())
4516 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4517 output.println(" RELEASE_REFERENCE_TO( runningSESE );");
4518 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4520 // the main task has no parent, just free its record
4521 output.println(" mlpFreeSESErecord( runningSESE );");
4524 // as this thread is wrapping up the task, make sure the thread-local var
4525 // for the currently running task record references an invalid task
4526 output.println(" runningSESE = (SESEcommon*) 0x1;");
4528 if( state.COREPROF ) {
4529 output.println("#ifdef CP_EVENTID_TASKRETIRE");
4530 output.println(" CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_END );");
4531 output.println("#endif");
4535 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
4537 FlatWriteDynamicVarNode fwdvn,
4540 if( !(state.MLP || state.OOOJAVA) ) {
4541 // should node should not be in an IR graph if the
4542 // MLP flag is not set
4543 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
4546 Hashtable<TempDescriptor, VSTWrapper> writeDynamic = fwdvn.getVar2src();
4548 assert writeDynamic != null;
4550 Iterator wdItr = writeDynamic.entrySet().iterator();
4551 while( wdItr.hasNext() ) {
4552 Map.Entry me = (Map.Entry) wdItr.next();
4553 TempDescriptor refVar = (TempDescriptor) me.getKey();
4554 VSTWrapper vstW = (VSTWrapper) me.getValue();
4555 VariableSourceToken vst = vstW.vst;
4557 output.println(" {");
4558 output.println(" SESEcommon* oldSrc = "+refVar+"_srcSESE;");
4561 // if there is no given source, this variable is ready so
4562 // mark src pointer NULL to signify that the var is up-to-date
4563 output.println(" "+refVar+"_srcSESE = NULL;");
4565 // otherwise we track where it will come from
4566 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
4567 output.println(" "+refVar+"_srcSESE = "+instance+";");
4568 output.println(" "+refVar+"_srcOffset = (INTPTR) &((("+
4569 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
4572 // no matter what we did above, track reference count of whatever
4573 // this variable pointed to, do release last in case we're just
4574 // copying the same value in because 1->2->1 is safe but ref count
4575 // 1->0->1 has a window where it looks like it should be free'd
4576 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4577 output.println(" if( "+refVar+"_srcSESE != NULL ) {");
4578 output.println(" ADD_REFERENCE_TO( "+refVar+"_srcSESE );");
4579 output.println(" }");
4580 output.println(" if( oldSrc != NULL ) {");
4581 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
4582 output.println(" }");
4583 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4585 output.println(" }");
4590 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
4591 if (state.CONSCHECK) {
4592 String specname=fcn.getSpec();
4593 String varname="repairstate___";
4594 output.println("{");
4595 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
4597 TempDescriptor[] temps=fcn.getTemps();
4598 String[] vars=fcn.getVars();
4599 for(int i=0; i<temps.length; i++) {
4600 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
4603 output.println("if (doanalysis"+specname+"("+varname+")) {");
4604 output.println("free"+specname+"_state("+varname+");");
4605 output.println("} else {");
4606 output.println("/* Bad invariant */");
4607 output.println("free"+specname+"_state("+varname+");");
4608 output.println("abort_task();");
4609 output.println("}");
4610 output.println("}");
4614 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
4616 MethodDescriptor md=fc.getMethod();
4617 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
4618 ClassDescriptor cn=md.getClassDesc();
4620 // if the called method is a static block or a static method or a constructor
4621 // need to check if it can be invoked inside some static block
4622 if((md.isStatic() || md.isStaticBlock() || md.isConstructor()) &&
4623 ((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic()))) {
4624 if(!md.isInvokedByStatic()) {
4625 System.err.println("Error: a method that is invoked inside a static block is not tagged!");
4627 // is a static block or is invoked in some static block
4628 ClassDescriptor cd = fm.getMethod().getClassDesc();
4630 // the same class, do nothing
4631 // TODO may want to invoke static field initialization here
4633 if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
4634 // need to check if the class' static fields have been initialized and/or
4635 // its static blocks have been executed
4636 output.println("#ifdef MGC_STATIC_INIT_CHECK");
4637 output.println("if(global_defs_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
4638 if(cn.getNumStaticFields() != 0) {
4639 // TODO add static field initialization here
4641 if(cn.getNumStaticBlocks() != 0) {
4642 MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
4643 output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
4645 output.println(" global_defs_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
4647 output.println("}");
4648 output.println("#endif // MGC_STATIC_INIT_CHECK");
4653 output.println("{");
4654 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4656 LocalityBinding fclb=locality.getBinding(lb, fc);
4657 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4659 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4660 output.print(objectparams.numPointers());
4661 output.print(", "+localsprefixaddr);
4662 if (md.getThis()!=null) {
4664 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
4666 if (fc.getThis()!=null&&md.getThis()==null) {
4667 System.out.println("WARNING!!!!!!!!!!!!");
4668 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
4672 for(int i=0; i<fc.numArgs(); i++) {
4673 Descriptor var=md.getParameter(i);
4674 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4675 if (objectparams.isParamPtr(paramtemp)) {
4676 TempDescriptor targ=fc.getArg(i);
4678 TypeDescriptor td=md.getParamType(i);
4680 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4682 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4685 output.println("};");
4690 if (fc.getReturnTemp()!=null)
4691 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
4693 /* Do we need to do virtual dispatch? */
4694 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
4697 LocalityBinding fclb=locality.getBinding(lb, fc);
4698 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4700 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4705 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4706 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4708 output.print(md.getReturnType().getSafeSymbol()+" ");
4709 output.print("(*)(");
4711 boolean printcomma=false;
4712 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4714 LocalityBinding fclb=locality.getBinding(lb, fc);
4715 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4717 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4721 for(int i=0; i<objectparams.numPrimitives(); i++) {
4722 TempDescriptor temp=objectparams.getPrimitive(i);
4726 if (temp.getType().isClass()||temp.getType().isArray())
4727 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
4729 output.print(temp.getType().getSafeSymbol());
4734 LocalityBinding fclb=locality.getBinding(lb, fc);
4735 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
4737 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
4741 boolean needcomma=false;
4742 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4743 output.print("&__parameterlist__");
4747 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4748 if (fc.getThis()!=null) {
4749 TypeDescriptor ptd=null;
4750 if(md.getThis() != null) {
4751 ptd = md.getThis().getType();
4753 ptd = fc.getThis().getType();
4757 if (ptd.isClass()&&!ptd.isArray())
4758 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4759 output.print(generateTemp(fm,fc.getThis(),lb));
4764 for(int i=0; i<fc.numArgs(); i++) {
4765 Descriptor var=md.getParameter(i);
4766 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4767 if (objectparams.isParamPrim(paramtemp)) {
4768 TempDescriptor targ=fc.getArg(i);
4772 TypeDescriptor ptd=md.getParamType(i);
4773 if (ptd.isClass()&&!ptd.isArray())
4774 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4775 output.print(generateTemp(fm, targ,lb));
4779 output.println(");");
4780 output.println(" }");
4783 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
4784 Set subclasses=typeutil.getSubClasses(thiscd);
4785 if (subclasses==null)
4787 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
4788 ClassDescriptor cd=(ClassDescriptor)classit.next();
4789 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
4790 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
4791 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
4792 if (md.matches(matchmd))
4799 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
4800 if (state.SINGLETM) {
4801 //single machine transactional memory case
4802 String field=ffn.getField().getSafeSymbol();
4803 String src=generateTemp(fm, ffn.getSrc(),lb);
4804 String dst=generateTemp(fm, ffn.getDst(),lb);
4806 output.println(dst+"="+ src +"->"+field+ ";");
4807 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
4808 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
4809 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
4810 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
4811 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
4812 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
4813 if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
4814 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4816 output.println("TRANSREADRD("+dst+", "+dst+");");
4819 } else if (state.DSM) {
4820 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
4821 if (status==LocalityAnalysis.GLOBAL) {
4822 String field=ffn.getField().getSafeSymbol();
4823 String src=generateTemp(fm, ffn.getSrc(),lb);
4824 String dst=generateTemp(fm, ffn.getDst(),lb);
4826 if (ffn.getField().getType().isPtr()) {
4828 //TODO: Uncomment this when we have runtime support
4829 //if (ffn.getSrc()==ffn.getDst()) {
4830 //output.println("{");
4831 //output.println("void * temp="+src+";");
4832 //output.println("if (temp&0x1) {");
4833 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
4834 //output.println(src+"->"+field+"="+temp+";");
4835 //output.println("}");
4836 //output.println(dst+"=temp;");
4837 //output.println("}");
4839 output.println(dst+"="+ src +"->"+field+ ";");
4840 //output.println("if ("+dst+"&0x1) {");
4841 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4842 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4843 //output.println(src+"->"+field+"="+src+"->"+field+";");
4844 //output.println("}");
4847 output.println(dst+"="+ src+"->"+field+";");
4849 } else if (status==LocalityAnalysis.LOCAL) {
4850 if (ffn.getField().getType().isPtr()&&
4851 ffn.getField().isGlobal()) {
4852 String field=ffn.getField().getSafeSymbol();
4853 String src=generateTemp(fm, ffn.getSrc(),lb);
4854 String dst=generateTemp(fm, ffn.getDst(),lb);
4855 output.println(dst+"="+ src +"->"+field+ ";");
4856 if (locality.getAtomic(lb).get(ffn).intValue()>0)
4857 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4858 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4860 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4861 } else if (status==LocalityAnalysis.EITHER) {
4862 //Code is reading from a null pointer
4863 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
4864 output.println("#ifndef RAW");
4865 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4866 output.println("#endif");
4867 //This should throw a suitable null pointer error
4868 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4870 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4872 // DEBUG if(!ffn.getDst().getType().isPrimitive()){
4873 // DEBUG output.println("within((void*)"+generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+");");
4875 if(ffn.getField().isStatic()) {
4877 if((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())) {
4878 // is a static block or is invoked in some static block
4879 ClassDescriptor cd = fm.getMethod().getClassDesc();
4880 ClassDescriptor cn = ffn.getSrc().getType().getClassDesc();
4882 // the same class, do nothing
4883 // TODO may want to invoke static field initialization here
4885 if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
4886 // need to check if the class' static fields have been initialized and/or
4887 // its static blocks have been executed
4888 output.println("#ifdef MGC_STATIC_INIT_CHECK");
4889 output.println("if(global_defs_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
4890 if(cn.getNumStaticFields() != 0) {
4891 // TODO add static field initialization here
4893 if(cn.getNumStaticBlocks() != 0) {
4894 MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
4895 output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
4897 output.println(" global_defs_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
4899 output.println("}");
4900 output.println("#endif // MGC_STATIC_INIT_CHECK");
4904 // redirect to the global_defs_p structure
4905 if(ffn.getSrc().getType().isStatic()) {
4906 // reference to the static field with Class name
4907 output.println(generateTemp(fm, ffn.getDst(),lb)+"=global_defs_p->"+ ffn.getSrc().getType().getClassDesc().getSafeSymbol()+ffn.getField().getSafeSymbol()+";");
4909 output.println(generateTemp(fm, ffn.getDst(),lb)+"=*"+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4911 //output.println(generateTemp(fm, ffn.getDst(),lb)+"=global_defs_p->"+ffn.getSrc().getType().getClassDesc().getSafeSymbol()+"->"+ ffn.getField().getSafeSymbol()+";");
4913 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4919 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
4920 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
4921 throw new Error("Can't set array length");
4922 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4923 //Single Machine Transaction Case
4924 boolean srcptr=fsfn.getSrc().getType().isPtr();
4925 String src=generateTemp(fm,fsfn.getSrc(),lb);
4926 String dst=generateTemp(fm,fsfn.getDst(),lb);
4927 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
4928 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
4929 output.println("{");
4930 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
4931 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
4932 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4934 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4937 if (wb.needBarrier(fsfn)&&
4938 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
4939 if (state.EVENTMONITOR) {
4940 output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
4942 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
4944 if (srcptr&!fsfn.getSrc().getType().isNull()) {
4945 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4946 output.println("}");
4948 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4950 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4951 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
4952 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
4953 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4955 String src=generateTemp(fm,fsfn.getSrc(),lb);
4956 String dst=generateTemp(fm,fsfn.getDst(),lb);
4958 output.println("{");
4959 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4961 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
4964 if (wb.needBarrier(fsfn))
4965 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
4967 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4969 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4970 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
4971 /** Check if we need to copy */
4972 output.println("if(!"+dst+"->"+localcopystr+") {");
4973 /* Link object into list */
4974 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4975 output.println(revertptr+"=revertlist;");
4976 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4977 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4979 output.println("COPY_OBJ("+dst+");");
4980 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4981 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4982 output.println("}");
4984 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4986 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4987 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
4988 //writing to a null...bad
4989 output.println("if ("+dst+") {");
4990 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
4992 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4994 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4997 output.println("}");
5000 if (state.FASTCHECK) {
5001 String dst=generateTemp(fm, fsfn.getDst(),lb);
5002 output.println("if(!"+dst+"->"+localcopystr+") {");
5003 /* Link object into list */
5004 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
5005 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
5007 output.println("COPY_OBJ("+dst+");");
5008 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
5009 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
5010 output.println("}");
5013 // DEBUG if(!fsfn.getField().getType().isPrimitive()){
5014 // DEBUG output.println("within((void*)"+generateTemp(fm,fsfn.getSrc(),lb)+");");
5016 if(fsfn.getField().isStatic()) {
5018 if((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())) {
5019 // is a static block or is invoked in some static block
5020 ClassDescriptor cd = fm.getMethod().getClassDesc();
5021 ClassDescriptor cn = fsfn.getDst().getType().getClassDesc();
5023 // the same class, do nothing
5024 // TODO may want to invoke static field initialization here
5026 if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
5027 // need to check if the class' static fields have been initialized and/or
5028 // its static blocks have been executed
5029 output.println("#ifdef MGC_STATIC_INIT_CHECK");
5030 output.println("if(global_defs_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
5031 if(cn.getNumStaticFields() != 0) {
5032 // TODO add static field initialization here
5034 if(cn.getNumStaticBlocks() != 0) {
5035 MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
5036 output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
5038 output.println(" global_defs_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
5040 output.println("}");
5041 output.println("#endif // MGC_STATIC_INIT_CHECK");
5045 // redirect to the global_defs_p structure
5046 if(fsfn.getDst().getType().isStatic()) {
5047 // reference to the static field with Class name
5048 output.println("global_defs_p->" + fsfn.getDst().getType().getClassDesc().getSafeSymbol() + fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
5050 output.println("*"+generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
5053 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
5058 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
5059 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
5062 if (elementtype.isArray()||elementtype.isClass())
5065 type=elementtype.getSafeSymbol()+" ";
5067 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
5068 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
5069 output.println("failedboundschk();");
5071 if (state.SINGLETM) {
5072 //Single machine transaction case
5073 String dst=generateTemp(fm, fen.getDst(),lb);
5074 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))) {
5075 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
5077 output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
5080 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
5081 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
5082 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
5083 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
5084 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
5085 if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
5086 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
5088 output.println("TRANSREADRD("+dst+", "+dst+");");
5091 } else if (state.DSM) {
5092 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
5093 if (status==LocalityAnalysis.GLOBAL) {
5094 String dst=generateTemp(fm, fen.getDst(),lb);
5095 if (elementtype.isPtr()) {
5096 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
5097 //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
5098 output.println("TRANSREAD("+dst+", "+dst+");");
5100 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
5102 } else if (status==LocalityAnalysis.LOCAL) {
5103 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
5104 } else if (status==LocalityAnalysis.EITHER) {
5105 //Code is reading from a null pointer
5106 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
5107 output.println("#ifndef RAW");
5108 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
5109 output.println("#endif");
5110 //This should throw a suitable null pointer error
5111 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
5113 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
5115 // DEBUG output.println("within((void*)"+generateTemp(fm,fen.getSrc(),lb)+");");
5116 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
5120 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
5121 //TODO: need dynamic check to make sure this assignment is actually legal
5122 //Because Object[] could actually be something more specific...ie. Integer[]
5124 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
5127 if (elementtype.isArray()||elementtype.isClass())
5130 type=elementtype.getSafeSymbol()+" ";
5132 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
5133 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
5134 output.println("failedboundschk();");
5137 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
5138 //Transaction set element case
5139 if (wb.needBarrier(fsen)&&
5140 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
5141 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
5143 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
5144 output.println("{");
5145 String src=generateTemp(fm, fsen.getSrc(), lb);
5146 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
5147 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
5148 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
5150 output.println("INTPTR srcoid=(INTPTR)"+src+";");
5152 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
5153 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
5155 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
5157 output.println("}");
5159 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
5160 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
5162 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
5165 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
5166 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
5167 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
5168 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
5169 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
5170 boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
5173 if (wb.needBarrier(fsen))
5174 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
5175 } else if (dstlocal) {
5176 /** Check if we need to copy */
5177 String dst=generateTemp(fm, fsen.getDst(),lb);
5178 output.println("if(!"+dst+"->"+localcopystr+") {");
5179 /* Link object into list */
5180 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5181 output.println(revertptr+"=revertlist;");
5182 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
5183 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
5185 output.println("COPY_OBJ("+dst+");");
5186 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
5187 output.println("revertlist=(struct ___Object___ *)"+dst+";");
5188 output.println("}");
5190 System.out.println("Node: "+fsen);
5191 System.out.println(lb);
5192 System.out.println("statusdst="+statusdst);
5193 System.out.println(fm.printMethod());
5194 throw new Error("Unknown array type");
5197 output.println("{");
5198 String src=generateTemp(fm, fsen.getSrc(), lb);
5199 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
5200 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
5201 output.println("}");
5203 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
5206 if (state.FASTCHECK) {
5207 String dst=generateTemp(fm, fsen.getDst(),lb);
5208 output.println("if(!"+dst+"->"+localcopystr+") {");
5209 /* Link object into list */
5210 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
5211 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
5213 output.println("COPY_OBJ("+dst+");");
5214 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
5215 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
5216 output.println("}");
5218 // DEBUG output.println("within((void*)"+generateTemp(fm,fsen.getDst(),lb)+");");
5219 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
5223 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
5224 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
5225 //Stash pointer in case of GC
5226 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5227 output.println(revertptr+"=revertlist;");
5229 if (state.SINGLETM) {
5230 if (fn.getType().isArray()) {
5231 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
5232 if (locality.getAtomic(lb).get(fn).intValue()>0) {
5233 //inside transaction
5234 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5236 //outside transaction
5237 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5240 if (locality.getAtomic(lb).get(fn).intValue()>0) {
5241 //inside transaction
5242 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
5244 //outside transaction
5245 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
5248 } else if (fn.getType().isArray()) {
5249 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
5250 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
5251 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5252 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5253 if(this.state.MLP || state.OOOJAVA){
5254 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray_mlp("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
5255 output.println(" oid += numWorkers;");
5257 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5260 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5263 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
5264 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
5265 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5266 if (this.state.MLP || state.OOOJAVA){
5267 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new_mlp("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
5268 output.println(" oid += numWorkers;");
5270 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
5273 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
5276 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
5277 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5278 String dst=generateTemp(fm,fn.getDst(),lb);
5279 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
5280 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
5281 output.println("revertlist=(struct ___Object___ *)"+dst+";");
5283 if (state.FASTCHECK) {
5284 String dst=generateTemp(fm,fn.getDst(),lb);
5285 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
5286 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
5287 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
5291 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
5292 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5293 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
5295 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
5299 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
5300 if (fon.getRight()!=null) {
5301 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
5302 if (fon.getLeft().getType().isLong())
5303 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
5305 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
5307 } else if (dc!=null) {
5308 output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
5309 if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
5310 output.print("(void *)");
5311 if (dc.getNeedLeftSrcTrans(lb, fon))
5312 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
5314 output.print(generateTemp(fm, fon.getLeft(),lb));
5315 output.print(")"+fon.getOp().toString()+"(");
5316 if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
5317 output.print("(void *)");
5318 if (dc.getNeedRightSrcTrans(lb, fon))
5319 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
5321 output.println(generateTemp(fm,fon.getRight(),lb)+");");
5323 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
5324 } else if (fon.getOp().getOp()==Operation.ASSIGN)
5325 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
5326 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
5327 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
5328 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
5329 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
5330 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
5331 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
5332 else if (fon.getOp().getOp()==Operation.COMP)
5333 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
5334 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
5335 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
5337 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
5340 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
5341 /* TODO: Do type check here */
5342 if (fcn.getType().isArray()) {
5343 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
5344 } else if (fcn.getType().isClass())
5345 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
5347 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
5350 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
5351 if (fln.getValue()==null)
5352 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
5353 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
5354 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5355 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
5356 //Stash pointer in case of GC
5357 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5358 output.println(revertptr+"=revertlist;");
5360 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
5361 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
5362 //Stash pointer in case of GC
5363 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5364 output.println("revertlist="+revertptr+";");
5367 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
5369 } else if (fln.getType().isBoolean()) {
5370 if (((Boolean)fln.getValue()).booleanValue())
5371 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
5373 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
5374 } else if (fln.getType().isChar()) {
5375 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
5376 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
5377 } else if (fln.getType().isLong()) {
5378 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
5380 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
5383 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
5384 if((fm.getMethod() != null) && (fm.getMethod().isStaticBlock())) {
5385 // a static block, check if it has been executed
5386 output.println(" global_defs_p->" + fm.getMethod().getClassDesc().getSafeSymbol()+"static_block_exe_flag = 1;");
5389 if (frn.getReturnTemp()!=null) {
5390 if (frn.getReturnTemp().getType().isPtr())
5391 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
5393 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
5395 output.println("return;");
5399 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
5402 //only record if this group has more than one exit
5403 if (branchanalysis.numJumps(fcb)>1) {
5404 left=branchanalysis.jumpValue(fcb, 0);
5405 right=branchanalysis.jumpValue(fcb, 1);
5407 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
5409 output.println("STOREBRANCH("+right+");");
5410 output.println("goto "+label+";");
5411 output.println("}");
5413 output.println("STOREBRANCH("+left+");");
5416 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
5417 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
5420 /** This method generates header information for the method or
5421 * task referenced by the Descriptor des. */
5422 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
5423 generateHeader(fm, lb, des, output, false);
5426 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
5428 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
5429 MethodDescriptor md=null;
5430 TaskDescriptor task=null;
5431 if (des instanceof MethodDescriptor)
5432 md=(MethodDescriptor) des;
5434 task=(TaskDescriptor) des;
5436 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
5438 if (md!=null&&md.getReturnType()!=null) {
5439 if (md.getReturnType().isClass()||md.getReturnType().isArray())
5440 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
5442 output.print(md.getReturnType().getSafeSymbol()+" ");
5444 //catch the constructor case
5445 output.print("void ");
5447 if (state.DSM||state.SINGLETM) {
5448 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5450 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5452 output.print(task.getSafeSymbol()+"(");
5454 boolean printcomma=false;
5455 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5457 if (state.DSM||state.SINGLETM) {
5458 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5460 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5462 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
5468 for(int i=0; i<objectparams.numPrimitives(); i++) {
5469 TempDescriptor temp=objectparams.getPrimitive(i);
5473 if (temp.getType().isClass()||temp.getType().isArray())
5474 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
5476 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
5478 output.println(") {");
5479 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
5480 /* Imprecise Task */
5481 output.println("void * parameterarray[]) {");
5482 /* Unpack variables */
5483 for(int i=0; i<objectparams.numPrimitives(); i++) {
5484 TempDescriptor temp=objectparams.getPrimitive(i);
5485 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
5487 for(int i=0; i<fm.numTags(); i++) {
5488 TempDescriptor temp=fm.getTag(i);
5489 int offset=i+objectparams.numPrimitives();
5490 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
5493 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
5494 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
5495 } else output.println(") {");
5498 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
5499 output.println("/* FlatFlagActionNode */");
5502 /* Process tag changes */
5503 Relation tagsettable=new Relation();
5504 Relation tagcleartable=new Relation();
5506 Iterator tagsit=ffan.getTempTagPairs();
5507 while (tagsit.hasNext()) {
5508 TempTagPair ttp=(TempTagPair) tagsit.next();
5509 TempDescriptor objtmp=ttp.getTemp();
5510 TagDescriptor tag=ttp.getTag();
5511 TempDescriptor tagtmp=ttp.getTagTemp();
5512 boolean tagstatus=ffan.getTagChange(ttp);
5514 tagsettable.put(objtmp, tagtmp);
5516 tagcleartable.put(objtmp, tagtmp);
5521 Hashtable flagandtable=new Hashtable();
5522 Hashtable flagortable=new Hashtable();
5524 /* Process flag changes */
5525 Iterator flagsit=ffan.getTempFlagPairs();
5526 while(flagsit.hasNext()) {
5527 TempFlagPair tfp=(TempFlagPair)flagsit.next();
5528 TempDescriptor temp=tfp.getTemp();
5529 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
5530 FlagDescriptor flag=tfp.getFlag();
5532 //Newly allocate objects that don't set any flags case
5533 if (flagortable.containsKey(temp)) {
5537 flagortable.put(temp,new Integer(mask));
5539 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
5540 boolean flagstatus=ffan.getFlagChange(tfp);
5543 if (flagortable.containsKey(temp)) {
5544 mask=((Integer)flagortable.get(temp)).intValue();
5547 flagortable.put(temp,new Integer(mask));
5549 int mask=0xFFFFFFFF;
5550 if (flagandtable.containsKey(temp)) {
5551 mask=((Integer)flagandtable.get(temp)).intValue();
5553 mask&=(0xFFFFFFFF^flagid);
5554 flagandtable.put(temp,new Integer(mask));
5560 HashSet flagtagset=new HashSet();
5561 flagtagset.addAll(flagortable.keySet());
5562 flagtagset.addAll(flagandtable.keySet());
5563 flagtagset.addAll(tagsettable.keySet());
5564 flagtagset.addAll(tagcleartable.keySet());
5566 Iterator ftit=flagtagset.iterator();
5567 while(ftit.hasNext()) {
5568 TempDescriptor temp=(TempDescriptor)ftit.next();
5571 Set tagtmps=tagcleartable.get(temp);
5572 if (tagtmps!=null) {
5573 Iterator tagit=tagtmps.iterator();
5574 while(tagit.hasNext()) {
5575 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5576 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5577 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5579 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5583 tagtmps=tagsettable.get(temp);
5584 if (tagtmps!=null) {
5585 Iterator tagit=tagtmps.iterator();
5586 while(tagit.hasNext()) {
5587 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5588 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5589 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5591 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
5596 int andmask=0xFFFFFFF;
5598 if (flagortable.containsKey(temp))
5599 ormask=((Integer)flagortable.get(temp)).intValue();
5600 if (flagandtable.containsKey(temp))
5601 andmask=((Integer)flagandtable.get(temp)).intValue();
5602 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
5603 generateObjectDistribute(ffan, fm, lb, temp, output);
5607 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
5608 PrintWriter output, int ormask, int andmask) {
5609 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
5610 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5612 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5616 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
5617 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
5620 void generateOptionalHeader(PrintWriter headers) {
5623 headers.println("#include \"task.h\"\n\n");
5624 headers.println("#ifndef _OPTIONAL_STRUCT_");
5625 headers.println("#define _OPTIONAL_STRUCT_");
5627 //STRUCT PREDICATEMEMBER
5628 headers.println("struct predicatemember{");
5629 headers.println("int type;");
5630 headers.println("int numdnfterms;");
5631 headers.println("int * flags;");
5632 headers.println("int numtags;");
5633 headers.println("int * tags;\n};\n\n");
5635 //STRUCT OPTIONALTASKDESCRIPTOR
5636 headers.println("struct optionaltaskdescriptor{");
5637 headers.println("struct taskdescriptor * task;");
5638 headers.println("int index;");
5639 headers.println("int numenterflags;");
5640 headers.println("int * enterflags;");
5641 headers.println("int numpredicatemembers;");
5642 headers.println("struct predicatemember ** predicatememberarray;");
5643 headers.println("};\n\n");
5645 //STRUCT TASKFAILURE
5646 headers.println("struct taskfailure {");
5647 headers.println("struct taskdescriptor * task;");
5648 headers.println("int index;");
5649 headers.println("int numoptionaltaskdescriptors;");
5650 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5652 //STRUCT FSANALYSISWRAPPER
5653 headers.println("struct fsanalysiswrapper{");
5654 headers.println("int flags;");
5655 headers.println("int numtags;");
5656 headers.println("int * tags;");
5657 headers.println("int numtaskfailures;");
5658 headers.println("struct taskfailure ** taskfailurearray;");
5659 headers.println("int numoptionaltaskdescriptors;");
5660 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5662 //STRUCT CLASSANALYSISWRAPPER
5663 headers.println("struct classanalysiswrapper{");
5664 headers.println("int type;");
5665 headers.println("int numotd;");
5666 headers.println("struct optionaltaskdescriptor ** otdarray;");
5667 headers.println("int numfsanalysiswrappers;");
5668 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
5670 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
5672 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
5673 while(taskit.hasNext()) {
5674 TaskDescriptor td=(TaskDescriptor)taskit.next();
5675 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
5680 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
5681 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
5682 int predicateindex = 0;
5683 //iterate through the classes concerned by the predicate
5684 Set c_vard = predicate.vardescriptors;
5685 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
5688 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
5689 VarDescriptor vard = (VarDescriptor)vard_it.next();
5690 TypeDescriptor typed = vard.getType();
5692 //generate for flags
5693 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
5694 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5696 if (fen_hashset!=null) {
5697 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
5698 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
5700 DNFFlag dflag=fen.getDNF();
5701 numberterms+=dflag.size();
5703 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
5705 for(int j=0; j<dflag.size(); j++) {
5707 output.println(",");
5708 Vector term=dflag.get(j);
5711 for(int k=0; k<term.size(); k++) {
5712 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
5713 FlagDescriptor fd=dfa.getFlag();
5714 boolean negated=dfa.getNegated();
5715 int flagid=1<<((Integer)flags.get(fd)).intValue();
5720 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
5725 output.println("};\n");
5728 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
5729 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5732 for(int j=0; j<tagel.numTags(); j++) {
5734 output.println(",");
5735 TempDescriptor tmp=tagel.getTemp(j);
5736 if (!slotnumber.containsKey(tmp)) {
5737 Integer slotint=new Integer(current_slot++);
5738 slotnumber.put(tmp,slotint);
5740 int slot=slotnumber.get(tmp).intValue();
5741 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
5743 numtags = tagel.numTags();
5745 output.println("};");
5747 //store the result into a predicatemember struct
5748 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5749 output.println("/*type*/"+typed.getClassDesc().getId()+",");
5750 output.println("/* number of dnf terms */"+numberterms+",");
5751 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5752 output.println("/* number of tag */"+numtags+",");
5753 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5754 output.println("};\n");
5759 //generate an array that stores the entire predicate
5760 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5761 for( int j = 0; j<predicateindex; j++) {
5762 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5763 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5765 output.println("};\n");
5766 return predicateindex;
5770 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
5771 generateOptionalHeader(headers);
5773 output.println("#include \"optionalstruct.h\"\n\n");
5774 output.println("#include \"stdlib.h\"\n");
5776 HashSet processedcd = new HashSet();
5778 Enumeration e = safeexecution.keys();
5779 while (e.hasMoreElements()) {
5782 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
5783 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
5785 //Generate the struct of optionals
5786 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5787 numotd = c_otd.size();
5788 if(maxotd<numotd) maxotd = numotd;
5789 if( !c_otd.isEmpty() ) {
5790 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5791 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5793 //generate the int arrays for the predicate
5794 Predicate predicate = otd.predicate;
5795 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
5796 TreeSet<Integer> fsset=new TreeSet<Integer>();
5797 //iterate through possible FSes corresponding to
5798 //the state when entering
5800 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
5801 FlagState fs = (FlagState)fses.next();
5803 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5804 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5805 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5808 fsset.add(new Integer(flagid));
5809 //tag information not needed because tag
5810 //changes are not tolerated.
5813 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5814 boolean needcomma=false;
5815 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
5818 output.println(it.next());
5821 output.println("};\n");
5824 //generate optionaltaskdescriptor that actually
5825 //includes exit fses, predicate and the task
5827 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5828 output.println("&task_"+otd.td.getSafeSymbol()+",");
5829 output.println("/*index*/"+otd.getIndex()+",");
5830 output.println("/*number of enter flags*/"+fsset.size()+",");
5831 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5832 output.println("/*number of members */"+predicateindex+",");
5833 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5834 output.println("};\n");
5838 // if there are no optionals, there is no need to build the rest of the struct
5840 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
5841 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5842 if( !c_otd.isEmpty() ) {
5843 boolean needcomma=false;
5844 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5845 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5847 output.println(",");
5849 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5852 output.println("};\n");
5854 //get all the possible flagstates reachable by an object
5855 Hashtable hashtbtemp = safeexecution.get(cdtemp);
5857 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
5858 fsts.addAll(hashtbtemp.keySet());
5859 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
5860 FlagState fs = (FlagState)fsit.next();
5863 //get the set of OptionalTaskDescriptors corresponding
5864 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
5865 //iterate through the OptionalTaskDescriptors and
5866 //store the pointers to the optionals struct (see on
5867 //top) into an array
5869 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
5870 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
5871 OptionalTaskDescriptor mm = mos.next();
5873 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
5875 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5878 output.println("};\n");
5880 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
5883 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5884 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5885 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5889 //process tag information
5892 boolean first = true;
5893 Enumeration tag_enum = fs.getTags();
5894 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5895 while(tag_enum.hasMoreElements()) {
5897 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
5901 output.println(", ");
5902 output.println("/*tagid*/"+state.getTagId(tagd));
5904 output.println("};");
5906 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
5907 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5908 TaskIndex ti=itti.next();
5912 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
5914 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
5915 boolean needcomma=false;
5916 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
5917 OptionalTaskDescriptor otd=otdit.next();
5921 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5923 output.println("};");
5925 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
5926 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
5927 output.print(ti.getIndex()+", ");
5928 output.print(otdset.size()+", ");
5929 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
5930 output.println("};");
5933 tiset=sa.getTaskIndex(fs);
5934 boolean needcomma=false;
5936 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5937 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5938 TaskIndex ti=itti.next();
5939 if (ti.isRuntime()) {
5946 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
5948 output.println("};\n");
5950 //Store the result in fsanalysiswrapper
5952 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
5953 output.println("/*flag*/"+flagid+",");
5954 output.println("/* number of tags*/"+tagcounter+",");
5955 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5956 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
5957 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5958 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
5959 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
5960 output.println("};\n");
5964 //Build the array of fsanalysiswrappers
5965 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
5966 boolean needcomma=false;
5967 for(int i = 0; i<fscounter; i++) {
5968 if (needcomma) output.print(",");
5969 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
5972 output.println("};");
5974 //Build the classanalysiswrapper referring to the previous array
5975 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
5976 output.println("/*type*/"+cdtemp.getId()+",");
5977 output.println("/*numotd*/"+numotd+",");
5978 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
5979 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
5980 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
5981 processedcd.add(cdtemp);
5984 //build an array containing every classes for which code has been build
5985 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
5986 for(int i=0; i<state.numClasses(); i++) {
5987 ClassDescriptor cn=cdarray[i];
5990 if ((cn != null) && (processedcd.contains(cn)))
5991 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
5993 output.print("NULL");
5995 output.println("};");
5997 output.println("#define MAXOTD "+maxotd);
5998 headers.println("#endif");
6001 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
6002 Relation r=new Relation();
6003 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
6004 OptionalTaskDescriptor otd=otdit.next();
6005 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
6009 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
6010 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
6011 Set s=r.get(it.next());
6012 for(Iterator it2=s.iterator(); it2.hasNext();) {
6013 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
6021 protected void outputTransCode(PrintWriter output) {
6024 private int calculateSizeOfSESEParamList(FlatSESEEnterNode fsen){
6026 Set<TempDescriptor> tdSet=new HashSet<TempDescriptor>();
6028 for (Iterator iterator = fsen.getInVarSet().iterator(); iterator.hasNext();) {
6029 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
6030 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
6031 tdSet.add(tempDescriptor);
6035 for (Iterator iterator = fsen.getOutVarSet().iterator(); iterator.hasNext();) {
6036 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
6037 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
6038 tdSet.add(tempDescriptor);
6042 return tdSet.size();
6045 private String calculateSizeOfSESEParamSize(FlatSESEEnterNode fsen){
6046 HashMap <String,Integer> map=new HashMap();
6047 HashSet <TempDescriptor> processed=new HashSet<TempDescriptor>();
6050 // space for all in and out set primitives
6051 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
6052 inSetAndOutSet.addAll( fsen.getInVarSet() );
6053 inSetAndOutSet.addAll( fsen.getOutVarSet() );
6055 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
6057 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
6058 while( itr.hasNext() ) {
6059 TempDescriptor temp = itr.next();
6060 TypeDescriptor type = temp.getType();
6061 if( !type.isPtr() ) {
6062 inSetAndOutSetPrims.add( temp );
6066 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
6067 while( itrPrims.hasNext() ) {
6068 TempDescriptor temp = itrPrims.next();
6069 TypeDescriptor type = temp.getType();
6070 if(type.isPrimitive()){
6071 Integer count=map.get(type.getSymbol());
6073 count=new Integer(1);
6074 map.put(type.getSymbol(), count);
6076 map.put(type.getSymbol(), new Integer(count.intValue()+1));
6081 Set<String> keySet=map.keySet();
6082 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
6083 String key = (String) iterator.next();
6084 rtr+="+sizeof("+key+")*"+map.get(key);