2 import IR.Tree.Modifiers;
3 import IR.Tree.FlagExpressionNode;
4 import IR.Tree.DNFFlag;
5 import IR.Tree.DNFFlagAtom;
6 import IR.Tree.TagExpressionList;
7 import IR.Tree.OffsetNode;
14 import Analysis.TaskStateAnalysis.FlagState;
15 import Analysis.TaskStateAnalysis.FlagComparator;
16 import Analysis.TaskStateAnalysis.OptionalTaskDescriptor;
17 import Analysis.TaskStateAnalysis.Predicate;
18 import Analysis.TaskStateAnalysis.SafetyAnalysis;
19 import Analysis.TaskStateAnalysis.TaskIndex;
20 import Analysis.Locality.LocalityAnalysis;
21 import Analysis.Locality.LocalityBinding;
22 import Analysis.Locality.DiscoverConflicts;
23 import Analysis.Locality.DCWrapper;
24 import Analysis.Locality.DelayComputation;
25 import Analysis.Locality.BranchAnalysis;
26 import Analysis.CallGraph.CallGraph;
27 import Analysis.Disjoint.AllocSite;
28 import Analysis.Disjoint.Effect;
29 import Analysis.Disjoint.ReachGraph;
30 import Analysis.Disjoint.Taint;
31 import Analysis.OoOJava.OoOJavaAnalysis;
32 import Analysis.Prefetch.*;
33 import Analysis.Loops.WriteBarrier;
34 import Analysis.Loops.GlobalFieldType;
35 import Analysis.Locality.TypeAnalysis;
36 import Analysis.MLP.ConflictGraph;
37 import Analysis.MLP.ConflictNode;
38 import Analysis.MLP.MLPAnalysis;
39 import Analysis.MLP.ParentChildConflictsMap;
40 import Analysis.MLP.SESELock;
41 import Analysis.MLP.SESEWaitingQueue;
42 import Analysis.MLP.VariableSourceToken;
43 import Analysis.MLP.VSTWrapper;
44 import Analysis.MLP.CodePlan;
45 import Analysis.MLP.SESEandAgePair;
46 import Analysis.MLP.WaitingElement;
48 public class BuildCode {
51 Hashtable paramstable;
56 String localsprefix="___locals___";
57 String localsprefixaddr="&"+localsprefix;
58 String localsprefixderef=localsprefix+".";
59 String fcrevert="___fcrevert___";
60 String paramsprefix="___params___";
61 String oidstr="___nextobject___";
62 String nextobjstr="___nextobject___";
63 String localcopystr="___localcopy___";
64 public static boolean GENERATEPRECISEGC=false;
65 public static String PREFIX="";
66 public static String arraytype="ArrayObject";
67 public static int flagcount = 0;
70 protected int maxtaskparams=0;
71 private int maxcount=0;
72 ClassDescriptor[] cdarray;
73 TypeDescriptor[] arraytable;
74 LocalityAnalysis locality;
75 Hashtable<LocalityBinding, TempDescriptor> reverttable;
76 Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>> backuptable;
81 String maxTaskRecSizeStr="__maxTaskRecSize___";
82 String mlperrstr = "if(status != 0) { "+
83 "sprintf(errmsg, \"MLP error at %s:%d\", __FILE__, __LINE__); "+
84 "perror(errmsg); exit(-1); }";
85 boolean nonSESEpass=true;
86 RuntimeConflictResolver rcr = null;
89 DiscoverConflicts recorddc;
94 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa) {
95 this(st, temptovar, typeutil, null, sa, pa, null, null);
98 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
99 this(st, temptovar, typeutil, null, sa, pa, mlpa, oooa);
102 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
103 this(st, temptovar, typeutil, locality, null, pa, mlpa, oooa);
106 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
112 callgraph=new CallGraph(state);
114 oidstr="___objlocation___";
115 this.temptovar=temptovar;
116 paramstable=new Hashtable();
117 tempstable=new Hashtable();
118 fieldorder=new Hashtable();
119 flagorder=new Hashtable();
120 this.typeutil=typeutil;
121 virtualcalls=new Virtual(state,locality);
122 if (locality!=null) {
123 this.locality=locality;
124 this.reverttable=new Hashtable<LocalityBinding, TempDescriptor>();
125 this.backuptable=new Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>>();
126 this.wb=new WriteBarrier(locality, st);
128 if (state.SINGLETM&&state.DCOPTS) {
129 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
130 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
131 this.dc=new DiscoverConflicts(locality, st, typeanalysis, gft);
134 if (state.DELAYCOMP) {
135 //TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
136 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
137 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
138 delaycomp=new DCWrapper(locality, st, typeanalysis, gft);
139 dc=delaycomp.getConflicts();
140 recorddc=new DiscoverConflicts(locality, st, typeanalysis, delaycomp.getCannotDelayMap(), true, true, null);
141 recorddc.doAnalysis();
145 /** The buildCode method outputs C code for all the methods. The Flat
146 * versions of the methods must already be generated and stored in
147 * the State object. */
148 PrintWriter outsandbox=null;
150 public void buildCode() {
151 /* Create output streams to write to */
152 PrintWriter outclassdefs=null;
153 PrintWriter outstructs=null;
154 PrintWriter outrepairstructs=null;
155 PrintWriter outmethodheader=null;
156 PrintWriter outmethod=null;
157 PrintWriter outvirtual=null;
158 PrintWriter outtask=null;
159 PrintWriter outtaskdefs=null;
160 PrintWriter outoptionalarrays=null;
161 PrintWriter optionalheaders=null;
162 PrintWriter outglobaldefs=null;
166 outsandbox=new PrintWriter(new FileOutputStream(PREFIX+"sandboxdefs.c"), true);
168 outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
169 outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
170 outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
171 outglobaldefs=new PrintWriter(new FileOutputStream(PREFIX+"globaldefs.h"), true);
172 outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
173 outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
175 outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
176 outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
177 if (state.OPTIONAL) {
178 outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
179 optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
182 if (state.structfile!=null) {
183 outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
185 } catch (Exception e) {
190 /* Build the virtual dispatch tables */
191 buildVirtualTables(outvirtual);
193 /* Output includes */
194 outmethodheader.println("#ifndef METHODHEADERS_H");
195 outmethodheader.println("#define METHODHEADERS_H");
196 outmethodheader.println("#include \"structdefs.h\"");
198 outmethodheader.println("#include \"dstm.h\"");
200 outmethodheader.println("#include \"sandbox.h\"");
202 if (state.EVENTMONITOR) {
203 outmethodheader.println("#include \"monitor.h\"");
205 if (state.SINGLETM) {
206 outmethodheader.println("#include \"tm.h\"");
207 outmethodheader.println("#include \"delaycomp.h\"");
208 outmethodheader.println("#include \"inlinestm.h\"");
210 if (state.ABORTREADERS) {
211 outmethodheader.println("#include \"abortreaders.h\"");
212 outmethodheader.println("#include <setjmp.h>");
214 if (state.MLP || state.OOOJAVA) {
215 outmethodheader.println("#include <stdlib.h>");
216 outmethodheader.println("#include <stdio.h>");
217 outmethodheader.println("#include <string.h>");
218 outmethodheader.println("#include \"mlp_runtime.h\"");
219 outmethodheader.println("#include \"psemaphore.h\"");
220 outmethodheader.println("#include \"memPool.h\"");
222 // spit out a global to inform all worker threads with
223 // the maximum size is for any task record
224 outmethodheader.println("extern int "+maxTaskRecSizeStr+";");
227 /* Output Structures */
228 outputStructs(outstructs);
230 // Output the C class declarations
231 // These could mutually reference each other
233 outglobaldefs.println("#ifndef __GLOBALDEF_H_");
234 outglobaldefs.println("#define __GLOBALDEF_H_");
235 outglobaldefs.println("");
236 outglobaldefs.println("struct global_defs_t {");
238 outclassdefs.println("#ifndef __CLASSDEF_H_");
239 outclassdefs.println("#define __CLASSDEF_H_");
240 outputClassDeclarations(outclassdefs, outglobaldefs);
242 // Output function prototypes and structures for parameters
243 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
244 while(it.hasNext()) {
245 ClassDescriptor cn=(ClassDescriptor)it.next();
246 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader, outglobaldefs);
248 outclassdefs.println("#endif");
249 outclassdefs.close();
250 outglobaldefs.println("};");
251 outglobaldefs.println("");
252 outglobaldefs.println("extern struct global_defs_t * global_defs_p;");
253 outglobaldefs.println("#endif");
254 outglobaldefs.flush();
255 outglobaldefs.close();
258 /* Map flags to integers */
259 /* The runtime keeps track of flags using these integers */
260 it=state.getClassSymbolTable().getDescriptorsIterator();
261 while(it.hasNext()) {
262 ClassDescriptor cn=(ClassDescriptor)it.next();
266 generateTaskStructs(outstructs, outmethodheader);
268 /* Outputs generic task structures if this is a task
270 outputTaskTypes(outtask);
273 if( state.MLP || state.OOOJAVA) {
274 // have to initialize some SESE compiler data before
275 // analyzing normal methods, which must happen before
276 // generating SESE internal code
278 Iterator<FlatSESEEnterNode> seseit;
280 seseit=mlpa.getAllSESEs().iterator();
282 seseit=oooa.getAllSESEs().iterator();
285 //TODO signal the object that will report errors
288 rcr = new RuntimeConflictResolver(PREFIX, oooa);
289 rcr.setGlobalEffects(oooa.getDisjointAnalysis().getEffectsAnalysis().getAllEffects());
290 } catch (FileNotFoundException e) {
291 System.out.println("Runtime Conflict Resolver could not create output file.");
295 while(seseit.hasNext()){
296 FlatSESEEnterNode fsen = seseit.next();
297 initializeSESE( fsen );
299 //this code will culminate all conflicts into one master hashtable.
300 if(state.RCR && rcr != null) {
301 Analysis.OoOJava.ConflictGraph conflictGraph;
302 Hashtable<Taint, Set<Effect>> conflicts;
304 System.out.println("-------");
305 System.out.println(fsen);
306 System.out.println(fsen.getIsCallerSESEplaceholder());
307 System.out.println(fsen.getParent());
309 if (fsen.getParent()!=null) {
310 conflictGraph = oooa.getConflictGraph(fsen.getParent());
311 System.out.println("CG="+conflictGraph);
312 if (conflictGraph!=null)
313 System.out.println("Conflicts="+conflictGraph.getConflictEffectSet(fsen));
316 if(!fsen.getIsCallerSESEplaceholder() && fsen.getParent()!=null &&
317 (conflictGraph = oooa.getConflictGraph(fsen.getParent())) != null &&
318 (conflicts = conflictGraph.getConflictEffectSet(fsen)) != null) {
319 FlatMethod fm=fsen.getfmEnclosing();
320 ReachGraph rg=oooa.getDisjointAnalysis().getReachGraph(fm.getMethod());
322 rg.writeGraph("RCR_RG_SESE_DEBUG");
324 rcr.addToTraverseToDoList(fsen, rg, conflicts);
330 /* Build the actual methods */
331 outputMethods(outmethod);
333 // Output function prototypes and structures for SESE's and code
334 if( state.MLP || state.OOOJAVA ) {
336 // spit out a global to inform all worker threads with
337 // the maximum size is for any task record
338 outmethod.println("int "+maxTaskRecSizeStr+" = 0;");
340 // used to differentiate, during code generation, whether we are
341 // passing over SESE body code, or non-SESE code
344 // first generate code for each sese's internals
345 Iterator<FlatSESEEnterNode> seseit;
347 seseit=mlpa.getAllSESEs().iterator();
349 seseit=oooa.getAllSESEs().iterator();
352 while(seseit.hasNext()) {
353 FlatSESEEnterNode fsen = seseit.next();
354 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
357 // then write the invokeSESE switch to decouple scheduler
358 // from having to do unique details of sese invocation
359 generateSESEinvocationMethod(outmethodheader, outmethod);
363 /* Output code for tasks */
364 outputTaskCode(outtaskdefs, outmethod);
366 /* Record maximum number of task parameters */
367 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
368 } else if (state.main!=null) {
369 /* Generate main method */
370 outputMainMethod(outmethod);
373 /* Generate information for task with optional parameters */
374 if (state.TASK&&state.OPTIONAL) {
375 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
376 outoptionalarrays.close();
379 /* Output structure definitions for repair tool */
380 if (state.structfile!=null) {
381 buildRepairStructs(outrepairstructs);
382 outrepairstructs.close();
386 outmethodheader.println("#endif");
387 outmethodheader.close();
389 outstructs.println("#endif");
393 System.out.println("Runtime Conflict Resolver Done.");
398 /* This code just generates the main C method for java programs.
399 * The main C method packs up the arguments into a string array
400 * and passes it to the java main method. */
402 protected void outputMainMethod(PrintWriter outmethod) {
403 outmethod.println("int main(int argc, const char *argv[]) {");
404 outmethod.println(" int i;");
406 if (state.MLP || state.OOOJAVA) {
408 // do a calculation to determine which task record
409 // is the largest, store that as a global value for
410 // allocating records
411 Iterator<FlatSESEEnterNode> seseit;
413 seseit=mlpa.getAllSESEs().iterator();
415 seseit=oooa.getAllSESEs().iterator();
417 while(seseit.hasNext()){
418 FlatSESEEnterNode fsen = seseit.next();
419 outmethod.println("if( sizeof( "+fsen.getSESErecordName()+
420 " ) > "+maxTaskRecSizeStr+
421 " ) { "+maxTaskRecSizeStr+
422 " = sizeof( "+fsen.getSESErecordName()+
426 outmethod.println(" runningSESE = NULL;");
428 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
430 //initializes data structures needed for the RCR traverser
431 if(state.RCR && rcr != null) {
432 outmethod.println(" initializeStructsRCR();");
437 if (state.DSMRECOVERYSTATS) {
438 outmethod.println("#ifdef RECOVERYSTATS \n");
439 outmethod.println("handle();\n");
440 outmethod.println("#endif\n");
442 outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
443 outmethod.println("handle();\n");
444 outmethod.println("#endif\n");
448 if (state.THREAD||state.DSM||state.SINGLETM) {
449 outmethod.println("initializethreads();");
452 outmethod.println("if (dstmStartup(argv[1])) {");
453 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
454 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
456 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
459 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
460 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
462 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
466 outmethod.println(" for(i=2;i<argc;i++) {");
468 outmethod.println(" for(i=1;i<argc;i++) {");
469 outmethod.println(" int length=strlen(argv[i]);");
470 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
471 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
473 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
476 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
478 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
479 outmethod.println(" }");
481 MethodDescriptor md=typeutil.getMain();
482 ClassDescriptor cd=typeutil.getMainClass();
484 outmethod.println(" {");
485 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
486 if (state.DSM||state.SINGLETM) {
487 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
489 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
490 outmethod.println("1, NULL,"+"stringarray};");
491 if (state.DSM||state.SINGLETM)
492 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
494 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
496 if (state.DSM||state.SINGLETM)
497 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
499 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
501 outmethod.println(" }");
504 outmethod.println("}");
507 if (state.THREAD||state.DSM||state.SINGLETM) {
508 outmethod.println("pthread_mutex_lock(&gclistlock);");
509 outmethod.println("threadcount--;");
510 outmethod.println("pthread_cond_signal(&gccond);");
511 outmethod.println("pthread_mutex_unlock(&gclistlock);");
514 if (state.DSM||state.SINGLETM) {
515 //outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
516 outmethod.println("#if defined(TRANSSTATS) \n");
517 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
518 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
519 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
520 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
522 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
523 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
524 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
525 outmethod.println("printf(\"ndirtyCacheObj= %d\\n\", ndirtyCacheObj);");
526 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
527 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
528 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
529 outmethod.println("printf(\"totalObjSize= %d\\n\", totalObjSize);");
530 outmethod.println("printf(\"sendRemoteReq= %d\\n\", sendRemoteReq);");
531 outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
532 } else if (state.SINGLETM) {
533 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
534 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
535 outmethod.println("#ifdef STMSTATS\n");
536 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
537 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
538 outmethod.println("}\n");
539 outmethod.println("#endif\n");
540 outmethod.println("fflush(stdout);");
542 outmethod.println("#endif\n");
545 if (state.EVENTMONITOR) {
546 outmethod.println("dumpdata();");
549 if (state.THREAD||state.SINGLETM)
550 outmethod.println("pthread_exit(NULL);");
552 if (state.MLP || state.OOOJAVA ) {
553 outmethod.println(" workScheduleBegin();");
556 outmethod.println("}");
559 /* This method outputs code for each task. */
561 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
562 /* Compile task based program */
563 outtaskdefs.println("#include \"task.h\"");
564 outtaskdefs.println("#include \"methodheaders.h\"");
565 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
566 while(taskit.hasNext()) {
567 TaskDescriptor td=(TaskDescriptor)taskit.next();
568 FlatMethod fm=state.getMethodFlat(td);
569 generateFlatMethod(fm, null, outmethod);
570 generateTaskDescriptor(outtaskdefs, fm, td);
573 //Output task descriptors
574 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
575 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
577 while(taskit.hasNext()) {
578 TaskDescriptor td=(TaskDescriptor)taskit.next();
582 outtaskdefs.println(",");
583 outtaskdefs.print("&task_"+td.getSafeSymbol());
585 outtaskdefs.println("};");
587 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
590 /* This method outputs most of the methods.c file. This includes
591 * some standard includes and then an array with the sizes of
592 * objets and array that stores supertype and then the code for
593 * the Java methods.. */
595 protected void outputMethods(PrintWriter outmethod) {
596 outmethod.println("#include \"methodheaders.h\"");
597 outmethod.println("#include \"virtualtable.h\"");
598 outmethod.println("#include \"runtime.h\"");
600 // always include: compiler directives will leave out
601 // instrumentation when option is not set
602 outmethod.println("#include \"coreprof/coreprof.h\"");
605 outmethod.println("#include \"sandboxdefs.c\"");
608 outmethod.println("#include \"addPrefetchEnhance.h\"");
609 outmethod.println("#include \"localobjects.h\"");
611 if (state.FASTCHECK) {
612 outmethod.println("#include \"localobjects.h\"");
614 if(state.MULTICORE) {
616 outmethod.println("#include \"task.h\"");
618 outmethod.println("#include \"multicoreruntime.h\"");
619 outmethod.println("#include \"runtime_arch.h\"");
621 if (state.THREAD||state.DSM||state.SINGLETM)
622 outmethod.println("#include <thread.h>");
623 if (state.main!=null) {
624 outmethod.println("#include <string.h>");
626 if (state.CONSCHECK) {
627 outmethod.println("#include \"checkers.h\"");
629 if (state.MLP || state.OOOJAVA ) {
630 outmethod.println("#include <stdlib.h>");
631 outmethod.println("#include <stdio.h>");
632 outmethod.println("#include \"mlp_runtime.h\"");
633 outmethod.println("#include \"psemaphore.h\"");
636 outmethod.println("#include \"trqueue.h\"");
637 outmethod.println("#include \"RuntimeConflictResolver.h\"");
638 outmethod.println("#include \"rcr_runtime.h\"");
642 outmethod.println("struct global_defs_t * global_defs_p;");
643 //Store the sizes of classes & array elements
644 generateSizeArray(outmethod);
646 //Store table of supertypes
647 generateSuperTypeTable(outmethod);
649 //Store the layout of classes
650 generateLayoutStructs(outmethod);
652 /* Generate code for methods */
653 if (state.DSM||state.SINGLETM) {
654 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
655 LocalityBinding lb=lbit.next();
656 MethodDescriptor md=lb.getMethod();
657 FlatMethod fm=state.getMethodFlat(md);
659 if (!md.getModifiers().isNative()) {
660 generateFlatMethod(fm, lb, outmethod);
661 //System.out.println("fm= " + fm + " md= " + md);
665 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
666 while(classit.hasNext()) {
667 ClassDescriptor cn=(ClassDescriptor)classit.next();
668 Iterator methodit=cn.getMethods();
669 while(methodit.hasNext()) {
670 /* Classify parameters */
671 MethodDescriptor md=(MethodDescriptor)methodit.next();
672 FlatMethod fm=state.getMethodFlat(md);
673 if (!md.getModifiers().isNative()) {
674 generateFlatMethod(fm, null, outmethod);
681 protected void outputStructs(PrintWriter outstructs) {
682 outstructs.println("#ifndef STRUCTDEFS_H");
683 outstructs.println("#define STRUCTDEFS_H");
684 outstructs.println("#include \"classdefs.h\"");
685 outstructs.println("#ifndef INTPTR");
686 outstructs.println("#ifdef BIT64");
687 outstructs.println("#define INTPTR long");
688 outstructs.println("#else");
689 outstructs.println("#define INTPTR int");
690 outstructs.println("#endif");
691 outstructs.println("#endif");
692 if( state.MLP || state.OOOJAVA ) {
693 outstructs.println("#include \"mlp_runtime.h\"");
694 outstructs.println("#include \"psemaphore.h\"");
697 /* Output #defines that the runtime uses to determine type
698 * numbers for various objects it needs */
699 outstructs.println("#define MAXCOUNT "+maxcount);
700 if (state.DSM||state.SINGLETM) {
701 LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
703 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
705 else if (state.SINGLETM) {
706 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
708 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
712 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
714 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
715 else if( state.SINGLETM)
716 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
717 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
720 outstructs.println("#define STRINGARRAYTYPE "+
721 (state.getArrayNumber(
722 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
724 outstructs.println("#define OBJECTARRAYTYPE "+
725 (state.getArrayNumber(
726 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
729 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
730 outstructs.println("#define CHARARRAYTYPE "+
731 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
733 outstructs.println("#define BYTEARRAYTYPE "+
734 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
736 outstructs.println("#define BYTEARRAYARRAYTYPE "+
737 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
739 outstructs.println("#define NUMCLASSES "+state.numClasses());
740 int totalClassSize = state.numClasses() + state.numArrays();
741 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
743 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
744 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
745 outstructs.println("#define TAGARRAYTYPE "+
746 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
750 protected void outputClassDeclarations(PrintWriter outclassdefs, PrintWriter outglobaldefs) {
751 if (state.THREAD||state.DSM||state.SINGLETM)
752 outclassdefs.println("#include <pthread.h>");
753 outclassdefs.println("#ifndef INTPTR");
754 outclassdefs.println("#ifdef BIT64");
755 outclassdefs.println("#define INTPTR long");
756 outclassdefs.println("#else");
757 outclassdefs.println("#define INTPTR int");
758 outclassdefs.println("#endif");
759 outclassdefs.println("#endif");
761 outclassdefs.println("#include \"optionalstruct.h\"");
762 outclassdefs.println("struct "+arraytype+";");
763 /* Start by declaring all structs */
764 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
765 while(it.hasNext()) {
766 ClassDescriptor cn=(ClassDescriptor)it.next();
767 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
769 outclassdefs.println("");
770 //Print out definition for array type
771 outclassdefs.println("struct "+arraytype+" {");
772 outclassdefs.println(" int type;");
773 if(state.MLP || state.OOOJAVA ){
774 outclassdefs.println(" int oid;");
775 outclassdefs.println(" int allocsite;");
777 if (state.EVENTMONITOR) {
778 outclassdefs.println(" int objuid;");
781 outclassdefs.println(" pthread_t tid;");
782 outclassdefs.println(" void * lockentry;");
783 outclassdefs.println(" int lockcount;");
786 outclassdefs.println(" int mutex;");
787 outclassdefs.println(" int objlock;");
788 if(state.MULTICOREGC) {
789 outclassdefs.println(" int marked;");
793 outclassdefs.println(" int flag;");
794 if(!state.MULTICORE) {
795 outclassdefs.println(" void * flagptr;");
797 outclassdefs.println(" int version;");
798 outclassdefs.println(" int * lock;"); // lock entry for this obj
799 outclassdefs.println(" int mutex;");
800 outclassdefs.println(" int lockcount;");
801 if(state.MULTICOREGC) {
802 outclassdefs.println(" int marked;");
806 outclassdefs.println(" int numfses;");
807 outclassdefs.println(" int * fses;");
810 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs, outglobaldefs);
812 if (state.STMARRAY) {
813 outclassdefs.println(" int lowindex;");
814 outclassdefs.println(" int highindex;");
817 outclassdefs.println(" int paddingforarray;");
818 if (state.DUALVIEW) {
819 outclassdefs.println(" int arrayversion;");
822 outclassdefs.println(" int ___length___;");
823 outclassdefs.println("};\n");
824 outclassdefs.println("extern int classsize[];");
825 outclassdefs.println("extern int hasflags[];");
826 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
827 outclassdefs.println("extern int supertypes[];");
828 outclassdefs.println("#include \"globaldefs.h\"");
829 outclassdefs.println("");
832 /** Prints out definitions for generic task structures */
834 private void outputTaskTypes(PrintWriter outtask) {
835 outtask.println("#ifndef _TASK_H");
836 outtask.println("#define _TASK_H");
837 outtask.println("struct parameterdescriptor {");
838 outtask.println("int type;");
839 outtask.println("int numberterms;");
840 outtask.println("int *intarray;");
841 outtask.println("void * queue;");
842 outtask.println("int numbertags;");
843 outtask.println("int *tagarray;");
844 outtask.println("};");
846 outtask.println("struct taskdescriptor {");
847 outtask.println("void * taskptr;");
848 outtask.println("int numParameters;");
849 outtask.println(" int numTotal;");
850 outtask.println("struct parameterdescriptor **descriptorarray;");
851 outtask.println("char * name;");
852 outtask.println("};");
853 outtask.println("extern struct taskdescriptor * taskarray[];");
854 outtask.println("extern numtasks;");
855 outtask.println("#endif");
859 private void buildRepairStructs(PrintWriter outrepairstructs) {
860 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
861 while(classit.hasNext()) {
862 ClassDescriptor cn=(ClassDescriptor)classit.next();
863 outrepairstructs.println("structure "+cn.getSymbol()+" {");
864 outrepairstructs.println(" int __type__;");
866 outrepairstructs.println(" int __flag__;");
867 if(!state.MULTICORE) {
868 outrepairstructs.println(" int __flagptr__;");
871 printRepairStruct(cn, outrepairstructs);
872 outrepairstructs.println("}\n");
875 for(int i=0; i<state.numArrays(); i++) {
876 TypeDescriptor tdarray=arraytable[i];
877 TypeDescriptor tdelement=tdarray.dereference();
878 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
879 outrepairstructs.println(" int __type__;");
880 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
881 outrepairstructs.println(" int length;");
883 // Need to add support to repair tool for this
884 if (tdelement.isClass()||tdelement.isArray())
885 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
887 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
889 outrepairstructs.println("}\n");
893 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
894 ClassDescriptor sp=cn.getSuperDesc();
896 printRepairStruct(sp, output);
898 Vector fields=(Vector)fieldorder.get(cn);
900 for(int i=0; i<fields.size(); i++) {
901 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
902 if (fd.getType().isArray()) {
903 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
904 } else if (fd.getType().isClass())
905 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
906 else if (fd.getType().isFloat())
907 output.println(" int "+fd.getSymbol()+"; /* really float */");
909 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
913 /** This method outputs TaskDescriptor information */
914 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
915 for (int i=0; i<task.numParameters(); i++) {
916 VarDescriptor param_var=task.getParameter(i);
917 TypeDescriptor param_type=task.getParamType(i);
918 FlagExpressionNode param_flag=task.getFlag(param_var);
919 TagExpressionList param_tag=task.getTag(param_var);
922 if (param_flag==null) {
923 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
924 output.println("0x0, 0x0 };");
927 DNFFlag dflag=param_flag.getDNF();
928 dnfterms=dflag.size();
930 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
931 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
932 for(int j=0; j<dflag.size(); j++) {
935 Vector term=dflag.get(j);
938 for(int k=0; k<term.size(); k++) {
939 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
940 FlagDescriptor fd=dfa.getFlag();
941 boolean negated=dfa.getNegated();
942 int flagid=1<<((Integer)flags.get(fd)).intValue();
947 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
949 output.println("};");
952 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
953 //BUG...added next line to fix, test with any task program
955 for(int j=0; j<param_tag.numTags(); j++) {
958 /* for each tag we need */
959 /* which slot it is */
960 /* what type it is */
961 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
962 TempDescriptor tmp=param_tag.getTemp(j);
963 int slot=fm.getTagInt(tmp);
964 output.println(slot+", "+state.getTagId(tvd.getTag()));
966 output.println("};");
968 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
969 output.println("/* type */"+param_type.getClassDesc().getId()+",");
970 output.println("/* number of DNF terms */"+dnfterms+",");
971 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
972 output.println("0,");
973 //BUG, added next line to fix and else statement...test
974 //with any task program
976 output.println("/* number of tags */"+param_tag.numTags()+",");
978 output.println("/* number of tags */ 0,");
979 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
980 output.println("};");
984 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
985 for (int i=0; i<task.numParameters(); i++) {
988 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
990 output.println("};");
992 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
993 output.println("&"+task.getSafeSymbol()+",");
994 output.println("/* number of parameters */" +task.numParameters() + ",");
995 int numtotal=task.numParameters()+fm.numTags();
996 output.println("/* number total parameters */" +numtotal + ",");
997 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
998 output.println("\""+task.getSymbol()+"\"");
999 output.println("};");
1003 /** The buildVirtualTables method outputs the virtual dispatch
1004 * tables for methods. */
1006 protected void buildVirtualTables(PrintWriter outvirtual) {
1007 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
1008 while(classit.hasNext()) {
1009 ClassDescriptor cd=(ClassDescriptor)classit.next();
1010 if (virtualcalls.getMethodCount(cd)>maxcount)
1011 maxcount=virtualcalls.getMethodCount(cd);
1013 MethodDescriptor[][] virtualtable=null;
1014 LocalityBinding[][] lbvirtualtable=null;
1015 if (state.DSM||state.SINGLETM)
1016 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
1018 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
1020 /* Fill in virtual table */
1021 classit=state.getClassSymbolTable().getDescriptorsIterator();
1022 while(classit.hasNext()) {
1023 ClassDescriptor cd=(ClassDescriptor)classit.next();
1024 if (state.DSM||state.SINGLETM)
1025 fillinRow(cd, lbvirtualtable, cd.getId());
1027 fillinRow(cd, virtualtable, cd.getId());
1030 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
1031 Iterator arrayit=state.getArrayIterator();
1032 while(arrayit.hasNext()) {
1033 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1034 int id=state.getArrayNumber(td);
1035 if (state.DSM||state.SINGLETM)
1036 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
1038 fillinRow(objectcd, virtualtable, id+state.numClasses());
1041 outvirtual.print("void * virtualtable[]={");
1042 boolean needcomma=false;
1043 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
1044 for(int j=0; j<maxcount; j++) {
1046 outvirtual.print(", ");
1047 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
1048 LocalityBinding lb=lbvirtualtable[i][j];
1049 MethodDescriptor md=lb.getMethod();
1050 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
1051 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
1052 MethodDescriptor md=virtualtable[i][j];
1053 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
1055 outvirtual.print("0");
1059 outvirtual.println("");
1061 outvirtual.println("};");
1065 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
1066 /* Get inherited methods */
1067 if (cd.getSuperDesc()!=null)
1068 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
1069 /* Override them with our methods */
1070 for(Iterator it=cd.getMethods(); it.hasNext();) {
1071 MethodDescriptor md=(MethodDescriptor)it.next();
1072 if (md.isStatic()||md.getReturnType()==null)
1074 int methodnum=virtualcalls.getMethodNumber(md);
1075 virtualtable[rownum][methodnum]=md;
1079 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
1080 /* Get inherited methods */
1081 if (cd.getSuperDesc()!=null)
1082 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
1083 /* Override them with our methods */
1084 if (locality.getClassBindings(cd)!=null)
1085 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
1086 LocalityBinding lb=lbit.next();
1087 MethodDescriptor md=lb.getMethod();
1088 //Is the method static or a constructor
1089 if (md.isStatic()||md.getReturnType()==null)
1091 int methodnum=virtualcalls.getLocalityNumber(lb);
1092 virtualtable[rownum][methodnum]=lb;
1096 /** Generate array that contains the sizes of class objects. The
1097 * object allocation functions in the runtime use this
1100 private void generateSizeArray(PrintWriter outclassdefs) {
1101 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
1102 outclassdefs.print("#ifdef TRANSSTATS \n");
1103 outclassdefs.print("extern int numTransAbort;\n");
1104 outclassdefs.print("extern int numTransCommit;\n");
1105 outclassdefs.print("extern int nSoftAbort;\n");
1107 outclassdefs.print("extern int nchashSearch;\n");
1108 outclassdefs.print("extern int nmhashSearch;\n");
1109 outclassdefs.print("extern int nprehashSearch;\n");
1110 outclassdefs.print("extern int ndirtyCacheObj;\n");
1111 outclassdefs.print("extern int nRemoteSend;\n");
1112 outclassdefs.print("extern int sendRemoteReq;\n");
1113 outclassdefs.print("extern int getResponse;\n");
1114 outclassdefs.print("extern int bytesSent;\n");
1115 outclassdefs.print("extern int bytesRecv;\n");
1116 outclassdefs.print("extern int totalObjSize;\n");
1117 outclassdefs.print("extern void handle();\n");
1118 } else if (state.SINGLETM) {
1119 outclassdefs.println("extern int nSoftAbortAbort;");
1120 outclassdefs.println("extern int nSoftAbortCommit;");
1121 outclassdefs.println("#ifdef STMSTATS\n");
1122 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
1123 outclassdefs.println("#endif\n");
1125 outclassdefs.print("#endif\n");
1127 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
1128 if(this.state.MLP || state.OOOJAVA ){
1129 outclassdefs.print("extern __thread int oid;\n");
1130 outclassdefs.print("extern int numWorkers;\n");
1133 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1134 cdarray=new ClassDescriptor[state.numClasses()];
1136 while(it.hasNext()) {
1137 ClassDescriptor cd=(ClassDescriptor)it.next();
1138 cdarray[cd.getId()]=cd;
1141 arraytable=new TypeDescriptor[state.numArrays()];
1143 Iterator arrayit=state.getArrayIterator();
1144 while(arrayit.hasNext()) {
1145 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1146 int id=state.getArrayNumber(td);
1152 /* Print out types */
1153 outclassdefs.println("/* ");
1154 for(int i=0; i<state.numClasses(); i++) {
1155 ClassDescriptor cd=cdarray[i];
1157 outclassdefs.println("NULL " + i);
1159 outclassdefs.println(cd +" "+i);
1163 for(int i=0; i<state.numArrays(); i++) {
1164 TypeDescriptor arraytd=arraytable[i];
1165 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
1168 outclassdefs.println("*/");
1171 outclassdefs.print("int classsize[]={");
1173 boolean needcomma=false;
1174 for(int i=0; i<state.numClasses(); i++) {
1176 outclassdefs.print(", ");
1178 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1180 outclassdefs.print("0");
1186 for(int i=0; i<state.numArrays(); i++) {
1188 outclassdefs.print(", ");
1189 TypeDescriptor tdelement=arraytable[i].dereference();
1190 if (tdelement.isArray()||tdelement.isClass())
1191 outclassdefs.print("sizeof(void *)");
1193 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1197 outclassdefs.println("};");
1199 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1201 outclassdefs.print("int typearray[]={");
1202 for(int i=0; i<state.numClasses(); i++) {
1203 ClassDescriptor cd=cdarray[i];
1204 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1206 outclassdefs.print(", ");
1208 outclassdefs.print("-1");
1210 outclassdefs.print(supercd.getId());
1214 for(int i=0; i<state.numArrays(); i++) {
1215 TypeDescriptor arraytd=arraytable[i];
1216 ClassDescriptor arraycd=arraytd.getClassDesc();
1217 if (arraycd==null) {
1219 outclassdefs.print(", ");
1220 outclassdefs.print(objectclass.getId());
1224 ClassDescriptor cd=arraycd.getSuperDesc();
1227 TypeDescriptor supertd=new TypeDescriptor(cd);
1228 supertd.setArrayCount(arraytd.getArrayCount());
1229 type=state.getArrayNumber(supertd);
1231 type+=state.numClasses();
1234 cd=cd.getSuperDesc();
1237 outclassdefs.print(", ");
1238 outclassdefs.print(type);
1242 outclassdefs.println("};");
1247 outclassdefs.print("int typearray2[]={");
1248 for(int i=0; i<state.numArrays(); i++) {
1249 TypeDescriptor arraytd=arraytable[i];
1250 ClassDescriptor arraycd=arraytd.getClassDesc();
1251 if (arraycd==null) {
1253 outclassdefs.print(", ");
1254 outclassdefs.print("-1");
1258 ClassDescriptor cd=arraycd.getSuperDesc();
1259 int level=arraytd.getArrayCount()-1;
1261 for(; level>0; level--) {
1262 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1263 supertd.setArrayCount(level);
1264 type=state.getArrayNumber(supertd);
1266 type+=state.numClasses();
1271 outclassdefs.print(", ");
1272 outclassdefs.print(type);
1276 outclassdefs.println("};");
1279 /** Constructs params and temp objects for each method or task.
1280 * These objects tell the compiler which temps need to be
1283 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1284 MethodDescriptor md=fm.getMethod();
1285 TaskDescriptor task=fm.getTask();
1286 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1287 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1289 paramstable.put(lb, objectparams);
1290 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1291 } else if (md!=null)
1292 paramstable.put(md, objectparams);
1294 paramstable.put(task, objectparams);
1296 for(int i=0; i<fm.numParameters(); i++) {
1297 TempDescriptor temp=fm.getParameter(i);
1298 TypeDescriptor type=temp.getType();
1299 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1300 objectparams.addPtr(temp);
1302 objectparams.addPrim(temp);
1303 if(lb!=null&&saveset.contains(temp)) {
1304 backuptable.get(lb).put(temp, temp.createNew());
1308 for(int i=0; i<fm.numTags(); i++) {
1309 TempDescriptor temp=fm.getTag(i);
1310 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1311 objectparams.addPtr(temp);
1313 objectparams.addPrim(temp);
1316 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1318 tempstable.put(lb, objecttemps);
1320 tempstable.put(md, objecttemps);
1322 tempstable.put(task, objecttemps);
1324 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1325 FlatNode fn=(FlatNode)nodeit.next();
1326 TempDescriptor[] writes=fn.writesTemps();
1327 for(int i=0; i<writes.length; i++) {
1328 TempDescriptor temp=writes[i];
1329 TypeDescriptor type=temp.getType();
1330 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1331 objecttemps.addPtr(temp);
1333 objecttemps.addPrim(temp);
1334 if(lb!=null&&saveset.contains(temp)&&
1335 !backuptable.get(lb).containsKey(temp))
1336 backuptable.get(lb).put(temp, temp.createNew());
1340 /* Create backup temps */
1342 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1343 TempDescriptor tmp=tmpit.next();
1344 TypeDescriptor type=tmp.getType();
1345 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1346 objecttemps.addPtr(tmp);
1348 objecttemps.addPrim(tmp);
1350 /* Create temp to hold revert table */
1351 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1352 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1353 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1354 objecttemps.addPtr(reverttmp);
1356 objecttemps.addPrim(reverttmp);
1357 reverttable.put(lb, reverttmp);
1362 /** This method outputs the following information about classes
1364 * (1) For classes, what are the locations of pointers.
1365 * (2) For arrays, does the array contain pointers or primitives.
1366 * (3) For classes, does the class contain flags.
1369 private void generateLayoutStructs(PrintWriter output) {
1370 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1371 while(it.hasNext()) {
1372 ClassDescriptor cn=(ClassDescriptor)it.next();
1373 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1374 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1376 while(allit.hasNext()) {
1377 FieldDescriptor fd=(FieldDescriptor)allit.next();
1378 TypeDescriptor type=fd.getType();
1379 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1384 output.print(count);
1385 allit=cn.getFieldTable().getAllDescriptorsIterator();
1386 while(allit.hasNext()) {
1387 FieldDescriptor fd=(FieldDescriptor)allit.next();
1388 TypeDescriptor type=fd.getType();
1389 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1392 output.println(",");
1393 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1396 output.println("};");
1398 output.println("unsigned INTPTR * pointerarray[]={");
1399 boolean needcomma=false;
1400 for(int i=0; i<state.numClasses(); i++) {
1401 ClassDescriptor cn=cdarray[i];
1403 output.println(",");
1406 output.print(cn.getSafeSymbol()+"_pointers");
1408 output.print("NULL");
1412 for(int i=0; i<state.numArrays(); i++) {
1414 output.println(", ");
1415 TypeDescriptor tdelement=arraytable[i].dereference();
1416 if (tdelement.isArray()||tdelement.isClass())
1417 output.print("((unsigned INTPTR *)1)");
1423 output.println("};");
1425 output.println("int hasflags[]={");
1426 for(int i=0; i<state.numClasses(); i++) {
1427 ClassDescriptor cn=cdarray[i];
1429 output.println(", ");
1431 if ((cn != null) && (cn.hasFlags()))
1436 output.println("};");
1439 /** Print out table to give us supertypes */
1440 private void generateSuperTypeTable(PrintWriter output) {
1441 output.println("int supertypes[]={");
1442 boolean needcomma=false;
1443 for(int i=0; i<state.numClasses(); i++) {
1444 ClassDescriptor cn=cdarray[i];
1446 output.println(",");
1448 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1449 ClassDescriptor cdsuper=cn.getSuperDesc();
1450 output.print(cdsuper.getId());
1454 output.println("};");
1457 /** Force consistent field ordering between inherited classes. */
1459 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout, PrintWriter globaldefout) {
1461 ClassDescriptor sp=cn.getSuperDesc();
1463 printClassStruct(sp, classdefout, globaldefout);
1465 if (!fieldorder.containsKey(cn)) {
1466 Vector fields=new Vector();
1467 fieldorder.put(cn,fields);
1468 Vector fieldvec=cn.getFieldVec();
1469 for(int i=0;i<fieldvec.size();i++) {
1470 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1471 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1475 Vector fields=(Vector)fieldorder.get(cn);
1477 for(int i=0; i<fields.size(); i++) {
1478 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1479 if (fd.getType().isClass()||fd.getType().isArray())
1480 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1481 else if(fd.isStatic()) {
1483 globaldefout.println(" "+fd.getType().getSafeSymbol()+ " "+cn.getSafeSymbol()+fd.getSafeSymbol()+";");
1484 classdefout.println(" "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1486 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1491 /* Map flags to integers consistently between inherited
1494 protected void mapFlags(ClassDescriptor cn) {
1495 ClassDescriptor sp=cn.getSuperDesc();
1499 if (!flagorder.containsKey(cn)) {
1500 Hashtable flags=new Hashtable();
1501 flagorder.put(cn,flags);
1503 Hashtable superflags=(Hashtable)flagorder.get(sp);
1504 Iterator superflagit=superflags.keySet().iterator();
1505 while(superflagit.hasNext()) {
1506 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1507 Integer number=(Integer)superflags.get(fd);
1508 flags.put(fd, number);
1509 if ((number.intValue()+1)>max)
1510 max=number.intValue()+1;
1514 Iterator flagit=cn.getFlags();
1515 while(flagit.hasNext()) {
1516 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1517 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1518 flags.put(fd, new Integer(max++));
1524 /** This function outputs (1) structures that parameters are
1525 * passed in (when PRECISE GC is enabled) and (2) function
1526 * prototypes for the methods */
1528 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout, PrintWriter globaldefout) {
1529 /* Output class structure */
1530 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1531 classdefout.println(" int type;");
1532 if(state.MLP || state.OOOJAVA){
1533 classdefout.println(" int oid;");
1534 classdefout.println(" int allocsite;");
1536 if (state.EVENTMONITOR) {
1537 classdefout.println(" int objuid;");
1540 classdefout.println(" pthread_t tid;");
1541 classdefout.println(" void * lockentry;");
1542 classdefout.println(" int lockcount;");
1545 classdefout.println(" int mutex;");
1546 classdefout.println(" int objlock;");
1547 if(state.MULTICOREGC) {
1548 classdefout.println(" int marked;");
1552 classdefout.println(" int flag;");
1553 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1554 classdefout.println(" void * flagptr;");
1555 } else if (state.MULTICORE) {
1556 classdefout.println(" int version;");
1557 classdefout.println(" int * lock;"); // lock entry for this obj
1558 classdefout.println(" int mutex;");
1559 classdefout.println(" int lockcount;");
1560 if(state.MULTICOREGC) {
1561 classdefout.println(" int marked;");
1564 if (state.OPTIONAL) {
1565 classdefout.println(" int numfses;");
1566 classdefout.println(" int * fses;");
1569 printClassStruct(cn, classdefout, globaldefout);
1570 classdefout.println("};\n");
1572 if (state.DSM||state.SINGLETM) {
1573 /* Cycle through LocalityBindings */
1574 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1575 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1577 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1578 LocalityBinding lb=lbit.next();
1579 MethodDescriptor md=lb.getMethod();
1580 if (md.getModifiers().isNative()) {
1581 //make sure we only print a native method once
1582 if (nativemethods.contains(md)) {
1583 FlatMethod fm=state.getMethodFlat(md);
1584 generateTempStructs(fm, lb);
1587 nativemethods.add(md);
1589 generateMethod(cn, md, lb, headersout, output);
1592 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1593 MethodDescriptor md=(MethodDescriptor)methodit.next();
1594 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1595 //Need to build param structure for library code
1596 FlatMethod fm=state.getMethodFlat(md);
1597 generateTempStructs(fm, null);
1598 generateMethodParam(cn, md, null, output);
1603 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1604 MethodDescriptor md=(MethodDescriptor)methodit.next();
1605 generateMethod(cn, md, null, headersout, output);
1609 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1610 /* Output parameter structure */
1611 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1612 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1613 if ((state.DSM||state.SINGLETM)&&lb!=null)
1614 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1616 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1617 output.println(" int size;");
1618 output.println(" void * next;");
1619 for(int i=0; i<objectparams.numPointers(); i++) {
1620 TempDescriptor temp=objectparams.getPointer(i);
1621 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1623 output.println("};\n");
1627 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1628 FlatMethod fm=state.getMethodFlat(md);
1629 generateTempStructs(fm, lb);
1631 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1632 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1634 generateMethodParam(cn, md, lb, output);
1636 /* Output temp structure */
1637 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1638 if (state.DSM||state.SINGLETM)
1639 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1641 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1642 output.println(" int size;");
1643 output.println(" void * next;");
1644 for(int i=0; i<objecttemps.numPointers(); i++) {
1645 TempDescriptor temp=objecttemps.getPointer(i);
1646 if (temp.getType().isNull())
1647 output.println(" void * "+temp.getSafeSymbol()+";");
1649 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1651 output.println("};\n");
1654 /********* Output method declaration ***********/
1655 if (state.DSM||state.SINGLETM) {
1656 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1658 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1660 /* First the return type */
1661 if (md.getReturnType()!=null) {
1662 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1663 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1665 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1667 //catch the constructor case
1668 headersout.print("void ");
1670 /* Next the method name */
1671 if (state.DSM||state.SINGLETM) {
1672 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1674 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1676 boolean printcomma=false;
1677 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1678 if (state.DSM||state.SINGLETM) {
1679 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1681 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1685 /* Output parameter list*/
1686 for(int i=0; i<objectparams.numPrimitives(); i++) {
1687 TempDescriptor temp=objectparams.getPrimitive(i);
1689 headersout.print(", ");
1691 if (temp.getType().isClass()||temp.getType().isArray())
1692 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1694 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1696 headersout.println(");\n");
1700 /** This function outputs (1) structures that parameters are
1701 * passed in (when PRECISE GC is enabled) and (2) function
1702 * prototypes for the tasks */
1704 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1705 /* Cycle through tasks */
1706 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1708 while(taskit.hasNext()) {
1709 /* Classify parameters */
1710 TaskDescriptor task=(TaskDescriptor)taskit.next();
1711 FlatMethod fm=state.getMethodFlat(task);
1712 generateTempStructs(fm, null);
1714 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1715 TempObject objecttemps=(TempObject) tempstable.get(task);
1717 /* Output parameter structure */
1718 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1719 output.println("struct "+task.getSafeSymbol()+"_params {");
1720 output.println(" int size;");
1721 output.println(" void * next;");
1722 for(int i=0; i<objectparams.numPointers(); i++) {
1723 TempDescriptor temp=objectparams.getPointer(i);
1724 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1727 output.println("};\n");
1728 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1729 maxtaskparams=objectparams.numPointers()+fm.numTags();
1733 /* Output temp structure */
1734 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1735 output.println("struct "+task.getSafeSymbol()+"_locals {");
1736 output.println(" int size;");
1737 output.println(" void * next;");
1738 for(int i=0; i<objecttemps.numPointers(); i++) {
1739 TempDescriptor temp=objecttemps.getPointer(i);
1740 if (temp.getType().isNull())
1741 output.println(" void * "+temp.getSafeSymbol()+";");
1742 else if(temp.getType().isTag())
1743 output.println(" struct "+
1744 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1746 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1748 output.println("};\n");
1751 /* Output task declaration */
1752 headersout.print("void " + task.getSafeSymbol()+"(");
1754 boolean printcomma=false;
1755 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1756 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1758 headersout.print("void * parameterarray[]");
1759 headersout.println(");\n");
1763 /***** Generate code for FlatMethod fm. *****/
1765 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1766 static int atomicmethodcount=0;
1769 BranchAnalysis branchanalysis;
1770 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1771 if (State.PRINTFLAT)
1772 System.out.println(fm.printMethod());
1773 MethodDescriptor md=fm.getMethod();
1774 TaskDescriptor task=fm.getTask();
1775 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1776 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1778 HashSet<AtomicRecord> arset=null;
1779 branchanalysis=null;
1781 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1783 if (atomicmethodmap==null)
1784 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1786 //fix these so we get right strings for local variables
1787 localsprefixaddr=localsprefix;
1788 localsprefixderef=localsprefix+"->";
1789 arset=new HashSet<AtomicRecord>();
1791 //build branchanalysis
1792 branchanalysis=new BranchAnalysis(locality, lb, delaycomp.getNotReady(lb), delaycomp.livecode(lb), state);
1794 //Generate commit methods here
1795 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1796 FlatNode fn=fnit.next();
1797 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1798 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
1799 delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
1800 //We have an atomic enter
1801 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1802 Set<FlatNode> exitset=faen.getExits();
1804 String methodname=md.getSymbol()+(atomicmethodcount++);
1805 AtomicRecord ar=new AtomicRecord();
1809 atomicmethodmap.put(faen, ar);
1811 //build data structure declaration
1812 output.println("struct atomicprimitives_"+methodname+" {");
1814 Set<FlatNode> recordset=delaycomp.livecode(lb);
1815 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1816 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1817 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1819 ar.reallivein=new HashSet(liveinto);
1821 ar.liveoutvirtualread=liveoutvirtualread;
1824 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1825 TempDescriptor tmp=it.next();
1826 //remove the pointers
1827 if (tmp.getType().isPtr()) {
1830 //let's print it here
1831 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1834 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1835 TempDescriptor tmp=it.next();
1836 //remove the pointers
1837 if (tmp.getType().isPtr()) {
1839 } else if (!liveinto.contains(tmp)) {
1840 //let's print it here
1841 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1844 output.println("};");
1846 //print out method name
1847 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) {");
1848 //build code for commit method
1850 //first define local primitives
1851 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1852 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1853 TempDescriptor tmp=tmpit.next();
1854 if (!tmp.getType().isPtr()) {
1855 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1856 //read from live into set
1857 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1860 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1864 //turn off write barrier generation
1866 state.SINGLETM=false;
1867 generateCode(faen, fm, lb, exitset, output, false);
1868 state.SINGLETM=true;
1869 //turn on write barrier generation
1871 output.println("}\n\n");
1875 //redefine these back to normal
1877 localsprefixaddr="&"+localsprefix;
1878 localsprefixderef=localsprefix+".";
1880 generateHeader(fm, lb, md!=null ? md : task,output);
1881 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1883 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1884 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1885 AtomicRecord ar=arit.next();
1886 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1890 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1891 if (md!=null&&(state.DSM||state.SINGLETM))
1892 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1893 else if (md!=null&&!(state.DSM||state.SINGLETM))
1894 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1896 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1897 output.print(objecttemp.numPointers()+",");
1898 output.print(paramsprefix);
1899 for(int j=0; j<objecttemp.numPointers(); j++)
1900 output.print(", NULL");
1901 output.println("};");
1904 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1905 TempDescriptor td=objecttemp.getPrimitive(i);
1906 TypeDescriptor type=td.getType();
1908 output.println(" void * "+td.getSafeSymbol()+";");
1909 else if (type.isClass()||type.isArray())
1910 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1912 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1916 if( state.MLP || state.OOOJAVA ) {
1917 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1918 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1919 if( (state.MLP && callerSESEplaceholder != mlpa.getMainSESE()) ||
1920 (state.OOOJAVA && callerSESEplaceholder != oooa.getMainSESE())
1922 // declare variables for naming static SESE's
1923 output.println(" /* static SESE names */");
1924 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1925 while( pItr.hasNext() ) {
1926 SESEandAgePair pair = pItr.next();
1927 output.println(" void* "+pair+" = NULL;");
1930 // declare variables for tracking dynamic sources
1931 output.println(" /* dynamic variable sources */");
1932 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1933 while( dynSrcItr.hasNext() ) {
1934 TempDescriptor dynSrcVar = dynSrcItr.next();
1935 output.println(" SESEcommon* "+dynSrcVar+"_srcSESE = NULL;");
1936 output.println(" INTPTR "+dynSrcVar+"_srcOffset = 0x1;");
1941 // set up related allocation sites's waiting queues
1944 ConflictGraph graph = null;
1945 graph = mlpa.getConflictGraphResults().get(fm);
1946 if (graph != null && graph.hasConflictEdge()) {
1947 output.println(" /* set up waiting queues */");
1948 output.println(" int numMemoryQueue=0;");
1949 output.println(" int memoryQueueItemID=0;");
1950 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
1952 System.out.println("#lockSet="+lockSet.hashCode());
1953 System.out.println("lockset="+lockSet);
1954 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1955 SESELock seseLock = (SESELock) iterator.next();
1956 System.out.println("id="+seseLock.getID());
1957 System.out.println("#="+seseLock);
1959 System.out.println("size="+lockSet.size());
1960 if (lockSet.size() > 0) {
1961 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1962 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
1963 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1968 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1969 if(callerSESEplaceholder!= oooa.getMainSESE()){
1970 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(callerSESEplaceholder);
1971 if (graph != null && graph.hasConflictEdge()) {
1972 output.println(" // set up waiting queues ");
1973 output.println(" int numMemoryQueue=0;");
1974 output.println(" int memoryQueueItemID=0;");
1975 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
1976 System.out.println("#lockSet="+lockSet.hashCode());
1977 System.out.println("lockset="+lockSet);
1978 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1979 Analysis.OoOJava.SESELock seseLock = (Analysis.OoOJava.SESELock) iterator.next();
1980 System.out.println("id="+seseLock.getID());
1981 System.out.println("#="+seseLock);
1983 System.out.println("size="+lockSet.size());
1984 if (lockSet.size() > 0) {
1985 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1986 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
1987 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1997 /* Check to see if we need to do a GC if this is a
1998 * multi-threaded program...*/
2000 if (((state.MLP||state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
2001 || this.state.MULTICOREGC) {
2002 //Don't bother if we aren't in recursive methods...The loops case will catch it
2003 if (callgraph.getAllMethods(md).contains(md)) {
2004 if (state.DSM&&lb.isAtomic())
2005 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
2006 else if (this.state.MULTICOREGC) {
2007 output.println("if(gcflag) gc("+localsprefixaddr+");");
2009 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2014 if(fm.getMethod().isStaticBlock()) {
2016 } else if((fm.getMethod().getReturnType() == null) && (cn != null)){
2017 // is a constructor, check and output initialization of the static fields
2018 Vector fields=(Vector)fieldorder.get(cn);
2020 for(int i=0; i<fields.size(); i++) {
2021 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
2024 output.println(generateTemp(fm,fm.getParameter(0),lb)+"->"+fd.getSafeSymbol()+"=&(global_defs_p->"+cn.getSafeSymbol()+fd.getSafeSymbol()+");");
2029 generateCode(fm.getNext(0), fm, lb, null, output, true);
2031 output.println("}\n\n");
2035 protected void initializeSESE( FlatSESEEnterNode fsen ) {
2037 FlatMethod fm = fsen.getfmEnclosing();
2038 MethodDescriptor md = fm.getMethod();
2039 ClassDescriptor cn = md.getClassDesc();
2042 // Creates bogus method descriptor to index into tables
2043 Modifiers modBogus = new Modifiers();
2044 MethodDescriptor mdBogus =
2045 new MethodDescriptor( modBogus,
2046 new TypeDescriptor( TypeDescriptor.VOID ),
2047 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
2050 mdBogus.setClassDesc( fsen.getcdEnclosing() );
2051 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
2052 fsen.setfmBogus( fmBogus );
2053 fsen.setmdBogus( mdBogus );
2055 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
2056 inSetAndOutSet.addAll( fsen.getInVarSet() );
2057 inSetAndOutSet.addAll( fsen.getOutVarSet() );
2059 // Build paramsobj for bogus method descriptor
2060 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
2061 paramstable.put( mdBogus, objectparams );
2063 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
2064 while( itr.hasNext() ) {
2065 TempDescriptor temp = itr.next();
2066 TypeDescriptor type = temp.getType();
2067 if( type.isPtr() ) {
2068 objectparams.addPtr( temp );
2070 objectparams.addPrim( temp );
2074 // Build normal temp object for bogus method descriptor
2075 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
2076 tempstable.put( mdBogus, objecttemps );
2078 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
2079 FlatNode fn = (FlatNode)nodeit.next();
2080 TempDescriptor[] writes = fn.writesTemps();
2082 for( int i = 0; i < writes.length; i++ ) {
2083 TempDescriptor temp = writes[i];
2084 TypeDescriptor type = temp.getType();
2086 if( type.isPtr() ) {
2087 objecttemps.addPtr( temp );
2089 objecttemps.addPrim( temp );
2095 // used when generating the specific SESE record struct
2096 // to remember the FIRST field name of sese records
2097 // that the current SESE depends on--we need to know the
2098 // offset to the first one for garbage collection
2099 protected void addingDepRecField( FlatSESEEnterNode fsen,
2101 if( fsen.getFirstDepRecField() == null ) {
2102 fsen.setFirstDepRecField( field );
2104 fsen.incNumDepRecs();
2107 protected void generateMethodSESE(FlatSESEEnterNode fsen,
2109 PrintWriter outputStructs,
2110 PrintWriter outputMethHead,
2111 PrintWriter outputMethods
2114 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
2115 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
2117 // generate locals structure
2118 outputStructs.println("struct "+
2119 fsen.getcdEnclosing().getSafeSymbol()+
2120 fsen.getmdBogus().getSafeSymbol()+"_"+
2121 fsen.getmdBogus().getSafeMethodDescriptor()+
2123 outputStructs.println(" int size;");
2124 outputStructs.println(" void * next;");
2125 for(int i=0; i<objecttemps.numPointers(); i++) {
2126 TempDescriptor temp=objecttemps.getPointer(i);
2128 if (temp.getType().isNull())
2129 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
2131 outputStructs.println(" struct "+
2132 temp.getType().getSafeSymbol()+" * "+
2133 temp.getSafeSymbol()+";");
2135 outputStructs.println("};\n");
2138 // divide in-set and out-set into objects and primitives to prep
2139 // for the record generation just below
2140 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
2141 inSetAndOutSet.addAll( fsen.getInVarSet() );
2142 inSetAndOutSet.addAll( fsen.getOutVarSet() );
2144 Set<TempDescriptor> inSetAndOutSetObjs = new HashSet<TempDescriptor>();
2145 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
2147 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
2148 while( itr.hasNext() ) {
2149 TempDescriptor temp = itr.next();
2150 TypeDescriptor type = temp.getType();
2151 if( type.isPtr() ) {
2152 inSetAndOutSetObjs.add( temp );
2154 inSetAndOutSetPrims.add( temp );
2159 // generate the SESE record structure
2160 outputStructs.println(fsen.getSESErecordName()+" {");
2162 // data common to any SESE, and it must be placed first so
2163 // a module that doesn't know what kind of SESE record this
2164 // is can cast the pointer to a common struct
2165 outputStructs.println(" SESEcommon common;");
2167 // then garbage list stuff
2168 outputStructs.println(" /* next is in-set and out-set objects that look like a garbage list */");
2169 outputStructs.println(" int size;");
2170 outputStructs.println(" void * next;");
2172 // I think that the set of TempDescriptors inSetAndOutSetObjs
2173 // calculated above should match the pointer object params
2174 // used in the following code, but let's just leave the working
2175 // implementation unless there is actually a problem...
2177 Vector<TempDescriptor> inset=fsen.getInVarsForDynamicCoarseConflictResolution();
2178 for(int i=0; i<inset.size();i++) {
2179 TempDescriptor temp=inset.get(i);
2180 if (temp.getType().isNull())
2181 outputStructs.println(" void * "+temp.getSafeSymbol()+
2182 "; /* in-or-out-set obj in gl */");
2184 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+
2185 temp.getSafeSymbol()+"; /* in-or-out-set obj in gl */");
2188 for(int i=0; i<objectparams.numPointers(); i++) {
2189 TempDescriptor temp=objectparams.getPointer(i);
2190 if (!inset.contains(temp)) {
2191 if (temp.getType().isNull())
2192 outputStructs.println(" void * "+temp.getSafeSymbol()+
2193 "; /* in-or-out-set obj in gl */");
2195 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+
2196 temp.getSafeSymbol()+"; /* in-or-out-set obj in gl */");
2200 outputStructs.println(" /* next is primitives for in-set and out-set and dynamic tracking */");
2202 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
2203 while( itrPrims.hasNext() ) {
2204 TempDescriptor temp = itrPrims.next();
2205 TypeDescriptor type = temp.getType();
2206 if(type.isPrimitive()){
2207 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+"; /* in-set or out-set primitive */");
2211 // note that the sese record pointer will be added below, just primitive part of tracking here
2212 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
2213 while( itrDynInVars.hasNext() ) {
2214 TempDescriptor dynInVar = itrDynInVars.next();
2215 outputStructs.println(" INTPTR "+dynInVar+"_srcOffset; /* dynamic tracking primitive */");
2219 outputStructs.println(" /* everything after this should be pointers to an SESE record */" );
2221 // other half of info for dynamic tracking, the SESE record pointer
2222 itrDynInVars = fsen.getDynamicInVarSet().iterator();
2223 while( itrDynInVars.hasNext() ) {
2224 TempDescriptor dynInVar = itrDynInVars.next();
2225 String depRecField = dynInVar+"_srcSESE";
2226 outputStructs.println(" SESEcommon* "+depRecField+";");
2227 addingDepRecField( fsen, depRecField );
2230 // statically known sese sources are record pointers, too
2231 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
2232 while( itrStaticInVarSrcs.hasNext() ) {
2233 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
2234 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
2235 addingDepRecField(fsen, srcPair.toString());
2239 if (inset.size()!=0)
2240 outputStructs.println("struct rcrRecord rcrRecords["+inset.size()+"];");
2243 if( fsen.getFirstDepRecField() != null ) {
2244 outputStructs.println(" /* compiler believes first dependent SESE record field above is: "+
2245 fsen.getFirstDepRecField()+" */" );
2247 outputStructs.println("};\n");
2250 // write method declaration to header file
2251 outputMethHead.print("void ");
2252 outputMethHead.print(fsen.getSESEmethodName()+"(");
2253 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
2254 outputMethHead.println(");\n");
2257 generateFlatMethodSESE( fsen.getfmBogus(),
2258 fsen.getcdEnclosing(),
2264 private void generateFlatMethodSESE(FlatMethod fm,
2266 FlatSESEEnterNode fsen,
2267 FlatSESEExitNode seseExit,
2271 MethodDescriptor md=fm.getMethod();
2273 output.print("void ");
2274 output.print(fsen.getSESEmethodName()+"(");
2275 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
2276 output.println("){\n");
2279 TempObject objecttemp=(TempObject) tempstable.get(md);
2281 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2282 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2283 output.print(objecttemp.numPointers()+",");
2284 output.print("&(((SESEcommon*)(___params___))[1])");
2285 for(int j=0; j<objecttemp.numPointers(); j++)
2286 output.print(", NULL");
2287 output.println("};");
2290 output.println(" /* regular local primitives */");
2291 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2292 TempDescriptor td=objecttemp.getPrimitive(i);
2293 TypeDescriptor type=td.getType();
2295 output.println(" void * "+td.getSafeSymbol()+";");
2296 else if (type.isClass()||type.isArray())
2297 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2299 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2303 // declare variables for naming static SESE's
2304 output.println(" /* static SESE names */");
2305 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
2306 while( pItr.hasNext() ) {
2307 SESEandAgePair pair = pItr.next();
2308 output.println(" SESEcommon* "+pair+" = NULL;");
2311 // declare variables for tracking dynamic sources
2312 output.println(" /* dynamic variable sources */");
2313 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
2314 while( dynSrcItr.hasNext() ) {
2315 TempDescriptor dynSrcVar = dynSrcItr.next();
2316 output.println(" SESEcommon* "+dynSrcVar+"_srcSESE = NULL;");
2317 output.println(" INTPTR "+dynSrcVar+"_srcOffset = 0x1;");
2320 // declare local temps for in-set primitives, and if it is
2321 // a ready-source variable, get the value from the record
2322 output.println(" /* local temps for in-set primitives */");
2323 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2324 while( itrInSet.hasNext() ) {
2325 TempDescriptor temp = itrInSet.next();
2326 TypeDescriptor type = temp.getType();
2327 if( !type.isPtr() ) {
2328 if( fsen.getReadyInVarSet().contains( temp ) ) {
2329 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2331 output.println(" "+type+" "+temp+";");
2336 // declare local temps for out-set primitives if its not already
2337 // in the in-set, and it's value will get written so no problem
2338 output.println(" /* local temp for out-set prim, not already in the in-set */");
2339 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2340 while( itrOutSet.hasNext() ) {
2341 TempDescriptor temp = itrOutSet.next();
2342 TypeDescriptor type = temp.getType();
2343 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2344 output.println(" "+type+" "+temp+";");
2349 // initialize thread-local var to a the task's record, which is fused
2350 // with the param list
2351 output.println(" ");
2352 output.println(" // code of this task's body should use this to access the running task record");
2353 output.println(" runningSESE = &(___params___->common);");
2354 output.println(" ");
2356 // setup memory queue
2359 output.println(" // set up memory queues ");
2360 output.println(" int numMemoryQueue=0;");
2361 output.println(" int memoryQueueItemID=0;");
2362 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(fsen);
2363 if (graph != null && graph.hasConflictEdge()) {
2364 output.println(" {");
2365 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
2366 System.out.println("#lockSet="+lockSet);
2367 if (lockSet.size() > 0) {
2368 output.println(" numMemoryQueue=" + lockSet.size() + ";");
2369 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
2370 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2373 output.println(" }");
2376 output.println(" // set up memory queues ");
2377 output.println(" int numMemoryQueue=0;");
2378 output.println(" int memoryQueueItemID=0;");
2379 ConflictGraph graph = null;
2380 graph = mlpa.getConflictGraphResults().get(fsen);
2381 if (graph != null && graph.hasConflictEdge()) {
2382 output.println(" {");
2383 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
2385 System.out.println("#lockSet="+lockSet);
2387 if (lockSet.size() > 0) {
2388 output.println(" numMemoryQueue=" + lockSet.size() + "; ");
2389 output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
2390 output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2393 output.println(" }");
2398 // set up a task's mem pool to recycle the allocation of children tasks
2399 // don't bother if the task never has children (a leaf task)
2400 output.println( "#ifndef OOO_DISABLE_TASKMEMPOOL" );
2401 if( !fsen.getIsLeafSESE() ) {
2402 output.println(" runningSESE->taskRecordMemPool = poolcreate( "+
2403 maxTaskRecSizeStr+" );");
2405 // make it clear we purposefully did not initialize this
2406 output.println(" runningSESE->taskRecordMemPool = (MemPool*)0x1;");
2408 output.println( "#endif // OOO_DISABLE_TASKMEMPOOL" );
2411 // copy in-set into place, ready vars were already
2412 // copied when the SESE was issued
2413 Iterator<TempDescriptor> tempItr;
2415 // static vars are from a known SESE
2416 output.println(" // copy variables from static sources");
2417 tempItr = fsen.getStaticInVarSet().iterator();
2418 while( tempItr.hasNext() ) {
2419 TempDescriptor temp = tempItr.next();
2420 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2421 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2422 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2423 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2426 output.println(" // decrement references to static sources");
2427 for( Iterator<SESEandAgePair> pairItr = fsen.getStaticInVarSrcs().iterator(); pairItr.hasNext(); ) {
2428 SESEandAgePair srcPair = pairItr.next();
2429 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
2430 output.println(" {");
2431 output.println(" SESEcommon* src = &("+paramsprefix+"->"+srcPair+"->common);");
2432 output.println(" RELEASE_REFERENCE_TO( src );");
2433 output.println(" }");
2434 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
2438 // dynamic vars come from an SESE and src
2439 output.println(" // copy variables from dynamic sources");
2440 tempItr = fsen.getDynamicInVarSet().iterator();
2441 while( tempItr.hasNext() ) {
2442 TempDescriptor temp = tempItr.next();
2443 TypeDescriptor type = temp.getType();
2445 // go grab it from the SESE source
2446 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2449 if( type.isNull() ) {
2451 } else if( type.isClass() || type.isArray() ) {
2452 typeStr = "struct "+type.getSafeSymbol()+"*";
2454 typeStr = type.getSafeSymbol();
2457 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2458 " = *(("+typeStr+"*) ((void*)"+
2459 paramsprefix+"->"+temp+"_srcSESE + "+
2460 paramsprefix+"->"+temp+"_srcOffset));");
2462 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
2463 output.println(" SESEcommon* src = "+paramsprefix+"->"+temp+"_srcSESE;");
2464 output.println(" RELEASE_REFERENCE_TO( src );");
2465 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
2467 // or if the source was our parent, its already in our record to grab
2468 output.println(" } else {");
2469 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2470 " = "+paramsprefix+"->"+temp+";");
2471 output.println(" }");
2474 // Check to see if we need to do a GC if this is a
2475 // multi-threaded program...
2476 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2477 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2478 //Don't bother if we aren't in recursive methods...The loops case will catch it
2479 // if (callgraph.getAllMethods(md).contains(md)) {
2480 // if(this.state.MULTICOREGC) {
2481 // output.println("if(gcflag) gc("+localsprefixaddr+");");
2483 // output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2488 if( state.COREPROF ) {
2489 output.println("#ifdef CP_EVENTID_TASKEXECUTE");
2490 output.println(" CP_LOGEVENT( CP_EVENTID_TASKEXECUTE, CP_EVENTTYPE_BEGIN );");
2491 output.println("#endif");
2494 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2495 exitset.add(seseExit);
2496 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2497 output.println("}\n\n");
2502 // when a new mlp thread is created for an issued SESE, it is started
2503 // by running this method which blocks on a cond variable until
2504 // it is allowed to transition to execute. Then a case statement
2505 // allows it to invoke the method with the proper SESE body, and after
2506 // exiting the SESE method, executes proper SESE exit code before the
2507 // thread can be destroyed
2508 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2509 PrintWriter outmethod
2512 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2513 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2514 outmethod.println( " int status;");
2515 outmethod.println( " char errmsg[128];");
2517 // generate a case for each SESE class that can be invoked
2518 outmethod.println( " switch( *((int*)seseRecord) ) {");
2519 outmethod.println( " ");
2520 Iterator<FlatSESEEnterNode> seseit;
2522 seseit=mlpa.getAllSESEs().iterator();
2524 seseit=oooa.getAllSESEs().iterator();
2526 while(seseit.hasNext()){
2527 FlatSESEEnterNode fsen = seseit.next();
2529 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2530 outmethod.println( " case "+fsen.getIdentifier()+":");
2531 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2533 if( (state.MLP && fsen.equals( mlpa.getMainSESE() )) ||
2534 (state.OOOJAVA && fsen.equals( oooa.getMainSESE() ))
2536 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2537 outmethod.println( " CP_EXIT();");
2538 outmethod.println( " CP_DUMP();");
2539 outmethod.println( " workScheduleExit();");
2540 outmethod.println( " exit( 0 );");
2543 outmethod.println( " break;");
2544 outmethod.println( "");
2547 // default case should never be taken, error out
2548 outmethod.println( " default:");
2549 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2550 outmethod.println( " exit(-30);");
2551 outmethod.println( " break;");
2552 outmethod.println( " }");
2553 outmethod.println( " return NULL;");
2554 outmethod.println( "}\n\n");
2558 protected void generateCode(FlatNode first,
2561 Set<FlatNode> stopset,
2562 PrintWriter output, boolean firstpass) {
2564 /* Assign labels to FlatNode's if necessary.*/
2566 Hashtable<FlatNode, Integer> nodetolabel;
2568 if (state.DELAYCOMP&&!firstpass)
2569 nodetolabel=dcassignLabels(first, stopset);
2571 nodetolabel=assignLabels(first, stopset);
2573 Set<FlatNode> storeset=null;
2574 HashSet<FlatNode> genset=null;
2575 HashSet<FlatNode> refset=null;
2576 Set<FlatNode> unionset=null;
2578 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2579 storeset=delaycomp.livecode(lb);
2580 genset=new HashSet<FlatNode>();
2581 if (state.STMARRAY&&!state.DUALVIEW) {
2582 refset=new HashSet<FlatNode>();
2583 refset.addAll(delaycomp.getDeref(lb));
2584 refset.removeAll(delaycomp.getCannotDelay(lb));
2585 refset.removeAll(delaycomp.getOther(lb));
2588 genset.addAll(delaycomp.getCannotDelay(lb));
2589 genset.addAll(delaycomp.getOther(lb));
2591 genset.addAll(delaycomp.getNotReady(lb));
2592 if (state.STMARRAY&&!state.DUALVIEW) {
2593 genset.removeAll(refset);
2596 unionset=new HashSet<FlatNode>();
2597 unionset.addAll(storeset);
2598 unionset.addAll(genset);
2599 if (state.STMARRAY&&!state.DUALVIEW)
2600 unionset.addAll(refset);
2603 /* Do the actual code generation */
2604 FlatNode current_node=null;
2605 HashSet tovisit=new HashSet();
2606 HashSet visited=new HashSet();
2608 tovisit.add(first.getNext(0));
2611 while(current_node!=null||!tovisit.isEmpty()) {
2612 if (current_node==null) {
2613 current_node=(FlatNode)tovisit.iterator().next();
2614 tovisit.remove(current_node);
2615 } else if (tovisit.contains(current_node)) {
2616 tovisit.remove(current_node);
2618 visited.add(current_node);
2619 if (nodetolabel.containsKey(current_node)) {
2620 output.println("L"+nodetolabel.get(current_node)+":");
2622 if (state.INSTRUCTIONFAILURE) {
2623 if (state.THREAD||state.DSM||state.SINGLETM) {
2624 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2626 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2628 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2630 if (!state.DELAYCOMP||firstpass) {
2631 generateFlatNode(fm, lb, current_node, output);
2633 //store primitive variables in out set
2634 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2635 Set<TempDescriptor> liveout=ar.liveout;
2636 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2637 TempDescriptor tmp=tmpit.next();
2638 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2641 if ((state.MLP || state.OOOJAVA) && stopset!=null) {
2642 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2643 assert current_node instanceof FlatSESEExitNode;
2644 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2645 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2646 assert fsen.getFlatExit().equals( fsxn );
2647 assert fsxn.getFlatEnter().equals( fsen );
2649 if (current_node.kind()!=FKind.FlatReturnNode) {
2650 output.println(" return;");
2653 } else if(current_node.numNext()==1) {
2655 if ((state.MLP|| state.OOOJAVA) &&
2656 current_node.kind()==FKind.FlatSESEEnterNode &&
2657 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2659 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2660 generateFlatNode(fm, lb, current_node, output);
2661 nextnode=fsen.getFlatExit().getNext(0);
2662 } else if (state.DELAYCOMP) {
2663 boolean specialprimitive=false;
2664 //skip literals...no need to add extra overhead
2665 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2666 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2667 if (!typedesc.isClass()&&!typedesc.isArray()) {
2668 specialprimitive=true;
2672 if (genset==null||genset.contains(current_node)||specialprimitive)
2673 generateFlatNode(fm, lb, current_node, output);
2674 if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2675 //need to acquire lock
2676 handleArrayDeref(fm, lb, current_node, output, firstpass);
2678 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2679 TempDescriptor wrtmp=current_node.writesTemps()[0];
2681 //need to store value written by previous node
2682 if (wrtmp.getType().isPtr()) {
2683 //only lock the objects that may actually need locking
2684 if (recorddc.getNeedTrans(lb, current_node)&&
2685 (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2686 wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2687 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2689 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2692 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2695 //need to read value read by previous node
2696 if (wrtmp.getType().isPtr()) {
2697 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2699 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");
2703 nextnode=current_node.getNext(0);
2706 generateFlatNode(fm, lb, current_node, output);
2707 nextnode=current_node.getNext(0);
2709 if (visited.contains(nextnode)) {
2710 output.println("goto L"+nodetolabel.get(nextnode)+";");
2713 current_node=nextnode;
2714 } else if (current_node.numNext()==2) {
2716 if (state.DELAYCOMP) {
2717 boolean computeside=false;
2719 //need to record which way it should go
2720 if (genset==null||genset.contains(current_node)) {
2721 if (storeset!=null&&storeset.contains(current_node)) {
2722 //need to store which way branch goes
2723 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2725 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2727 //which side to execute
2731 if (genset.contains(current_node)) {
2732 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2733 } else if (storeset.contains(current_node)) {
2735 branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2737 //which side to execute
2742 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2744 if (leftset.size()==0)
2746 if (visited.contains(current_node.getNext(branch))) {
2747 //already visited -- build jump
2748 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2751 current_node=current_node.getNext(branch);
2754 if (!visited.contains(current_node.getNext(1)))
2755 tovisit.add(current_node.getNext(1));
2756 if (visited.contains(current_node.getNext(0))) {
2757 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2760 current_node=current_node.getNext(0);
2764 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2765 if (!visited.contains(current_node.getNext(1)))
2766 tovisit.add(current_node.getNext(1));
2767 if (visited.contains(current_node.getNext(0))) {
2768 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2771 current_node=current_node.getNext(0);
2773 } else throw new Error();
2777 protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2778 if (fn.kind()==FKind.FlatSetElementNode) {
2779 FlatSetElementNode fsen=(FlatSetElementNode) fn;
2780 String dst=generateTemp(fm, fsen.getDst(), lb);
2781 String src=generateTemp(fm, fsen.getSrc(), lb);
2782 String index=generateTemp(fm, fsen.getIndex(), lb);
2783 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2785 if (elementtype.isArray()||elementtype.isClass())
2788 type=elementtype.getSafeSymbol()+" ";
2790 output.println("STOREARRAY("+dst+","+index+","+type+")");
2792 output.println("{");
2793 output.println(" struct ArrayObject *array;");
2794 output.println(" int index;");
2795 output.println(" RESTOREARRAY(array,index);");
2796 output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2797 output.println("}");
2799 } else if (fn.kind()==FKind.FlatElementNode) {
2800 FlatElementNode fen=(FlatElementNode) fn;
2801 String src=generateTemp(fm, fen.getSrc(), lb);
2802 String index=generateTemp(fm, fen.getIndex(), lb);
2803 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2804 String dst=generateTemp(fm, fen.getDst(), lb);
2806 if (elementtype.isArray()||elementtype.isClass())
2809 type=elementtype.getSafeSymbol()+" ";
2811 output.println("STOREARRAY("+src+","+index+","+type+")");
2813 output.println("{");
2814 output.println(" struct ArrayObject *array;");
2815 output.println(" int index;");
2816 output.println(" RESTOREARRAY(array,index);");
2817 output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2818 output.println("}");
2822 /** Special label assignment for delaycomputation */
2823 protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2824 HashSet tovisit=new HashSet();
2825 HashSet visited=new HashSet();
2827 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2829 //Label targets of branches
2830 Set<FlatNode> targets=branchanalysis.getTargets();
2831 for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2832 nodetolabel.put(it.next(), new Integer(labelindex++));
2837 /*Assign labels first. A node needs a label if the previous
2838 * node has two exits or this node is a join point. */
2840 while(!tovisit.isEmpty()) {
2841 FlatNode fn=(FlatNode)tovisit.iterator().next();
2846 if(lastset!=null&&lastset.contains(fn)) {
2847 // if last is not null and matches, don't go
2848 // any further for assigning labels
2852 for(int i=0; i<fn.numNext(); i++) {
2853 FlatNode nn=fn.getNext(i);
2856 //1) Edge >1 of node
2857 nodetolabel.put(nn,new Integer(labelindex++));
2859 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2863 nodetolabel.put(nn,new Integer(labelindex++));
2871 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2872 return assignLabels(first, null);
2875 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2876 HashSet tovisit=new HashSet();
2877 HashSet visited=new HashSet();
2879 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2882 /*Assign labels first. A node needs a label if the previous
2883 * node has two exits or this node is a join point. */
2885 while(!tovisit.isEmpty()) {
2886 FlatNode fn=(FlatNode)tovisit.iterator().next();
2891 if(lastset!=null&&lastset.contains(fn)) {
2892 // if last is not null and matches, don't go
2893 // any further for assigning labels
2897 for(int i=0; i<fn.numNext(); i++) {
2898 FlatNode nn=fn.getNext(i);
2901 //1) Edge >1 of node
2902 nodetolabel.put(nn,new Integer(labelindex++));
2904 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2908 nodetolabel.put(nn,new Integer(labelindex++));
2916 /** Generate text string that corresponds to the TempDescriptor td. */
2917 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2918 MethodDescriptor md=fm.getMethod();
2919 TaskDescriptor task=fm.getTask();
2920 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2922 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2923 return td.getSafeSymbol();
2926 if (objecttemps.isLocalPtr(td)) {
2927 return localsprefixderef+td.getSafeSymbol();
2930 if (objecttemps.isParamPtr(td)) {
2931 return paramsprefix+"->"+td.getSafeSymbol();
2937 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2939 // insert pre-node actions from the code plan
2940 if( state.MLP|| state.OOOJAVA ) {
2944 cp = mlpa.getCodePlan( fn );
2946 cp = oooa.getCodePlan(fn);
2951 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2953 // for each sese and age pair that this parent statement
2954 // must stall on, take that child's stall semaphore, the
2955 // copying of values comes after the statement
2956 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2957 while( vstItr.hasNext() ) {
2958 VariableSourceToken vst = vstItr.next();
2960 SESEandAgePair pair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2962 output.println(" {");
2963 output.println(" "+pair.getSESE().getSESErecordName()+"* child = ("+
2964 pair.getSESE().getSESErecordName()+"*) "+pair+";");
2966 output.println(" SESEcommon* childCom = (SESEcommon*) "+pair+";");
2968 if( state.COREPROF ) {
2969 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
2970 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
2971 output.println("#endif");
2974 output.println(" pthread_mutex_lock( &(childCom->lock) );");
2975 output.println(" if( childCom->doneExecuting == FALSE ) {");
2976 output.println(" psem_reset( &runningSESEstallSem );");
2977 output.println(" childCom->parentsStallSem = &runningSESEstallSem;");
2978 output.println(" pthread_mutex_unlock( &(childCom->lock) );");
2979 output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );");
2980 output.println(" } else {");
2981 output.println(" pthread_mutex_unlock( &(childCom->lock) );");
2982 output.println(" }");
2984 // copy things we might have stalled for
2985 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2986 while( tdItr.hasNext() ) {
2987 TempDescriptor td = tdItr.next();
2988 FlatMethod fmContext;
2989 if( currentSESE.getIsCallerSESEplaceholder() ) {
2990 fmContext = currentSESE.getfmEnclosing();
2992 fmContext = currentSESE.getfmBogus();
2994 output.println(" "+generateTemp( fmContext, td, null )+
2995 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2998 if( state.COREPROF ) {
2999 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
3000 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
3001 output.println("#endif");
3004 output.println(" }");
3007 // for each variable with a dynamic source, stall just for that variable
3008 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
3009 while( dynItr.hasNext() ) {
3010 TempDescriptor dynVar = dynItr.next();
3012 // only stall if the dynamic source is not yourself, denoted by src==NULL
3013 // otherwise the dynamic write nodes will have the local var up-to-date
3014 output.println(" {");
3015 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
3017 output.println(" SESEcommon* childCom = (SESEcommon*) "+dynVar+"_srcSESE;");
3019 if( state.COREPROF ) {
3020 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
3021 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
3022 output.println("#endif");
3025 output.println(" pthread_mutex_lock( &(childCom->lock) );");
3026 output.println(" if( childCom->doneExecuting == FALSE ) {");
3027 output.println(" psem_reset( &runningSESEstallSem );");
3028 output.println(" childCom->parentsStallSem = &runningSESEstallSem;");
3029 output.println(" pthread_mutex_unlock( &(childCom->lock) );");
3030 output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );");
3031 output.println(" } else {");
3032 output.println(" pthread_mutex_unlock( &(childCom->lock) );");
3033 output.println(" }");
3035 FlatMethod fmContext;
3036 if( currentSESE.getIsCallerSESEplaceholder() ) {
3037 fmContext = currentSESE.getfmEnclosing();
3039 fmContext = currentSESE.getfmBogus();
3042 TypeDescriptor type = dynVar.getType();
3044 if( type.isNull() ) {
3046 } else if( type.isClass() || type.isArray() ) {
3047 typeStr = "struct "+type.getSafeSymbol()+"*";
3049 typeStr = type.getSafeSymbol();
3052 output.println(" "+generateTemp( fmContext, dynVar, null )+
3053 " = *(("+typeStr+"*) ((void*)"+
3054 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
3056 if( state.COREPROF ) {
3057 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
3058 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
3059 output.println("#endif");
3062 output.println(" }");
3063 output.println(" }");
3066 // for each assignment of a variable to rhs that has a dynamic source,
3067 // copy the dynamic sources
3068 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
3069 while( dynAssignItr.hasNext() ) {
3070 Map.Entry me = (Map.Entry) dynAssignItr.next();
3071 TempDescriptor lhs = (TempDescriptor) me.getKey();
3072 TempDescriptor rhs = (TempDescriptor) me.getValue();
3074 output.println(" {");
3075 output.println(" SESEcommon* oldSrc = "+lhs+"_srcSESE;");
3077 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
3078 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
3080 // no matter what we did above, track reference count of whatever
3081 // this variable pointed to, do release last in case we're just
3082 // copying the same value in because 1->2->1 is safe but ref count
3083 // 1->0->1 has a window where it looks like it should be free'd
3084 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3085 output.println(" if( "+rhs+"_srcSESE != NULL ) {");
3086 output.println(" ADD_REFERENCE_TO( "+rhs+"_srcSESE );");
3087 output.println(" }");
3088 output.println(" if( oldSrc != NULL ) {");
3089 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
3090 output.println(" }");
3091 output.println(" }");
3092 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
3095 // for each lhs that is dynamic from a non-dynamic source, set the
3096 // dynamic source vars to the current SESE
3097 dynItr = cp.getDynAssignCurr().iterator();
3098 while( dynItr.hasNext() ) {
3099 TempDescriptor dynVar = dynItr.next();
3100 assert currentSESE.getDynamicVarSet().contains( dynVar );
3102 // first release a reference to current record
3103 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3104 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
3105 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
3106 output.println(" }");
3107 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
3109 output.println(" "+dynVar+"_srcSESE = NULL;");
3113 // handling stall site
3114 if (state.OOOJAVA) {
3115 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(currentSESE);
3117 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
3118 Set<Analysis.OoOJava.WaitingElement> waitingElementSet =
3119 graph.getStallSiteWaitingElementSet(fn, seseLockSet);
3121 if(waitingElementSet.size()>0){
3122 output.println("// stall on parent's stall sites ");
3123 output.println(" {");
3124 output.println(" REntry* rentry;");
3126 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
3127 Analysis.OoOJava.WaitingElement waitingElement = (Analysis.OoOJava.WaitingElement) iterator.next();
3130 Analysis.OoOJava.ConflictGraph conflictGraph = graph;
3131 Hashtable<Taint, Set<Effect>> conflicts;
3132 ReachGraph rg = oooa.getDisjointAnalysis().getReachGraph(currentSESE.getmdEnclosing());
3133 if(rcr.cSideDebug) {
3134 rg.writeGraph("RCR_RG_STALLSITE_DEBUG");
3136 if((conflictGraph != null) &&
3137 (conflicts = graph.getConflictEffectSet(fn)) != null &&
3139 rcr.addToTraverseToDoList(fn, waitingElement.getTempDesc(), rg, conflicts);
3143 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3144 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", runningSESE);");
3146 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", runningSESE, (void*)&" +generateTemp(fm,waitingElement.getTempDesc(),lb)+ ");");
3148 output.println(" psem_init( &(rentry->parentStallSem) );");
3149 output.println(" rentry->queue=runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3150 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()
3151 + "],rentry)==NOTREADY){");
3152 if( state.COREPROF ) {
3153 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3154 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3155 output.println("#endif");
3157 output.println(" psem_take( &(rentry->parentStallSem), (struct garbagelist *)&___locals___ );");
3158 if( state.COREPROF ) {
3159 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3160 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3161 output.println("#endif");
3163 output.println(" } ");
3166 output.println(" "+rcr.getTraverserInvocation(waitingElement.getTempDesc(),
3167 generateTemp(fm, waitingElement.getTempDesc(), null), fn));
3170 output.println(" }");
3174 ParentChildConflictsMap conflictsMap = mlpa.getConflictsResults().get(fn);
3175 if (conflictsMap != null) {
3176 Set<Long> allocSet = conflictsMap.getAllocationSiteIDSetofStallSite();
3177 if (allocSet.size() > 0) {
3178 FlatNode enclosingFlatNode=null;
3179 if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
3180 enclosingFlatNode=currentSESE.getfmEnclosing();
3182 enclosingFlatNode=currentSESE;
3184 ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
3185 HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
3186 Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
3188 if(waitingElementSet.size()>0){
3189 output.println("// stall on parent's stall sites ");
3190 output.println(" {");
3191 output.println(" REntry* rentry;");
3193 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
3194 WaitingElement waitingElement = (WaitingElement) iterator.next();
3196 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3197 // HERE! a parent might conflict with a child
3198 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", runningSESE);");
3200 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", runningSESE, (void*)&___locals___."+ waitingElement.getDynID() + ");");
3202 output.println(" psem_init( &(rentry->parentStallSem) );");
3203 output.println(" rentry->queue=runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3205 .println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()
3206 + "],rentry)==NOTREADY){");
3207 if( state.COREPROF ) {
3208 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3209 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3210 output.println("#endif");
3212 output.println(" psem_take( &(rentry->parentStallSem), (struct garbagelist *)&___locals___ );");
3213 if( state.COREPROF ) {
3214 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3215 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3216 output.println("#endif");
3218 output.println(" } ");
3220 output.println(" }");
3229 case FKind.FlatAtomicEnterNode:
3230 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
3233 case FKind.FlatAtomicExitNode:
3234 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
3237 case FKind.FlatInstanceOfNode:
3238 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
3241 case FKind.FlatSESEEnterNode:
3242 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
3245 case FKind.FlatSESEExitNode:
3246 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
3249 case FKind.FlatWriteDynamicVarNode:
3250 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
3253 case FKind.FlatGlobalConvNode:
3254 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
3257 case FKind.FlatTagDeclaration:
3258 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
3261 case FKind.FlatCall:
3262 generateFlatCall(fm, lb, (FlatCall) fn,output);
3265 case FKind.FlatFieldNode:
3266 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
3269 case FKind.FlatElementNode:
3270 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
3273 case FKind.FlatSetElementNode:
3274 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
3277 case FKind.FlatSetFieldNode:
3278 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
3282 generateFlatNew(fm, lb, (FlatNew) fn,output);
3285 case FKind.FlatOpNode:
3286 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
3289 case FKind.FlatCastNode:
3290 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
3293 case FKind.FlatLiteralNode:
3294 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
3297 case FKind.FlatReturnNode:
3298 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
3302 output.println("/* nop */");
3305 case FKind.FlatGenReachNode:
3306 // this node is just for generating a reach graph
3307 // in disjointness analysis at a particular program point
3310 case FKind.FlatExit:
3311 output.println("/* exit */");
3314 case FKind.FlatBackEdge:
3315 if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3316 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3318 if(state.DSM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3319 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3321 if (((state.MLP|| state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
3322 || (this.state.MULTICOREGC)) {
3323 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
3324 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
3325 } else if(this.state.MULTICOREGC) {
3326 output.println("if (gcflag) gc("+localsprefixaddr+");");
3328 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3331 output.println("/* nop */");
3334 case FKind.FlatCheckNode:
3335 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
3338 case FKind.FlatFlagActionNode:
3339 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
3342 case FKind.FlatPrefetchNode:
3343 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
3346 case FKind.FlatOffsetNode:
3347 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
3354 // insert post-node actions from the code-plan
3357 CodePlan cp = mlpa.getCodePlan( fn );
3365 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
3366 output.println("/* FlatOffsetNode */");
3367 FieldDescriptor fd=fofn.getField();
3368 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
3369 output.println("/* offset */");
3372 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
3373 if (state.PREFETCH) {
3374 Vector oids = new Vector();
3375 Vector fieldoffset = new Vector();
3376 Vector endoffset = new Vector();
3377 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
3378 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
3379 PrefetchPair pp = (PrefetchPair) it.next();
3380 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
3381 /* Find prefetches that can generate oid */
3382 if(statusbase == LocalityAnalysis.GLOBAL) {
3383 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
3385 } else if (statusbase == LocalityAnalysis.LOCAL) {
3386 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
3393 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
3394 output.println("{");
3395 output.println("/* prefetch */");
3396 output.println("/* prefetchid_" + fpn.siteid + " */");
3397 output.println("void * prefptr;");
3398 output.println("int tmpindex;");
3400 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
3401 /*Create C code for oid array */
3402 output.print(" unsigned int oidarray_[] = {");
3403 boolean needcomma=false;
3404 for (Iterator it = oids.iterator(); it.hasNext();) {
3407 output.print(it.next());
3410 output.println("};");
3412 /*Create C code for endoffset values */
3413 output.print(" unsigned short endoffsetarry_[] = {");
3415 for (Iterator it = endoffset.iterator(); it.hasNext();) {
3418 output.print(it.next());
3421 output.println("};");
3423 /*Create C code for Field Offset Values */
3424 output.print(" short fieldarry_[] = {");
3426 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
3429 output.print(it.next());
3432 output.println("};");
3433 /* make the prefetch call to Runtime */
3434 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
3435 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
3436 output.println(" }");
3437 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
3438 output.println(" } else {");
3439 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
3440 output.println(" }");
3441 output.println("}");
3445 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
3446 short offsetcount = 0;
3450 } else if (localbase) {
3451 for(; breakindex<pp.desc.size(); breakindex++) {
3452 Descriptor desc=pp.getDescAt(breakindex);
3453 if (desc instanceof FieldDescriptor) {
3454 FieldDescriptor fd=(FieldDescriptor)desc;
3455 if (fd.isGlobal()) {
3463 if (breakindex>pp.desc.size()) //all local
3466 TypeDescriptor lasttype=pp.base.getType();
3467 String basestr=generateTemp(fm, pp.base, lb);
3469 boolean maybenull=fm.getMethod().isStatic()||
3470 !pp.base.equals(fm.getParameter(0));
3472 for(int i=0; i<breakindex; i++) {
3473 String indexcheck="";
3475 Descriptor desc=pp.getDescAt(i);
3476 if (desc instanceof FieldDescriptor) {
3477 FieldDescriptor fd=(FieldDescriptor)desc;
3479 if (!teststr.equals(""))
3481 teststr+="((prefptr="+basestr+")!=NULL)";
3482 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3484 basestr=basestr+"->"+fd.getSafeSymbol();
3487 lasttype=fd.getType();
3489 IndexDescriptor id=(IndexDescriptor)desc;
3490 indexcheck="((tmpindex=";
3491 for(int j=0; j<id.tddesc.size(); j++) {
3492 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3494 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3496 if (!teststr.equals(""))
3498 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3499 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3501 lasttype=lasttype.dereference();
3506 if (teststr.equals("")) {
3507 oid="((unsigned int)"+basestr+")";
3509 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3513 for(int i = breakindex; i < pp.desc.size(); i++) {
3514 String newfieldoffset;
3515 Object desc = pp.getDescAt(i);
3516 if(desc instanceof FieldDescriptor) {
3517 FieldDescriptor fd=(FieldDescriptor)desc;
3518 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3519 lasttype=fd.getType();
3521 newfieldoffset = "";
3522 IndexDescriptor id=(IndexDescriptor)desc;
3523 for(int j = 0; j < id.tddesc.size(); j++) {
3524 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3526 newfieldoffset += id.offset.toString();
3527 lasttype=lasttype.dereference();
3529 fieldoffset.add(newfieldoffset);
3532 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3533 base+=pp.desc.size()-breakindex;
3534 endoffset.add(new Short((short)base));
3539 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3540 if (lb!=fgcn.getLocality())
3542 /* Have to generate flat globalconv */
3543 if (fgcn.getMakePtr()) {
3545 //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3546 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3548 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3549 //need to do translation
3550 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3551 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3552 if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3553 output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3555 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3559 /* Need to convert to OID */
3560 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3561 if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3562 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3564 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3570 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3572 if (fion.getType().isArray()) {
3573 type=state.getArrayNumber(fion.getType())+state.numClasses();
3575 type=fion.getType().getClassDesc().getId();
3578 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3579 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3581 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3584 int sandboxcounter=0;
3585 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3586 /* Check to see if we need to generate code for this atomic */
3587 if (locality==null) {
3588 if (GENERATEPRECISEGC) {
3589 output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3590 output.println("stopforgc((struct garbagelist *) &___locals___);");
3591 output.println("pthread_mutex_lock(&atomiclock);");
3592 output.println("restartaftergc();");
3593 output.println("}");
3595 output.println("pthread_mutex_lock(&atomiclock);");
3600 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3604 if (state.SANDBOX) {
3605 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3606 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3609 if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3610 AtomicRecord ar=atomicmethodmap.get(faen);
3612 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3613 TempDescriptor tmp=tmpit.next();
3614 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3617 //copy outs that depend on path
3618 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3619 TempDescriptor tmp=tmpit.next();
3620 if (!ar.livein.contains(tmp))
3621 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3625 /* Backup the temps. */
3626 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3627 TempDescriptor tmp=tmpit.next();
3628 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3631 output.println("goto transstart"+faen.getIdentifier()+";");
3633 /******* Print code to retry aborted transaction *******/
3634 output.println("transretry"+faen.getIdentifier()+":");
3637 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3638 TempDescriptor tmp=tmpit.next();
3639 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3643 /********* Need to revert local object store ********/
3644 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3646 output.println("while ("+revertptr+") {");
3647 output.println("struct ___Object___ * tmpptr;");
3648 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3649 output.println("REVERT_OBJ("+revertptr+");");
3650 output.println(revertptr+"=tmpptr;");
3651 output.println("}");
3653 /******* Tell the runtime to start the transaction *******/
3655 output.println("transstart"+faen.getIdentifier()+":");
3656 if (state.SANDBOX) {
3657 output.println("transaction_check_counter=*counter_reset_pointer;");
3660 output.println("transStart();");
3662 if (state.ABORTREADERS||state.SANDBOX) {
3664 output.println("abortenabled=1;");
3665 output.println("if (_setjmp(aborttrans)) {");
3666 output.println(" goto transretry"+faen.getIdentifier()+"; }");
3670 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3671 /* Check to see if we need to generate code for this atomic */
3672 if (locality==null) {
3673 output.println("pthread_mutex_unlock(&atomiclock);");
3676 if (locality.getAtomic(lb).get(faen).intValue()>0)
3678 //store the revert list before we lose the transaction object
3681 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3682 output.println(revertptr+"=revertlist;");
3683 output.println("if (transCommit()) {");
3684 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3685 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3686 output.println("} else {");
3687 /* Need to commit local object store */
3688 output.println("while ("+revertptr+") {");
3689 output.println("struct ___Object___ * tmpptr;");
3690 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3691 output.println("COMMIT_OBJ("+revertptr+");");
3692 output.println(revertptr+"=tmpptr;");
3693 output.println("}");
3694 output.println("}");
3698 if (!state.DELAYCOMP) {
3700 output.println("if (transCommit()) {");
3701 /* Transaction aborts if it returns true */
3702 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3703 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3704 output.println("}");
3706 if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
3707 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3708 output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3710 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3711 TempDescriptor tmp=tmpit.next();
3712 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3714 } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3715 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3717 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3718 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3719 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3720 output.println("}");
3722 output.println("else {");
3723 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3724 TempDescriptor tmp=tmpit.next();
3725 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3727 output.println("}");
3729 output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3730 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3731 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3732 output.println("}");
3737 public void generateFlatSESEEnterNode( FlatMethod fm,
3739 FlatSESEEnterNode fsen,
3740 PrintWriter output) {
3741 // if MLP flag is off, okay that SESE nodes are in IR graph,
3742 // just skip over them and code generates exactly the same
3743 if( !(state.MLP || state.OOOJAVA) ) {
3746 // there may be an SESE in an unreachable method, skip over
3747 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
3748 (state.OOOJAVA && !oooa.getAllSESEs().contains(fsen))
3753 // also, if we have encountered a placeholder, just skip it
3754 if( fsen.getIsCallerSESEplaceholder() ) {
3758 output.println(" {");
3760 if( state.COREPROF ) {
3761 output.println("#ifdef CP_EVENTID_TASKDISPATCH");
3762 output.println(" CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_BEGIN );");
3763 output.println("#endif");
3767 // before doing anything, lock your own record and increment the running children
3768 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3769 (state.OOOJAVA && fsen != oooa.getMainSESE())
3771 output.println(" atomic_inc(&(runningSESE->numRunningChildren));");
3774 // allocate the space for this record
3775 output.println( "#ifndef OOO_DISABLE_TASKMEMPOOL" );
3777 output.println( "#ifdef CP_EVENTID_POOLALLOC");
3778 output.println( " CP_LOGEVENT( CP_EVENTID_POOLALLOC, CP_EVENTTYPE_BEGIN );");
3779 output.println( "#endif");
3780 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3781 (state.OOOJAVA && fsen != oooa.getMainSESE())
3784 fsen.getSESErecordName()+"* seseToIssue = ("+
3785 fsen.getSESErecordName()+"*) poolalloc( runningSESE->taskRecordMemPool );");
3788 fsen.getSESErecordName()+"* seseToIssue = ("+
3789 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3790 fsen.getSESErecordName()+" ) );");
3792 output.println( "#ifdef CP_EVENTID_POOLALLOC");
3793 output.println( " CP_LOGEVENT( CP_EVENTID_POOLALLOC, CP_EVENTTYPE_END );");
3794 output.println( "#endif");
3796 output.println( "#else // OOO_DISABLE_TASKMEMPOOL" );
3798 fsen.getSESErecordName()+"* seseToIssue = ("+
3799 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3800 fsen.getSESErecordName()+" ) );");
3801 output.println( "#endif // OOO_DISABLE_TASKMEMPOOL" );
3804 // set up the SESE in-set and out-set objects, which look
3805 // like a garbage list
3806 output.println(" struct garbagelist * gl= (struct garbagelist *)&(((SESEcommon*)(seseToIssue))[1]);");
3807 output.println(" gl->size="+calculateSizeOfSESEParamList(fsen)+";");
3808 output.println(" gl->next = NULL;");
3810 // there are pointers to SESE records the newly-issued SESE
3811 // will use to get values it depends on them for--how many
3812 // are there, and what is the offset from the total SESE
3813 // record to the first dependent record pointer?
3814 output.println(" seseToIssue->common.numDependentSESErecords="+
3815 fsen.getNumDepRecs()+";");
3817 // we only need this (and it will only compile) when the number of dependent
3818 // SESE records is non-zero
3819 if( fsen.getFirstDepRecField() != null ) {
3820 output.println(" seseToIssue->common.offsetToDepSESErecords=(INTPTR)sizeof("+
3821 fsen.getSESErecordName()+") - (INTPTR)&((("+
3822 fsen.getSESErecordName()+"*)0)->"+fsen.getFirstDepRecField()+");"
3826 if (state.RCR&&fsen.getInVarsForDynamicCoarseConflictResolution().size()>0) {
3827 output.println(" seseToIssue->common.offsetToParamRecords=(INTPTR)sizeof("+fsen.getSESErecordName()+") - (INTPTR) & ((("+fsen.getSESErecordName()+"*)0)->rcrRecords);");
3830 // fill in common data
3831 output.println(" int localCount=0;");
3832 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3833 output.println(" seseToIssue->common.parentsStallSem = NULL;");
3834 output.println(" seseToIssue->common.forwardList = createQueue();");
3835 output.println(" seseToIssue->common.unresolvedDependencies = 10000;");
3836 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3837 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3838 output.println(" seseToIssue->common.numRunningChildren = 0;");
3839 output.println(" seseToIssue->common.parent = runningSESE;");
3840 // start with refCount = 2, one being the count that the child itself
3841 // will decrement when it retires, to say it is done using its own
3842 // record, and the other count is for the parent that will remember
3843 // the static name of this new child below
3844 output.println(" seseToIssue->common.refCount = 2;");
3846 // all READY in-vars should be copied now and be done with it
3847 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3848 while( tempItr.hasNext() ) {
3849 TempDescriptor temp = tempItr.next();
3851 // when we are issuing the main SESE or an SESE with placeholder
3852 // caller SESE as parent, generate temp child child's eclosing method,
3853 // otherwise use the parent's enclosing method as the context
3854 boolean useParentContext = false;
3856 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3857 (state.OOOJAVA && fsen != oooa.getMainSESE())
3859 assert fsen.getParent() != null;
3860 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3861 useParentContext = true;
3865 if( useParentContext ) {
3866 output.println(" seseToIssue->"+temp+" = "+
3867 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3869 output.println(" seseToIssue->"+temp+" = "+
3870 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3874 // before potentially adding this SESE to other forwarding lists,
3876 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3879 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3880 (state.OOOJAVA && fsen != oooa.getMainSESE())
3882 // count up outstanding dependencies, static first, then dynamic
3883 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3884 while( staticSrcsItr.hasNext() ) {
3885 SESEandAgePair srcPair = staticSrcsItr.next();
3886 output.println(" {");
3887 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3888 output.println(" pthread_mutex_lock( &(src->lock) );");
3890 output.println(" if( !src->doneExecuting ) {");
3891 output.println(" addNewItem( src->forwardList, seseToIssue );");
3892 output.println(" ++(localCount);");
3893 output.println(" }");
3894 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3895 output.println(" ADD_REFERENCE_TO( src );");
3896 output.println("#endif" );
3897 output.println(" pthread_mutex_unlock( &(src->lock) );");
3898 output.println(" }");
3900 // whether or not it is an outstanding dependency, make sure
3901 // to pass the static name to the child's record
3902 output.println(" seseToIssue->"+srcPair+" = "+
3903 "("+srcPair.getSESE().getSESErecordName()+"*)"+
3907 // dynamic sources might already be accounted for in the static list,
3908 // so only add them to forwarding lists if they're not already there
3909 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3910 while( dynVarsItr.hasNext() ) {
3911 TempDescriptor dynInVar = dynVarsItr.next();
3912 output.println(" {");
3913 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3915 // the dynamic source is NULL if it comes from your own space--you can't pass
3916 // the address off to the new child, because you're not done executing and
3917 // might change the variable, so copy it right now
3918 output.println(" if( src != NULL ) {");
3919 output.println(" pthread_mutex_lock( &(src->lock) );");
3923 output.println(" if( isEmpty( src->forwardList ) ||");
3924 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3925 output.println(" if( !src->doneExecuting ) {");
3926 output.println(" addNewItem( src->forwardList, seseToIssue );");
3927 output.println(" ++(localCount);");
3928 output.println(" }");
3929 output.println(" }");
3930 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3931 output.println(" ADD_REFERENCE_TO( src );");
3932 output.println("#endif" );
3933 output.println(" pthread_mutex_unlock( &(src->lock) );");
3934 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3935 output.println(" } else {");
3937 boolean useParentContext = false;
3938 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3939 (state.OOOJAVA && fsen != oooa.getMainSESE())
3941 assert fsen.getParent() != null;
3942 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3943 useParentContext = true;
3946 if( useParentContext ) {
3947 output.println(" seseToIssue->"+dynInVar+" = "+
3948 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3950 output.println(" seseToIssue->"+dynInVar+" = "+
3951 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3954 output.println(" }");
3955 output.println(" }");
3957 // even if the value is already copied, make sure your NULL source
3958 // gets passed so child knows it already has the dynamic value
3959 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3965 // maintain pointers for finding dynamic SESE
3966 // instances from static names
3967 SESEandAgePair pairNewest = new SESEandAgePair( fsen, 0 );
3968 SESEandAgePair pairOldest = new SESEandAgePair( fsen, fsen.getOldestAgeToTrack() );
3969 if( fsen.getParent() != null &&
3970 fsen.getParent().getNeededStaticNames().contains( pairNewest )
3972 output.println(" {");
3973 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3974 output.println(" SESEcommon* oldest = "+pairOldest+";");
3975 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
3977 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3978 SESEandAgePair pair1 = new SESEandAgePair( fsen, i );
3979 SESEandAgePair pair2 = new SESEandAgePair( fsen, i-1 );
3980 output.println(" "+pair1+" = "+pair2+";");
3982 output.println(" "+pairNewest+" = &(seseToIssue->common);");
3984 // no need to add a reference to whatever is the newest record, because
3985 // we initialized seseToIssue->refCount to *2*
3986 // but release a reference to whatever was the oldest BEFORE the shift
3987 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3988 output.println(" if( oldest != NULL ) {");
3989 output.println(" RELEASE_REFERENCE_TO( oldest );");
3990 output.println(" }");
3991 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
3992 output.println(" }");
3997 if( state.COREPROF ) {
3998 output.println("#ifdef CP_EVENTID_PREPAREMEMQ");
3999 output.println(" CP_LOGEVENT( CP_EVENTID_PREPAREMEMQ, CP_EVENTTYPE_BEGIN );");
4000 output.println("#endif");
4005 // count up memory conflict dependencies,
4007 dispatchMEMRC(fm, lb, fsen, output);
4008 } else if(state.OOOJAVA){
4009 FlatSESEEnterNode parent = fsen.getParent();
4010 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(parent);
4011 if (graph != null && graph.hasConflictEdge()) {
4012 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
4014 output.println(" //add memory queue element");
4015 Analysis.OoOJava.SESEWaitingQueue seseWaitingQueue=
4016 graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet);
4017 if(seseWaitingQueue.getWaitingElementSize()>0) {
4018 output.println(" {");
4019 output.println(" REntry* rentry=NULL;");
4020 output.println(" INTPTR* pointer=NULL;");
4021 output.println(" seseToIssue->common.rentryIdx=0;");
4023 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
4024 for (Iterator iterator = queueIDSet.iterator(); iterator.hasNext();) {
4025 Integer key = (Integer) iterator.next();
4026 int queueID=key.intValue();
4027 Set<Analysis.OoOJava.WaitingElement> waitingQueueSet =
4028 seseWaitingQueue.getWaitingElementSet(queueID);
4029 int enqueueType=seseWaitingQueue.getType(queueID);
4030 if(enqueueType==SESEWaitingQueue.EXCEPTION) {
4031 output.println(" INITIALIZEBUF(runningSESE->memoryQueueArray[" + queueID+ "]);");
4033 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2.hasNext();) {
4034 Analysis.OoOJava.WaitingElement waitingElement
4035 = (Analysis.OoOJava.WaitingElement) iterator2.next();
4036 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
4037 output.println(" rentry=mlpCreateREntry("
4038 + waitingElement.getStatus()
4039 + ", &(seseToIssue->common));");
4041 TempDescriptor td = waitingElement.getTempDesc();
4042 // decide whether waiting element is dynamic or static
4043 if (fsen.getDynamicInVarSet().contains(td)) {
4044 // dynamic in-var case
4045 output.println(" pointer=seseToIssue->"
4046 + waitingElement.getDynID()
4047 + "_srcSESE+seseToIssue->"
4048 + waitingElement.getDynID()
4050 output.println(" rentry=mlpCreateFineREntry("
4051 + waitingElement.getStatus()
4052 + ", &(seseToIssue->common), pointer );");
4053 } else if (fsen.getStaticInVarSet().contains(td)) {
4054 // static in-var case
4055 VariableSourceToken vst = fsen.getStaticInVarSrc(td);
4058 String srcId = "SESE_" + vst.getSESE().getPrettyIdentifier()
4059 + vst.getSESE().getIdentifier()
4060 + "_" + vst.getAge();
4061 output.println(" pointer=(void*)&seseToIssue->"
4067 output.println(" rentry=mlpCreateFineREntry("
4068 + waitingElement.getStatus()
4069 + ", &(seseToIssue->common), pointer );");
4072 output.println(" rentry=mlpCreateFineREntry("
4073 + waitingElement.getStatus()
4074 + ", &(seseToIssue->common), (void*)&seseToIssue->"
4075 + waitingElement.getDynID()
4079 output.println(" rentry->queue=runningSESE->memoryQueueArray["
4080 + waitingElement.getQueueID()
4083 if(enqueueType==SESEWaitingQueue.NORMAL){
4084 output.println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4085 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["
4086 + waitingElement.getQueueID()
4087 + "],rentry)==NOTREADY) {");
4088 output.println(" localCount++;");
4089 output.println(" }");
4091 output.println(" ADDRENTRYTOBUF(runningSESE->memoryQueueArray[" + waitingElement.getQueueID() + "],rentry);");
4094 if(enqueueType!=SESEWaitingQueue.NORMAL){
4095 output.println(" localCount+=RESOLVEBUF(runningSESE->memoryQueueArray["
4096 + queueID+ "],&seseToIssue->common);");
4099 output.println(" }");
4104 ConflictGraph graph = null;
4105 FlatSESEEnterNode parent = fsen.getParent();
4106 if (parent != null) {
4107 if (parent.isCallerSESEplaceholder) {
4108 graph = mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
4110 graph = mlpa.getConflictGraphResults().get(parent);
4113 if (graph != null && graph.hasConflictEdge()) {
4114 HashSet<SESELock> seseLockSet = mlpa.getConflictGraphLockMap()
4117 output.println(" //add memory queue element");
4118 SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(fsen.getIdentifier(),
4120 if(seseWaitingQueue.getWaitingElementSize()>0){
4121 output.println(" {");
4122 output.println(" REntry* rentry=NULL;");
4123 output.println(" INTPTR* pointer=NULL;");
4124 output.println(" seseToIssue->common.rentryIdx=0;");
4126 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
4127 for (Iterator iterator = queueIDSet.iterator(); iterator
4129 Integer key = (Integer) iterator.next();
4130 int queueID=key.intValue();
4131 Set<WaitingElement> waitingQueueSet = seseWaitingQueue.getWaitingElementSet(queueID);
4132 int enqueueType=seseWaitingQueue.getType(queueID);
4133 if(enqueueType==SESEWaitingQueue.EXCEPTION){
4134 output.println(" INITIALIZEBUF(runningSESE->memoryQueueArray["
4137 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2
4139 WaitingElement waitingElement = (WaitingElement) iterator2
4141 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
4142 output.println(" rentry=mlpCreateREntry("
4143 + waitingElement.getStatus()
4144 + ", &(seseToIssue->common));");
4146 TempDescriptor td = waitingElement
4148 // decide whether waiting element is dynamic or
4150 if (fsen.getDynamicInVarSet().contains(td)) {
4151 // dynamic in-var case
4152 output.println(" pointer=seseToIssue->"
4153 + waitingElement.getDynID()
4154 + "_srcSESE+seseToIssue->"
4155 + waitingElement.getDynID()
4158 .println(" rentry=mlpCreateFineREntry("
4161 + ", &(seseToIssue->common), pointer );");
4162 } else if (fsen.getStaticInVarSet()
4164 // static in-var case
4165 VariableSourceToken vst = fsen
4166 .getStaticInVarSrc(td);
4169 String srcId = "SESE_"
4171 .getPrettyIdentifier()
4172 + vst.getSESE().getIdentifier()
4173 + "_" + vst.getAge();
4175 .println(" pointer=(void*)&seseToIssue->"
4182 .println(" rentry=mlpCreateFineREntry("
4185 + ", &(seseToIssue->common), pointer );");
4190 .println(" rentry=mlpCreateFineREntry("
4193 + ", &(seseToIssue->common), (void*)&seseToIssue->"
4194 + waitingElement.getDynID()
4199 .println(" rentry->queue=runningSESE->memoryQueueArray["
4200 + waitingElement.getQueueID()
4203 if(enqueueType==SESEWaitingQueue.NORMAL){
4205 .println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4207 .println(" if(ADDRENTRY(runningSESE->memoryQueueArray["
4208 + waitingElement.getQueueID()
4209 + "],rentry)==NOTREADY){");
4210 output.println(" ++(localCount);");
4211 output.println(" } ");
4214 .println(" ADDRENTRYTOBUF(runningSESE->memoryQueueArray["
4215 + waitingElement.getQueueID()
4219 if(enqueueType!=SESEWaitingQueue.NORMAL){
4220 output.println(" localCount+=RESOLVEBUF(runningSESE->memoryQueueArray["
4221 + queueID+ "],&seseToIssue->common);");
4224 output.println(" }");
4231 if( state.COREPROF ) {
4232 output.println("#ifdef CP_EVENTID_PREPAREMEMQ");
4233 output.println(" CP_LOGEVENT( CP_EVENTID_PREPAREMEMQ, CP_EVENTTYPE_END );");
4234 output.println("#endif");
4237 // Enqueue Task Record
4239 output.println(" enqueueTR(TRqueue, (void *)seseToIssue);");
4242 // if there were no outstanding dependencies, issue here
4243 output.println(" if( atomic_sub_and_test(10000-localCount,&(seseToIssue->common.unresolvedDependencies) ) ) {");
4244 output.println(" workScheduleSubmit( (void*)seseToIssue );");
4245 output.println(" }");
4249 if( state.COREPROF ) {
4250 output.println("#ifdef CP_EVENTID_TASKDISPATCH");
4251 output.println(" CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_END );");
4252 output.println("#endif");
4255 output.println(" }");
4259 void dispatchMEMRC(FlatMethod fm, LocalityBinding lb, FlatSESEEnterNode fsen, PrintWriter output) {
4260 FlatSESEEnterNode parent = fsen.getParent();
4261 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(parent);
4262 if (graph != null && graph.hasConflictEdge()) {
4263 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
4264 Analysis.OoOJava.SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet);
4265 if(seseWaitingQueue.getWaitingElementSize()>0) {
4266 output.println(" {");
4267 output.println(" REntry* rentry=NULL;");
4268 output.println(" INTPTR* pointer=NULL;");
4269 output.println(" seseToIssue->common.rentryIdx=0;");
4270 output.println(" int dispCount;");
4271 Vector<TempDescriptor> invars=fsen.getInVarsForDynamicCoarseConflictResolution();
4272 for(int i=0;i<invars.size();i++) {
4273 TempDescriptor td=invars.get(i);
4274 Set<Analysis.OoOJava.WaitingElement> weset=seseWaitingQueue.getWaitingElementSet(td);
4275 int numqueues=weset.size();
4276 output.println(" seseToIssue->rcrRecords["+i+"]="+numqueues+";");
4277 output.println(" dispCount=0;");
4278 for(Iterator<Analysis.OoOJava.WaitingElement> wtit=weset.iterator();wtit.hasNext();) {
4279 Analysis.OoOJava.WaitingElement waitingElement=wtit.next();
4280 int queueID=waitingElement.getQueueID();
4281 assert(waitingElement.getStatus()>=ConflictNode.COARSE);
4282 output.println(" rentry=mlpCreateREntry(" + waitingElement.getStatus() + ", &(seseToIssue->common));");
4283 output.println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4284 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "],rentry)==READY) {");
4285 output.println(" dispCount++;");
4286 output.println(" }");
4288 output.println(" if(!dispCount || !atomic_sub_and_test(dispCount,&(seseToIssue->rcrRecords["+i+"])))");
4289 output.println(" localCount++;");
4290 if (fsen.getDynamicInVarSet().contains(td)) {
4291 // dynamic in-var case
4292 //output.println(" pointer=seseToIssue->" + waitingElement.getDynID()+ "_srcSESE+seseToIssue->"+ waitingElement.getDynID()+ "_srcOffset;");
4293 //output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", &(seseToIssue->common), pointer );");
4296 output.println(" }");
4301 public void generateFlatSESEExitNode( FlatMethod fm,
4303 FlatSESEExitNode fsexn,
4307 // if MLP flag is off, okay that SESE nodes are in IR graph,
4308 // just skip over them and code generates exactly the same
4309 if( ! (state.MLP || state.OOOJAVA) ) {
4313 // get the enter node for this exit that has meta data embedded
4314 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
4316 // there may be an SESE in an unreachable method, skip over
4317 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
4318 (state.OOOJAVA && !oooa.getAllSESEs().contains( fsen ))
4323 // also, if we have encountered a placeholder, just jump it
4324 if( fsen.getIsCallerSESEplaceholder() ) {
4328 if( state.COREPROF ) {
4329 output.println("#ifdef CP_EVENTID_TASKEXECUTE");
4330 output.println(" CP_LOGEVENT( CP_EVENTID_TASKEXECUTE, CP_EVENTTYPE_END );");
4331 output.println("#endif");
4334 output.println(" /* SESE exiting */");
4336 if( state.COREPROF ) {
4337 output.println("#ifdef CP_EVENTID_TASKRETIRE");
4338 output.println(" CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_BEGIN );");
4339 output.println("#endif");
4343 // this SESE cannot be done until all of its children are done
4344 // so grab your own lock with the condition variable for watching
4345 // that the number of your running children is greater than zero
4346 output.println(" pthread_mutex_lock( &(runningSESE->lock) );");
4347 output.println(" if( runningSESE->numRunningChildren > 0 ) {");
4348 output.println(" stopforgc( (struct garbagelist *)&___locals___ );");
4349 output.println(" do {");
4350 output.println(" pthread_cond_wait( &(runningSESE->runningChildrenCond), &(runningSESE->lock) );");
4351 output.println(" } while( runningSESE->numRunningChildren > 0 );");
4352 output.println(" restartaftergc();");
4353 output.println(" }");
4356 // copy out-set from local temps into the sese record
4357 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
4358 while( itr.hasNext() ) {
4359 TempDescriptor temp = itr.next();
4361 // only have to do this for primitives non-arrays
4363 temp.getType().isPrimitive() && !temp.getType().isArray()
4369 // have to determine the context enclosing this sese
4370 boolean useParentContext = false;
4372 if( (state.MLP &&fsen != mlpa.getMainSESE()) ||
4373 (state.OOOJAVA &&fsen != oooa.getMainSESE())
4375 assert fsen.getParent() != null;
4376 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
4377 useParentContext = true;
4382 if( useParentContext ) {
4383 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
4385 from = generateTemp( fsen.getfmEnclosing(), temp, null );
4388 output.println(" "+paramsprefix+
4389 "->"+temp.getSafeSymbol()+
4393 // mark yourself done, your task data is now read-only
4394 output.println(" runningSESE->doneExecuting = TRUE;");
4396 // if parent is stalling on you, let them know you're done
4397 if( (state.MLP && fsexn.getFlatEnter() != mlpa.getMainSESE()) ||
4398 (state.OOOJAVA && fsexn.getFlatEnter() != oooa.getMainSESE())
4400 output.println(" if( runningSESE->parentsStallSem != NULL ) {");
4401 output.println(" psem_give( runningSESE->parentsStallSem );");
4402 output.println(" }");
4405 output.println(" pthread_mutex_unlock( &(runningSESE->lock) );");
4407 // decrement dependency count for all SESE's on your forwarding list
4410 output.println(" while( !isEmpty( runningSESE->forwardList ) ) {");
4411 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( runningSESE->forwardList );");
4414 output.println(" if(consumer->rentryIdx>0){");
4415 output.println(" // resolved null pointer");
4416 output.println(" int idx;");
4417 output.println(" for(idx=0;idx<consumer->rentryIdx;idx++){");
4418 output.println(" resolvePointer(consumer->rentryArray[idx]);");
4419 output.println(" }");
4420 output.println(" }");
4423 output.println(" if( atomic_sub_and_test( 1, &(consumer->unresolvedDependencies) ) ){");
4424 output.println(" workScheduleSubmit( (void*)consumer );");
4425 output.println(" }");
4426 output.println(" }");
4430 // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
4431 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4432 (state.OOOJAVA && fsen != oooa.getMainSESE())
4436 output.println(" /* check memory dependency*/");
4437 output.println(" {");
4438 output.println(" int idx;");
4439 output.println(" for(idx=0;idx<___params___->common.rentryIdx;idx++){");
4440 output.println(" REntry* re=___params___->common.rentryArray[idx];");
4441 output.println(" RETIRERENTRY(re->queue,re);");
4442 output.println(" }");
4443 output.println(" }");
4448 // last of all, decrement your parent's number of running children
4449 output.println(" if( runningSESE->parent != NULL ) {");
4450 output.println(" if( atomic_sub_and_test( 1, &(runningSESE->parent->numRunningChildren) ) ) {");
4451 output.println(" pthread_mutex_lock ( &(runningSESE->parent->lock) );");
4452 output.println(" pthread_cond_signal ( &(runningSESE->parent->runningChildrenCond) );");
4453 output.println(" pthread_mutex_unlock( &(runningSESE->parent->lock) );");
4454 output.println(" }");
4455 output.println(" }");
4457 // a task has variables to track static/dynamic instances
4458 // that serve as sources, release the parent's ref of each
4459 // non-null var of these types
4460 output.println(" // releasing static SESEs");
4461 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4462 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
4463 while( pItr.hasNext() ) {
4464 SESEandAgePair pair = pItr.next();
4465 output.println(" if( "+pair+" != NULL ) {");
4466 output.println(" RELEASE_REFERENCE_TO( "+pair+" );");
4467 output.println(" }");
4469 output.println(" // releasing dynamic variable sources");
4470 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
4471 while( dynSrcItr.hasNext() ) {
4472 TempDescriptor dynSrcVar = dynSrcItr.next();
4473 output.println(" if( "+dynSrcVar+"_srcSESE != NULL ) {");
4474 output.println(" RELEASE_REFERENCE_TO( "+dynSrcVar+"_srcSESE );");
4475 output.println(" }");
4477 // destroy this task's mempool if it is not a leaf task
4478 if( !fsen.getIsLeafSESE() ) {
4479 output.println(" pooldestroy( runningSESE->taskRecordMemPool );");
4481 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4484 // if this is not the Main sese (which has no parent) then return
4485 // THIS task's record to the PARENT'S task record pool, and only if
4486 // the reference count is now zero
4487 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4488 (state.OOOJAVA && fsen != oooa.getMainSESE())
4490 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4491 output.println(" RELEASE_REFERENCE_TO( runningSESE );");
4492 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4494 // the main task has no parent, just free its record
4495 output.println(" mlpFreeSESErecord( runningSESE );");
4498 // as this thread is wrapping up the task, make sure the thread-local var
4499 // for the currently running task record references an invalid task
4500 output.println(" runningSESE = (SESEcommon*) 0x1;");
4502 if( state.COREPROF ) {
4503 output.println("#ifdef CP_EVENTID_TASKRETIRE");
4504 output.println(" CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_END );");
4505 output.println("#endif");
4509 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
4511 FlatWriteDynamicVarNode fwdvn,
4514 if( !(state.MLP || state.OOOJAVA) ) {
4515 // should node should not be in an IR graph if the
4516 // MLP flag is not set
4517 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
4520 Hashtable<TempDescriptor, VSTWrapper> writeDynamic = fwdvn.getVar2src();
4522 assert writeDynamic != null;
4524 Iterator wdItr = writeDynamic.entrySet().iterator();
4525 while( wdItr.hasNext() ) {
4526 Map.Entry me = (Map.Entry) wdItr.next();
4527 TempDescriptor refVar = (TempDescriptor) me.getKey();
4528 VSTWrapper vstW = (VSTWrapper) me.getValue();
4529 VariableSourceToken vst = vstW.vst;
4531 output.println(" {");
4532 output.println(" SESEcommon* oldSrc = "+refVar+"_srcSESE;");
4535 // if there is no given source, this variable is ready so
4536 // mark src pointer NULL to signify that the var is up-to-date
4537 output.println(" "+refVar+"_srcSESE = NULL;");
4539 // otherwise we track where it will come from
4540 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
4541 output.println(" "+refVar+"_srcSESE = "+instance+";");
4542 output.println(" "+refVar+"_srcOffset = (INTPTR) &((("+
4543 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
4546 // no matter what we did above, track reference count of whatever
4547 // this variable pointed to, do release last in case we're just
4548 // copying the same value in because 1->2->1 is safe but ref count
4549 // 1->0->1 has a window where it looks like it should be free'd
4550 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4551 output.println(" if( "+refVar+"_srcSESE != NULL ) {");
4552 output.println(" ADD_REFERENCE_TO( "+refVar+"_srcSESE );");
4553 output.println(" }");
4554 output.println(" if( oldSrc != NULL ) {");
4555 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
4556 output.println(" }");
4557 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4559 output.println(" }");
4564 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
4565 if (state.CONSCHECK) {
4566 String specname=fcn.getSpec();
4567 String varname="repairstate___";
4568 output.println("{");
4569 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
4571 TempDescriptor[] temps=fcn.getTemps();
4572 String[] vars=fcn.getVars();
4573 for(int i=0; i<temps.length; i++) {
4574 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
4577 output.println("if (doanalysis"+specname+"("+varname+")) {");
4578 output.println("free"+specname+"_state("+varname+");");
4579 output.println("} else {");
4580 output.println("/* Bad invariant */");
4581 output.println("free"+specname+"_state("+varname+");");
4582 output.println("abort_task();");
4583 output.println("}");
4584 output.println("}");
4588 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
4590 MethodDescriptor md=fc.getMethod();
4591 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
4592 ClassDescriptor cn=md.getClassDesc();
4593 output.println("{");
4594 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4596 LocalityBinding fclb=locality.getBinding(lb, fc);
4597 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4599 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4600 output.print(objectparams.numPointers());
4601 output.print(", "+localsprefixaddr);
4602 if (md.getThis()!=null) {
4604 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
4606 if (fc.getThis()!=null&&md.getThis()==null) {
4607 System.out.println("WARNING!!!!!!!!!!!!");
4608 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
4612 for(int i=0; i<fc.numArgs(); i++) {
4613 Descriptor var=md.getParameter(i);
4614 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4615 if (objectparams.isParamPtr(paramtemp)) {
4616 TempDescriptor targ=fc.getArg(i);
4618 TypeDescriptor td=md.getParamType(i);
4620 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4622 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4625 output.println("};");
4630 if (fc.getReturnTemp()!=null)
4631 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
4633 /* Do we need to do virtual dispatch? */
4634 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
4637 LocalityBinding fclb=locality.getBinding(lb, fc);
4638 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4640 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4645 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4646 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4648 output.print(md.getReturnType().getSafeSymbol()+" ");
4649 output.print("(*)(");
4651 boolean printcomma=false;
4652 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4654 LocalityBinding fclb=locality.getBinding(lb, fc);
4655 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4657 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4661 for(int i=0; i<objectparams.numPrimitives(); i++) {
4662 TempDescriptor temp=objectparams.getPrimitive(i);
4666 if (temp.getType().isClass()||temp.getType().isArray())
4667 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
4669 output.print(temp.getType().getSafeSymbol());
4674 LocalityBinding fclb=locality.getBinding(lb, fc);
4675 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
4677 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
4681 boolean needcomma=false;
4682 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4683 output.print("&__parameterlist__");
4687 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4688 if (fc.getThis()!=null) {
4689 TypeDescriptor ptd=null;
4690 if(md.getThis() != null) {
4691 ptd = md.getThis().getType();
4693 ptd = fc.getThis().getType();
4697 if (ptd.isClass()&&!ptd.isArray())
4698 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4699 output.print(generateTemp(fm,fc.getThis(),lb));
4704 for(int i=0; i<fc.numArgs(); i++) {
4705 Descriptor var=md.getParameter(i);
4706 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4707 if (objectparams.isParamPrim(paramtemp)) {
4708 TempDescriptor targ=fc.getArg(i);
4712 TypeDescriptor ptd=md.getParamType(i);
4713 if (ptd.isClass()&&!ptd.isArray())
4714 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4715 output.print(generateTemp(fm, targ,lb));
4719 output.println(");");
4720 output.println(" }");
4723 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
4724 Set subclasses=typeutil.getSubClasses(thiscd);
4725 if (subclasses==null)
4727 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
4728 ClassDescriptor cd=(ClassDescriptor)classit.next();
4729 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
4730 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
4731 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
4732 if (md.matches(matchmd))
4739 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
4740 if (state.SINGLETM) {
4741 //single machine transactional memory case
4742 String field=ffn.getField().getSafeSymbol();
4743 String src=generateTemp(fm, ffn.getSrc(),lb);
4744 String dst=generateTemp(fm, ffn.getDst(),lb);
4746 output.println(dst+"="+ src +"->"+field+ ";");
4747 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
4748 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
4749 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
4750 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
4751 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
4752 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
4753 if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
4754 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4756 output.println("TRANSREADRD("+dst+", "+dst+");");
4759 } else if (state.DSM) {
4760 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
4761 if (status==LocalityAnalysis.GLOBAL) {
4762 String field=ffn.getField().getSafeSymbol();
4763 String src=generateTemp(fm, ffn.getSrc(),lb);
4764 String dst=generateTemp(fm, ffn.getDst(),lb);
4766 if (ffn.getField().getType().isPtr()) {
4768 //TODO: Uncomment this when we have runtime support
4769 //if (ffn.getSrc()==ffn.getDst()) {
4770 //output.println("{");
4771 //output.println("void * temp="+src+";");
4772 //output.println("if (temp&0x1) {");
4773 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
4774 //output.println(src+"->"+field+"="+temp+";");
4775 //output.println("}");
4776 //output.println(dst+"=temp;");
4777 //output.println("}");
4779 output.println(dst+"="+ src +"->"+field+ ";");
4780 //output.println("if ("+dst+"&0x1) {");
4781 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4782 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4783 //output.println(src+"->"+field+"="+src+"->"+field+";");
4784 //output.println("}");
4787 output.println(dst+"="+ src+"->"+field+";");
4789 } else if (status==LocalityAnalysis.LOCAL) {
4790 if (ffn.getField().getType().isPtr()&&
4791 ffn.getField().isGlobal()) {
4792 String field=ffn.getField().getSafeSymbol();
4793 String src=generateTemp(fm, ffn.getSrc(),lb);
4794 String dst=generateTemp(fm, ffn.getDst(),lb);
4795 output.println(dst+"="+ src +"->"+field+ ";");
4796 if (locality.getAtomic(lb).get(ffn).intValue()>0)
4797 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4798 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4800 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4801 } else if (status==LocalityAnalysis.EITHER) {
4802 //Code is reading from a null pointer
4803 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
4804 output.println("#ifndef RAW");
4805 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4806 output.println("#endif");
4807 //This should throw a suitable null pointer error
4808 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4810 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4812 // DEBUG if(!ffn.getDst().getType().isPrimitive()){
4813 // DEBUG output.println("within((void*)"+generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+");");
4815 if(ffn.getField().isStatic()) {
4816 // static field, redirect to the global_defs_p structure
4817 if(ffn.getSrc().getType().isStatic()) {
4818 // reference to the static field with Class name
4819 output.println(generateTemp(fm, ffn.getDst(),lb)+"=global_defs_p->"+ ffn.getSrc().getType().getClassDesc().getSafeSymbol()+ffn.getField().getSafeSymbol()+";");
4821 output.println(generateTemp(fm, ffn.getDst(),lb)+"=*"+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4823 //output.println(generateTemp(fm, ffn.getDst(),lb)+"=global_defs_p->"+ffn.getSrc().getType().getClassDesc().getSafeSymbol()+"->"+ ffn.getField().getSafeSymbol()+";");
4825 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4831 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
4832 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
4833 throw new Error("Can't set array length");
4834 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4835 //Single Machine Transaction Case
4836 boolean srcptr=fsfn.getSrc().getType().isPtr();
4837 String src=generateTemp(fm,fsfn.getSrc(),lb);
4838 String dst=generateTemp(fm,fsfn.getDst(),lb);
4839 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
4840 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
4841 output.println("{");
4842 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
4843 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
4844 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4846 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4849 if (wb.needBarrier(fsfn)&&
4850 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
4851 if (state.EVENTMONITOR) {
4852 output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
4854 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
4856 if (srcptr&!fsfn.getSrc().getType().isNull()) {
4857 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4858 output.println("}");
4860 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4862 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4863 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
4864 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
4865 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4867 String src=generateTemp(fm,fsfn.getSrc(),lb);
4868 String dst=generateTemp(fm,fsfn.getDst(),lb);
4870 output.println("{");
4871 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4873 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
4876 if (wb.needBarrier(fsfn))
4877 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
4879 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4881 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4882 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
4883 /** Check if we need to copy */
4884 output.println("if(!"+dst+"->"+localcopystr+") {");
4885 /* Link object into list */
4886 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4887 output.println(revertptr+"=revertlist;");
4888 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4889 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4891 output.println("COPY_OBJ("+dst+");");
4892 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4893 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4894 output.println("}");
4896 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4898 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4899 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
4900 //writing to a null...bad
4901 output.println("if ("+dst+") {");
4902 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
4904 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4906 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4909 output.println("}");
4912 if (state.FASTCHECK) {
4913 String dst=generateTemp(fm, fsfn.getDst(),lb);
4914 output.println("if(!"+dst+"->"+localcopystr+") {");
4915 /* Link object into list */
4916 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4917 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4919 output.println("COPY_OBJ("+dst+");");
4920 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4921 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4922 output.println("}");
4925 // DEBUG if(!fsfn.getField().getType().isPrimitive()){
4926 // DEBUG output.println("within((void*)"+generateTemp(fm,fsfn.getSrc(),lb)+");");
4928 if(fsfn.getField().isStatic()) {
4929 // static field, redirect to the global_defs_p structure
4930 if(fsfn.getDst().getType().isStatic()) {
4931 // reference to the static field with Class name
4932 output.println("global_defs_p->" + fsfn.getDst().getType().getClassDesc().getSafeSymbol() + fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4934 output.println("*"+generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4937 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4942 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
4943 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
4946 if (elementtype.isArray()||elementtype.isClass())
4949 type=elementtype.getSafeSymbol()+" ";
4951 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
4952 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
4953 output.println("failedboundschk();");
4955 if (state.SINGLETM) {
4956 //Single machine transaction case
4957 String dst=generateTemp(fm, fen.getDst(),lb);
4958 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))) {
4959 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4961 output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
4964 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
4965 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
4966 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
4967 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
4968 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
4969 if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
4970 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4972 output.println("TRANSREADRD("+dst+", "+dst+");");
4975 } else if (state.DSM) {
4976 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
4977 if (status==LocalityAnalysis.GLOBAL) {
4978 String dst=generateTemp(fm, fen.getDst(),lb);
4979 if (elementtype.isPtr()) {
4980 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4981 //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
4982 output.println("TRANSREAD("+dst+", "+dst+");");
4984 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4986 } else if (status==LocalityAnalysis.LOCAL) {
4987 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4988 } else if (status==LocalityAnalysis.EITHER) {
4989 //Code is reading from a null pointer
4990 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
4991 output.println("#ifndef RAW");
4992 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4993 output.println("#endif");
4994 //This should throw a suitable null pointer error
4995 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4997 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4999 // DEBUG output.println("within((void*)"+generateTemp(fm,fen.getSrc(),lb)+");");
5000 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
5004 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
5005 //TODO: need dynamic check to make sure this assignment is actually legal
5006 //Because Object[] could actually be something more specific...ie. Integer[]
5008 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
5011 if (elementtype.isArray()||elementtype.isClass())
5014 type=elementtype.getSafeSymbol()+" ";
5016 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
5017 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
5018 output.println("failedboundschk();");
5021 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
5022 //Transaction set element case
5023 if (wb.needBarrier(fsen)&&
5024 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
5025 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
5027 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
5028 output.println("{");
5029 String src=generateTemp(fm, fsen.getSrc(), lb);
5030 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
5031 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
5032 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
5034 output.println("INTPTR srcoid=(INTPTR)"+src+";");
5036 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
5037 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
5039 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
5041 output.println("}");
5043 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
5044 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
5046 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
5049 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
5050 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
5051 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
5052 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
5053 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
5054 boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
5057 if (wb.needBarrier(fsen))
5058 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
5059 } else if (dstlocal) {
5060 /** Check if we need to copy */
5061 String dst=generateTemp(fm, fsen.getDst(),lb);
5062 output.println("if(!"+dst+"->"+localcopystr+") {");
5063 /* Link object into list */
5064 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5065 output.println(revertptr+"=revertlist;");
5066 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
5067 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
5069 output.println("COPY_OBJ("+dst+");");
5070 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
5071 output.println("revertlist=(struct ___Object___ *)"+dst+";");
5072 output.println("}");
5074 System.out.println("Node: "+fsen);
5075 System.out.println(lb);
5076 System.out.println("statusdst="+statusdst);
5077 System.out.println(fm.printMethod());
5078 throw new Error("Unknown array type");
5081 output.println("{");
5082 String src=generateTemp(fm, fsen.getSrc(), lb);
5083 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
5084 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
5085 output.println("}");
5087 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
5090 if (state.FASTCHECK) {
5091 String dst=generateTemp(fm, fsen.getDst(),lb);
5092 output.println("if(!"+dst+"->"+localcopystr+") {");
5093 /* Link object into list */
5094 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
5095 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
5097 output.println("COPY_OBJ("+dst+");");
5098 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
5099 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
5100 output.println("}");
5102 // DEBUG output.println("within((void*)"+generateTemp(fm,fsen.getDst(),lb)+");");
5103 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
5107 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
5108 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
5109 //Stash pointer in case of GC
5110 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5111 output.println(revertptr+"=revertlist;");
5113 if (state.SINGLETM) {
5114 if (fn.getType().isArray()) {
5115 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
5116 if (locality.getAtomic(lb).get(fn).intValue()>0) {
5117 //inside transaction
5118 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5120 //outside transaction
5121 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5124 if (locality.getAtomic(lb).get(fn).intValue()>0) {
5125 //inside transaction
5126 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
5128 //outside transaction
5129 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
5132 } else if (fn.getType().isArray()) {
5133 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
5134 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
5135 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5136 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5137 if(this.state.MLP || state.OOOJAVA){
5138 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray_mlp("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
5139 output.println(" oid += numWorkers;");
5141 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5144 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5147 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
5148 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
5149 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5150 if (this.state.MLP || state.OOOJAVA){
5151 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new_mlp("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
5152 output.println(" oid += numWorkers;");
5154 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
5157 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
5160 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
5161 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5162 String dst=generateTemp(fm,fn.getDst(),lb);
5163 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
5164 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
5165 output.println("revertlist=(struct ___Object___ *)"+dst+";");
5167 if (state.FASTCHECK) {
5168 String dst=generateTemp(fm,fn.getDst(),lb);
5169 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
5170 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
5171 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
5175 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
5176 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5177 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
5179 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
5183 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
5184 if (fon.getRight()!=null) {
5185 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
5186 if (fon.getLeft().getType().isLong())
5187 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
5189 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
5191 } else if (dc!=null) {
5192 output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
5193 if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
5194 output.print("(void *)");
5195 if (dc.getNeedLeftSrcTrans(lb, fon))
5196 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
5198 output.print(generateTemp(fm, fon.getLeft(),lb));
5199 output.print(")"+fon.getOp().toString()+"(");
5200 if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
5201 output.print("(void *)");
5202 if (dc.getNeedRightSrcTrans(lb, fon))
5203 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
5205 output.println(generateTemp(fm,fon.getRight(),lb)+");");
5207 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
5208 } else if (fon.getOp().getOp()==Operation.ASSIGN)
5209 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
5210 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
5211 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
5212 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
5213 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
5214 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
5215 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
5216 else if (fon.getOp().getOp()==Operation.COMP)
5217 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
5218 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
5219 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
5221 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
5224 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
5225 /* TODO: Do type check here */
5226 if (fcn.getType().isArray()) {
5227 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
5228 } else if (fcn.getType().isClass())
5229 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
5231 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
5234 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
5235 if (fln.getValue()==null)
5236 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
5237 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
5238 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5239 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
5240 //Stash pointer in case of GC
5241 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5242 output.println(revertptr+"=revertlist;");
5244 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
5245 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
5246 //Stash pointer in case of GC
5247 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5248 output.println("revertlist="+revertptr+";");
5251 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
5253 } else if (fln.getType().isBoolean()) {
5254 if (((Boolean)fln.getValue()).booleanValue())
5255 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
5257 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
5258 } else if (fln.getType().isChar()) {
5259 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
5260 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
5261 } else if (fln.getType().isLong()) {
5262 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
5264 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
5267 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
5268 if (frn.getReturnTemp()!=null) {
5269 if (frn.getReturnTemp().getType().isPtr())
5270 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
5272 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
5274 output.println("return;");
5278 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
5281 //only record if this group has more than one exit
5282 if (branchanalysis.numJumps(fcb)>1) {
5283 left=branchanalysis.jumpValue(fcb, 0);
5284 right=branchanalysis.jumpValue(fcb, 1);
5286 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
5288 output.println("STOREBRANCH("+right+");");
5289 output.println("goto "+label+";");
5290 output.println("}");
5292 output.println("STOREBRANCH("+left+");");
5295 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
5296 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
5299 /** This method generates header information for the method or
5300 * task referenced by the Descriptor des. */
5301 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
5302 generateHeader(fm, lb, des, output, false);
5305 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
5307 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
5308 MethodDescriptor md=null;
5309 TaskDescriptor task=null;
5310 if (des instanceof MethodDescriptor)
5311 md=(MethodDescriptor) des;
5313 task=(TaskDescriptor) des;
5315 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
5317 if (md!=null&&md.getReturnType()!=null) {
5318 if (md.getReturnType().isClass()||md.getReturnType().isArray())
5319 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
5321 output.print(md.getReturnType().getSafeSymbol()+" ");
5323 //catch the constructor case
5324 output.print("void ");
5326 if (state.DSM||state.SINGLETM) {
5327 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5329 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5331 output.print(task.getSafeSymbol()+"(");
5333 boolean printcomma=false;
5334 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5336 if (state.DSM||state.SINGLETM) {
5337 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5339 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5341 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
5347 for(int i=0; i<objectparams.numPrimitives(); i++) {
5348 TempDescriptor temp=objectparams.getPrimitive(i);
5352 if (temp.getType().isClass()||temp.getType().isArray())
5353 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
5355 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
5357 output.println(") {");
5358 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
5359 /* Imprecise Task */
5360 output.println("void * parameterarray[]) {");
5361 /* Unpack variables */
5362 for(int i=0; i<objectparams.numPrimitives(); i++) {
5363 TempDescriptor temp=objectparams.getPrimitive(i);
5364 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
5366 for(int i=0; i<fm.numTags(); i++) {
5367 TempDescriptor temp=fm.getTag(i);
5368 int offset=i+objectparams.numPrimitives();
5369 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
5372 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
5373 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
5374 } else output.println(") {");
5377 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
5378 output.println("/* FlatFlagActionNode */");
5381 /* Process tag changes */
5382 Relation tagsettable=new Relation();
5383 Relation tagcleartable=new Relation();
5385 Iterator tagsit=ffan.getTempTagPairs();
5386 while (tagsit.hasNext()) {
5387 TempTagPair ttp=(TempTagPair) tagsit.next();
5388 TempDescriptor objtmp=ttp.getTemp();
5389 TagDescriptor tag=ttp.getTag();
5390 TempDescriptor tagtmp=ttp.getTagTemp();
5391 boolean tagstatus=ffan.getTagChange(ttp);
5393 tagsettable.put(objtmp, tagtmp);
5395 tagcleartable.put(objtmp, tagtmp);
5400 Hashtable flagandtable=new Hashtable();
5401 Hashtable flagortable=new Hashtable();
5403 /* Process flag changes */
5404 Iterator flagsit=ffan.getTempFlagPairs();
5405 while(flagsit.hasNext()) {
5406 TempFlagPair tfp=(TempFlagPair)flagsit.next();
5407 TempDescriptor temp=tfp.getTemp();
5408 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
5409 FlagDescriptor flag=tfp.getFlag();
5411 //Newly allocate objects that don't set any flags case
5412 if (flagortable.containsKey(temp)) {
5416 flagortable.put(temp,new Integer(mask));
5418 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
5419 boolean flagstatus=ffan.getFlagChange(tfp);
5422 if (flagortable.containsKey(temp)) {
5423 mask=((Integer)flagortable.get(temp)).intValue();
5426 flagortable.put(temp,new Integer(mask));
5428 int mask=0xFFFFFFFF;
5429 if (flagandtable.containsKey(temp)) {
5430 mask=((Integer)flagandtable.get(temp)).intValue();
5432 mask&=(0xFFFFFFFF^flagid);
5433 flagandtable.put(temp,new Integer(mask));
5439 HashSet flagtagset=new HashSet();
5440 flagtagset.addAll(flagortable.keySet());
5441 flagtagset.addAll(flagandtable.keySet());
5442 flagtagset.addAll(tagsettable.keySet());
5443 flagtagset.addAll(tagcleartable.keySet());
5445 Iterator ftit=flagtagset.iterator();
5446 while(ftit.hasNext()) {
5447 TempDescriptor temp=(TempDescriptor)ftit.next();
5450 Set tagtmps=tagcleartable.get(temp);
5451 if (tagtmps!=null) {
5452 Iterator tagit=tagtmps.iterator();
5453 while(tagit.hasNext()) {
5454 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5455 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5456 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5458 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5462 tagtmps=tagsettable.get(temp);
5463 if (tagtmps!=null) {
5464 Iterator tagit=tagtmps.iterator();
5465 while(tagit.hasNext()) {
5466 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5467 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5468 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5470 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
5475 int andmask=0xFFFFFFF;
5477 if (flagortable.containsKey(temp))
5478 ormask=((Integer)flagortable.get(temp)).intValue();
5479 if (flagandtable.containsKey(temp))
5480 andmask=((Integer)flagandtable.get(temp)).intValue();
5481 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
5482 generateObjectDistribute(ffan, fm, lb, temp, output);
5486 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
5487 PrintWriter output, int ormask, int andmask) {
5488 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
5489 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5491 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5495 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
5496 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
5499 void generateOptionalHeader(PrintWriter headers) {
5502 headers.println("#include \"task.h\"\n\n");
5503 headers.println("#ifndef _OPTIONAL_STRUCT_");
5504 headers.println("#define _OPTIONAL_STRUCT_");
5506 //STRUCT PREDICATEMEMBER
5507 headers.println("struct predicatemember{");
5508 headers.println("int type;");
5509 headers.println("int numdnfterms;");
5510 headers.println("int * flags;");
5511 headers.println("int numtags;");
5512 headers.println("int * tags;\n};\n\n");
5514 //STRUCT OPTIONALTASKDESCRIPTOR
5515 headers.println("struct optionaltaskdescriptor{");
5516 headers.println("struct taskdescriptor * task;");
5517 headers.println("int index;");
5518 headers.println("int numenterflags;");
5519 headers.println("int * enterflags;");
5520 headers.println("int numpredicatemembers;");
5521 headers.println("struct predicatemember ** predicatememberarray;");
5522 headers.println("};\n\n");
5524 //STRUCT TASKFAILURE
5525 headers.println("struct taskfailure {");
5526 headers.println("struct taskdescriptor * task;");
5527 headers.println("int index;");
5528 headers.println("int numoptionaltaskdescriptors;");
5529 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5531 //STRUCT FSANALYSISWRAPPER
5532 headers.println("struct fsanalysiswrapper{");
5533 headers.println("int flags;");
5534 headers.println("int numtags;");
5535 headers.println("int * tags;");
5536 headers.println("int numtaskfailures;");
5537 headers.println("struct taskfailure ** taskfailurearray;");
5538 headers.println("int numoptionaltaskdescriptors;");
5539 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5541 //STRUCT CLASSANALYSISWRAPPER
5542 headers.println("struct classanalysiswrapper{");
5543 headers.println("int type;");
5544 headers.println("int numotd;");
5545 headers.println("struct optionaltaskdescriptor ** otdarray;");
5546 headers.println("int numfsanalysiswrappers;");
5547 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
5549 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
5551 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
5552 while(taskit.hasNext()) {
5553 TaskDescriptor td=(TaskDescriptor)taskit.next();
5554 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
5559 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
5560 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
5561 int predicateindex = 0;
5562 //iterate through the classes concerned by the predicate
5563 Set c_vard = predicate.vardescriptors;
5564 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
5567 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
5568 VarDescriptor vard = (VarDescriptor)vard_it.next();
5569 TypeDescriptor typed = vard.getType();
5571 //generate for flags
5572 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
5573 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5575 if (fen_hashset!=null) {
5576 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
5577 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
5579 DNFFlag dflag=fen.getDNF();
5580 numberterms+=dflag.size();
5582 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
5584 for(int j=0; j<dflag.size(); j++) {
5586 output.println(",");
5587 Vector term=dflag.get(j);
5590 for(int k=0; k<term.size(); k++) {
5591 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
5592 FlagDescriptor fd=dfa.getFlag();
5593 boolean negated=dfa.getNegated();
5594 int flagid=1<<((Integer)flags.get(fd)).intValue();
5599 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
5604 output.println("};\n");
5607 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
5608 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5611 for(int j=0; j<tagel.numTags(); j++) {
5613 output.println(",");
5614 TempDescriptor tmp=tagel.getTemp(j);
5615 if (!slotnumber.containsKey(tmp)) {
5616 Integer slotint=new Integer(current_slot++);
5617 slotnumber.put(tmp,slotint);
5619 int slot=slotnumber.get(tmp).intValue();
5620 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
5622 numtags = tagel.numTags();
5624 output.println("};");
5626 //store the result into a predicatemember struct
5627 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5628 output.println("/*type*/"+typed.getClassDesc().getId()+",");
5629 output.println("/* number of dnf terms */"+numberterms+",");
5630 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5631 output.println("/* number of tag */"+numtags+",");
5632 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5633 output.println("};\n");
5638 //generate an array that stores the entire predicate
5639 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5640 for( int j = 0; j<predicateindex; j++) {
5641 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5642 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5644 output.println("};\n");
5645 return predicateindex;
5649 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
5650 generateOptionalHeader(headers);
5652 output.println("#include \"optionalstruct.h\"\n\n");
5653 output.println("#include \"stdlib.h\"\n");
5655 HashSet processedcd = new HashSet();
5657 Enumeration e = safeexecution.keys();
5658 while (e.hasMoreElements()) {
5661 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
5662 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
5664 //Generate the struct of optionals
5665 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5666 numotd = c_otd.size();
5667 if(maxotd<numotd) maxotd = numotd;
5668 if( !c_otd.isEmpty() ) {
5669 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5670 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5672 //generate the int arrays for the predicate
5673 Predicate predicate = otd.predicate;
5674 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
5675 TreeSet<Integer> fsset=new TreeSet<Integer>();
5676 //iterate through possible FSes corresponding to
5677 //the state when entering
5679 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
5680 FlagState fs = (FlagState)fses.next();
5682 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5683 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5684 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5687 fsset.add(new Integer(flagid));
5688 //tag information not needed because tag
5689 //changes are not tolerated.
5692 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5693 boolean needcomma=false;
5694 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
5697 output.println(it.next());
5700 output.println("};\n");
5703 //generate optionaltaskdescriptor that actually
5704 //includes exit fses, predicate and the task
5706 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5707 output.println("&task_"+otd.td.getSafeSymbol()+",");
5708 output.println("/*index*/"+otd.getIndex()+",");
5709 output.println("/*number of enter flags*/"+fsset.size()+",");
5710 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5711 output.println("/*number of members */"+predicateindex+",");
5712 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5713 output.println("};\n");
5717 // if there are no optionals, there is no need to build the rest of the struct
5719 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
5720 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5721 if( !c_otd.isEmpty() ) {
5722 boolean needcomma=false;
5723 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5724 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5726 output.println(",");
5728 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5731 output.println("};\n");
5733 //get all the possible flagstates reachable by an object
5734 Hashtable hashtbtemp = safeexecution.get(cdtemp);
5736 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
5737 fsts.addAll(hashtbtemp.keySet());
5738 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
5739 FlagState fs = (FlagState)fsit.next();
5742 //get the set of OptionalTaskDescriptors corresponding
5743 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
5744 //iterate through the OptionalTaskDescriptors and
5745 //store the pointers to the optionals struct (see on
5746 //top) into an array
5748 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
5749 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
5750 OptionalTaskDescriptor mm = mos.next();
5752 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
5754 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5757 output.println("};\n");
5759 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
5762 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5763 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5764 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5768 //process tag information
5771 boolean first = true;
5772 Enumeration tag_enum = fs.getTags();
5773 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5774 while(tag_enum.hasMoreElements()) {
5776 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
5780 output.println(", ");
5781 output.println("/*tagid*/"+state.getTagId(tagd));
5783 output.println("};");
5785 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
5786 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5787 TaskIndex ti=itti.next();
5791 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
5793 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
5794 boolean needcomma=false;
5795 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
5796 OptionalTaskDescriptor otd=otdit.next();
5800 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5802 output.println("};");
5804 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
5805 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
5806 output.print(ti.getIndex()+", ");
5807 output.print(otdset.size()+", ");
5808 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
5809 output.println("};");
5812 tiset=sa.getTaskIndex(fs);
5813 boolean needcomma=false;
5815 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5816 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5817 TaskIndex ti=itti.next();
5818 if (ti.isRuntime()) {
5825 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
5827 output.println("};\n");
5829 //Store the result in fsanalysiswrapper
5831 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
5832 output.println("/*flag*/"+flagid+",");
5833 output.println("/* number of tags*/"+tagcounter+",");
5834 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5835 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
5836 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5837 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
5838 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
5839 output.println("};\n");
5843 //Build the array of fsanalysiswrappers
5844 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
5845 boolean needcomma=false;
5846 for(int i = 0; i<fscounter; i++) {
5847 if (needcomma) output.print(",");
5848 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
5851 output.println("};");
5853 //Build the classanalysiswrapper referring to the previous array
5854 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
5855 output.println("/*type*/"+cdtemp.getId()+",");
5856 output.println("/*numotd*/"+numotd+",");
5857 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
5858 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
5859 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
5860 processedcd.add(cdtemp);
5863 //build an array containing every classes for which code has been build
5864 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
5865 for(int i=0; i<state.numClasses(); i++) {
5866 ClassDescriptor cn=cdarray[i];
5869 if ((cn != null) && (processedcd.contains(cn)))
5870 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
5872 output.print("NULL");
5874 output.println("};");
5876 output.println("#define MAXOTD "+maxotd);
5877 headers.println("#endif");
5880 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
5881 Relation r=new Relation();
5882 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
5883 OptionalTaskDescriptor otd=otdit.next();
5884 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
5888 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
5889 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
5890 Set s=r.get(it.next());
5891 for(Iterator it2=s.iterator(); it2.hasNext();) {
5892 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
5900 protected void outputTransCode(PrintWriter output) {
5903 private int calculateSizeOfSESEParamList(FlatSESEEnterNode fsen){
5905 Set<TempDescriptor> tdSet=new HashSet<TempDescriptor>();
5907 for (Iterator iterator = fsen.getInVarSet().iterator(); iterator.hasNext();) {
5908 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5909 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5910 tdSet.add(tempDescriptor);
5914 for (Iterator iterator = fsen.getOutVarSet().iterator(); iterator.hasNext();) {
5915 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5916 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5917 tdSet.add(tempDescriptor);
5921 return tdSet.size();
5924 private String calculateSizeOfSESEParamSize(FlatSESEEnterNode fsen){
5925 HashMap <String,Integer> map=new HashMap();
5926 HashSet <TempDescriptor> processed=new HashSet<TempDescriptor>();
5929 // space for all in and out set primitives
5930 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
5931 inSetAndOutSet.addAll( fsen.getInVarSet() );
5932 inSetAndOutSet.addAll( fsen.getOutVarSet() );
5934 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
5936 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
5937 while( itr.hasNext() ) {
5938 TempDescriptor temp = itr.next();
5939 TypeDescriptor type = temp.getType();
5940 if( !type.isPtr() ) {
5941 inSetAndOutSetPrims.add( temp );
5945 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
5946 while( itrPrims.hasNext() ) {
5947 TempDescriptor temp = itrPrims.next();
5948 TypeDescriptor type = temp.getType();
5949 if(type.isPrimitive()){
5950 Integer count=map.get(type.getSymbol());
5952 count=new Integer(1);
5953 map.put(type.getSymbol(), count);
5955 map.put(type.getSymbol(), new Integer(count.intValue()+1));
5960 Set<String> keySet=map.keySet();
5961 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
5962 String key = (String) iterator.next();
5963 rtr+="+sizeof("+key+")*"+map.get(key);