2 import IR.Tree.Modifiers;
3 import IR.Tree.FlagExpressionNode;
4 import IR.Tree.DNFFlag;
5 import IR.Tree.DNFFlagAtom;
6 import IR.Tree.TagExpressionList;
7 import IR.Tree.OffsetNode;
14 import Analysis.TaskStateAnalysis.FlagState;
15 import Analysis.TaskStateAnalysis.FlagComparator;
16 import Analysis.TaskStateAnalysis.OptionalTaskDescriptor;
17 import Analysis.TaskStateAnalysis.Predicate;
18 import Analysis.TaskStateAnalysis.SafetyAnalysis;
19 import Analysis.TaskStateAnalysis.TaskIndex;
20 import Analysis.Locality.LocalityAnalysis;
21 import Analysis.Locality.LocalityBinding;
22 import Analysis.Locality.DiscoverConflicts;
23 import Analysis.Locality.DCWrapper;
24 import Analysis.Locality.DelayComputation;
25 import Analysis.Locality.BranchAnalysis;
26 import Analysis.CallGraph.CallGraph;
27 import Analysis.Disjoint.AllocSite;
28 import Analysis.Disjoint.Effect;
29 import Analysis.Disjoint.ReachGraph;
30 import Analysis.Disjoint.Taint;
31 import Analysis.OoOJava.OoOJavaAnalysis;
32 import Analysis.Prefetch.*;
33 import Analysis.Loops.WriteBarrier;
34 import Analysis.Loops.GlobalFieldType;
35 import Analysis.Locality.TypeAnalysis;
36 import Analysis.MLP.ConflictGraph;
37 import Analysis.MLP.ConflictNode;
38 import Analysis.MLP.MLPAnalysis;
39 import Analysis.MLP.ParentChildConflictsMap;
40 import Analysis.MLP.SESELock;
41 import Analysis.MLP.SESEWaitingQueue;
42 import Analysis.MLP.VariableSourceToken;
43 import Analysis.MLP.VSTWrapper;
44 import Analysis.MLP.CodePlan;
45 import Analysis.MLP.SESEandAgePair;
46 import Analysis.MLP.WaitingElement;
48 public class BuildCode {
51 Hashtable paramstable;
56 String localsprefix="___locals___";
57 String localsprefixaddr="&"+localsprefix;
58 String localsprefixderef=localsprefix+".";
59 String fcrevert="___fcrevert___";
60 String paramsprefix="___params___";
61 String oidstr="___nextobject___";
62 String nextobjstr="___nextobject___";
63 String localcopystr="___localcopy___";
64 public static boolean GENERATEPRECISEGC=false;
65 public static String PREFIX="";
66 public static String arraytype="ArrayObject";
67 public static int flagcount = 0;
70 protected int maxtaskparams=0;
71 private int maxcount=0;
72 ClassDescriptor[] cdarray;
73 TypeDescriptor[] arraytable;
74 LocalityAnalysis locality;
75 Hashtable<LocalityBinding, TempDescriptor> reverttable;
76 Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>> backuptable;
81 String maxTaskRecSizeStr="__maxTaskRecSize___";
82 String mlperrstr = "if(status != 0) { "+
83 "sprintf(errmsg, \"MLP error at %s:%d\", __FILE__, __LINE__); "+
84 "perror(errmsg); exit(-1); }";
85 boolean nonSESEpass=true;
86 RuntimeConflictResolver rcr = null;
89 DiscoverConflicts recorddc;
94 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa) {
95 this(st, temptovar, typeutil, null, sa, pa, null, null);
98 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
99 this(st, temptovar, typeutil, null, sa, pa, mlpa, oooa);
102 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
103 this(st, temptovar, typeutil, locality, null, pa, mlpa, oooa);
106 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
112 callgraph=new CallGraph(state);
114 oidstr="___objlocation___";
115 this.temptovar=temptovar;
116 paramstable=new Hashtable();
117 tempstable=new Hashtable();
118 fieldorder=new Hashtable();
119 flagorder=new Hashtable();
120 this.typeutil=typeutil;
121 virtualcalls=new Virtual(state,locality);
122 if (locality!=null) {
123 this.locality=locality;
124 this.reverttable=new Hashtable<LocalityBinding, TempDescriptor>();
125 this.backuptable=new Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>>();
126 this.wb=new WriteBarrier(locality, st);
128 if (state.SINGLETM&&state.DCOPTS) {
129 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
130 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
131 this.dc=new DiscoverConflicts(locality, st, typeanalysis, gft);
134 if (state.DELAYCOMP) {
135 //TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
136 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
137 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
138 delaycomp=new DCWrapper(locality, st, typeanalysis, gft);
139 dc=delaycomp.getConflicts();
140 recorddc=new DiscoverConflicts(locality, st, typeanalysis, delaycomp.getCannotDelayMap(), true, true, null);
141 recorddc.doAnalysis();
145 /** The buildCode method outputs C code for all the methods. The Flat
146 * versions of the methods must already be generated and stored in
147 * the State object. */
148 PrintWriter outsandbox=null;
150 public void buildCode() {
151 /* Create output streams to write to */
152 PrintWriter outclassdefs=null;
153 PrintWriter outstructs=null;
154 PrintWriter outrepairstructs=null;
155 PrintWriter outmethodheader=null;
156 PrintWriter outmethod=null;
157 PrintWriter outvirtual=null;
158 PrintWriter outtask=null;
159 PrintWriter outtaskdefs=null;
160 PrintWriter outoptionalarrays=null;
161 PrintWriter optionalheaders=null;
162 PrintWriter outglobaldefs=null;
166 outsandbox=new PrintWriter(new FileOutputStream(PREFIX+"sandboxdefs.c"), true);
168 outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
169 outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
170 outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
172 // TODO add version for normal Java later
173 outglobaldefs=new PrintWriter(new FileOutputStream(PREFIX+"globaldefs.h"), true);
175 outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
176 outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
178 outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
179 outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
180 if (state.OPTIONAL) {
181 outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
182 optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
185 if (state.structfile!=null) {
186 outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
188 } catch (Exception e) {
193 /* Build the virtual dispatch tables */
194 buildVirtualTables(outvirtual);
196 /* Tag the methods that are invoked by static blocks */
197 tagMethodInvokedByStaticBlock();
199 /* Output includes */
200 outmethodheader.println("#ifndef METHODHEADERS_H");
201 outmethodheader.println("#define METHODHEADERS_H");
202 outmethodheader.println("#include \"structdefs.h\"");
204 outmethodheader.println("#include \"dstm.h\"");
206 outmethodheader.println("#include \"sandbox.h\"");
208 if (state.EVENTMONITOR) {
209 outmethodheader.println("#include \"monitor.h\"");
211 if (state.SINGLETM) {
212 outmethodheader.println("#include \"tm.h\"");
213 outmethodheader.println("#include \"delaycomp.h\"");
214 outmethodheader.println("#include \"inlinestm.h\"");
216 if (state.ABORTREADERS) {
217 outmethodheader.println("#include \"abortreaders.h\"");
218 outmethodheader.println("#include <setjmp.h>");
220 if (state.MLP || state.OOOJAVA) {
221 outmethodheader.println("#include <stdlib.h>");
222 outmethodheader.println("#include <stdio.h>");
223 outmethodheader.println("#include <string.h>");
224 outmethodheader.println("#include \"mlp_runtime.h\"");
225 outmethodheader.println("#include \"psemaphore.h\"");
226 outmethodheader.println("#include \"memPool.h\"");
229 outmethodheader.println("#include \"rcr_runtime.h\"");
231 // spit out a global to inform all worker threads with
232 // the maximum size is for any task record
233 outmethodheader.println("extern int "+maxTaskRecSizeStr+";");
236 /* Output Structures */
237 outputStructs(outstructs);
239 // Output the C class declarations
240 // These could mutually reference each other
243 // TODO add version for normal Java later
244 outglobaldefs.println("#ifndef __GLOBALDEF_H_");
245 outglobaldefs.println("#define __GLOBALDEF_H_");
246 outglobaldefs.println("");
247 outglobaldefs.println("struct global_defs_t {");
250 outclassdefs.println("#ifndef __CLASSDEF_H_");
251 outclassdefs.println("#define __CLASSDEF_H_");
252 outputClassDeclarations(outclassdefs, outglobaldefs);
254 // Output function prototypes and structures for parameters
255 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
256 while(it.hasNext()) {
257 ClassDescriptor cn=(ClassDescriptor)it.next();
258 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader, outglobaldefs);
260 outclassdefs.println("#endif");
261 outclassdefs.close();
263 // TODO add version for normal Java later
264 outglobaldefs.println("};");
265 outglobaldefs.println("");
266 outglobaldefs.println("extern struct global_defs_t * global_defs_p;");
267 outglobaldefs.println("#endif");
268 outglobaldefs.flush();
269 outglobaldefs.close();
273 /* Map flags to integers */
274 /* The runtime keeps track of flags using these integers */
275 it=state.getClassSymbolTable().getDescriptorsIterator();
276 while(it.hasNext()) {
277 ClassDescriptor cn=(ClassDescriptor)it.next();
281 generateTaskStructs(outstructs, outmethodheader);
283 /* Outputs generic task structures if this is a task
285 outputTaskTypes(outtask);
288 if( state.MLP || state.OOOJAVA) {
289 // have to initialize some SESE compiler data before
290 // analyzing normal methods, which must happen before
291 // generating SESE internal code
293 Iterator<FlatSESEEnterNode> seseit;
295 seseit=mlpa.getAllSESEs().iterator();
297 seseit=oooa.getAllSESEs().iterator();
300 //TODO signal the object that will report errors
303 rcr = new RuntimeConflictResolver(PREFIX, oooa);
304 rcr.setGlobalEffects(oooa.getDisjointAnalysis().getEffectsAnalysis().getAllEffects());
305 } catch (FileNotFoundException e) {
306 System.out.println("Runtime Conflict Resolver could not create output file.");
311 while(seseit.hasNext()){
312 FlatSESEEnterNode fsen = seseit.next();
313 initializeSESE( fsen );
317 /* Build the actual methods */
318 outputMethods(outmethod);
320 // Output function prototypes and structures for SESE's and code
321 if( state.MLP || state.OOOJAVA ) {
323 // spit out a global to inform all worker threads with
324 // the maximum size is for any task record
325 outmethod.println("int "+maxTaskRecSizeStr+" = 0;");
327 // used to differentiate, during code generation, whether we are
328 // passing over SESE body code, or non-SESE code
331 // first generate code for each sese's internals
332 Iterator<FlatSESEEnterNode> seseit;
334 seseit=mlpa.getAllSESEs().iterator();
336 seseit=oooa.getAllSESEs().iterator();
339 while(seseit.hasNext()) {
340 FlatSESEEnterNode fsen = seseit.next();
341 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
344 // then write the invokeSESE switch to decouple scheduler
345 // from having to do unique details of sese invocation
346 generateSESEinvocationMethod(outmethodheader, outmethod);
350 /* Output code for tasks */
351 outputTaskCode(outtaskdefs, outmethod);
353 /* Record maximum number of task parameters */
354 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
355 } else if (state.main!=null) {
356 /* Generate main method */
357 outputMainMethod(outmethod);
360 /* Generate information for task with optional parameters */
361 if (state.TASK&&state.OPTIONAL) {
362 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
363 outoptionalarrays.close();
366 /* Output structure definitions for repair tool */
367 if (state.structfile!=null) {
368 buildRepairStructs(outrepairstructs);
369 outrepairstructs.close();
373 outmethodheader.println("#endif");
374 outmethodheader.close();
376 outstructs.println("#endif");
380 System.out.println("Runtime Conflict Resolver Done.");
384 /* This method goes though the call graph and tag those methods that are
385 * invoked inside static blocks
387 protected void tagMethodInvokedByStaticBlock() {
389 Iterator it_sclasses = this.state.getSClassSymbolTable().getDescriptorsIterator();
390 MethodDescriptor current_md=null;
391 HashSet tovisit=new HashSet();
392 HashSet visited=new HashSet();
394 while(it_sclasses.hasNext()) {
395 ClassDescriptor cd = (ClassDescriptor)it_sclasses.next();
396 MethodDescriptor md = (MethodDescriptor)cd.getMethodTable().get("staticblocks");
402 while(!tovisit.isEmpty()) {
403 current_md=(MethodDescriptor)tovisit.iterator().next();
404 tovisit.remove(current_md);
405 visited.add(current_md);
406 Iterator it_callee = this.callgraph.getCalleeSet(current_md).iterator();
407 while(it_callee.hasNext()) {
408 Descriptor d = (Descriptor)it_callee.next();
409 if(d instanceof MethodDescriptor) {
410 if(!visited.contains(d)) {
411 ((MethodDescriptor)d).setIsInvokedByStatic(true);
417 } // TODO for normal Java version
420 /* This code generates code for each static block and static field
422 protected void outputStaticBlocks(PrintWriter outmethod) {
423 // execute all the static blocks and all the static field initializations
427 /* This code generates code to create a Class object for each class for
430 protected void outputClassObjects(PrintWriter outmethod) {
431 // for each class, initialize its Class object
433 SymbolTable ctbl = this.state.getClassSymbolTable();
434 Iterator it_classes = ctbl.getDescriptorsIterator();
435 while(it_classes.hasNext()) {
436 ClassDescriptor t_cd = (ClassDescriptor)it_classes.next();
437 outmethod.println(" {");
438 outmethod.println(" global_defs_p->"+t_cd.getSafeSymbol()+"classobj.type="+t_cd.getId()+";");
439 outmethod.println(" initlock((struct ___Object___ *)(&(global_defs_p->"+t_cd.getSafeSymbol()+"classobj)));");
440 outmethod.println(" }");
442 } // else TODO normal java version
445 /* This code just generates the main C method for java programs.
446 * The main C method packs up the arguments into a string array
447 * and passes it to the java main method. */
449 protected void outputMainMethod(PrintWriter outmethod) {
450 outmethod.println("int main(int argc, const char *argv[]) {");
451 outmethod.println(" int i;");
453 outputStaticBlocks(outmethod);
454 outputClassObjects(outmethod);
456 if (state.MLP || state.OOOJAVA) {
458 // do a calculation to determine which task record
459 // is the largest, store that as a global value for
460 // allocating records
461 Iterator<FlatSESEEnterNode> seseit;
463 seseit=mlpa.getAllSESEs().iterator();
465 seseit=oooa.getAllSESEs().iterator();
467 while(seseit.hasNext()){
468 FlatSESEEnterNode fsen = seseit.next();
469 outmethod.println("if( sizeof( "+fsen.getSESErecordName()+
470 " ) > "+maxTaskRecSizeStr+
471 " ) { "+maxTaskRecSizeStr+
472 " = sizeof( "+fsen.getSESErecordName()+
476 outmethod.println(" runningSESE = NULL;");
478 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
480 //initializes data structures needed for the RCR traverser
481 if(state.RCR && rcr != null) {
482 outmethod.println(" initializeStructsRCR();");
483 outmethod.println(" createAndFillMasterHashStructureArray();");
488 if (state.DSMRECOVERYSTATS) {
489 outmethod.println("#ifdef RECOVERYSTATS \n");
490 outmethod.println("handle();\n");
491 outmethod.println("#endif\n");
493 outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
494 outmethod.println("handle();\n");
495 outmethod.println("#endif\n");
499 if (state.THREAD||state.DSM||state.SINGLETM) {
500 outmethod.println("initializethreads();");
503 outmethod.println("if (dstmStartup(argv[1])) {");
504 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
505 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
507 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
510 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
511 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
513 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
517 outmethod.println(" for(i=2;i<argc;i++) {");
519 outmethod.println(" for(i=1;i<argc;i++) {");
520 outmethod.println(" int length=strlen(argv[i]);");
521 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
522 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
524 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
527 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
529 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
530 outmethod.println(" }");
532 MethodDescriptor md=typeutil.getMain();
533 ClassDescriptor cd=typeutil.getMainClass();
535 outmethod.println(" {");
536 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
537 if (state.DSM||state.SINGLETM) {
538 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
540 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
541 outmethod.println("1, NULL,"+"stringarray};");
542 if (state.DSM||state.SINGLETM)
543 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
545 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
547 if (state.DSM||state.SINGLETM)
548 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
550 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
552 outmethod.println(" }");
555 outmethod.println("}");
558 if (state.THREAD||state.DSM||state.SINGLETM) {
559 outmethod.println("pthread_mutex_lock(&gclistlock);");
560 outmethod.println("threadcount--;");
561 outmethod.println("pthread_cond_signal(&gccond);");
562 outmethod.println("pthread_mutex_unlock(&gclistlock);");
565 if (state.DSM||state.SINGLETM) {
566 //outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
567 outmethod.println("#if defined(TRANSSTATS) \n");
568 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
569 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
570 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
571 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
573 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
574 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
575 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
576 outmethod.println("printf(\"ndirtyCacheObj= %d\\n\", ndirtyCacheObj);");
577 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
578 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
579 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
580 outmethod.println("printf(\"totalObjSize= %d\\n\", totalObjSize);");
581 outmethod.println("printf(\"sendRemoteReq= %d\\n\", sendRemoteReq);");
582 outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
583 } else if (state.SINGLETM) {
584 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
585 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
586 outmethod.println("#ifdef STMSTATS\n");
587 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
588 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
589 outmethod.println("}\n");
590 outmethod.println("#endif\n");
591 outmethod.println("fflush(stdout);");
593 outmethod.println("#endif\n");
596 if (state.EVENTMONITOR) {
597 outmethod.println("dumpdata();");
600 if (state.THREAD||state.SINGLETM)
601 outmethod.println("pthread_exit(NULL);");
603 if (state.MLP || state.OOOJAVA ) {
604 outmethod.println(" workScheduleBegin();");
607 outmethod.println("}");
610 /* This method outputs code for each task. */
612 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
613 /* Compile task based program */
614 outtaskdefs.println("#include \"task.h\"");
615 outtaskdefs.println("#include \"methodheaders.h\"");
616 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
617 while(taskit.hasNext()) {
618 TaskDescriptor td=(TaskDescriptor)taskit.next();
619 FlatMethod fm=state.getMethodFlat(td);
620 generateFlatMethod(fm, null, outmethod);
621 generateTaskDescriptor(outtaskdefs, fm, td);
624 //Output task descriptors
625 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
626 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
628 while(taskit.hasNext()) {
629 TaskDescriptor td=(TaskDescriptor)taskit.next();
633 outtaskdefs.println(",");
634 outtaskdefs.print("&task_"+td.getSafeSymbol());
636 outtaskdefs.println("};");
638 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
641 /* This method outputs most of the methods.c file. This includes
642 * some standard includes and then an array with the sizes of
643 * objets and array that stores supertype and then the code for
644 * the Java methods.. */
646 protected void outputMethods(PrintWriter outmethod) {
647 outmethod.println("#include \"methodheaders.h\"");
648 outmethod.println("#include \"virtualtable.h\"");
649 outmethod.println("#include \"runtime.h\"");
651 // always include: compiler directives will leave out
652 // instrumentation when option is not set
653 outmethod.println("#include \"coreprof/coreprof.h\"");
656 outmethod.println("#include \"sandboxdefs.c\"");
659 outmethod.println("#include \"addPrefetchEnhance.h\"");
660 outmethod.println("#include \"localobjects.h\"");
662 if (state.FASTCHECK) {
663 outmethod.println("#include \"localobjects.h\"");
665 if(state.MULTICORE) {
667 outmethod.println("#include \"task.h\"");
669 outmethod.println("#include \"multicoreruntime.h\"");
670 outmethod.println("#include \"runtime_arch.h\"");
672 if (state.THREAD||state.DSM||state.SINGLETM) {
673 outmethod.println("#include <thread.h>");
676 outmethod.println("#include \"thread.h\"");
678 if (state.main!=null) {
679 outmethod.println("#include <string.h>");
681 if (state.CONSCHECK) {
682 outmethod.println("#include \"checkers.h\"");
684 if (state.MLP || state.OOOJAVA ) {
685 outmethod.println("#include <stdlib.h>");
686 outmethod.println("#include <stdio.h>");
687 outmethod.println("#include \"mlp_runtime.h\"");
688 outmethod.println("#include \"psemaphore.h\"");
691 outmethod.println("#include \"trqueue.h\"");
692 outmethod.println("#include \"RuntimeConflictResolver.h\"");
693 outmethod.println("#include \"rcr_runtime.h\"");
698 // TODO add version for normal Java later
699 outmethod.println("struct global_defs_t * global_defs_p;");
701 //Store the sizes of classes & array elements
702 generateSizeArray(outmethod);
704 //Store table of supertypes
705 generateSuperTypeTable(outmethod);
707 //Store the layout of classes
708 generateLayoutStructs(outmethod);
710 /* Generate code for methods */
711 if (state.DSM||state.SINGLETM) {
712 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
713 LocalityBinding lb=lbit.next();
714 MethodDescriptor md=lb.getMethod();
715 FlatMethod fm=state.getMethodFlat(md);
717 if (!md.getModifiers().isNative()) {
718 generateFlatMethod(fm, lb, outmethod);
719 //System.out.println("fm= " + fm + " md= " + md);
723 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
724 while(classit.hasNext()) {
725 ClassDescriptor cn=(ClassDescriptor)classit.next();
726 Iterator methodit=cn.getMethods();
727 while(methodit.hasNext()) {
728 /* Classify parameters */
729 MethodDescriptor md=(MethodDescriptor)methodit.next();
730 FlatMethod fm=state.getMethodFlat(md);
731 if (!md.getModifiers().isNative()) {
732 generateFlatMethod(fm, null, outmethod);
739 protected void outputStructs(PrintWriter outstructs) {
740 outstructs.println("#ifndef STRUCTDEFS_H");
741 outstructs.println("#define STRUCTDEFS_H");
742 outstructs.println("#include \"classdefs.h\"");
743 outstructs.println("#ifndef INTPTR");
744 outstructs.println("#ifdef BIT64");
745 outstructs.println("#define INTPTR long");
746 outstructs.println("#else");
747 outstructs.println("#define INTPTR int");
748 outstructs.println("#endif");
749 outstructs.println("#endif");
750 if( state.MLP || state.OOOJAVA ) {
751 outstructs.println("#include \"mlp_runtime.h\"");
752 outstructs.println("#include \"psemaphore.h\"");
755 outstructs.println("#include \"rcr_runtime.h\"");
759 /* Output #defines that the runtime uses to determine type
760 * numbers for various objects it needs */
761 outstructs.println("#define MAXCOUNT "+maxcount);
762 if (state.DSM||state.SINGLETM) {
763 LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
765 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
767 else if (state.SINGLETM) {
768 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
770 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
774 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
776 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
777 else if( state.SINGLETM)
778 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
779 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
782 outstructs.println("#define STRINGARRAYTYPE "+
783 (state.getArrayNumber(
784 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
786 outstructs.println("#define OBJECTARRAYTYPE "+
787 (state.getArrayNumber(
788 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
791 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
792 outstructs.println("#define CHARARRAYTYPE "+
793 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
795 outstructs.println("#define BYTEARRAYTYPE "+
796 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
798 outstructs.println("#define BYTEARRAYARRAYTYPE "+
799 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
801 outstructs.println("#define NUMCLASSES "+state.numClasses());
802 int totalClassSize = state.numClasses() + state.numArrays();
803 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
805 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
806 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
807 outstructs.println("#define TAGARRAYTYPE "+
808 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
812 protected void outputClassDeclarations(PrintWriter outclassdefs, PrintWriter outglobaldefs) {
813 if (state.THREAD||state.DSM||state.SINGLETM)
814 outclassdefs.println("#include <pthread.h>");
815 outclassdefs.println("#ifndef INTPTR");
816 outclassdefs.println("#ifdef BIT64");
817 outclassdefs.println("#define INTPTR long");
818 outclassdefs.println("#else");
819 outclassdefs.println("#define INTPTR int");
820 outclassdefs.println("#endif");
821 outclassdefs.println("#endif");
823 outclassdefs.println("#include \"optionalstruct.h\"");
824 outclassdefs.println("struct "+arraytype+";");
825 /* Start by declaring all structs */
826 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
827 while(it.hasNext()) {
828 ClassDescriptor cn=(ClassDescriptor)it.next();
829 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
832 // TODO add version for normal Java later
833 if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
834 // this class has static fields/blocks, need to add a global flag to
835 // indicate if its static fields have been initialized and/or if its
836 // static blocks have been executed
837 outglobaldefs.println(" int "+cn.getSafeSymbol()+"static_block_exe_flag;");
840 // for each class, create a global object
841 outglobaldefs.println(" struct Class "+cn.getSafeSymbol()+"classobj;");
844 outclassdefs.println("");
845 //Print out definition for array type
846 outclassdefs.println("struct "+arraytype+" {");
847 outclassdefs.println(" int type;");
848 if(state.MLP || state.OOOJAVA ){
849 outclassdefs.println(" int oid;");
850 outclassdefs.println(" int allocsite;");
852 if (state.EVENTMONITOR) {
853 outclassdefs.println(" int objuid;");
856 outclassdefs.println(" pthread_t tid;");
857 outclassdefs.println(" void * lockentry;");
858 outclassdefs.println(" int lockcount;");
861 outclassdefs.println(" int mutex;");
862 outclassdefs.println(" int objlock;");
863 if(state.MULTICOREGC) {
864 outclassdefs.println(" int marked;");
868 outclassdefs.println(" int flag;");
869 if(!state.MULTICORE) {
870 outclassdefs.println(" void * flagptr;");
872 outclassdefs.println(" int version;");
873 outclassdefs.println(" int * lock;"); // lock entry for this obj
874 outclassdefs.println(" int mutex;");
875 outclassdefs.println(" int lockcount;");
876 if(state.MULTICOREGC) {
877 outclassdefs.println(" int marked;");
881 outclassdefs.println(" int numfses;");
882 outclassdefs.println(" int * fses;");
885 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs, outglobaldefs);
887 if (state.STMARRAY) {
888 outclassdefs.println(" int lowindex;");
889 outclassdefs.println(" int highindex;");
892 outclassdefs.println(" int paddingforarray;");
893 if (state.DUALVIEW) {
894 outclassdefs.println(" int arrayversion;");
897 outclassdefs.println(" int ___length___;");
898 outclassdefs.println("};\n");
901 // TODO add version for normal Java later
902 outclassdefs.println("");
903 //Print out definition for Class type
904 outclassdefs.println("struct Class {");
905 outclassdefs.println(" int type;");
906 if(state.MLP || state.OOOJAVA ){
907 outclassdefs.println(" int oid;");
908 outclassdefs.println(" int allocsite;");
910 if (state.EVENTMONITOR) {
911 outclassdefs.println(" int objuid;");
914 outclassdefs.println(" pthread_t tid;");
915 outclassdefs.println(" void * lockentry;");
916 outclassdefs.println(" int lockcount;");
919 outclassdefs.println(" int mutex;");
920 outclassdefs.println(" int objlock;");
921 if(state.MULTICOREGC) {
922 outclassdefs.println(" int marked;");
926 outclassdefs.println(" int flag;");
927 if(!state.MULTICORE) {
928 outclassdefs.println(" void * flagptr;");
930 outclassdefs.println(" int version;");
931 outclassdefs.println(" int * lock;"); // lock entry for this obj
932 outclassdefs.println(" int mutex;");
933 outclassdefs.println(" int lockcount;");
934 if(state.MULTICOREGC) {
935 outclassdefs.println(" int marked;");
939 outclassdefs.println(" int numfses;");
940 outclassdefs.println(" int * fses;");
943 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs, outglobaldefs);
944 outclassdefs.println("};\n");
947 outclassdefs.println("");
948 outclassdefs.println("extern int classsize[];");
949 outclassdefs.println("extern int hasflags[];");
950 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
951 outclassdefs.println("extern int supertypes[];");
953 // TODO add version for normal Java later
954 outclassdefs.println("#include \"globaldefs.h\"");
956 outclassdefs.println("");
959 /** Prints out definitions for generic task structures */
961 private void outputTaskTypes(PrintWriter outtask) {
962 outtask.println("#ifndef _TASK_H");
963 outtask.println("#define _TASK_H");
964 outtask.println("struct parameterdescriptor {");
965 outtask.println("int type;");
966 outtask.println("int numberterms;");
967 outtask.println("int *intarray;");
968 outtask.println("void * queue;");
969 outtask.println("int numbertags;");
970 outtask.println("int *tagarray;");
971 outtask.println("};");
973 outtask.println("struct taskdescriptor {");
974 outtask.println("void * taskptr;");
975 outtask.println("int numParameters;");
976 outtask.println(" int numTotal;");
977 outtask.println("struct parameterdescriptor **descriptorarray;");
978 outtask.println("char * name;");
979 outtask.println("};");
980 outtask.println("extern struct taskdescriptor * taskarray[];");
981 outtask.println("extern numtasks;");
982 outtask.println("#endif");
986 private void buildRepairStructs(PrintWriter outrepairstructs) {
987 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
988 while(classit.hasNext()) {
989 ClassDescriptor cn=(ClassDescriptor)classit.next();
990 outrepairstructs.println("structure "+cn.getSymbol()+" {");
991 outrepairstructs.println(" int __type__;");
993 outrepairstructs.println(" int __flag__;");
994 if(!state.MULTICORE) {
995 outrepairstructs.println(" int __flagptr__;");
998 printRepairStruct(cn, outrepairstructs);
999 outrepairstructs.println("}\n");
1002 for(int i=0; i<state.numArrays(); i++) {
1003 TypeDescriptor tdarray=arraytable[i];
1004 TypeDescriptor tdelement=tdarray.dereference();
1005 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
1006 outrepairstructs.println(" int __type__;");
1007 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
1008 outrepairstructs.println(" int length;");
1010 // Need to add support to repair tool for this
1011 if (tdelement.isClass()||tdelement.isArray())
1012 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
1014 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
1016 outrepairstructs.println("}\n");
1020 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
1021 ClassDescriptor sp=cn.getSuperDesc();
1023 printRepairStruct(sp, output);
1025 Vector fields=(Vector)fieldorder.get(cn);
1027 for(int i=0; i<fields.size(); i++) {
1028 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1029 if (fd.getType().isArray()) {
1030 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
1031 } else if (fd.getType().isClass())
1032 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
1033 else if (fd.getType().isFloat())
1034 output.println(" int "+fd.getSymbol()+"; /* really float */");
1036 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
1040 /** This method outputs TaskDescriptor information */
1041 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
1042 for (int i=0; i<task.numParameters(); i++) {
1043 VarDescriptor param_var=task.getParameter(i);
1044 TypeDescriptor param_type=task.getParamType(i);
1045 FlagExpressionNode param_flag=task.getFlag(param_var);
1046 TagExpressionList param_tag=task.getTag(param_var);
1049 if (param_flag==null) {
1050 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
1051 output.println("0x0, 0x0 };");
1054 DNFFlag dflag=param_flag.getDNF();
1055 dnfterms=dflag.size();
1057 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
1058 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
1059 for(int j=0; j<dflag.size(); j++) {
1061 output.println(",");
1062 Vector term=dflag.get(j);
1065 for(int k=0; k<term.size(); k++) {
1066 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
1067 FlagDescriptor fd=dfa.getFlag();
1068 boolean negated=dfa.getNegated();
1069 int flagid=1<<((Integer)flags.get(fd)).intValue();
1074 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
1076 output.println("};");
1079 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
1080 //BUG...added next line to fix, test with any task program
1081 if (param_tag!=null)
1082 for(int j=0; j<param_tag.numTags(); j++) {
1084 output.println(",");
1085 /* for each tag we need */
1086 /* which slot it is */
1087 /* what type it is */
1088 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
1089 TempDescriptor tmp=param_tag.getTemp(j);
1090 int slot=fm.getTagInt(tmp);
1091 output.println(slot+", "+state.getTagId(tvd.getTag()));
1093 output.println("};");
1095 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
1096 output.println("/* type */"+param_type.getClassDesc().getId()+",");
1097 output.println("/* number of DNF terms */"+dnfterms+",");
1098 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
1099 output.println("0,");
1100 //BUG, added next line to fix and else statement...test
1101 //with any task program
1102 if (param_tag!=null)
1103 output.println("/* number of tags */"+param_tag.numTags()+",");
1105 output.println("/* number of tags */ 0,");
1106 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
1107 output.println("};");
1111 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
1112 for (int i=0; i<task.numParameters(); i++) {
1114 output.println(",");
1115 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
1117 output.println("};");
1119 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
1120 output.println("&"+task.getSafeSymbol()+",");
1121 output.println("/* number of parameters */" +task.numParameters() + ",");
1122 int numtotal=task.numParameters()+fm.numTags();
1123 output.println("/* number total parameters */" +numtotal + ",");
1124 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
1125 output.println("\""+task.getSymbol()+"\"");
1126 output.println("};");
1130 /** The buildVirtualTables method outputs the virtual dispatch
1131 * tables for methods. */
1133 protected void buildVirtualTables(PrintWriter outvirtual) {
1134 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
1135 while(classit.hasNext()) {
1136 ClassDescriptor cd=(ClassDescriptor)classit.next();
1137 if (virtualcalls.getMethodCount(cd)>maxcount)
1138 maxcount=virtualcalls.getMethodCount(cd);
1140 MethodDescriptor[][] virtualtable=null;
1141 LocalityBinding[][] lbvirtualtable=null;
1142 if (state.DSM||state.SINGLETM)
1143 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
1145 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
1147 /* Fill in virtual table */
1148 classit=state.getClassSymbolTable().getDescriptorsIterator();
1149 while(classit.hasNext()) {
1150 ClassDescriptor cd=(ClassDescriptor)classit.next();
1151 if (state.DSM||state.SINGLETM)
1152 fillinRow(cd, lbvirtualtable, cd.getId());
1154 fillinRow(cd, virtualtable, cd.getId());
1157 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
1158 Iterator arrayit=state.getArrayIterator();
1159 while(arrayit.hasNext()) {
1160 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1161 int id=state.getArrayNumber(td);
1162 if (state.DSM||state.SINGLETM)
1163 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
1165 fillinRow(objectcd, virtualtable, id+state.numClasses());
1168 outvirtual.print("void * virtualtable[]={");
1169 boolean needcomma=false;
1170 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
1171 for(int j=0; j<maxcount; j++) {
1173 outvirtual.print(", ");
1174 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
1175 LocalityBinding lb=lbvirtualtable[i][j];
1176 MethodDescriptor md=lb.getMethod();
1177 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
1178 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
1179 MethodDescriptor md=virtualtable[i][j];
1180 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
1182 outvirtual.print("0");
1186 outvirtual.println("");
1188 outvirtual.println("};");
1192 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
1193 /* Get inherited methods */
1194 if (cd.getSuperDesc()!=null)
1195 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
1197 // TODO add version for normal Java later
1198 Iterator it_sifs = cd.getSuperInterfaces();
1199 while(it_sifs.hasNext()) {
1200 ClassDescriptor superif = (ClassDescriptor)it_sifs.next();
1201 fillinRow(superif, virtualtable, rownum);
1204 /* Override them with our methods */
1205 for(Iterator it=cd.getMethods(); it.hasNext();) {
1206 MethodDescriptor md=(MethodDescriptor)it.next();
1207 if (md.isStatic()||md.getReturnType()==null)
1209 int methodnum=virtualcalls.getMethodNumber(md);
1210 virtualtable[rownum][methodnum]=md;
1214 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
1215 /* Get inherited methods */
1216 if (cd.getSuperDesc()!=null)
1217 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
1218 /* Override them with our methods */
1219 if (locality.getClassBindings(cd)!=null)
1220 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
1221 LocalityBinding lb=lbit.next();
1222 MethodDescriptor md=lb.getMethod();
1223 //Is the method static or a constructor
1224 if (md.isStatic()||md.getReturnType()==null)
1226 int methodnum=virtualcalls.getLocalityNumber(lb);
1227 virtualtable[rownum][methodnum]=lb;
1231 /** Generate array that contains the sizes of class objects. The
1232 * object allocation functions in the runtime use this
1235 private void generateSizeArray(PrintWriter outclassdefs) {
1236 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
1237 outclassdefs.print("#ifdef TRANSSTATS \n");
1238 outclassdefs.print("extern int numTransAbort;\n");
1239 outclassdefs.print("extern int numTransCommit;\n");
1240 outclassdefs.print("extern int nSoftAbort;\n");
1242 outclassdefs.print("extern int nchashSearch;\n");
1243 outclassdefs.print("extern int nmhashSearch;\n");
1244 outclassdefs.print("extern int nprehashSearch;\n");
1245 outclassdefs.print("extern int ndirtyCacheObj;\n");
1246 outclassdefs.print("extern int nRemoteSend;\n");
1247 outclassdefs.print("extern int sendRemoteReq;\n");
1248 outclassdefs.print("extern int getResponse;\n");
1249 outclassdefs.print("extern int bytesSent;\n");
1250 outclassdefs.print("extern int bytesRecv;\n");
1251 outclassdefs.print("extern int totalObjSize;\n");
1252 outclassdefs.print("extern void handle();\n");
1253 } else if (state.SINGLETM) {
1254 outclassdefs.println("extern int nSoftAbortAbort;");
1255 outclassdefs.println("extern int nSoftAbortCommit;");
1256 outclassdefs.println("#ifdef STMSTATS\n");
1257 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
1258 outclassdefs.println("#endif\n");
1260 outclassdefs.print("#endif\n");
1262 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
1263 if(this.state.MLP || state.OOOJAVA ){
1264 outclassdefs.print("extern __thread int oid;\n");
1265 outclassdefs.print("extern int numWorkSchedWorkers;\n");
1268 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1269 cdarray=new ClassDescriptor[state.numClasses()];
1271 while(it.hasNext()) {
1272 ClassDescriptor cd=(ClassDescriptor)it.next();
1273 cdarray[cd.getId()]=cd;
1276 arraytable=new TypeDescriptor[state.numArrays()];
1278 Iterator arrayit=state.getArrayIterator();
1279 while(arrayit.hasNext()) {
1280 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1281 int id=state.getArrayNumber(td);
1287 /* Print out types */
1288 outclassdefs.println("/* ");
1289 for(int i=0; i<state.numClasses(); i++) {
1290 ClassDescriptor cd=cdarray[i];
1292 outclassdefs.println("NULL " + i);
1294 outclassdefs.println(cd +" "+i);
1298 for(int i=0; i<state.numArrays(); i++) {
1299 TypeDescriptor arraytd=arraytable[i];
1300 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
1303 outclassdefs.println("*/");
1306 outclassdefs.print("int classsize[]={");
1308 boolean needcomma=false;
1309 for(int i=0; i<state.numClasses(); i++) {
1311 outclassdefs.print(", ");
1313 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1315 outclassdefs.print("0");
1321 for(int i=0; i<state.numArrays(); i++) {
1323 outclassdefs.print(", ");
1324 TypeDescriptor tdelement=arraytable[i].dereference();
1325 if (tdelement.isArray()||tdelement.isClass())
1326 outclassdefs.print("sizeof(void *)");
1328 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1332 outclassdefs.println("};");
1334 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1336 outclassdefs.print("int typearray[]={");
1337 for(int i=0; i<state.numClasses(); i++) {
1338 ClassDescriptor cd=cdarray[i];
1339 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1341 outclassdefs.print(", ");
1343 outclassdefs.print("-1");
1345 outclassdefs.print(supercd.getId());
1349 for(int i=0; i<state.numArrays(); i++) {
1350 TypeDescriptor arraytd=arraytable[i];
1351 ClassDescriptor arraycd=arraytd.getClassDesc();
1352 if (arraycd==null) {
1354 outclassdefs.print(", ");
1355 outclassdefs.print(objectclass.getId());
1359 ClassDescriptor cd=arraycd.getSuperDesc();
1362 TypeDescriptor supertd=new TypeDescriptor(cd);
1363 supertd.setArrayCount(arraytd.getArrayCount());
1364 type=state.getArrayNumber(supertd);
1366 type+=state.numClasses();
1369 cd=cd.getSuperDesc();
1372 outclassdefs.print(", ");
1373 outclassdefs.print(type);
1377 outclassdefs.println("};");
1382 outclassdefs.print("int typearray2[]={");
1383 for(int i=0; i<state.numArrays(); i++) {
1384 TypeDescriptor arraytd=arraytable[i];
1385 ClassDescriptor arraycd=arraytd.getClassDesc();
1386 if (arraycd==null) {
1388 outclassdefs.print(", ");
1389 outclassdefs.print("-1");
1393 ClassDescriptor cd=arraycd.getSuperDesc();
1394 int level=arraytd.getArrayCount()-1;
1396 for(; level>0; level--) {
1397 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1398 supertd.setArrayCount(level);
1399 type=state.getArrayNumber(supertd);
1401 type+=state.numClasses();
1406 outclassdefs.print(", ");
1407 outclassdefs.print(type);
1411 outclassdefs.println("};");
1414 /** Constructs params and temp objects for each method or task.
1415 * These objects tell the compiler which temps need to be
1418 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1419 MethodDescriptor md=fm.getMethod();
1420 TaskDescriptor task=fm.getTask();
1421 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1422 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1424 paramstable.put(lb, objectparams);
1425 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1426 } else if (md!=null)
1427 paramstable.put(md, objectparams);
1429 paramstable.put(task, objectparams);
1431 for(int i=0; i<fm.numParameters(); i++) {
1432 TempDescriptor temp=fm.getParameter(i);
1433 TypeDescriptor type=temp.getType();
1434 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1435 objectparams.addPtr(temp);
1437 objectparams.addPrim(temp);
1438 if(lb!=null&&saveset.contains(temp)) {
1439 backuptable.get(lb).put(temp, temp.createNew());
1443 for(int i=0; i<fm.numTags(); i++) {
1444 TempDescriptor temp=fm.getTag(i);
1445 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1446 objectparams.addPtr(temp);
1448 objectparams.addPrim(temp);
1451 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1453 tempstable.put(lb, objecttemps);
1455 tempstable.put(md, objecttemps);
1457 tempstable.put(task, objecttemps);
1459 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1460 FlatNode fn=(FlatNode)nodeit.next();
1461 TempDescriptor[] writes=fn.writesTemps();
1462 for(int i=0; i<writes.length; i++) {
1463 TempDescriptor temp=writes[i];
1464 TypeDescriptor type=temp.getType();
1465 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1466 objecttemps.addPtr(temp);
1468 objecttemps.addPrim(temp);
1469 if(lb!=null&&saveset.contains(temp)&&
1470 !backuptable.get(lb).containsKey(temp))
1471 backuptable.get(lb).put(temp, temp.createNew());
1475 /* Create backup temps */
1477 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1478 TempDescriptor tmp=tmpit.next();
1479 TypeDescriptor type=tmp.getType();
1480 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1481 objecttemps.addPtr(tmp);
1483 objecttemps.addPrim(tmp);
1485 /* Create temp to hold revert table */
1486 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1487 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1488 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1489 objecttemps.addPtr(reverttmp);
1491 objecttemps.addPrim(reverttmp);
1492 reverttable.put(lb, reverttmp);
1497 /** This method outputs the following information about classes
1499 * (1) For classes, what are the locations of pointers.
1500 * (2) For arrays, does the array contain pointers or primitives.
1501 * (3) For classes, does the class contain flags.
1504 private void generateLayoutStructs(PrintWriter output) {
1505 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1506 while(it.hasNext()) {
1507 ClassDescriptor cn=(ClassDescriptor)it.next();
1508 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1509 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1511 while(allit.hasNext()) {
1512 FieldDescriptor fd=(FieldDescriptor)allit.next();
1513 TypeDescriptor type=fd.getType();
1514 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1519 output.print(count);
1520 allit=cn.getFieldTable().getAllDescriptorsIterator();
1521 while(allit.hasNext()) {
1522 FieldDescriptor fd=(FieldDescriptor)allit.next();
1523 TypeDescriptor type=fd.getType();
1524 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1527 output.println(",");
1528 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1531 output.println("};");
1533 output.println("unsigned INTPTR * pointerarray[]={");
1534 boolean needcomma=false;
1535 for(int i=0; i<state.numClasses(); i++) {
1536 ClassDescriptor cn=cdarray[i];
1538 output.println(",");
1541 output.print(cn.getSafeSymbol()+"_pointers");
1543 output.print("NULL");
1547 for(int i=0; i<state.numArrays(); i++) {
1549 output.println(", ");
1550 TypeDescriptor tdelement=arraytable[i].dereference();
1551 if (tdelement.isArray()||tdelement.isClass())
1552 output.print("((unsigned INTPTR *)1)");
1558 output.println("};");
1560 output.println("int hasflags[]={");
1561 for(int i=0; i<state.numClasses(); i++) {
1562 ClassDescriptor cn=cdarray[i];
1564 output.println(", ");
1566 if ((cn != null) && (cn.hasFlags()))
1571 output.println("};");
1574 /** Print out table to give us supertypes */
1575 private void generateSuperTypeTable(PrintWriter output) {
1576 output.println("int supertypes[]={");
1577 boolean needcomma=false;
1578 for(int i=0; i<state.numClasses(); i++) {
1579 ClassDescriptor cn=cdarray[i];
1581 output.println(",");
1583 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1584 ClassDescriptor cdsuper=cn.getSuperDesc();
1585 output.print(cdsuper.getId());
1589 output.println("};");
1592 /** Force consistent field ordering between inherited classes. */
1594 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout, PrintWriter globaldefout) {
1596 ClassDescriptor sp=cn.getSuperDesc();
1598 printClassStruct(sp, classdefout, globaldefout);
1600 if (!fieldorder.containsKey(cn)) {
1601 Vector fields=new Vector();
1602 fieldorder.put(cn,fields);
1603 Vector fieldvec=cn.getFieldVec();
1604 for(int i=0;i<fieldvec.size();i++) {
1605 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1606 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1610 Vector fields=(Vector)fieldorder.get(cn);
1612 for(int i=0; i<fields.size(); i++) {
1613 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1614 if (fd.getType().isClass()||fd.getType().isArray())
1615 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1616 else if ((state.MGC) && (fd.isStatic())) {
1617 // TODO add version for normal Java later
1619 globaldefout.println(" "+fd.getType().getSafeSymbol()+ " "+cn.getSafeSymbol()+fd.getSafeSymbol()+";");
1620 classdefout.println(" "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1622 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1627 /* Map flags to integers consistently between inherited
1630 protected void mapFlags(ClassDescriptor cn) {
1631 ClassDescriptor sp=cn.getSuperDesc();
1635 if (!flagorder.containsKey(cn)) {
1636 Hashtable flags=new Hashtable();
1637 flagorder.put(cn,flags);
1639 Hashtable superflags=(Hashtable)flagorder.get(sp);
1640 Iterator superflagit=superflags.keySet().iterator();
1641 while(superflagit.hasNext()) {
1642 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1643 Integer number=(Integer)superflags.get(fd);
1644 flags.put(fd, number);
1645 if ((number.intValue()+1)>max)
1646 max=number.intValue()+1;
1650 Iterator flagit=cn.getFlags();
1651 while(flagit.hasNext()) {
1652 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1653 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1654 flags.put(fd, new Integer(max++));
1660 /** This function outputs (1) structures that parameters are
1661 * passed in (when PRECISE GC is enabled) and (2) function
1662 * prototypes for the methods */
1664 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout, PrintWriter globaldefout) {
1665 /* Output class structure */
1666 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1667 classdefout.println(" int type;");
1668 if(state.MLP || state.OOOJAVA){
1669 classdefout.println(" int oid;");
1670 classdefout.println(" int allocsite;");
1672 if (state.EVENTMONITOR) {
1673 classdefout.println(" int objuid;");
1676 classdefout.println(" pthread_t tid;");
1677 classdefout.println(" void * lockentry;");
1678 classdefout.println(" int lockcount;");
1681 classdefout.println(" int mutex;");
1682 classdefout.println(" int objlock;");
1683 if(state.MULTICOREGC) {
1684 classdefout.println(" int marked;");
1688 classdefout.println(" int flag;");
1689 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1690 classdefout.println(" void * flagptr;");
1691 } else if (state.MULTICORE) {
1692 classdefout.println(" int version;");
1693 classdefout.println(" int * lock;"); // lock entry for this obj
1694 classdefout.println(" int mutex;");
1695 classdefout.println(" int lockcount;");
1696 if(state.MULTICOREGC) {
1697 classdefout.println(" int marked;");
1700 if (state.OPTIONAL) {
1701 classdefout.println(" int numfses;");
1702 classdefout.println(" int * fses;");
1705 printClassStruct(cn, classdefout, globaldefout);
1706 classdefout.println("};\n");
1708 if (state.DSM||state.SINGLETM) {
1709 /* Cycle through LocalityBindings */
1710 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1711 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1713 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1714 LocalityBinding lb=lbit.next();
1715 MethodDescriptor md=lb.getMethod();
1716 if (md.getModifiers().isNative()) {
1717 //make sure we only print a native method once
1718 if (nativemethods.contains(md)) {
1719 FlatMethod fm=state.getMethodFlat(md);
1720 generateTempStructs(fm, lb);
1723 nativemethods.add(md);
1725 generateMethod(cn, md, lb, headersout, output);
1728 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1729 MethodDescriptor md=(MethodDescriptor)methodit.next();
1730 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1731 //Need to build param structure for library code
1732 FlatMethod fm=state.getMethodFlat(md);
1733 generateTempStructs(fm, null);
1734 generateMethodParam(cn, md, null, output);
1739 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1740 MethodDescriptor md=(MethodDescriptor)methodit.next();
1741 generateMethod(cn, md, null, headersout, output);
1745 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1746 /* Output parameter structure */
1747 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1748 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1749 if ((state.DSM||state.SINGLETM)&&lb!=null)
1750 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1752 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1753 output.println(" int size;");
1754 output.println(" void * next;");
1755 for(int i=0; i<objectparams.numPointers(); i++) {
1756 TempDescriptor temp=objectparams.getPointer(i);
1757 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1759 output.println("};\n");
1763 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1764 FlatMethod fm=state.getMethodFlat(md);
1765 generateTempStructs(fm, lb);
1767 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1768 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1770 generateMethodParam(cn, md, lb, output);
1772 /* Output temp structure */
1773 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1774 if (state.DSM||state.SINGLETM)
1775 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1777 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1778 output.println(" int size;");
1779 output.println(" void * next;");
1780 for(int i=0; i<objecttemps.numPointers(); i++) {
1781 TempDescriptor temp=objecttemps.getPointer(i);
1782 if (temp.getType().isNull())
1783 output.println(" void * "+temp.getSafeSymbol()+";");
1785 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1787 output.println("};\n");
1790 /********* Output method declaration ***********/
1791 if (state.DSM||state.SINGLETM) {
1792 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1794 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1796 /* First the return type */
1797 if (md.getReturnType()!=null) {
1798 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1799 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1801 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1803 //catch the constructor case
1804 headersout.print("void ");
1806 /* Next the method name */
1807 if (state.DSM||state.SINGLETM) {
1808 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1810 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1812 boolean printcomma=false;
1813 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1814 if (state.DSM||state.SINGLETM) {
1815 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1817 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1821 /* Output parameter list*/
1822 for(int i=0; i<objectparams.numPrimitives(); i++) {
1823 TempDescriptor temp=objectparams.getPrimitive(i);
1825 headersout.print(", ");
1827 if (temp.getType().isClass()||temp.getType().isArray())
1828 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1830 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1832 headersout.println(");\n");
1836 /** This function outputs (1) structures that parameters are
1837 * passed in (when PRECISE GC is enabled) and (2) function
1838 * prototypes for the tasks */
1840 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1841 /* Cycle through tasks */
1842 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1844 while(taskit.hasNext()) {
1845 /* Classify parameters */
1846 TaskDescriptor task=(TaskDescriptor)taskit.next();
1847 FlatMethod fm=state.getMethodFlat(task);
1848 generateTempStructs(fm, null);
1850 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1851 TempObject objecttemps=(TempObject) tempstable.get(task);
1853 /* Output parameter structure */
1854 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1855 output.println("struct "+task.getSafeSymbol()+"_params {");
1856 output.println(" int size;");
1857 output.println(" void * next;");
1858 for(int i=0; i<objectparams.numPointers(); i++) {
1859 TempDescriptor temp=objectparams.getPointer(i);
1860 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1863 output.println("};\n");
1864 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1865 maxtaskparams=objectparams.numPointers()+fm.numTags();
1869 /* Output temp structure */
1870 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1871 output.println("struct "+task.getSafeSymbol()+"_locals {");
1872 output.println(" int size;");
1873 output.println(" void * next;");
1874 for(int i=0; i<objecttemps.numPointers(); i++) {
1875 TempDescriptor temp=objecttemps.getPointer(i);
1876 if (temp.getType().isNull())
1877 output.println(" void * "+temp.getSafeSymbol()+";");
1878 else if(temp.getType().isTag())
1879 output.println(" struct "+
1880 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1882 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1884 output.println("};\n");
1887 /* Output task declaration */
1888 headersout.print("void " + task.getSafeSymbol()+"(");
1890 boolean printcomma=false;
1891 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1892 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1894 headersout.print("void * parameterarray[]");
1895 headersout.println(");\n");
1899 /***** Generate code for FlatMethod fm. *****/
1901 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1902 static int atomicmethodcount=0;
1905 BranchAnalysis branchanalysis;
1906 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1907 if (State.PRINTFLAT)
1908 System.out.println(fm.printMethod());
1909 MethodDescriptor md=fm.getMethod();
1910 TaskDescriptor task=fm.getTask();
1911 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1912 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1914 HashSet<AtomicRecord> arset=null;
1915 branchanalysis=null;
1917 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1919 if (atomicmethodmap==null)
1920 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1922 //fix these so we get right strings for local variables
1923 localsprefixaddr=localsprefix;
1924 localsprefixderef=localsprefix+"->";
1925 arset=new HashSet<AtomicRecord>();
1927 //build branchanalysis
1928 branchanalysis=new BranchAnalysis(locality, lb, delaycomp.getNotReady(lb), delaycomp.livecode(lb), state);
1930 //Generate commit methods here
1931 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1932 FlatNode fn=fnit.next();
1933 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1934 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
1935 delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
1936 //We have an atomic enter
1937 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1938 Set<FlatNode> exitset=faen.getExits();
1940 String methodname=md.getSymbol()+(atomicmethodcount++);
1941 AtomicRecord ar=new AtomicRecord();
1945 atomicmethodmap.put(faen, ar);
1947 //build data structure declaration
1948 output.println("struct atomicprimitives_"+methodname+" {");
1950 Set<FlatNode> recordset=delaycomp.livecode(lb);
1951 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1952 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1953 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1955 ar.reallivein=new HashSet(liveinto);
1957 ar.liveoutvirtualread=liveoutvirtualread;
1960 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1961 TempDescriptor tmp=it.next();
1962 //remove the pointers
1963 if (tmp.getType().isPtr()) {
1966 //let's print it here
1967 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1970 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1971 TempDescriptor tmp=it.next();
1972 //remove the pointers
1973 if (tmp.getType().isPtr()) {
1975 } else if (!liveinto.contains(tmp)) {
1976 //let's print it here
1977 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1980 output.println("};");
1982 //print out method name
1983 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) {");
1984 //build code for commit method
1986 //first define local primitives
1987 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1988 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1989 TempDescriptor tmp=tmpit.next();
1990 if (!tmp.getType().isPtr()) {
1991 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1992 //read from live into set
1993 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1996 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
2000 //turn off write barrier generation
2002 state.SINGLETM=false;
2003 generateCode(faen, fm, lb, exitset, output, false);
2004 state.SINGLETM=true;
2005 //turn on write barrier generation
2007 output.println("}\n\n");
2011 //redefine these back to normal
2013 localsprefixaddr="&"+localsprefix;
2014 localsprefixderef=localsprefix+".";
2016 generateHeader(fm, lb, md!=null ? md : task,output);
2017 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2019 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2020 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
2021 AtomicRecord ar=arit.next();
2022 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
2026 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2027 if (md!=null&&(state.DSM||state.SINGLETM))
2028 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2029 else if (md!=null&&!(state.DSM||state.SINGLETM))
2030 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2032 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
2033 output.print(objecttemp.numPointers()+",");
2034 output.print(paramsprefix);
2035 for(int j=0; j<objecttemp.numPointers(); j++)
2036 output.print(", NULL");
2037 output.println("};");
2040 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2041 TempDescriptor td=objecttemp.getPrimitive(i);
2042 TypeDescriptor type=td.getType();
2044 output.println(" void * "+td.getSafeSymbol()+";");
2045 else if (type.isClass()||type.isArray())
2046 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2048 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2052 if( state.MLP || state.OOOJAVA ) {
2053 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
2054 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
2055 if( (state.MLP && callerSESEplaceholder != mlpa.getMainSESE()) ||
2056 (state.OOOJAVA && callerSESEplaceholder != oooa.getMainSESE())
2058 // declare variables for naming static SESE's
2059 output.println(" /* static SESE names */");
2060 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
2061 while( pItr.hasNext() ) {
2062 SESEandAgePair pair = pItr.next();
2063 output.println(" void* "+pair+" = NULL;");
2066 // declare variables for tracking dynamic sources
2067 output.println(" /* dynamic variable sources */");
2068 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
2069 while( dynSrcItr.hasNext() ) {
2070 TempDescriptor dynSrcVar = dynSrcItr.next();
2071 output.println(" SESEcommon* "+dynSrcVar+"_srcSESE = NULL;");
2072 output.println(" INTPTR "+dynSrcVar+"_srcOffset = 0x1;");
2077 // set up related allocation sites's waiting queues
2080 ConflictGraph graph = null;
2081 graph = mlpa.getConflictGraphResults().get(fm);
2082 if (graph != null && graph.hasConflictEdge()) {
2083 output.println(" /* set up waiting queues */");
2084 output.println(" int numMemoryQueue=0;");
2085 output.println(" int memoryQueueItemID=0;");
2086 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
2088 System.out.println("#lockSet="+lockSet.hashCode());
2089 System.out.println("lockset="+lockSet);
2090 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
2091 SESELock seseLock = (SESELock) iterator.next();
2092 System.out.println("id="+seseLock.getID());
2093 System.out.println("#="+seseLock);
2095 System.out.println("size="+lockSet.size());
2096 if (lockSet.size() > 0) {
2097 output.println(" numMemoryQueue=" + lockSet.size() + ";");
2098 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
2099 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2104 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
2105 if(callerSESEplaceholder!= oooa.getMainSESE()){
2106 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(callerSESEplaceholder);
2107 if (graph != null && graph.hasConflictEdge()) {
2108 output.println(" // set up waiting queues ");
2109 output.println(" int numMemoryQueue=0;");
2110 output.println(" int memoryQueueItemID=0;");
2111 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
2112 System.out.println("#lockSet="+lockSet.hashCode());
2113 System.out.println("lockset="+lockSet);
2114 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
2115 Analysis.OoOJava.SESELock seseLock = (Analysis.OoOJava.SESELock) iterator.next();
2116 System.out.println("id="+seseLock.getID());
2117 System.out.println("#="+seseLock);
2119 System.out.println("size="+lockSet.size());
2120 if (lockSet.size() > 0) {
2121 output.println(" numMemoryQueue=" + lockSet.size() + ";");
2122 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
2123 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2133 /* Check to see if we need to do a GC if this is a
2134 * multi-threaded program...*/
2136 if (((state.MLP||state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
2137 || this.state.MULTICOREGC) {
2138 //Don't bother if we aren't in recursive methods...The loops case will catch it
2139 if (callgraph.getAllMethods(md).contains(md)) {
2140 if (state.DSM&&lb.isAtomic())
2141 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
2142 else if (this.state.MULTICOREGC) {
2143 output.println("if(gcflag) gc("+localsprefixaddr+");");
2145 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2151 // TODO add version for normal Java later
2152 if(fm.getMethod().isStaticBlock()) {
2153 // a static block, check if it has been executed
2154 output.println(" if(global_defs_p->" + cn.getSafeSymbol()+"static_block_exe_flag != 0) {");
2155 output.println(" return;");
2156 output.println(" }");
2159 if((!fm.getMethod().isStaticBlock()) && (fm.getMethod().getReturnType() == null) && (cn != null)){
2160 // is a constructor, check and output initialization of the static fields
2161 // here does not initialize the static fields of the class, instead it
2162 // redirect the corresponding fields in the object to the global_defs_p
2163 Vector fields=(Vector)fieldorder.get(cn);
2165 for(int i=0; i<fields.size(); i++) {
2166 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
2169 output.println(generateTemp(fm,fm.getParameter(0),lb)+"->"+fd.getSafeSymbol()+"=&(global_defs_p->"+cn.getSafeSymbol()+fd.getSafeSymbol()+");");
2175 generateCode(fm.getNext(0), fm, lb, null, output, true);
2177 output.println("}\n\n");
2181 protected void initializeSESE( FlatSESEEnterNode fsen ) {
2183 FlatMethod fm = fsen.getfmEnclosing();
2184 MethodDescriptor md = fm.getMethod();
2185 ClassDescriptor cn = md.getClassDesc();
2188 // Creates bogus method descriptor to index into tables
2189 Modifiers modBogus = new Modifiers();
2190 MethodDescriptor mdBogus =
2191 new MethodDescriptor( modBogus,
2192 new TypeDescriptor( TypeDescriptor.VOID ),
2193 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
2196 mdBogus.setClassDesc( fsen.getcdEnclosing() );
2197 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
2198 fsen.setfmBogus( fmBogus );
2199 fsen.setmdBogus( mdBogus );
2201 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
2202 inSetAndOutSet.addAll( fsen.getInVarSet() );
2203 inSetAndOutSet.addAll( fsen.getOutVarSet() );
2205 // Build paramsobj for bogus method descriptor
2206 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
2207 paramstable.put( mdBogus, objectparams );
2209 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
2210 while( itr.hasNext() ) {
2211 TempDescriptor temp = itr.next();
2212 TypeDescriptor type = temp.getType();
2213 if( type.isPtr() ) {
2214 objectparams.addPtr( temp );
2216 objectparams.addPrim( temp );
2220 // Build normal temp object for bogus method descriptor
2221 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
2222 tempstable.put( mdBogus, objecttemps );
2224 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
2225 FlatNode fn = (FlatNode)nodeit.next();
2226 TempDescriptor[] writes = fn.writesTemps();
2228 for( int i = 0; i < writes.length; i++ ) {
2229 TempDescriptor temp = writes[i];
2230 TypeDescriptor type = temp.getType();
2232 if( type.isPtr() ) {
2233 objecttemps.addPtr( temp );
2235 objecttemps.addPrim( temp );
2241 // used when generating the specific SESE record struct
2242 // to remember the FIRST field name of sese records
2243 // that the current SESE depends on--we need to know the
2244 // offset to the first one for garbage collection
2245 protected void addingDepRecField( FlatSESEEnterNode fsen,
2247 if( fsen.getFirstDepRecField() == null ) {
2248 fsen.setFirstDepRecField( field );
2250 fsen.incNumDepRecs();
2253 protected void generateMethodSESE(FlatSESEEnterNode fsen,
2255 PrintWriter outputStructs,
2256 PrintWriter outputMethHead,
2257 PrintWriter outputMethods
2260 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
2261 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
2263 // generate locals structure
2264 outputStructs.println("struct "+
2265 fsen.getcdEnclosing().getSafeSymbol()+
2266 fsen.getmdBogus().getSafeSymbol()+"_"+
2267 fsen.getmdBogus().getSafeMethodDescriptor()+
2269 outputStructs.println(" int size;");
2270 outputStructs.println(" void * next;");
2271 for(int i=0; i<objecttemps.numPointers(); i++) {
2272 TempDescriptor temp=objecttemps.getPointer(i);
2274 if (temp.getType().isNull())
2275 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
2277 outputStructs.println(" struct "+
2278 temp.getType().getSafeSymbol()+" * "+
2279 temp.getSafeSymbol()+";");
2281 outputStructs.println("};\n");
2284 // divide in-set and out-set into objects and primitives to prep
2285 // for the record generation just below
2286 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
2287 inSetAndOutSet.addAll( fsen.getInVarSet() );
2288 inSetAndOutSet.addAll( fsen.getOutVarSet() );
2290 Set<TempDescriptor> inSetAndOutSetObjs = new HashSet<TempDescriptor>();
2291 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
2293 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
2294 while( itr.hasNext() ) {
2295 TempDescriptor temp = itr.next();
2296 TypeDescriptor type = temp.getType();
2297 if( type.isPtr() ) {
2298 inSetAndOutSetObjs.add( temp );
2300 inSetAndOutSetPrims.add( temp );
2305 // generate the SESE record structure
2306 outputStructs.println(fsen.getSESErecordName()+" {");
2308 // data common to any SESE, and it must be placed first so
2309 // a module that doesn't know what kind of SESE record this
2310 // is can cast the pointer to a common struct
2311 outputStructs.println(" SESEcommon common;");
2313 // then garbage list stuff
2314 outputStructs.println(" /* next is in-set and out-set objects that look like a garbage list */");
2315 outputStructs.println(" int size;");
2316 outputStructs.println(" void * next;");
2318 // I think that the set of TempDescriptors inSetAndOutSetObjs
2319 // calculated above should match the pointer object params
2320 // used in the following code, but let's just leave the working
2321 // implementation unless there is actually a problem...
2323 Vector<TempDescriptor> inset=fsen.getInVarsForDynamicCoarseConflictResolution();
2324 for(int i=0; i<inset.size();i++) {
2325 TempDescriptor temp=inset.get(i);
2326 if (temp.getType().isNull())
2327 outputStructs.println(" void * "+temp.getSafeSymbol()+
2328 "; /* in-or-out-set obj in gl */");
2330 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+
2331 temp.getSafeSymbol()+"; /* in-or-out-set obj in gl */");
2334 for(int i=0; i<objectparams.numPointers(); i++) {
2335 TempDescriptor temp=objectparams.getPointer(i);
2336 if (!inset.contains(temp)) {
2337 if (temp.getType().isNull())
2338 outputStructs.println(" void * "+temp.getSafeSymbol()+
2339 "; /* in-or-out-set obj in gl */");
2341 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+
2342 temp.getSafeSymbol()+"; /* in-or-out-set obj in gl */");
2346 outputStructs.println(" /* next is primitives for in-set and out-set and dynamic tracking */");
2348 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
2349 while( itrPrims.hasNext() ) {
2350 TempDescriptor temp = itrPrims.next();
2351 TypeDescriptor type = temp.getType();
2352 if(type.isPrimitive()){
2353 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+"; /* in-set or out-set primitive */");
2357 // note that the sese record pointer will be added below, just primitive part of tracking here
2358 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
2359 while( itrDynInVars.hasNext() ) {
2360 TempDescriptor dynInVar = itrDynInVars.next();
2361 outputStructs.println(" INTPTR "+dynInVar+"_srcOffset; /* dynamic tracking primitive */");
2365 outputStructs.println(" /* everything after this should be pointers to an SESE record */" );
2367 // other half of info for dynamic tracking, the SESE record pointer
2368 itrDynInVars = fsen.getDynamicInVarSet().iterator();
2369 while( itrDynInVars.hasNext() ) {
2370 TempDescriptor dynInVar = itrDynInVars.next();
2371 String depRecField = dynInVar+"_srcSESE";
2372 outputStructs.println(" SESEcommon* "+depRecField+";");
2373 addingDepRecField( fsen, depRecField );
2376 // statically known sese sources are record pointers, too
2377 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
2378 while( itrStaticInVarSrcs.hasNext() ) {
2379 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
2380 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
2381 addingDepRecField(fsen, srcPair.toString());
2385 if (inset.size()!=0)
2386 outputStructs.println("struct rcrRecord rcrRecords["+inset.size()+"];");
2389 if( fsen.getFirstDepRecField() != null ) {
2390 outputStructs.println(" /* compiler believes first dependent SESE record field above is: "+
2391 fsen.getFirstDepRecField()+" */" );
2393 outputStructs.println("};\n");
2396 // write method declaration to header file
2397 outputMethHead.print("void ");
2398 outputMethHead.print(fsen.getSESEmethodName()+"(");
2399 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
2400 outputMethHead.println(");\n");
2403 generateFlatMethodSESE( fsen.getfmBogus(),
2404 fsen.getcdEnclosing(),
2410 private void generateFlatMethodSESE(FlatMethod fm,
2412 FlatSESEEnterNode fsen,
2413 FlatSESEExitNode seseExit,
2417 MethodDescriptor md=fm.getMethod();
2419 output.print("void ");
2420 output.print(fsen.getSESEmethodName()+"(");
2421 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
2422 output.println("){\n");
2425 TempObject objecttemp=(TempObject) tempstable.get(md);
2427 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2428 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2429 output.print(objecttemp.numPointers()+",");
2430 output.print("&(((SESEcommon*)(___params___))[1])");
2431 for(int j=0; j<objecttemp.numPointers(); j++)
2432 output.print(", NULL");
2433 output.println("};");
2436 output.println(" /* regular local primitives */");
2437 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2438 TempDescriptor td=objecttemp.getPrimitive(i);
2439 TypeDescriptor type=td.getType();
2441 output.println(" void * "+td.getSafeSymbol()+";");
2442 else if (type.isClass()||type.isArray())
2443 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2445 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2449 // declare variables for naming static SESE's
2450 output.println(" /* static SESE names */");
2451 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
2452 while( pItr.hasNext() ) {
2453 SESEandAgePair pair = pItr.next();
2454 output.println(" SESEcommon* "+pair+" = NULL;");
2457 // declare variables for tracking dynamic sources
2458 output.println(" /* dynamic variable sources */");
2459 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
2460 while( dynSrcItr.hasNext() ) {
2461 TempDescriptor dynSrcVar = dynSrcItr.next();
2462 output.println(" SESEcommon* "+dynSrcVar+"_srcSESE = NULL;");
2463 output.println(" INTPTR "+dynSrcVar+"_srcOffset = 0x1;");
2466 // declare local temps for in-set primitives, and if it is
2467 // a ready-source variable, get the value from the record
2468 output.println(" /* local temps for in-set primitives */");
2469 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2470 while( itrInSet.hasNext() ) {
2471 TempDescriptor temp = itrInSet.next();
2472 TypeDescriptor type = temp.getType();
2473 if( !type.isPtr() ) {
2474 if( fsen.getReadyInVarSet().contains( temp ) ) {
2475 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2477 output.println(" "+type+" "+temp+";");
2482 // declare local temps for out-set primitives if its not already
2483 // in the in-set, and it's value will get written so no problem
2484 output.println(" /* local temp for out-set prim, not already in the in-set */");
2485 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2486 while( itrOutSet.hasNext() ) {
2487 TempDescriptor temp = itrOutSet.next();
2488 TypeDescriptor type = temp.getType();
2489 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2490 output.println(" "+type+" "+temp+";");
2495 // initialize thread-local var to a the task's record, which is fused
2496 // with the param list
2497 output.println(" ");
2498 output.println(" // code of this task's body should use this to access the running task record");
2499 output.println(" runningSESE = &(___params___->common);");
2500 output.println(" childSESE = 0;");
2501 output.println(" ");
2503 // setup memory queue
2506 output.println(" // set up memory queues ");
2507 output.println(" int numMemoryQueue=0;");
2508 output.println(" int memoryQueueItemID=0;");
2509 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(fsen);
2510 if (graph != null && graph.hasConflictEdge()) {
2511 output.println(" {");
2512 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
2513 System.out.println("#lockSet="+lockSet);
2514 if (lockSet.size() > 0) {
2515 output.println(" numMemoryQueue=" + lockSet.size() + ";");
2516 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
2517 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2520 output.println(" }");
2523 output.println(" // set up memory queues ");
2524 output.println(" int numMemoryQueue=0;");
2525 output.println(" int memoryQueueItemID=0;");
2526 ConflictGraph graph = null;
2527 graph = mlpa.getConflictGraphResults().get(fsen);
2528 if (graph != null && graph.hasConflictEdge()) {
2529 output.println(" {");
2530 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
2532 System.out.println("#lockSet="+lockSet);
2534 if (lockSet.size() > 0) {
2535 output.println(" numMemoryQueue=" + lockSet.size() + "; ");
2536 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
2537 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2540 output.println(" }");
2545 // set up a task's mem pool to recycle the allocation of children tasks
2546 // don't bother if the task never has children (a leaf task)
2547 output.println( "#ifndef OOO_DISABLE_TASKMEMPOOL" );
2548 if( !fsen.getIsLeafSESE() ) {
2549 output.println(" runningSESE->taskRecordMemPool = taskpoolcreate( "+
2550 maxTaskRecSizeStr+" );");
2552 // make it clear we purposefully did not initialize this
2553 output.println(" runningSESE->taskRecordMemPool = (MemPool*)0x7;");
2555 output.println( "#endif // OOO_DISABLE_TASKMEMPOOL" );
2558 // copy in-set into place, ready vars were already
2559 // copied when the SESE was issued
2560 Iterator<TempDescriptor> tempItr;
2562 // static vars are from a known SESE
2563 output.println(" // copy variables from static sources");
2564 tempItr = fsen.getStaticInVarSet().iterator();
2565 while( tempItr.hasNext() ) {
2566 TempDescriptor temp = tempItr.next();
2567 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2568 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2569 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2570 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2573 output.println(" // decrement references to static sources");
2574 for( Iterator<SESEandAgePair> pairItr = fsen.getStaticInVarSrcs().iterator(); pairItr.hasNext(); ) {
2575 SESEandAgePair srcPair = pairItr.next();
2576 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
2577 output.println(" {");
2578 output.println(" SESEcommon* src = &("+paramsprefix+"->"+srcPair+"->common);");
2579 output.println(" RELEASE_REFERENCE_TO( src );");
2580 output.println(" }");
2581 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
2585 // dynamic vars come from an SESE and src
2586 output.println(" // copy variables from dynamic sources");
2587 tempItr = fsen.getDynamicInVarSet().iterator();
2588 while( tempItr.hasNext() ) {
2589 TempDescriptor temp = tempItr.next();
2590 TypeDescriptor type = temp.getType();
2592 // go grab it from the SESE source
2593 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2596 if( type.isNull() ) {
2598 } else if( type.isClass() || type.isArray() ) {
2599 typeStr = "struct "+type.getSafeSymbol()+"*";
2601 typeStr = type.getSafeSymbol();
2604 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2605 " = *(("+typeStr+"*) ((void*)"+
2606 paramsprefix+"->"+temp+"_srcSESE + "+
2607 paramsprefix+"->"+temp+"_srcOffset));");
2609 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
2610 output.println(" SESEcommon* src = "+paramsprefix+"->"+temp+"_srcSESE;");
2611 output.println(" RELEASE_REFERENCE_TO( src );");
2612 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
2614 // or if the source was our parent, its already in our record to grab
2615 output.println(" } else {");
2616 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2617 " = "+paramsprefix+"->"+temp+";");
2618 output.println(" }");
2621 // Check to see if we need to do a GC if this is a
2622 // multi-threaded program...
2623 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2624 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2625 //Don't bother if we aren't in recursive methods...The loops case will catch it
2626 // if (callgraph.getAllMethods(md).contains(md)) {
2627 // if(this.state.MULTICOREGC) {
2628 // output.println("if(gcflag) gc("+localsprefixaddr+");");
2630 // output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2635 if( state.COREPROF ) {
2636 output.println("#ifdef CP_EVENTID_TASKEXECUTE");
2637 output.println(" CP_LOGEVENT( CP_EVENTID_TASKEXECUTE, CP_EVENTTYPE_BEGIN );");
2638 output.println("#endif");
2641 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2642 exitset.add(seseExit);
2643 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2644 output.println("}\n\n");
2649 // when a new mlp thread is created for an issued SESE, it is started
2650 // by running this method which blocks on a cond variable until
2651 // it is allowed to transition to execute. Then a case statement
2652 // allows it to invoke the method with the proper SESE body, and after
2653 // exiting the SESE method, executes proper SESE exit code before the
2654 // thread can be destroyed
2655 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2656 PrintWriter outmethod
2659 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2660 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2661 outmethod.println( " int status;");
2662 outmethod.println( " char errmsg[128];");
2664 // generate a case for each SESE class that can be invoked
2665 outmethod.println( " switch( ((SESEcommon*)seseRecord)->classID ) {");
2666 outmethod.println( " ");
2667 Iterator<FlatSESEEnterNode> seseit;
2669 seseit=mlpa.getAllSESEs().iterator();
2671 seseit=oooa.getAllSESEs().iterator();
2673 while(seseit.hasNext()){
2674 FlatSESEEnterNode fsen = seseit.next();
2676 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2677 outmethod.println( " case "+fsen.getIdentifier()+":");
2678 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2680 if( (state.MLP && fsen.equals( mlpa.getMainSESE() )) ||
2681 (state.OOOJAVA && fsen.equals( oooa.getMainSESE() ))
2683 outmethod.println( " workScheduleExit();");
2686 outmethod.println( " break;");
2687 outmethod.println( "");
2690 // default case should never be taken, error out
2691 outmethod.println( " default:");
2692 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2693 outmethod.println( " exit(-30);");
2694 outmethod.println( " break;");
2695 outmethod.println( " }");
2696 outmethod.println( " return NULL;");
2697 outmethod.println( "}\n\n");
2701 protected void generateCode(FlatNode first,
2704 Set<FlatNode> stopset,
2706 boolean firstpass) {
2708 /* Assign labels to FlatNode's if necessary.*/
2710 Hashtable<FlatNode, Integer> nodetolabel;
2712 if (state.DELAYCOMP&&!firstpass)
2713 nodetolabel=dcassignLabels(first, stopset);
2715 nodetolabel=assignLabels(first, stopset);
2717 Set<FlatNode> storeset=null;
2718 HashSet<FlatNode> genset=null;
2719 HashSet<FlatNode> refset=null;
2720 Set<FlatNode> unionset=null;
2722 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2723 storeset=delaycomp.livecode(lb);
2724 genset=new HashSet<FlatNode>();
2725 if (state.STMARRAY&&!state.DUALVIEW) {
2726 refset=new HashSet<FlatNode>();
2727 refset.addAll(delaycomp.getDeref(lb));
2728 refset.removeAll(delaycomp.getCannotDelay(lb));
2729 refset.removeAll(delaycomp.getOther(lb));
2732 genset.addAll(delaycomp.getCannotDelay(lb));
2733 genset.addAll(delaycomp.getOther(lb));
2735 genset.addAll(delaycomp.getNotReady(lb));
2736 if (state.STMARRAY&&!state.DUALVIEW) {
2737 genset.removeAll(refset);
2740 unionset=new HashSet<FlatNode>();
2741 unionset.addAll(storeset);
2742 unionset.addAll(genset);
2743 if (state.STMARRAY&&!state.DUALVIEW)
2744 unionset.addAll(refset);
2747 /* Do the actual code generation */
2748 FlatNode current_node=null;
2749 HashSet tovisit=new HashSet();
2750 HashSet visited=new HashSet();
2752 tovisit.add(first.getNext(0));
2755 while(current_node!=null||!tovisit.isEmpty()) {
2756 if (current_node==null) {
2757 current_node=(FlatNode)tovisit.iterator().next();
2758 tovisit.remove(current_node);
2759 } else if (tovisit.contains(current_node)) {
2760 tovisit.remove(current_node);
2762 visited.add(current_node);
2763 if (nodetolabel.containsKey(current_node)) {
2764 output.println("L"+nodetolabel.get(current_node)+":");
2766 if (state.INSTRUCTIONFAILURE) {
2767 if (state.THREAD||state.DSM||state.SINGLETM) {
2768 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2770 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2772 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2774 if (!state.DELAYCOMP||firstpass) {
2775 generateFlatNode(fm, lb, current_node, output);
2777 //store primitive variables in out set
2778 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2779 Set<TempDescriptor> liveout=ar.liveout;
2780 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2781 TempDescriptor tmp=tmpit.next();
2782 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2785 if ((state.MLP || state.OOOJAVA) && stopset!=null) {
2786 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2787 assert current_node instanceof FlatSESEExitNode;
2788 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2789 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2790 assert fsen.getFlatExit().equals( fsxn );
2791 assert fsxn.getFlatEnter().equals( fsen );
2793 if (current_node.kind()!=FKind.FlatReturnNode) {
2795 // TODO add version for normal Java later
2796 if((fm.getMethod() != null) && (fm.getMethod().isStaticBlock())) {
2797 // a static block, check if it has been executed
2798 output.println(" global_defs_p->" + fm.getMethod().getClassDesc().getSafeSymbol()+"static_block_exe_flag = 1;");
2802 output.println(" return;");
2805 } else if(current_node.numNext()==1) {
2807 if ((state.MLP|| state.OOOJAVA) &&
2808 current_node.kind()==FKind.FlatSESEEnterNode &&
2809 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2811 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2812 generateFlatNode(fm, lb, current_node, output);
2813 nextnode=fsen.getFlatExit().getNext(0);
2814 } else if (state.DELAYCOMP) {
2815 boolean specialprimitive=false;
2816 //skip literals...no need to add extra overhead
2817 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2818 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2819 if (!typedesc.isClass()&&!typedesc.isArray()) {
2820 specialprimitive=true;
2824 if (genset==null||genset.contains(current_node)||specialprimitive)
2825 generateFlatNode(fm, lb, current_node, output);
2826 if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2827 //need to acquire lock
2828 handleArrayDeref(fm, lb, current_node, output, firstpass);
2830 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2831 TempDescriptor wrtmp=current_node.writesTemps()[0];
2833 //need to store value written by previous node
2834 if (wrtmp.getType().isPtr()) {
2835 //only lock the objects that may actually need locking
2836 if (recorddc.getNeedTrans(lb, current_node)&&
2837 (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2838 wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2839 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2841 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2844 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2847 //need to read value read by previous node
2848 if (wrtmp.getType().isPtr()) {
2849 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2851 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");
2855 nextnode=current_node.getNext(0);
2858 generateFlatNode(fm, lb, current_node, output);
2859 nextnode=current_node.getNext(0);
2861 if (visited.contains(nextnode)) {
2862 output.println("goto L"+nodetolabel.get(nextnode)+";");
2865 current_node=nextnode;
2866 } else if (current_node.numNext()==2) {
2868 if (state.DELAYCOMP) {
2869 boolean computeside=false;
2871 //need to record which way it should go
2872 if (genset==null||genset.contains(current_node)) {
2873 if (storeset!=null&&storeset.contains(current_node)) {
2874 //need to store which way branch goes
2875 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2877 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2879 //which side to execute
2883 if (genset.contains(current_node)) {
2884 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2885 } else if (storeset.contains(current_node)) {
2887 branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2889 //which side to execute
2894 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2896 if (leftset.size()==0)
2898 if (visited.contains(current_node.getNext(branch))) {
2899 //already visited -- build jump
2900 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2903 current_node=current_node.getNext(branch);
2906 if (!visited.contains(current_node.getNext(1)))
2907 tovisit.add(current_node.getNext(1));
2908 if (visited.contains(current_node.getNext(0))) {
2909 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2912 current_node=current_node.getNext(0);
2916 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2917 if (!visited.contains(current_node.getNext(1)))
2918 tovisit.add(current_node.getNext(1));
2919 if (visited.contains(current_node.getNext(0))) {
2920 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2923 current_node=current_node.getNext(0);
2925 } else throw new Error();
2929 protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2930 if (fn.kind()==FKind.FlatSetElementNode) {
2931 FlatSetElementNode fsen=(FlatSetElementNode) fn;
2932 String dst=generateTemp(fm, fsen.getDst(), lb);
2933 String src=generateTemp(fm, fsen.getSrc(), lb);
2934 String index=generateTemp(fm, fsen.getIndex(), lb);
2935 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2937 if (elementtype.isArray()||elementtype.isClass())
2940 type=elementtype.getSafeSymbol()+" ";
2942 output.println("STOREARRAY("+dst+","+index+","+type+")");
2944 output.println("{");
2945 output.println(" struct ArrayObject *array;");
2946 output.println(" int index;");
2947 output.println(" RESTOREARRAY(array,index);");
2948 output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2949 output.println("}");
2951 } else if (fn.kind()==FKind.FlatElementNode) {
2952 FlatElementNode fen=(FlatElementNode) fn;
2953 String src=generateTemp(fm, fen.getSrc(), lb);
2954 String index=generateTemp(fm, fen.getIndex(), lb);
2955 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2956 String dst=generateTemp(fm, fen.getDst(), lb);
2958 if (elementtype.isArray()||elementtype.isClass())
2961 type=elementtype.getSafeSymbol()+" ";
2963 output.println("STOREARRAY("+src+","+index+","+type+")");
2965 output.println("{");
2966 output.println(" struct ArrayObject *array;");
2967 output.println(" int index;");
2968 output.println(" RESTOREARRAY(array,index);");
2969 output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2970 output.println("}");
2974 /** Special label assignment for delaycomputation */
2975 protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2976 HashSet tovisit=new HashSet();
2977 HashSet visited=new HashSet();
2979 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2981 //Label targets of branches
2982 Set<FlatNode> targets=branchanalysis.getTargets();
2983 for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2984 nodetolabel.put(it.next(), new Integer(labelindex++));
2989 /*Assign labels first. A node needs a label if the previous
2990 * node has two exits or this node is a join point. */
2992 while(!tovisit.isEmpty()) {
2993 FlatNode fn=(FlatNode)tovisit.iterator().next();
2998 if(lastset!=null&&lastset.contains(fn)) {
2999 // if last is not null and matches, don't go
3000 // any further for assigning labels
3004 for(int i=0; i<fn.numNext(); i++) {
3005 FlatNode nn=fn.getNext(i);
3008 //1) Edge >1 of node
3009 nodetolabel.put(nn,new Integer(labelindex++));
3011 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
3015 nodetolabel.put(nn,new Integer(labelindex++));
3023 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
3024 return assignLabels(first, null);
3027 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
3028 HashSet tovisit=new HashSet();
3029 HashSet visited=new HashSet();
3031 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
3034 /*Assign labels first. A node needs a label if the previous
3035 * node has two exits or this node is a join point. */
3037 while(!tovisit.isEmpty()) {
3038 FlatNode fn=(FlatNode)tovisit.iterator().next();
3043 if(lastset!=null&&lastset.contains(fn)) {
3044 // if last is not null and matches, don't go
3045 // any further for assigning labels
3049 for(int i=0; i<fn.numNext(); i++) {
3050 FlatNode nn=fn.getNext(i);
3053 //1) Edge >1 of node
3054 nodetolabel.put(nn,new Integer(labelindex++));
3056 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
3060 nodetolabel.put(nn,new Integer(labelindex++));
3068 /** Generate text string that corresponds to the TempDescriptor td. */
3069 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
3070 MethodDescriptor md=fm.getMethod();
3071 TaskDescriptor task=fm.getTask();
3072 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
3074 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
3075 return td.getSafeSymbol();
3078 if (objecttemps.isLocalPtr(td)) {
3079 return localsprefixderef+td.getSafeSymbol();
3082 if (objecttemps.isParamPtr(td)) {
3083 return paramsprefix+"->"+td.getSafeSymbol();
3089 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
3091 // insert pre-node actions from the code plan
3092 if( state.MLP|| state.OOOJAVA ) {
3096 cp = mlpa.getCodePlan( fn );
3098 cp = oooa.getCodePlan(fn);
3103 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
3105 // for each sese and age pair that this parent statement
3106 // must stall on, take that child's stall semaphore, the
3107 // copying of values comes after the statement
3108 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
3109 while( vstItr.hasNext() ) {
3110 VariableSourceToken vst = vstItr.next();
3112 SESEandAgePair pair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
3114 output.println(" {");
3115 output.println(" "+pair.getSESE().getSESErecordName()+"* child = ("+
3116 pair.getSESE().getSESErecordName()+"*) "+pair+";");
3118 output.println(" SESEcommon* childCom = (SESEcommon*) "+pair+";");
3120 if( state.COREPROF ) {
3121 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
3122 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
3123 output.println("#endif");
3126 output.println(" pthread_mutex_lock( &(childCom->lock) );");
3127 output.println(" if( childCom->doneExecuting == FALSE ) {");
3128 output.println(" psem_reset( &runningSESEstallSem );");
3129 output.println(" childCom->parentsStallSem = &runningSESEstallSem;");
3130 output.println(" pthread_mutex_unlock( &(childCom->lock) );");
3131 output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );");
3132 output.println(" } else {");
3133 output.println(" pthread_mutex_unlock( &(childCom->lock) );");
3134 output.println(" }");
3136 // copy things we might have stalled for
3137 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
3138 while( tdItr.hasNext() ) {
3139 TempDescriptor td = tdItr.next();
3140 FlatMethod fmContext;
3141 if( currentSESE.getIsCallerSESEplaceholder() ) {
3142 fmContext = currentSESE.getfmEnclosing();
3144 fmContext = currentSESE.getfmBogus();
3146 output.println(" "+generateTemp( fmContext, td, null )+
3147 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
3150 if( state.COREPROF ) {
3151 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
3152 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
3153 output.println("#endif");
3156 output.println(" }");
3159 // for each variable with a dynamic source, stall just for that variable
3160 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
3161 while( dynItr.hasNext() ) {
3162 TempDescriptor dynVar = dynItr.next();
3164 // only stall if the dynamic source is not yourself, denoted by src==NULL
3165 // otherwise the dynamic write nodes will have the local var up-to-date
3166 output.println(" {");
3167 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
3169 output.println(" SESEcommon* childCom = (SESEcommon*) "+dynVar+"_srcSESE;");
3171 if( state.COREPROF ) {
3172 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
3173 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
3174 output.println("#endif");
3177 output.println(" pthread_mutex_lock( &(childCom->lock) );");
3178 output.println(" if( childCom->doneExecuting == FALSE ) {");
3179 output.println(" psem_reset( &runningSESEstallSem );");
3180 output.println(" childCom->parentsStallSem = &runningSESEstallSem;");
3181 output.println(" pthread_mutex_unlock( &(childCom->lock) );");
3182 output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );");
3183 output.println(" } else {");
3184 output.println(" pthread_mutex_unlock( &(childCom->lock) );");
3185 output.println(" }");
3187 FlatMethod fmContext;
3188 if( currentSESE.getIsCallerSESEplaceholder() ) {
3189 fmContext = currentSESE.getfmEnclosing();
3191 fmContext = currentSESE.getfmBogus();
3194 TypeDescriptor type = dynVar.getType();
3196 if( type.isNull() ) {
3198 } else if( type.isClass() || type.isArray() ) {
3199 typeStr = "struct "+type.getSafeSymbol()+"*";
3201 typeStr = type.getSafeSymbol();
3204 output.println(" "+generateTemp( fmContext, dynVar, null )+
3205 " = *(("+typeStr+"*) ((void*)"+
3206 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
3208 if( state.COREPROF ) {
3209 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
3210 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
3211 output.println("#endif");
3214 output.println(" }");
3215 output.println(" }");
3218 // for each assignment of a variable to rhs that has a dynamic source,
3219 // copy the dynamic sources
3220 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
3221 while( dynAssignItr.hasNext() ) {
3222 Map.Entry me = (Map.Entry) dynAssignItr.next();
3223 TempDescriptor lhs = (TempDescriptor) me.getKey();
3224 TempDescriptor rhs = (TempDescriptor) me.getValue();
3226 output.println(" {");
3227 output.println(" SESEcommon* oldSrc = "+lhs+"_srcSESE;");
3229 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
3230 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
3232 // no matter what we did above, track reference count of whatever
3233 // this variable pointed to, do release last in case we're just
3234 // copying the same value in because 1->2->1 is safe but ref count
3235 // 1->0->1 has a window where it looks like it should be free'd
3236 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3237 output.println(" if( "+rhs+"_srcSESE != NULL ) {");
3238 output.println(" ADD_REFERENCE_TO( "+rhs+"_srcSESE );");
3239 output.println(" }");
3240 output.println(" if( oldSrc != NULL ) {");
3241 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
3242 output.println(" }");
3243 output.println(" }");
3244 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
3247 // for each lhs that is dynamic from a non-dynamic source, set the
3248 // dynamic source vars to the current SESE
3249 dynItr = cp.getDynAssignCurr().iterator();
3250 while( dynItr.hasNext() ) {
3251 TempDescriptor dynVar = dynItr.next();
3252 assert currentSESE.getDynamicVarSet().contains( dynVar );
3254 // first release a reference to current record
3255 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3256 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
3257 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
3258 output.println(" }");
3259 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
3261 output.println(" "+dynVar+"_srcSESE = NULL;");
3265 // handling stall site
3266 if (state.OOOJAVA) {
3267 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(currentSESE);
3269 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
3270 Set<Analysis.OoOJava.WaitingElement> waitingElementSet = graph.getStallSiteWaitingElementSet(fn, seseLockSet);
3272 if(waitingElementSet.size()>0){
3273 output.println("// stall on parent's stall sites ");
3274 output.println(" {");
3275 output.println(" REntry* rentry;");
3277 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
3278 Analysis.OoOJava.WaitingElement waitingElement = (Analysis.OoOJava.WaitingElement) iterator.next();
3279 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3280 output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "],"+waitingElement.getStatus()+ ", runningSESE);");
3282 output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "],"+ waitingElement.getStatus()+ ", runningSESE, (void*)&" +generateTemp(fm,waitingElement.getTempDesc(),lb)+ ");");
3284 output.println(" rentry->parentStallSem=&runningSESEstallSem;");
3285 output.println(" psem_reset( &runningSESEstallSem);");
3286 output.println(" rentry->tag=runningSESEstallSem.tag;");
3287 output.println(" rentry->queue=runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3288 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "],rentry)==NOTREADY){");
3289 if( state.COREPROF ) {
3290 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3291 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3292 output.println("#endif");
3295 //no need to enqueue parent effect if coarse grained conflict clears us
3296 output.println(" while(stallrecord.common.rcrstatus) ;");
3297 output.println(" BARRIER();");
3298 output.println(" stallrecord.common.parentsStallSem=&runningSESEstallSem;");
3299 output.println(" stallrecord.tag=rentry->tag;");
3300 output.println(" stallrecord.___obj___=(struct ___Object___ *)"+generateTemp(fm, waitingElement.getTempDesc(), null)+";");
3301 output.println(" stallrecord.common.classID=-"+rcr.getTraverserID(waitingElement.getTempDesc(), fn)+";");
3302 //mark the record used..so we won't use it again until it is free
3303 output.println(" stallrecord.common.rcrstatus=1;");
3304 output.println(" enqueueTR(TRqueue, (void *)&stallrecord);");
3306 output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );");
3307 if( state.COREPROF ) {
3308 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3309 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3310 output.println("#endif");
3312 output.println(" } ");
3314 output.println(" }");
3318 ParentChildConflictsMap conflictsMap = mlpa.getConflictsResults().get(fn);
3319 if (conflictsMap != null) {
3320 Set<Long> allocSet = conflictsMap.getAllocationSiteIDSetofStallSite();
3321 if (allocSet.size() > 0) {
3322 FlatNode enclosingFlatNode=null;
3323 if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
3324 enclosingFlatNode=currentSESE.getfmEnclosing();
3326 enclosingFlatNode=currentSESE;
3328 ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
3329 HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
3330 Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
3332 if(waitingElementSet.size()>0){
3333 output.println("// stall on parent's stall sites ");
3334 output.println(" {");
3335 output.println(" REntry* rentry;");
3337 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
3338 WaitingElement waitingElement = (WaitingElement) iterator.next();
3340 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3341 // HERE! a parent might conflict with a child
3342 output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "],"+ waitingElement.getStatus()+ ", runningSESE);");
3344 output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "],"+ waitingElement.getStatus()+ ", runningSESE, (void*)&___locals___."+ waitingElement.getDynID() + ");");
3346 output.println(" rentry->parentStallSem=&runningSESEstallSem;");
3347 output.println(" psem_reset( &runningSESEstallSem);");
3348 output.println(" rentry->tag=runningSESEstallSem.tag;");
3349 output.println(" rentry->queue=runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3350 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+"],rentry)==NOTREADY) {");
3351 if( state.COREPROF ) {
3352 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3353 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3354 output.println("#endif");
3356 output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );");
3357 if( state.COREPROF ) {
3358 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3359 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3360 output.println("#endif");
3362 output.println(" } ");
3364 output.println(" }");
3373 case FKind.FlatAtomicEnterNode:
3374 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
3377 case FKind.FlatAtomicExitNode:
3378 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
3381 case FKind.FlatInstanceOfNode:
3382 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
3385 case FKind.FlatSESEEnterNode:
3386 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
3389 case FKind.FlatSESEExitNode:
3390 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
3393 case FKind.FlatWriteDynamicVarNode:
3394 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
3397 case FKind.FlatGlobalConvNode:
3398 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
3401 case FKind.FlatTagDeclaration:
3402 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
3405 case FKind.FlatCall:
3406 generateFlatCall(fm, lb, (FlatCall) fn,output);
3409 case FKind.FlatFieldNode:
3410 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
3413 case FKind.FlatElementNode:
3414 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
3417 case FKind.FlatSetElementNode:
3418 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
3421 case FKind.FlatSetFieldNode:
3422 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
3426 generateFlatNew(fm, lb, (FlatNew) fn,output);
3429 case FKind.FlatOpNode:
3430 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
3433 case FKind.FlatCastNode:
3434 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
3437 case FKind.FlatLiteralNode:
3438 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
3441 case FKind.FlatReturnNode:
3442 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
3446 output.println("/* nop */");
3449 case FKind.FlatGenReachNode:
3450 // this node is just for generating a reach graph
3451 // in disjointness analysis at a particular program point
3454 case FKind.FlatExit:
3455 output.println("/* exit */");
3458 case FKind.FlatBackEdge:
3459 if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3460 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3462 if(state.DSM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3463 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3465 if (((state.MLP|| state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
3466 || (this.state.MULTICOREGC)) {
3467 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
3468 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
3469 } else if(this.state.MULTICOREGC) {
3470 output.println("if (gcflag) gc("+localsprefixaddr+");");
3472 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3475 output.println("/* nop */");
3478 case FKind.FlatCheckNode:
3479 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
3482 case FKind.FlatFlagActionNode:
3483 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
3486 case FKind.FlatPrefetchNode:
3487 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
3490 case FKind.FlatOffsetNode:
3491 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
3498 // insert post-node actions from the code-plan
3501 CodePlan cp = mlpa.getCodePlan( fn );
3509 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
3510 output.println("/* FlatOffsetNode */");
3511 FieldDescriptor fd=fofn.getField();
3512 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
3513 output.println("/* offset */");
3516 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
3517 if (state.PREFETCH) {
3518 Vector oids = new Vector();
3519 Vector fieldoffset = new Vector();
3520 Vector endoffset = new Vector();
3521 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
3522 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
3523 PrefetchPair pp = (PrefetchPair) it.next();
3524 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
3525 /* Find prefetches that can generate oid */
3526 if(statusbase == LocalityAnalysis.GLOBAL) {
3527 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
3529 } else if (statusbase == LocalityAnalysis.LOCAL) {
3530 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
3537 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
3538 output.println("{");
3539 output.println("/* prefetch */");
3540 output.println("/* prefetchid_" + fpn.siteid + " */");
3541 output.println("void * prefptr;");
3542 output.println("int tmpindex;");
3544 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
3545 /*Create C code for oid array */
3546 output.print(" unsigned int oidarray_[] = {");
3547 boolean needcomma=false;
3548 for (Iterator it = oids.iterator(); it.hasNext();) {
3551 output.print(it.next());
3554 output.println("};");
3556 /*Create C code for endoffset values */
3557 output.print(" unsigned short endoffsetarry_[] = {");
3559 for (Iterator it = endoffset.iterator(); it.hasNext();) {
3562 output.print(it.next());
3565 output.println("};");
3567 /*Create C code for Field Offset Values */
3568 output.print(" short fieldarry_[] = {");
3570 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
3573 output.print(it.next());
3576 output.println("};");
3577 /* make the prefetch call to Runtime */
3578 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
3579 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
3580 output.println(" }");
3581 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
3582 output.println(" } else {");
3583 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
3584 output.println(" }");
3585 output.println("}");
3589 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
3590 short offsetcount = 0;
3594 } else if (localbase) {
3595 for(; breakindex<pp.desc.size(); breakindex++) {
3596 Descriptor desc=pp.getDescAt(breakindex);
3597 if (desc instanceof FieldDescriptor) {
3598 FieldDescriptor fd=(FieldDescriptor)desc;
3599 if (fd.isGlobal()) {
3607 if (breakindex>pp.desc.size()) //all local
3610 TypeDescriptor lasttype=pp.base.getType();
3611 String basestr=generateTemp(fm, pp.base, lb);
3613 boolean maybenull=fm.getMethod().isStatic()||
3614 !pp.base.equals(fm.getParameter(0));
3616 for(int i=0; i<breakindex; i++) {
3617 String indexcheck="";
3619 Descriptor desc=pp.getDescAt(i);
3620 if (desc instanceof FieldDescriptor) {
3621 FieldDescriptor fd=(FieldDescriptor)desc;
3623 if (!teststr.equals(""))
3625 teststr+="((prefptr="+basestr+")!=NULL)";
3626 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3628 basestr=basestr+"->"+fd.getSafeSymbol();
3631 lasttype=fd.getType();
3633 IndexDescriptor id=(IndexDescriptor)desc;
3634 indexcheck="((tmpindex=";
3635 for(int j=0; j<id.tddesc.size(); j++) {
3636 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3638 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3640 if (!teststr.equals(""))
3642 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3643 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3645 lasttype=lasttype.dereference();
3650 if (teststr.equals("")) {
3651 oid="((unsigned int)"+basestr+")";
3653 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3657 for(int i = breakindex; i < pp.desc.size(); i++) {
3658 String newfieldoffset;
3659 Object desc = pp.getDescAt(i);
3660 if(desc instanceof FieldDescriptor) {
3661 FieldDescriptor fd=(FieldDescriptor)desc;
3662 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3663 lasttype=fd.getType();
3665 newfieldoffset = "";
3666 IndexDescriptor id=(IndexDescriptor)desc;
3667 for(int j = 0; j < id.tddesc.size(); j++) {
3668 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3670 newfieldoffset += id.offset.toString();
3671 lasttype=lasttype.dereference();
3673 fieldoffset.add(newfieldoffset);
3676 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3677 base+=pp.desc.size()-breakindex;
3678 endoffset.add(new Short((short)base));
3683 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3684 if (lb!=fgcn.getLocality())
3686 /* Have to generate flat globalconv */
3687 if (fgcn.getMakePtr()) {
3689 //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3690 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3692 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3693 //need to do translation
3694 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3695 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3696 if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3697 output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3699 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3703 /* Need to convert to OID */
3704 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3705 if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3706 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3708 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3714 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3716 if (fion.getType().isArray()) {
3717 type=state.getArrayNumber(fion.getType())+state.numClasses();
3719 type=fion.getType().getClassDesc().getId();
3722 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3723 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3725 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3728 int sandboxcounter=0;
3729 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3730 /* Check to see if we need to generate code for this atomic */
3731 if (locality==null) {
3732 if (GENERATEPRECISEGC) {
3733 output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3734 output.println("stopforgc((struct garbagelist *) &___locals___);");
3735 output.println("pthread_mutex_lock(&atomiclock);");
3736 output.println("restartaftergc();");
3737 output.println("}");
3739 output.println("pthread_mutex_lock(&atomiclock);");
3744 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3748 if (state.SANDBOX) {
3749 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3750 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3753 if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3754 AtomicRecord ar=atomicmethodmap.get(faen);
3756 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3757 TempDescriptor tmp=tmpit.next();
3758 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3761 //copy outs that depend on path
3762 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3763 TempDescriptor tmp=tmpit.next();
3764 if (!ar.livein.contains(tmp))
3765 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3769 /* Backup the temps. */
3770 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3771 TempDescriptor tmp=tmpit.next();
3772 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3775 output.println("goto transstart"+faen.getIdentifier()+";");
3777 /******* Print code to retry aborted transaction *******/
3778 output.println("transretry"+faen.getIdentifier()+":");
3781 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3782 TempDescriptor tmp=tmpit.next();
3783 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3787 /********* Need to revert local object store ********/
3788 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3790 output.println("while ("+revertptr+") {");
3791 output.println("struct ___Object___ * tmpptr;");
3792 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3793 output.println("REVERT_OBJ("+revertptr+");");
3794 output.println(revertptr+"=tmpptr;");
3795 output.println("}");
3797 /******* Tell the runtime to start the transaction *******/
3799 output.println("transstart"+faen.getIdentifier()+":");
3800 if (state.SANDBOX) {
3801 output.println("transaction_check_counter=*counter_reset_pointer;");
3804 output.println("transStart();");
3806 if (state.ABORTREADERS||state.SANDBOX) {
3808 output.println("abortenabled=1;");
3809 output.println("if (_setjmp(aborttrans)) {");
3810 output.println(" goto transretry"+faen.getIdentifier()+"; }");
3814 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3815 /* Check to see if we need to generate code for this atomic */
3816 if (locality==null) {
3817 output.println("pthread_mutex_unlock(&atomiclock);");
3820 if (locality.getAtomic(lb).get(faen).intValue()>0)
3822 //store the revert list before we lose the transaction object
3825 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3826 output.println(revertptr+"=revertlist;");
3827 output.println("if (transCommit()) {");
3828 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3829 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3830 output.println("} else {");
3831 /* Need to commit local object store */
3832 output.println("while ("+revertptr+") {");
3833 output.println("struct ___Object___ * tmpptr;");
3834 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3835 output.println("COMMIT_OBJ("+revertptr+");");
3836 output.println(revertptr+"=tmpptr;");
3837 output.println("}");
3838 output.println("}");
3842 if (!state.DELAYCOMP) {
3844 output.println("if (transCommit()) {");
3845 /* Transaction aborts if it returns true */
3846 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3847 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3848 output.println("}");
3850 if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
3851 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3852 output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3854 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3855 TempDescriptor tmp=tmpit.next();
3856 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3858 } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3859 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3861 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3862 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3863 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3864 output.println("}");
3866 output.println("else {");
3867 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3868 TempDescriptor tmp=tmpit.next();
3869 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3871 output.println("}");
3873 output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3874 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3875 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3876 output.println("}");
3881 public void generateFlatSESEEnterNode( FlatMethod fm,
3883 FlatSESEEnterNode fsen,
3884 PrintWriter output) {
3885 // if MLP flag is off, okay that SESE nodes are in IR graph,
3886 // just skip over them and code generates exactly the same
3887 if( !(state.MLP || state.OOOJAVA) ) {
3890 // there may be an SESE in an unreachable method, skip over
3891 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
3892 (state.OOOJAVA && !oooa.getAllSESEs().contains(fsen))
3897 // also, if we have encountered a placeholder, just skip it
3898 if( fsen.getIsCallerSESEplaceholder() ) {
3902 output.println(" {");
3904 if( state.COREPROF ) {
3905 output.println("#ifdef CP_EVENTID_TASKDISPATCH");
3906 output.println(" CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_BEGIN );");
3907 output.println("#endif");
3911 // before doing anything, lock your own record and increment the running children
3912 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3913 (state.OOOJAVA && fsen != oooa.getMainSESE())
3915 output.println(" childSESE++;");
3918 // allocate the space for this record
3919 output.println( "#ifndef OOO_DISABLE_TASKMEMPOOL" );
3921 output.println( "#ifdef CP_EVENTID_POOLALLOC");
3922 output.println( " CP_LOGEVENT( CP_EVENTID_POOLALLOC, CP_EVENTTYPE_BEGIN );");
3923 output.println( "#endif");
3924 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3925 (state.OOOJAVA && fsen != oooa.getMainSESE())
3928 fsen.getSESErecordName()+"* seseToIssue = ("+
3929 fsen.getSESErecordName()+"*) taskpoolalloc( runningSESE->taskRecordMemPool );");
3932 fsen.getSESErecordName()+"* seseToIssue = ("+
3933 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3934 fsen.getSESErecordName()+" ) );");
3936 output.println( "#ifdef CP_EVENTID_POOLALLOC");
3937 output.println( " CP_LOGEVENT( CP_EVENTID_POOLALLOC, CP_EVENTTYPE_END );");
3938 output.println( "#endif");
3940 output.println( "#else // OOO_DISABLE_TASKMEMPOOL" );
3942 fsen.getSESErecordName()+"* seseToIssue = ("+
3943 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3944 fsen.getSESErecordName()+" ) );");
3945 output.println( "#endif // OOO_DISABLE_TASKMEMPOOL" );
3948 // set up the SESE in-set and out-set objects, which look
3949 // like a garbage list
3950 output.println(" struct garbagelist * gl= (struct garbagelist *)&(((SESEcommon*)(seseToIssue))[1]);");
3951 output.println(" gl->size="+calculateSizeOfSESEParamList(fsen)+";");
3952 output.println(" gl->next = NULL;");
3955 //flag the SESE status as 1...it will be reset
3956 output.println(" seseToIssue->common.rcrstatus=1;");
3959 // there are pointers to SESE records the newly-issued SESE
3960 // will use to get values it depends on them for--how many
3961 // are there, and what is the offset from the total SESE
3962 // record to the first dependent record pointer?
3963 output.println(" seseToIssue->common.numDependentSESErecords="+
3964 fsen.getNumDepRecs()+";");
3966 // we only need this (and it will only compile) when the number of dependent
3967 // SESE records is non-zero
3968 if( fsen.getFirstDepRecField() != null ) {
3969 output.println(" seseToIssue->common.offsetToDepSESErecords=(INTPTR)sizeof("+
3970 fsen.getSESErecordName()+") - (INTPTR)&((("+
3971 fsen.getSESErecordName()+"*)0)->"+fsen.getFirstDepRecField()+");"
3975 if (state.RCR&&fsen.getInVarsForDynamicCoarseConflictResolution().size()>0) {
3976 output.println(" seseToIssue->common.offsetToParamRecords=(INTPTR) & ((("+fsen.getSESErecordName()+"*)0)->rcrRecords);");
3979 // fill in common data
3980 output.println(" int localCount=0;");
3981 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3982 output.println(" seseToIssue->common.unresolvedDependencies = 10000;");
3983 output.println(" seseToIssue->common.parentsStallSem = NULL;");
3984 output.println(" initQueue(&seseToIssue->common.forwardList);");
3985 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3986 output.println(" seseToIssue->common.numRunningChildren = 0;");
3987 output.println( "#ifdef OOO_DISABLE_TASKMEMPOOL" );
3988 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3989 output.println("#endif");
3990 output.println(" seseToIssue->common.parent = runningSESE;");
3991 // start with refCount = 2, one being the count that the child itself
3992 // will decrement when it retires, to say it is done using its own
3993 // record, and the other count is for the parent that will remember
3994 // the static name of this new child below
3996 // if we're using RCR, ref count is 3 because the traverser has
3998 output.println(" seseToIssue->common.refCount = 3;");
4000 output.println(" seseToIssue->common.refCount = 2;");
4003 // all READY in-vars should be copied now and be done with it
4004 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
4005 while( tempItr.hasNext() ) {
4006 TempDescriptor temp = tempItr.next();
4008 // when we are issuing the main SESE or an SESE with placeholder
4009 // caller SESE as parent, generate temp child child's eclosing method,
4010 // otherwise use the parent's enclosing method as the context
4011 boolean useParentContext = false;
4013 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4014 (state.OOOJAVA && fsen != oooa.getMainSESE())
4016 assert fsen.getParent() != null;
4017 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
4018 useParentContext = true;
4022 if( useParentContext ) {
4023 output.println(" seseToIssue->"+temp+" = "+
4024 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
4026 output.println(" seseToIssue->"+temp+" = "+
4027 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
4031 // before potentially adding this SESE to other forwarding lists,
4033 output.println( "#ifdef OOO_DISABLE_TASKMEMPOOL" );
4034 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
4035 output.println("#endif");
4037 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4038 (state.OOOJAVA && fsen != oooa.getMainSESE())
4040 // count up outstanding dependencies, static first, then dynamic
4041 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
4042 while( staticSrcsItr.hasNext() ) {
4043 SESEandAgePair srcPair = staticSrcsItr.next();
4044 output.println(" {");
4045 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
4046 output.println(" pthread_mutex_lock( &(src->lock) );");
4048 output.println(" if( !src->doneExecuting ) {");
4049 output.println(" addNewItem( &src->forwardList, seseToIssue );");
4050 output.println(" ++(localCount);");
4051 output.println(" }");
4052 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4053 output.println(" ADD_REFERENCE_TO( src );");
4054 output.println("#endif" );
4055 output.println(" pthread_mutex_unlock( &(src->lock) );");
4056 output.println(" }");
4058 // whether or not it is an outstanding dependency, make sure
4059 // to pass the static name to the child's record
4060 output.println(" seseToIssue->"+srcPair+" = "+
4061 "("+srcPair.getSESE().getSESErecordName()+"*)"+
4065 // dynamic sources might already be accounted for in the static list,
4066 // so only add them to forwarding lists if they're not already there
4067 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
4068 while( dynVarsItr.hasNext() ) {
4069 TempDescriptor dynInVar = dynVarsItr.next();
4070 output.println(" {");
4071 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
4073 // the dynamic source is NULL if it comes from your own space--you can't pass
4074 // the address off to the new child, because you're not done executing and
4075 // might change the variable, so copy it right now
4076 output.println(" if( src != NULL ) {");
4077 output.println(" pthread_mutex_lock( &(src->lock) );");
4081 output.println(" if( isEmpty( &src->forwardList ) ||");
4082 output.println(" seseToIssue != peekItem( &src->forwardList ) ) {");
4083 output.println(" if( !src->doneExecuting ) {");
4084 output.println(" addNewItem( &src->forwardList, seseToIssue );");
4085 output.println(" ++(localCount);");
4086 output.println(" }");
4087 output.println(" }");
4088 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4089 output.println(" ADD_REFERENCE_TO( src );");
4090 output.println("#endif" );
4091 output.println(" pthread_mutex_unlock( &(src->lock) );");
4092 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
4093 output.println(" } else {");
4095 boolean useParentContext = false;
4096 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4097 (state.OOOJAVA && fsen != oooa.getMainSESE())
4099 assert fsen.getParent() != null;
4100 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
4101 useParentContext = true;
4104 if( useParentContext ) {
4105 output.println(" seseToIssue->"+dynInVar+" = "+
4106 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
4108 output.println(" seseToIssue->"+dynInVar+" = "+
4109 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
4112 output.println(" }");
4113 output.println(" }");
4115 // even if the value is already copied, make sure your NULL source
4116 // gets passed so child knows it already has the dynamic value
4117 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
4123 // maintain pointers for finding dynamic SESE
4124 // instances from static names
4125 SESEandAgePair pairNewest = new SESEandAgePair( fsen, 0 );
4126 SESEandAgePair pairOldest = new SESEandAgePair( fsen, fsen.getOldestAgeToTrack() );
4127 if( fsen.getParent() != null &&
4128 fsen.getParent().getNeededStaticNames().contains( pairNewest )
4130 output.println(" {");
4131 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4132 output.println(" SESEcommon* oldest = "+pairOldest+";");
4133 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4135 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
4136 SESEandAgePair pair1 = new SESEandAgePair( fsen, i );
4137 SESEandAgePair pair2 = new SESEandAgePair( fsen, i-1 );
4138 output.println(" "+pair1+" = "+pair2+";");
4140 output.println(" "+pairNewest+" = &(seseToIssue->common);");
4142 // no need to add a reference to whatever is the newest record, because
4143 // we initialized seseToIssue->refCount to *2*
4144 // but release a reference to whatever was the oldest BEFORE the shift
4145 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4146 output.println(" if( oldest != NULL ) {");
4147 output.println(" RELEASE_REFERENCE_TO( oldest );");
4148 output.println(" }");
4149 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4150 output.println(" }");
4155 if( state.COREPROF ) {
4156 output.println("#ifdef CP_EVENTID_PREPAREMEMQ");
4157 output.println(" CP_LOGEVENT( CP_EVENTID_PREPAREMEMQ, CP_EVENTTYPE_BEGIN );");
4158 output.println("#endif");
4163 // count up memory conflict dependencies,
4165 dispatchMEMRC(fm, lb, fsen, output);
4166 } else if(state.OOOJAVA){
4167 FlatSESEEnterNode parent = fsen.getParent();
4168 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(parent);
4169 if (graph != null && graph.hasConflictEdge()) {
4170 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
4172 output.println(" //add memory queue element");
4173 Analysis.OoOJava.SESEWaitingQueue seseWaitingQueue=
4174 graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet);
4175 if(seseWaitingQueue.getWaitingElementSize()>0) {
4176 output.println(" {");
4177 output.println(" REntry* rentry=NULL;");
4178 output.println(" INTPTR* pointer=NULL;");
4179 output.println(" seseToIssue->common.rentryIdx=0;");
4181 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
4182 for (Iterator iterator = queueIDSet.iterator(); iterator.hasNext();) {
4183 Integer key = (Integer) iterator.next();
4184 int queueID=key.intValue();
4185 Set<Analysis.OoOJava.WaitingElement> waitingQueueSet =
4186 seseWaitingQueue.getWaitingElementSet(queueID);
4187 int enqueueType=seseWaitingQueue.getType(queueID);
4188 if(enqueueType==SESEWaitingQueue.EXCEPTION) {
4189 output.println(" INITIALIZEBUF(runningSESE->memoryQueueArray[" + queueID+ "]);");
4191 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2.hasNext();) {
4192 Analysis.OoOJava.WaitingElement waitingElement
4193 = (Analysis.OoOJava.WaitingElement) iterator2.next();
4194 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
4195 output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
4196 + waitingElement.getStatus()
4197 + ", &(seseToIssue->common));");
4199 TempDescriptor td = waitingElement.getTempDesc();
4200 // decide whether waiting element is dynamic or static
4201 if (fsen.getDynamicInVarSet().contains(td)) {
4202 // dynamic in-var case
4203 output.println(" pointer=seseToIssue->"
4204 + waitingElement.getDynID()
4205 + "_srcSESE+seseToIssue->"
4206 + waitingElement.getDynID()
4208 output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
4209 + waitingElement.getStatus()
4210 + ", &(seseToIssue->common), pointer );");
4211 } else if (fsen.getStaticInVarSet().contains(td)) {
4212 // static in-var case
4213 VariableSourceToken vst = fsen.getStaticInVarSrc(td);
4216 String srcId = "SESE_" + vst.getSESE().getPrettyIdentifier()
4217 + vst.getSESE().getIdentifier()
4218 + "_" + vst.getAge();
4219 output.println(" pointer=(void*)&seseToIssue->"
4225 output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
4226 + waitingElement.getStatus()
4227 + ", &(seseToIssue->common), pointer );");
4230 output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
4231 + waitingElement.getStatus()
4232 + ", &(seseToIssue->common), (void*)&seseToIssue->"
4233 + waitingElement.getDynID()
4237 output.println(" rentry->queue=runningSESE->memoryQueueArray["
4238 + waitingElement.getQueueID()
4241 if(enqueueType==SESEWaitingQueue.NORMAL){
4242 output.println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4243 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["
4244 + waitingElement.getQueueID()
4245 + "],rentry)==NOTREADY) {");
4246 output.println(" localCount++;");
4247 output.println(" }");
4249 output.println(" ADDRENTRYTOBUF(runningSESE->memoryQueueArray[" + waitingElement.getQueueID() + "],rentry);");
4252 if(enqueueType!=SESEWaitingQueue.NORMAL){
4253 output.println(" localCount+=RESOLVEBUF(runningSESE->memoryQueueArray["
4254 + queueID+ "],&seseToIssue->common);");
4257 output.println(" }");
4262 ConflictGraph graph = null;
4263 FlatSESEEnterNode parent = fsen.getParent();
4264 if (parent != null) {
4265 if (parent.isCallerSESEplaceholder) {
4266 graph = mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
4268 graph = mlpa.getConflictGraphResults().get(parent);
4271 if (graph != null && graph.hasConflictEdge()) {
4272 HashSet<SESELock> seseLockSet = mlpa.getConflictGraphLockMap()
4275 output.println(" //add memory queue element");
4276 SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(fsen.getIdentifier(),
4278 if(seseWaitingQueue.getWaitingElementSize()>0){
4279 output.println(" {");
4280 output.println(" REntry* rentry=NULL;");
4281 output.println(" INTPTR* pointer=NULL;");
4282 output.println(" seseToIssue->common.rentryIdx=0;");
4284 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
4285 for (Iterator iterator = queueIDSet.iterator(); iterator
4287 Integer key = (Integer) iterator.next();
4288 int queueID=key.intValue();
4289 Set<WaitingElement> waitingQueueSet = seseWaitingQueue.getWaitingElementSet(queueID);
4290 int enqueueType=seseWaitingQueue.getType(queueID);
4291 if(enqueueType==SESEWaitingQueue.EXCEPTION){
4292 output.println(" INITIALIZEBUF(runningSESE->memoryQueueArray["
4295 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2
4297 WaitingElement waitingElement = (WaitingElement) iterator2
4299 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
4300 output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
4301 + waitingElement.getStatus()
4302 + ", &(seseToIssue->common));");
4304 TempDescriptor td = waitingElement
4306 // decide whether waiting element is dynamic or
4308 if (fsen.getDynamicInVarSet().contains(td)) {
4309 // dynamic in-var case
4310 output.println(" pointer=seseToIssue->"
4311 + waitingElement.getDynID()
4312 + "_srcSESE+seseToIssue->"
4313 + waitingElement.getDynID()
4316 .println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
4319 + ", &(seseToIssue->common), pointer );");
4320 } else if (fsen.getStaticInVarSet()
4322 // static in-var case
4323 VariableSourceToken vst = fsen
4324 .getStaticInVarSrc(td);
4327 String srcId = "SESE_"
4329 .getPrettyIdentifier()
4330 + vst.getSESE().getIdentifier()
4331 + "_" + vst.getAge();
4333 .println(" pointer=(void*)&seseToIssue->"
4340 .println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
4343 + ", &(seseToIssue->common), pointer );");
4348 .println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
4351 + ", &(seseToIssue->common), (void*)&seseToIssue->"
4352 + waitingElement.getDynID()
4357 .println(" rentry->queue=runningSESE->memoryQueueArray["
4358 + waitingElement.getQueueID()
4361 if(enqueueType==SESEWaitingQueue.NORMAL){
4363 .println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4365 .println(" if(ADDRENTRY(runningSESE->memoryQueueArray["
4366 + waitingElement.getQueueID()
4367 + "],rentry)==NOTREADY){");
4368 output.println(" ++(localCount);");
4369 output.println(" } ");
4372 .println(" ADDRENTRYTOBUF(runningSESE->memoryQueueArray["
4373 + waitingElement.getQueueID()
4377 if(enqueueType!=SESEWaitingQueue.NORMAL){
4378 output.println(" localCount+=RESOLVEBUF(runningSESE->memoryQueueArray["
4379 + queueID+ "],&seseToIssue->common);");
4382 output.println(" }");
4389 if( state.COREPROF ) {
4390 output.println("#ifdef CP_EVENTID_PREPAREMEMQ");
4391 output.println(" CP_LOGEVENT( CP_EVENTID_PREPAREMEMQ, CP_EVENTTYPE_END );");
4392 output.println("#endif");
4395 // Enqueue Task Record
4397 output.println(" enqueueTR(TRqueue, (void *)seseToIssue);");
4400 // if there were no outstanding dependencies, issue here
4401 output.println(" if( atomic_sub_and_test(10000-localCount,&(seseToIssue->common.unresolvedDependencies) ) ) {");
4402 output.println(" workScheduleSubmit( (void*)seseToIssue );");
4403 output.println(" }");
4407 if( state.COREPROF ) {
4408 output.println("#ifdef CP_EVENTID_TASKDISPATCH");
4409 output.println(" CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_END );");
4410 output.println("#endif");
4413 output.println(" }");
4417 void dispatchMEMRC(FlatMethod fm, LocalityBinding lb, FlatSESEEnterNode fsen, PrintWriter output) {
4418 FlatSESEEnterNode parent = fsen.getParent();
4419 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(parent);
4420 if (graph != null && graph.hasConflictEdge()) {
4421 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
4422 Analysis.OoOJava.SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet);
4423 if(seseWaitingQueue.getWaitingElementSize()>0) {
4424 output.println(" {");
4425 output.println(" REntry* rentry=NULL;");
4426 output.println(" INTPTR* pointer=NULL;");
4427 output.println(" seseToIssue->common.rentryIdx=0;");
4428 output.println(" int dispCount;");
4429 Vector<TempDescriptor> invars=fsen.getInVarsForDynamicCoarseConflictResolution();
4430 System.out.println(fm.getMethod()+"["+invars+"]");
4431 for(int i=0;i<invars.size();i++) {
4432 TempDescriptor td=invars.get(i);
4433 Set<Analysis.OoOJava.WaitingElement> weset=seseWaitingQueue.getWaitingElementSet(td);
4435 System.out.println("ERROR:"+td+" "+fsen+" "+fm.getMethod());
4436 int numqueues=weset.size();
4437 output.println(" seseToIssue->rcrRecords["+i+"].flag="+numqueues+";");
4438 output.println(" dispCount=0;");
4439 for(Iterator<Analysis.OoOJava.WaitingElement> wtit=weset.iterator();wtit.hasNext();) {
4440 Analysis.OoOJava.WaitingElement waitingElement=wtit.next();
4441 int queueID=waitingElement.getQueueID();
4442 assert(waitingElement.getStatus()>=ConflictNode.COARSE);
4443 output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "]," + waitingElement.getStatus() + ", &(seseToIssue->common));");
4444 output.println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4445 output.println(" rentry->queue=runningSESE->memoryQueueArray[" + waitingElement.getQueueID()+"];");
4446 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "],rentry)==READY) {");
4447 output.println(" dispCount++;");
4448 output.println(" }");
4450 output.println(" if(!dispCount || !atomic_sub_and_test(dispCount,&(seseToIssue->rcrRecords["+i+"].flag)))");
4451 output.println(" localCount++;");
4452 if (fsen.getDynamicInVarSet().contains(td)) {
4453 // dynamic in-var case
4454 //output.println(" pointer=seseToIssue->" + waitingElement.getDynID()+ "_srcSESE+seseToIssue->"+ waitingElement.getDynID()+ "_srcOffset;");
4455 //output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", &(seseToIssue->common), pointer );");
4458 output.println(" }");
4463 public void generateFlatSESEExitNode( FlatMethod fm,
4465 FlatSESEExitNode fsexn,
4466 PrintWriter output) {
4468 // if MLP flag is off, okay that SESE nodes are in IR graph,
4469 // just skip over them and code generates exactly the same
4470 if( ! (state.MLP || state.OOOJAVA) ) {
4474 // get the enter node for this exit that has meta data embedded
4475 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
4477 // there may be an SESE in an unreachable method, skip over
4478 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
4479 (state.OOOJAVA && !oooa.getAllSESEs().contains( fsen ))
4484 // also, if we have encountered a placeholder, just jump it
4485 if( fsen.getIsCallerSESEplaceholder() ) {
4489 if( state.COREPROF ) {
4490 output.println("#ifdef CP_EVENTID_TASKEXECUTE");
4491 output.println(" CP_LOGEVENT( CP_EVENTID_TASKEXECUTE, CP_EVENTTYPE_END );");
4492 output.println("#endif");
4495 output.println(" /* SESE exiting */");
4497 if( state.COREPROF ) {
4498 output.println("#ifdef CP_EVENTID_TASKRETIRE");
4499 output.println(" CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_BEGIN );");
4500 output.println("#endif");
4504 // this SESE cannot be done until all of its children are done
4505 // so grab your own lock with the condition variable for watching
4506 // that the number of your running children is greater than zero
4507 output.println(" atomic_add(childSESE, &runningSESE->numRunningChildren);");
4508 output.println(" pthread_mutex_lock( &(runningSESE->lock) );");
4509 output.println(" if( runningSESE->numRunningChildren > 0 ) {");
4510 output.println(" stopforgc( (struct garbagelist *)&___locals___ );");
4511 output.println(" do {");
4512 output.println(" pthread_cond_wait( &(runningSESE->runningChildrenCond), &(runningSESE->lock) );");
4513 output.println(" } while( runningSESE->numRunningChildren > 0 );");
4514 output.println(" restartaftergc();");
4515 output.println(" }");
4518 // copy out-set from local temps into the sese record
4519 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
4520 while( itr.hasNext() ) {
4521 TempDescriptor temp = itr.next();
4523 // only have to do this for primitives non-arrays
4525 temp.getType().isPrimitive() && !temp.getType().isArray()
4531 // have to determine the context enclosing this sese
4532 boolean useParentContext = false;
4534 if( (state.MLP &&fsen != mlpa.getMainSESE()) ||
4535 (state.OOOJAVA &&fsen != oooa.getMainSESE())
4537 assert fsen.getParent() != null;
4538 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
4539 useParentContext = true;
4544 if( useParentContext ) {
4545 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
4547 from = generateTemp( fsen.getfmEnclosing(), temp, null );
4550 output.println(" "+paramsprefix+
4551 "->"+temp.getSafeSymbol()+
4555 // mark yourself done, your task data is now read-only
4556 output.println(" runningSESE->doneExecuting = TRUE;");
4558 // if parent is stalling on you, let them know you're done
4559 if( (state.MLP && fsexn.getFlatEnter() != mlpa.getMainSESE()) ||
4560 (state.OOOJAVA && fsexn.getFlatEnter() != oooa.getMainSESE())
4562 output.println(" if( runningSESE->parentsStallSem != NULL ) {");
4563 output.println(" psem_give( runningSESE->parentsStallSem );");
4564 output.println(" }");
4567 output.println(" pthread_mutex_unlock( &(runningSESE->lock) );");
4569 // decrement dependency count for all SESE's on your forwarding list
4572 output.println(" while( !isEmpty( &runningSESE->forwardList ) ) {");
4573 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( &runningSESE->forwardList );");
4576 output.println(" if(consumer->rentryIdx>0){");
4577 output.println(" // resolved null pointer");
4578 output.println(" int idx;");
4579 output.println(" for(idx=0;idx<consumer->rentryIdx;idx++){");
4580 output.println(" resolvePointer(consumer->rentryArray[idx]);");
4581 output.println(" }");
4582 output.println(" }");
4584 output.println(" if( atomic_sub_and_test( 1, &(consumer->unresolvedDependencies) ) ){");
4585 output.println(" workScheduleSubmit( (void*)consumer );");
4586 output.println(" }");
4587 output.println(" }");
4591 // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
4592 if((state.MLP && fsen != mlpa.getMainSESE()) ||
4593 (state.OOOJAVA && fsen != oooa.getMainSESE())) {
4595 output.println(" /* check memory dependency*/");
4596 output.println(" {");
4597 output.println(" int idx;");
4598 output.println(" for(idx=0;idx<___params___->common.rentryIdx;idx++){");
4599 output.println(" REntry* re=___params___->common.rentryArray[idx];");
4600 output.println(" RETIRERENTRY(re->queue,re);");
4601 output.println(" }");
4602 output.println(" }");
4606 if (state.RCR&&fsen.getDynamicInVarSet().size()>0) {
4607 /* Make sure the running SESE is finished */
4608 output.println(" if (unlikely(runningSESE->rcrstatus!=0)) {");
4609 output.println(" if(!CAS(&runningSESE->rcrstatus,1,0)) {");
4610 output.println(" while(runningSESE->rcrstatus) {");
4611 output.println(" BARRIER();");
4612 output.println(" sched_yield();");
4613 output.println(" }");
4614 output.println(" }");
4615 output.println(" }");
4616 output.println("{");
4617 output.println(" int idx,idx2;");
4618 if (fsen.getDynamicInVarSet().size()==1) {
4619 output.println(" idx=0; {");
4621 output.println(" for(idx=0;idx<"+fsen.getDynamicInVarSet().size()+";idx++){");
4623 output.println(" struct rcrRecord *rec="+paramsprefix+"->rcrRecords[idx];");
4624 output.println(" while(rec!=NULL) {");
4625 output.println(" for(idx2=0;idx2<rec->index;idx2++) {");
4626 output.println(" rcr_RETIREHASHTABLE(allHashStructures[0],rec,rec->array[idx2], (BinItem_rcr *) rcr->ptrarray[idx2]);");
4627 output.println(" }");//exit idx2 for loop
4628 output.println(" rec=rec->next;");
4629 output.println(" }");//exit rec while loop
4630 output.println(" }");//exit idx for loop
4631 output.println("}");
4635 // a task has variables to track static/dynamic instances
4636 // that serve as sources, release the parent's ref of each
4637 // non-null var of these types
4638 output.println(" // releasing static SESEs");
4639 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4640 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
4641 while( pItr.hasNext() ) {
4642 SESEandAgePair pair = pItr.next();
4643 output.println(" if( "+pair+" != NULL ) {");
4644 output.println(" RELEASE_REFERENCE_TO( "+pair+" );");
4645 output.println(" }");
4647 output.println(" // releasing dynamic variable sources");
4648 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
4649 while( dynSrcItr.hasNext() ) {
4650 TempDescriptor dynSrcVar = dynSrcItr.next();
4651 output.println(" if( "+dynSrcVar+"_srcSESE != NULL ) {");
4652 output.println(" RELEASE_REFERENCE_TO( "+dynSrcVar+"_srcSESE );");
4653 output.println(" }");
4655 // destroy this task's mempool if it is not a leaf task
4656 if( !fsen.getIsLeafSESE() ) {
4657 output.println(" pooldestroy( runningSESE->taskRecordMemPool );");
4659 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4662 output.println("{");
4663 output.println("SESEcommon *myparent=runningSESE->parent;");
4665 // if this is not the Main sese (which has no parent) then return
4666 // THIS task's record to the PARENT'S task record pool, and only if
4667 // the reference count is now zero
4668 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4669 (state.OOOJAVA && fsen != oooa.getMainSESE())
4671 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4672 output.println(" RELEASE_REFERENCE_TO( runningSESE );");
4673 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4675 // the main task has no parent, just free its record
4676 output.println(" mlpFreeSESErecord( runningSESE );");
4680 // last of all, decrement your parent's number of running children
4681 output.println(" if( myparent != NULL ) {");
4682 output.println(" if( atomic_sub_and_test( 1, &(myparent->numRunningChildren) ) ) {");
4683 output.println(" pthread_mutex_lock ( &(myparent->lock) );");
4684 output.println(" pthread_cond_signal ( &(myparent->runningChildrenCond) );");
4685 output.println(" pthread_mutex_unlock( &(myparent->lock) );");
4686 output.println(" }");
4687 output.println(" }");
4689 output.println("}");
4691 // as this thread is wrapping up the task, make sure the thread-local var
4692 // for the currently running task record references an invalid task
4693 output.println(" runningSESE = (SESEcommon*) 0x1;");
4695 if( state.COREPROF ) {
4696 output.println("#ifdef CP_EVENTID_TASKRETIRE");
4697 output.println(" CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_END );");
4698 output.println("#endif");
4702 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
4704 FlatWriteDynamicVarNode fwdvn,
4707 if( !(state.MLP || state.OOOJAVA) ) {
4708 // should node should not be in an IR graph if the
4709 // MLP flag is not set
4710 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
4713 Hashtable<TempDescriptor, VSTWrapper> writeDynamic = fwdvn.getVar2src();
4715 assert writeDynamic != null;
4717 Iterator wdItr = writeDynamic.entrySet().iterator();
4718 while( wdItr.hasNext() ) {
4719 Map.Entry me = (Map.Entry) wdItr.next();
4720 TempDescriptor refVar = (TempDescriptor) me.getKey();
4721 VSTWrapper vstW = (VSTWrapper) me.getValue();
4722 VariableSourceToken vst = vstW.vst;
4724 output.println(" {");
4725 output.println(" SESEcommon* oldSrc = "+refVar+"_srcSESE;");
4728 // if there is no given source, this variable is ready so
4729 // mark src pointer NULL to signify that the var is up-to-date
4730 output.println(" "+refVar+"_srcSESE = NULL;");
4732 // otherwise we track where it will come from
4733 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
4734 output.println(" "+refVar+"_srcSESE = "+instance+";");
4735 output.println(" "+refVar+"_srcOffset = (INTPTR) &((("+
4736 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
4739 // no matter what we did above, track reference count of whatever
4740 // this variable pointed to, do release last in case we're just
4741 // copying the same value in because 1->2->1 is safe but ref count
4742 // 1->0->1 has a window where it looks like it should be free'd
4743 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4744 output.println(" if( "+refVar+"_srcSESE != NULL ) {");
4745 output.println(" ADD_REFERENCE_TO( "+refVar+"_srcSESE );");
4746 output.println(" }");
4747 output.println(" if( oldSrc != NULL ) {");
4748 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
4749 output.println(" }");
4750 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4752 output.println(" }");
4757 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
4758 if (state.CONSCHECK) {
4759 String specname=fcn.getSpec();
4760 String varname="repairstate___";
4761 output.println("{");
4762 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
4764 TempDescriptor[] temps=fcn.getTemps();
4765 String[] vars=fcn.getVars();
4766 for(int i=0; i<temps.length; i++) {
4767 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
4770 output.println("if (doanalysis"+specname+"("+varname+")) {");
4771 output.println("free"+specname+"_state("+varname+");");
4772 output.println("} else {");
4773 output.println("/* Bad invariant */");
4774 output.println("free"+specname+"_state("+varname+");");
4775 output.println("abort_task();");
4776 output.println("}");
4777 output.println("}");
4781 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
4783 MethodDescriptor md=fc.getMethod();
4784 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
4785 ClassDescriptor cn=md.getClassDesc();
4787 // if the called method is a static block or a static method or a constructor
4788 // need to check if it can be invoked inside some static block
4790 // TODO add version for normal Java later
4791 if((md.isStatic() || md.isStaticBlock() || md.isConstructor()) &&
4792 ((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic()))) {
4793 if(!md.isInvokedByStatic()) {
4794 System.err.println("Error: a method that is invoked inside a static block is not tagged!");
4796 // is a static block or is invoked in some static block
4797 ClassDescriptor cd = fm.getMethod().getClassDesc();
4799 // the same class, do nothing
4800 // TODO may want to invoke static field initialization here
4802 if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
4803 // need to check if the class' static fields have been initialized and/or
4804 // its static blocks have been executed
4805 output.println("#ifdef MGC_STATIC_INIT_CHECK");
4806 output.println("if(global_defs_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
4807 if(cn.getNumStaticFields() != 0) {
4808 // TODO add static field initialization here
4810 if(cn.getNumStaticBlocks() != 0) {
4811 MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
4812 output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
4814 output.println(" global_defs_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
4816 output.println("}");
4817 output.println("#endif // MGC_STATIC_INIT_CHECK");
4823 output.println("{");
4824 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4826 LocalityBinding fclb=locality.getBinding(lb, fc);
4827 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4829 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4830 output.print(objectparams.numPointers());
4831 output.print(", "+localsprefixaddr);
4832 if (md.getThis()!=null) {
4834 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
4836 if (fc.getThis()!=null&&md.getThis()==null) {
4837 System.out.println("WARNING!!!!!!!!!!!!");
4838 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
4842 for(int i=0; i<fc.numArgs(); i++) {
4843 Descriptor var=md.getParameter(i);
4844 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4845 if (objectparams.isParamPtr(paramtemp)) {
4846 TempDescriptor targ=fc.getArg(i);
4848 TypeDescriptor td=md.getParamType(i);
4850 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4852 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4855 output.println("};");
4860 if (fc.getReturnTemp()!=null)
4861 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
4863 /* Do we need to do virtual dispatch? */
4864 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
4867 LocalityBinding fclb=locality.getBinding(lb, fc);
4868 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4870 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4875 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4876 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4878 output.print(md.getReturnType().getSafeSymbol()+" ");
4879 output.print("(*)(");
4881 boolean printcomma=false;
4882 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4884 LocalityBinding fclb=locality.getBinding(lb, fc);
4885 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4887 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4891 for(int i=0; i<objectparams.numPrimitives(); i++) {
4892 TempDescriptor temp=objectparams.getPrimitive(i);
4896 if (temp.getType().isClass()||temp.getType().isArray())
4897 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
4899 output.print(temp.getType().getSafeSymbol());
4904 LocalityBinding fclb=locality.getBinding(lb, fc);
4905 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
4907 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
4911 boolean needcomma=false;
4912 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4913 output.print("&__parameterlist__");
4917 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4918 if (fc.getThis()!=null) {
4919 TypeDescriptor ptd=null;
4920 if(md.getThis() != null) {
4921 ptd = md.getThis().getType();
4923 ptd = fc.getThis().getType();
4927 if (ptd.isClass()&&!ptd.isArray())
4928 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4929 output.print(generateTemp(fm,fc.getThis(),lb));
4934 for(int i=0; i<fc.numArgs(); i++) {
4935 Descriptor var=md.getParameter(i);
4936 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4937 if (objectparams.isParamPrim(paramtemp)) {
4938 TempDescriptor targ=fc.getArg(i);
4942 TypeDescriptor ptd=md.getParamType(i);
4943 if (ptd.isClass()&&!ptd.isArray())
4944 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4945 output.print(generateTemp(fm, targ,lb));
4949 output.println(");");
4950 output.println(" }");
4953 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
4954 Set subclasses=typeutil.getSubClasses(thiscd);
4955 if (subclasses==null)
4957 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
4958 ClassDescriptor cd=(ClassDescriptor)classit.next();
4959 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
4960 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
4961 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
4962 if (md.matches(matchmd))
4969 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
4970 if (state.SINGLETM) {
4971 //single machine transactional memory case
4972 String field=ffn.getField().getSafeSymbol();
4973 String src=generateTemp(fm, ffn.getSrc(),lb);
4974 String dst=generateTemp(fm, ffn.getDst(),lb);
4976 output.println(dst+"="+ src +"->"+field+ ";");
4977 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
4978 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
4979 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
4980 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
4981 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
4982 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
4983 if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
4984 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4986 output.println("TRANSREADRD("+dst+", "+dst+");");
4989 } else if (state.DSM) {
4990 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
4991 if (status==LocalityAnalysis.GLOBAL) {
4992 String field=ffn.getField().getSafeSymbol();
4993 String src=generateTemp(fm, ffn.getSrc(),lb);
4994 String dst=generateTemp(fm, ffn.getDst(),lb);
4996 if (ffn.getField().getType().isPtr()) {
4998 //TODO: Uncomment this when we have runtime support
4999 //if (ffn.getSrc()==ffn.getDst()) {
5000 //output.println("{");
5001 //output.println("void * temp="+src+";");
5002 //output.println("if (temp&0x1) {");
5003 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
5004 //output.println(src+"->"+field+"="+temp+";");
5005 //output.println("}");
5006 //output.println(dst+"=temp;");
5007 //output.println("}");
5009 output.println(dst+"="+ src +"->"+field+ ";");
5010 //output.println("if ("+dst+"&0x1) {");
5011 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
5012 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
5013 //output.println(src+"->"+field+"="+src+"->"+field+";");
5014 //output.println("}");
5017 output.println(dst+"="+ src+"->"+field+";");
5019 } else if (status==LocalityAnalysis.LOCAL) {
5020 if (ffn.getField().getType().isPtr()&&
5021 ffn.getField().isGlobal()) {
5022 String field=ffn.getField().getSafeSymbol();
5023 String src=generateTemp(fm, ffn.getSrc(),lb);
5024 String dst=generateTemp(fm, ffn.getDst(),lb);
5025 output.println(dst+"="+ src +"->"+field+ ";");
5026 if (locality.getAtomic(lb).get(ffn).intValue()>0)
5027 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
5028 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
5030 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
5031 } else if (status==LocalityAnalysis.EITHER) {
5032 //Code is reading from a null pointer
5033 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
5034 output.println("#ifndef RAW");
5035 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
5036 output.println("#endif");
5037 //This should throw a suitable null pointer error
5038 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
5040 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
5042 // DEBUG if(!ffn.getDst().getType().isPrimitive()){
5043 // DEBUG output.println("within((void*)"+generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+");");
5046 // TODO add version for normal Java later
5047 if(ffn.getField().isStatic()) {
5049 if((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())) {
5050 // is a static block or is invoked in some static block
5051 ClassDescriptor cd = fm.getMethod().getClassDesc();
5052 ClassDescriptor cn = ffn.getSrc().getType().getClassDesc();
5054 // the same class, do nothing
5055 // TODO may want to invoke static field initialization here
5057 if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
5058 // need to check if the class' static fields have been initialized and/or
5059 // its static blocks have been executed
5060 output.println("#ifdef MGC_STATIC_INIT_CHECK");
5061 output.println("if(global_defs_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
5062 if(cn.getNumStaticFields() != 0) {
5063 // TODO add static field initialization here
5065 if(cn.getNumStaticBlocks() != 0) {
5066 MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
5067 output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
5069 output.println(" global_defs_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
5071 output.println("}");
5072 output.println("#endif // MGC_STATIC_INIT_CHECK");
5076 // redirect to the global_defs_p structure
5077 if(ffn.getSrc().getType().isStatic()) {
5078 // reference to the static field with Class name
5079 output.println(generateTemp(fm, ffn.getDst(),lb)+"=global_defs_p->"+ ffn.getSrc().getType().getClassDesc().getSafeSymbol()+ffn.getField().getSafeSymbol()+";");
5081 output.println(generateTemp(fm, ffn.getDst(),lb)+"=*"+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
5083 //output.println(generateTemp(fm, ffn.getDst(),lb)+"=global_defs_p->"+ffn.getSrc().getType().getClassDesc().getSafeSymbol()+"->"+ ffn.getField().getSafeSymbol()+";");
5085 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
5088 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
5094 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
5095 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
5096 throw new Error("Can't set array length");
5097 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
5098 //Single Machine Transaction Case
5099 boolean srcptr=fsfn.getSrc().getType().isPtr();
5100 String src=generateTemp(fm,fsfn.getSrc(),lb);
5101 String dst=generateTemp(fm,fsfn.getDst(),lb);
5102 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
5103 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
5104 output.println("{");
5105 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
5106 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
5107 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
5109 output.println("INTPTR srcoid=(INTPTR)"+src+";");
5112 if (wb.needBarrier(fsfn)&&
5113 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
5114 if (state.EVENTMONITOR) {
5115 output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
5117 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
5119 if (srcptr&!fsfn.getSrc().getType().isNull()) {
5120 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
5121 output.println("}");
5123 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
5125 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
5126 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
5127 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
5128 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
5130 String src=generateTemp(fm,fsfn.getSrc(),lb);
5131 String dst=generateTemp(fm,fsfn.getDst(),lb);
5133 output.println("{");
5134 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
5136 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
5139 if (wb.needBarrier(fsfn))
5140 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
5142 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
5144 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
5145 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
5146 /** Check if we need to copy */
5147 output.println("if(!"+dst+"->"+localcopystr+") {");
5148 /* Link object into list */
5149 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5150 output.println(revertptr+"=revertlist;");
5151 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
5152 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
5154 output.println("COPY_OBJ("+dst+");");
5155 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
5156 output.println("revertlist=(struct ___Object___ *)"+dst+";");
5157 output.println("}");
5159 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
5161 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
5162 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
5163 //writing to a null...bad
5164 output.println("if ("+dst+") {");
5165 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
5167 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
5169 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
5172 output.println("}");
5175 if (state.FASTCHECK) {
5176 String dst=generateTemp(fm, fsfn.getDst(),lb);
5177 output.println("if(!"+dst+"->"+localcopystr+") {");
5178 /* Link object into list */
5179 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
5180 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
5182 output.println("COPY_OBJ("+dst+");");
5183 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
5184 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
5185 output.println("}");
5188 // DEBUG if(!fsfn.getField().getType().isPrimitive()){
5189 // DEBUG output.println("within((void*)"+generateTemp(fm,fsfn.getSrc(),lb)+");");
5192 // TODO add version for normal Java later
5193 if(fsfn.getField().isStatic()) {
5195 if((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())) {
5196 // is a static block or is invoked in some static block
5197 ClassDescriptor cd = fm.getMethod().getClassDesc();
5198 ClassDescriptor cn = fsfn.getDst().getType().getClassDesc();
5200 // the same class, do nothing
5201 // TODO may want to invoke static field initialization here
5203 if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
5204 // need to check if the class' static fields have been initialized and/or
5205 // its static blocks have been executed
5206 output.println("#ifdef MGC_STATIC_INIT_CHECK");
5207 output.println("if(global_defs_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
5208 if(cn.getNumStaticFields() != 0) {
5209 // TODO add static field initialization here
5211 if(cn.getNumStaticBlocks() != 0) {
5212 MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
5213 output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
5215 output.println(" global_defs_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
5217 output.println("}");
5218 output.println("#endif // MGC_STATIC_INIT_CHECK");
5222 // redirect to the global_defs_p structure
5223 if(fsfn.getDst().getType().isStatic()) {
5224 // reference to the static field with Class name
5225 output.println("global_defs_p->" + fsfn.getDst().getType().getClassDesc().getSafeSymbol() + fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
5227 output.println("*"+generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
5230 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
5233 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
5238 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
5239 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
5242 if (elementtype.isArray()||elementtype.isClass())
5245 type=elementtype.getSafeSymbol()+" ";
5247 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
5248 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
5249 output.println("failedboundschk();");
5251 if (state.SINGLETM) {
5252 //Single machine transaction case
5253 String dst=generateTemp(fm, fen.getDst(),lb);
5254 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))) {
5255 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
5257 output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
5260 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
5261 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
5262 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
5263 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
5264 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
5265 if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
5266 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
5268 output.println("TRANSREADRD("+dst+", "+dst+");");
5271 } else if (state.DSM) {
5272 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
5273 if (status==LocalityAnalysis.GLOBAL) {
5274 String dst=generateTemp(fm, fen.getDst(),lb);
5275 if (elementtype.isPtr()) {
5276 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
5277 //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
5278 output.println("TRANSREAD("+dst+", "+dst+");");
5280 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
5282 } else if (status==LocalityAnalysis.LOCAL) {
5283 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
5284 } else if (status==LocalityAnalysis.EITHER) {
5285 //Code is reading from a null pointer
5286 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
5287 output.println("#ifndef RAW");
5288 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
5289 output.println("#endif");
5290 //This should throw a suitable null pointer error
5291 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
5293 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
5295 // DEBUG output.println("within((void*)"+generateTemp(fm,fen.getSrc(),lb)+");");
5296 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
5300 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
5301 //TODO: need dynamic check to make sure this assignment is actually legal
5302 //Because Object[] could actually be something more specific...ie. Integer[]
5304 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
5307 if (elementtype.isArray()||elementtype.isClass())
5310 type=elementtype.getSafeSymbol()+" ";
5312 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
5313 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
5314 output.println("failedboundschk();");
5317 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
5318 //Transaction set element case
5319 if (wb.needBarrier(fsen)&&
5320 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
5321 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
5323 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
5324 output.println("{");
5325 String src=generateTemp(fm, fsen.getSrc(), lb);
5326 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
5327 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
5328 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
5330 output.println("INTPTR srcoid=(INTPTR)"+src+";");
5332 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
5333 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
5335 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
5337 output.println("}");
5339 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
5340 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
5342 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
5345 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
5346 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
5347 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
5348 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
5349 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
5350 boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
5353 if (wb.needBarrier(fsen))
5354 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
5355 } else if (dstlocal) {
5356 /** Check if we need to copy */
5357 String dst=generateTemp(fm, fsen.getDst(),lb);
5358 output.println("if(!"+dst+"->"+localcopystr+") {");
5359 /* Link object into list */
5360 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5361 output.println(revertptr+"=revertlist;");
5362 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
5363 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
5365 output.println("COPY_OBJ("+dst+");");
5366 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
5367 output.println("revertlist=(struct ___Object___ *)"+dst+";");
5368 output.println("}");
5370 System.out.println("Node: "+fsen);
5371 System.out.println(lb);
5372 System.out.println("statusdst="+statusdst);
5373 System.out.println(fm.printMethod());
5374 throw new Error("Unknown array type");
5377 output.println("{");
5378 String src=generateTemp(fm, fsen.getSrc(), lb);
5379 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
5380 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
5381 output.println("}");
5383 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
5386 if (state.FASTCHECK) {
5387 String dst=generateTemp(fm, fsen.getDst(),lb);
5388 output.println("if(!"+dst+"->"+localcopystr+") {");
5389 /* Link object into list */
5390 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
5391 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
5393 output.println("COPY_OBJ("+dst+");");
5394 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
5395 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
5396 output.println("}");
5398 // DEBUG output.println("within((void*)"+generateTemp(fm,fsen.getDst(),lb)+");");
5399 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
5403 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
5404 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
5405 //Stash pointer in case of GC
5406 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5407 output.println(revertptr+"=revertlist;");
5409 if (state.SINGLETM) {
5410 if (fn.getType().isArray()) {
5411 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
5412 if (locality.getAtomic(lb).get(fn).intValue()>0) {
5413 //inside transaction
5414 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5416 //outside transaction
5417 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5420 if (locality.getAtomic(lb).get(fn).intValue()>0) {
5421 //inside transaction
5422 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
5424 //outside transaction
5425 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
5428 } else if (fn.getType().isArray()) {
5429 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
5430 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
5431 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5432 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5433 if(this.state.MLP || state.OOOJAVA){
5434 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray_mlp("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
5435 output.println(" oid += numWorkSchedWorkers;");
5437 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5440 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5443 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
5444 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
5445 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5446 if (this.state.MLP || state.OOOJAVA){
5447 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new_mlp("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
5448 output.println(" oid += numWorkSchedWorkers;");
5450 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
5453 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
5456 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
5457 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5458 String dst=generateTemp(fm,fn.getDst(),lb);
5459 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
5460 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
5461 output.println("revertlist=(struct ___Object___ *)"+dst+";");
5463 if (state.FASTCHECK) {
5464 String dst=generateTemp(fm,fn.getDst(),lb);
5465 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
5466 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
5467 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
5471 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
5472 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5473 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
5475 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
5479 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
5480 if (fon.getRight()!=null) {
5481 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
5482 if (fon.getLeft().getType().isLong())
5483 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
5485 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
5487 } else if (dc!=null) {
5488 output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
5489 if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
5490 output.print("(void *)");
5491 if (dc.getNeedLeftSrcTrans(lb, fon))
5492 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
5494 output.print(generateTemp(fm, fon.getLeft(),lb));
5495 output.print(")"+fon.getOp().toString()+"(");
5496 if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
5497 output.print("(void *)");
5498 if (dc.getNeedRightSrcTrans(lb, fon))
5499 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
5501 output.println(generateTemp(fm,fon.getRight(),lb)+");");
5503 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
5504 } else if (fon.getOp().getOp()==Operation.ASSIGN)
5505 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
5506 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
5507 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
5508 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
5509 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
5510 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
5511 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
5512 else if (fon.getOp().getOp()==Operation.COMP)
5513 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
5514 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
5515 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
5517 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
5520 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
5521 /* TODO: Do type check here */
5522 if (fcn.getType().isArray()) {
5523 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
5524 } else if (fcn.getType().isClass())
5525 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
5527 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
5530 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
5531 if (fln.getValue()==null)
5532 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
5533 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
5534 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5535 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
5536 //Stash pointer in case of GC
5537 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5538 output.println(revertptr+"=revertlist;");
5540 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
5541 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
5542 //Stash pointer in case of GC
5543 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5544 output.println("revertlist="+revertptr+";");
5547 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
5549 } else if (fln.getType().isBoolean()) {
5550 if (((Boolean)fln.getValue()).booleanValue())
5551 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
5553 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
5554 } else if (fln.getType().isChar()) {
5555 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
5556 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
5557 } else if (fln.getType().isLong()) {
5558 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
5560 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
5563 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
5565 // TODO add version for normal Java later
5566 if((fm.getMethod() != null) && (fm.getMethod().isStaticBlock())) {
5567 // a static block, check if it has been executed
5568 output.println(" global_defs_p->" + fm.getMethod().getClassDesc().getSafeSymbol()+"static_block_exe_flag = 1;");
5572 if (frn.getReturnTemp()!=null) {
5573 if (frn.getReturnTemp().getType().isPtr())
5574 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
5576 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
5578 output.println("return;");
5582 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
5585 //only record if this group has more than one exit
5586 if (branchanalysis.numJumps(fcb)>1) {
5587 left=branchanalysis.jumpValue(fcb, 0);
5588 right=branchanalysis.jumpValue(fcb, 1);
5590 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
5592 output.println("STOREBRANCH("+right+");");
5593 output.println("goto "+label+";");
5594 output.println("}");
5596 output.println("STOREBRANCH("+left+");");
5599 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
5600 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
5603 /** This method generates header information for the method or
5604 * task referenced by the Descriptor des. */
5605 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
5606 generateHeader(fm, lb, des, output, false);
5609 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
5611 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
5612 MethodDescriptor md=null;
5613 TaskDescriptor task=null;
5614 if (des instanceof MethodDescriptor)
5615 md=(MethodDescriptor) des;
5617 task=(TaskDescriptor) des;
5619 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
5621 if (md!=null&&md.getReturnType()!=null) {
5622 if (md.getReturnType().isClass()||md.getReturnType().isArray())
5623 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
5625 output.print(md.getReturnType().getSafeSymbol()+" ");
5627 //catch the constructor case
5628 output.print("void ");
5630 if (state.DSM||state.SINGLETM) {
5631 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5633 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5635 output.print(task.getSafeSymbol()+"(");
5637 boolean printcomma=false;
5638 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5640 if (state.DSM||state.SINGLETM) {
5641 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5643 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5645 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
5651 for(int i=0; i<objectparams.numPrimitives(); i++) {
5652 TempDescriptor temp=objectparams.getPrimitive(i);
5656 if (temp.getType().isClass()||temp.getType().isArray())
5657 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
5659 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
5661 output.println(") {");
5662 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
5663 /* Imprecise Task */
5664 output.println("void * parameterarray[]) {");
5665 /* Unpack variables */
5666 for(int i=0; i<objectparams.numPrimitives(); i++) {
5667 TempDescriptor temp=objectparams.getPrimitive(i);
5668 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
5670 for(int i=0; i<fm.numTags(); i++) {
5671 TempDescriptor temp=fm.getTag(i);
5672 int offset=i+objectparams.numPrimitives();
5673 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
5676 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
5677 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
5678 } else output.println(") {");
5681 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
5682 output.println("/* FlatFlagActionNode */");
5685 /* Process tag changes */
5686 Relation tagsettable=new Relation();
5687 Relation tagcleartable=new Relation();
5689 Iterator tagsit=ffan.getTempTagPairs();
5690 while (tagsit.hasNext()) {
5691 TempTagPair ttp=(TempTagPair) tagsit.next();
5692 TempDescriptor objtmp=ttp.getTemp();
5693 TagDescriptor tag=ttp.getTag();
5694 TempDescriptor tagtmp=ttp.getTagTemp();
5695 boolean tagstatus=ffan.getTagChange(ttp);
5697 tagsettable.put(objtmp, tagtmp);
5699 tagcleartable.put(objtmp, tagtmp);
5704 Hashtable flagandtable=new Hashtable();
5705 Hashtable flagortable=new Hashtable();
5707 /* Process flag changes */
5708 Iterator flagsit=ffan.getTempFlagPairs();
5709 while(flagsit.hasNext()) {
5710 TempFlagPair tfp=(TempFlagPair)flagsit.next();
5711 TempDescriptor temp=tfp.getTemp();
5712 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
5713 FlagDescriptor flag=tfp.getFlag();
5715 //Newly allocate objects that don't set any flags case
5716 if (flagortable.containsKey(temp)) {
5720 flagortable.put(temp,new Integer(mask));
5722 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
5723 boolean flagstatus=ffan.getFlagChange(tfp);
5726 if (flagortable.containsKey(temp)) {
5727 mask=((Integer)flagortable.get(temp)).intValue();
5730 flagortable.put(temp,new Integer(mask));
5732 int mask=0xFFFFFFFF;
5733 if (flagandtable.containsKey(temp)) {
5734 mask=((Integer)flagandtable.get(temp)).intValue();
5736 mask&=(0xFFFFFFFF^flagid);
5737 flagandtable.put(temp,new Integer(mask));
5743 HashSet flagtagset=new HashSet();
5744 flagtagset.addAll(flagortable.keySet());
5745 flagtagset.addAll(flagandtable.keySet());
5746 flagtagset.addAll(tagsettable.keySet());
5747 flagtagset.addAll(tagcleartable.keySet());
5749 Iterator ftit=flagtagset.iterator();
5750 while(ftit.hasNext()) {
5751 TempDescriptor temp=(TempDescriptor)ftit.next();
5754 Set tagtmps=tagcleartable.get(temp);
5755 if (tagtmps!=null) {
5756 Iterator tagit=tagtmps.iterator();
5757 while(tagit.hasNext()) {
5758 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5759 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5760 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5762 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5766 tagtmps=tagsettable.get(temp);
5767 if (tagtmps!=null) {
5768 Iterator tagit=tagtmps.iterator();
5769 while(tagit.hasNext()) {
5770 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5771 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5772 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5774 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
5779 int andmask=0xFFFFFFF;
5781 if (flagortable.containsKey(temp))
5782 ormask=((Integer)flagortable.get(temp)).intValue();
5783 if (flagandtable.containsKey(temp))
5784 andmask=((Integer)flagandtable.get(temp)).intValue();
5785 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
5786 generateObjectDistribute(ffan, fm, lb, temp, output);
5790 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
5791 PrintWriter output, int ormask, int andmask) {
5792 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
5793 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5795 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5799 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
5800 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
5803 void generateOptionalHeader(PrintWriter headers) {
5806 headers.println("#include \"task.h\"\n\n");
5807 headers.println("#ifndef _OPTIONAL_STRUCT_");
5808 headers.println("#define _OPTIONAL_STRUCT_");
5810 //STRUCT PREDICATEMEMBER
5811 headers.println("struct predicatemember{");
5812 headers.println("int type;");
5813 headers.println("int numdnfterms;");
5814 headers.println("int * flags;");
5815 headers.println("int numtags;");
5816 headers.println("int * tags;\n};\n\n");
5818 //STRUCT OPTIONALTASKDESCRIPTOR
5819 headers.println("struct optionaltaskdescriptor{");
5820 headers.println("struct taskdescriptor * task;");
5821 headers.println("int index;");
5822 headers.println("int numenterflags;");
5823 headers.println("int * enterflags;");
5824 headers.println("int numpredicatemembers;");
5825 headers.println("struct predicatemember ** predicatememberarray;");
5826 headers.println("};\n\n");
5828 //STRUCT TASKFAILURE
5829 headers.println("struct taskfailure {");
5830 headers.println("struct taskdescriptor * task;");
5831 headers.println("int index;");
5832 headers.println("int numoptionaltaskdescriptors;");
5833 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5835 //STRUCT FSANALYSISWRAPPER
5836 headers.println("struct fsanalysiswrapper{");
5837 headers.println("int flags;");
5838 headers.println("int numtags;");
5839 headers.println("int * tags;");
5840 headers.println("int numtaskfailures;");
5841 headers.println("struct taskfailure ** taskfailurearray;");
5842 headers.println("int numoptionaltaskdescriptors;");
5843 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5845 //STRUCT CLASSANALYSISWRAPPER
5846 headers.println("struct classanalysiswrapper{");
5847 headers.println("int type;");
5848 headers.println("int numotd;");
5849 headers.println("struct optionaltaskdescriptor ** otdarray;");
5850 headers.println("int numfsanalysiswrappers;");
5851 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
5853 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
5855 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
5856 while(taskit.hasNext()) {
5857 TaskDescriptor td=(TaskDescriptor)taskit.next();
5858 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
5863 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
5864 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
5865 int predicateindex = 0;
5866 //iterate through the classes concerned by the predicate
5867 Set c_vard = predicate.vardescriptors;
5868 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
5871 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
5872 VarDescriptor vard = (VarDescriptor)vard_it.next();
5873 TypeDescriptor typed = vard.getType();
5875 //generate for flags
5876 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
5877 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5879 if (fen_hashset!=null) {
5880 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
5881 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
5883 DNFFlag dflag=fen.getDNF();
5884 numberterms+=dflag.size();
5886 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
5888 for(int j=0; j<dflag.size(); j++) {
5890 output.println(",");
5891 Vector term=dflag.get(j);
5894 for(int k=0; k<term.size(); k++) {
5895 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
5896 FlagDescriptor fd=dfa.getFlag();
5897 boolean negated=dfa.getNegated();
5898 int flagid=1<<((Integer)flags.get(fd)).intValue();
5903 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
5908 output.println("};\n");
5911 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
5912 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5915 for(int j=0; j<tagel.numTags(); j++) {
5917 output.println(",");
5918 TempDescriptor tmp=tagel.getTemp(j);
5919 if (!slotnumber.containsKey(tmp)) {
5920 Integer slotint=new Integer(current_slot++);
5921 slotnumber.put(tmp,slotint);
5923 int slot=slotnumber.get(tmp).intValue();
5924 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
5926 numtags = tagel.numTags();
5928 output.println("};");
5930 //store the result into a predicatemember struct
5931 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5932 output.println("/*type*/"+typed.getClassDesc().getId()+",");
5933 output.println("/* number of dnf terms */"+numberterms+",");
5934 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5935 output.println("/* number of tag */"+numtags+",");
5936 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5937 output.println("};\n");
5942 //generate an array that stores the entire predicate
5943 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5944 for( int j = 0; j<predicateindex; j++) {
5945 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5946 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5948 output.println("};\n");
5949 return predicateindex;
5953 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
5954 generateOptionalHeader(headers);
5956 output.println("#include \"optionalstruct.h\"\n\n");
5957 output.println("#include \"stdlib.h\"\n");
5959 HashSet processedcd = new HashSet();
5961 Enumeration e = safeexecution.keys();
5962 while (e.hasMoreElements()) {
5965 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
5966 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
5968 //Generate the struct of optionals
5969 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5970 numotd = c_otd.size();
5971 if(maxotd<numotd) maxotd = numotd;
5972 if( !c_otd.isEmpty() ) {
5973 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5974 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5976 //generate the int arrays for the predicate
5977 Predicate predicate = otd.predicate;
5978 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
5979 TreeSet<Integer> fsset=new TreeSet<Integer>();
5980 //iterate through possible FSes corresponding to
5981 //the state when entering
5983 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
5984 FlagState fs = (FlagState)fses.next();
5986 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5987 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5988 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5991 fsset.add(new Integer(flagid));
5992 //tag information not needed because tag
5993 //changes are not tolerated.
5996 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5997 boolean needcomma=false;
5998 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
6001 output.println(it.next());
6004 output.println("};\n");
6007 //generate optionaltaskdescriptor that actually
6008 //includes exit fses, predicate and the task
6010 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
6011 output.println("&task_"+otd.td.getSafeSymbol()+",");
6012 output.println("/*index*/"+otd.getIndex()+",");
6013 output.println("/*number of enter flags*/"+fsset.size()+",");
6014 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
6015 output.println("/*number of members */"+predicateindex+",");
6016 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
6017 output.println("};\n");
6021 // if there are no optionals, there is no need to build the rest of the struct
6023 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
6024 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
6025 if( !c_otd.isEmpty() ) {
6026 boolean needcomma=false;
6027 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
6028 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
6030 output.println(",");
6032 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
6035 output.println("};\n");
6037 //get all the possible flagstates reachable by an object
6038 Hashtable hashtbtemp = safeexecution.get(cdtemp);
6040 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
6041 fsts.addAll(hashtbtemp.keySet());
6042 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
6043 FlagState fs = (FlagState)fsit.next();
6046 //get the set of OptionalTaskDescriptors corresponding
6047 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
6048 //iterate through the OptionalTaskDescriptors and
6049 //store the pointers to the optionals struct (see on
6050 //top) into an array
6052 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
6053 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
6054 OptionalTaskDescriptor mm = mos.next();
6056 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
6058 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
6061 output.println("};\n");
6063 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
6066 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
6067 FlagDescriptor flagd = (FlagDescriptor)flags.next();
6068 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
6072 //process tag information
6075 boolean first = true;
6076 Enumeration tag_enum = fs.getTags();
6077 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
6078 while(tag_enum.hasMoreElements()) {
6080 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
6084 output.println(", ");
6085 output.println("/*tagid*/"+state.getTagId(tagd));
6087 output.println("};");
6089 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
6090 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
6091 TaskIndex ti=itti.next();
6095 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
6097 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
6098 boolean needcomma=false;
6099 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
6100 OptionalTaskDescriptor otd=otdit.next();
6104 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
6106 output.println("};");
6108 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
6109 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
6110 output.print(ti.getIndex()+", ");
6111 output.print(otdset.size()+", ");
6112 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
6113 output.println("};");
6116 tiset=sa.getTaskIndex(fs);
6117 boolean needcomma=false;
6119 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
6120 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
6121 TaskIndex ti=itti.next();
6122 if (ti.isRuntime()) {
6129 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
6131 output.println("};\n");
6133 //Store the result in fsanalysiswrapper
6135 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
6136 output.println("/*flag*/"+flagid+",");
6137 output.println("/* number of tags*/"+tagcounter+",");
6138 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
6139 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
6140 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
6141 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
6142 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
6143 output.println("};\n");
6147 //Build the array of fsanalysiswrappers
6148 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
6149 boolean needcomma=false;
6150 for(int i = 0; i<fscounter; i++) {
6151 if (needcomma) output.print(",");
6152 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
6155 output.println("};");
6157 //Build the classanalysiswrapper referring to the previous array
6158 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
6159 output.println("/*type*/"+cdtemp.getId()+",");
6160 output.println("/*numotd*/"+numotd+",");
6161 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
6162 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
6163 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
6164 processedcd.add(cdtemp);
6167 //build an array containing every classes for which code has been build
6168 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
6169 for(int i=0; i<state.numClasses(); i++) {
6170 ClassDescriptor cn=cdarray[i];
6173 if ((cn != null) && (processedcd.contains(cn)))
6174 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
6176 output.print("NULL");
6178 output.println("};");
6180 output.println("#define MAXOTD "+maxotd);
6181 headers.println("#endif");
6184 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
6185 Relation r=new Relation();
6186 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
6187 OptionalTaskDescriptor otd=otdit.next();
6188 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
6192 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
6193 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
6194 Set s=r.get(it.next());
6195 for(Iterator it2=s.iterator(); it2.hasNext();) {
6196 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
6204 protected void outputTransCode(PrintWriter output) {
6207 private int calculateSizeOfSESEParamList(FlatSESEEnterNode fsen){
6209 Set<TempDescriptor> tdSet=new HashSet<TempDescriptor>();
6211 for (Iterator iterator = fsen.getInVarSet().iterator(); iterator.hasNext();) {
6212 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
6213 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
6214 tdSet.add(tempDescriptor);
6218 for (Iterator iterator = fsen.getOutVarSet().iterator(); iterator.hasNext();) {
6219 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
6220 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
6221 tdSet.add(tempDescriptor);
6225 return tdSet.size();
6228 private String calculateSizeOfSESEParamSize(FlatSESEEnterNode fsen){
6229 HashMap <String,Integer> map=new HashMap();
6230 HashSet <TempDescriptor> processed=new HashSet<TempDescriptor>();
6233 // space for all in and out set primitives
6234 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
6235 inSetAndOutSet.addAll( fsen.getInVarSet() );
6236 inSetAndOutSet.addAll( fsen.getOutVarSet() );
6238 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
6240 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
6241 while( itr.hasNext() ) {
6242 TempDescriptor temp = itr.next();
6243 TypeDescriptor type = temp.getType();
6244 if( !type.isPtr() ) {
6245 inSetAndOutSetPrims.add( temp );
6249 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
6250 while( itrPrims.hasNext() ) {
6251 TempDescriptor temp = itrPrims.next();
6252 TypeDescriptor type = temp.getType();
6253 if(type.isPrimitive()){
6254 Integer count=map.get(type.getSymbol());
6256 count=new Integer(1);
6257 map.put(type.getSymbol(), count);
6259 map.put(type.getSymbol(), new Integer(count.intValue()+1));
6264 Set<String> keySet=map.keySet();
6265 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
6266 String key = (String) iterator.next();
6267 rtr+="+sizeof("+key+")*"+map.get(key);