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* common = (SESEcommon*) "+pair+";");
2967 if( state.COREPROF ) {
2968 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
2969 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
2970 output.println("#endif");
2972 output.println(" pthread_mutex_lock( &(common->lock) );");
2973 output.println(" if( common->doneExecuting == FALSE ) {");
2974 output.println(" stopforgc((struct garbagelist *)&___locals___);");
2975 output.println(" do {");
2976 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2977 output.println(" } while( common->doneExecuting == FALSE );");
2978 output.println(" restartaftergc();");
2979 output.println(" }");
2980 output.println(" pthread_mutex_unlock( &(common->lock) );");
2982 // copy things we might have stalled for
2983 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2984 while( tdItr.hasNext() ) {
2985 TempDescriptor td = tdItr.next();
2986 FlatMethod fmContext;
2987 if( currentSESE.getIsCallerSESEplaceholder() ) {
2988 fmContext = currentSESE.getfmEnclosing();
2990 fmContext = currentSESE.getfmBogus();
2992 output.println(" "+generateTemp( fmContext, td, null )+
2993 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2995 if( state.COREPROF ) {
2996 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
2997 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
2998 output.println("#endif");
3000 output.println(" }");
3003 // for each variable with a dynamic source, stall just for that variable
3004 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
3005 while( dynItr.hasNext() ) {
3006 TempDescriptor dynVar = dynItr.next();
3008 // only stall if the dynamic source is not yourself, denoted by src==NULL
3009 // otherwise the dynamic write nodes will have the local var up-to-date
3010 output.println(" {");
3011 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
3012 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
3013 if( state.COREPROF ) {
3014 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
3015 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
3016 output.println("#endif");
3018 output.println(" psem_take( &(common->stallSem) );");
3020 FlatMethod fmContext;
3021 if( currentSESE.getIsCallerSESEplaceholder() ) {
3022 fmContext = currentSESE.getfmEnclosing();
3024 fmContext = currentSESE.getfmBogus();
3027 TypeDescriptor type=dynVar.getType();
3029 if( type.isNull() ) {
3031 } else if( type.isClass() || type.isArray() ) {
3032 typeStr = "struct "+type.getSafeSymbol()+"*";
3034 typeStr = type.getSafeSymbol();
3037 output.println(" "+generateTemp( fmContext, dynVar, null )+
3038 " = *(("+typeStr+"*) ((void*)"+
3039 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
3040 if( state.COREPROF ) {
3041 output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
3042 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
3043 output.println("#endif");
3045 output.println(" }");
3046 output.println(" }");
3049 // for each assignment of a variable to rhs that has a dynamic source,
3050 // copy the dynamic sources
3051 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
3052 while( dynAssignItr.hasNext() ) {
3053 Map.Entry me = (Map.Entry) dynAssignItr.next();
3054 TempDescriptor lhs = (TempDescriptor) me.getKey();
3055 TempDescriptor rhs = (TempDescriptor) me.getValue();
3057 output.println(" {");
3058 output.println(" SESEcommon* oldSrc = "+lhs+"_srcSESE;");
3060 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
3061 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
3063 // no matter what we did above, track reference count of whatever
3064 // this variable pointed to, do release last in case we're just
3065 // copying the same value in because 1->2->1 is safe but ref count
3066 // 1->0->1 has a window where it looks like it should be free'd
3067 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3068 output.println(" if( "+rhs+"_srcSESE != NULL ) {");
3069 output.println(" ADD_REFERENCE_TO( "+rhs+"_srcSESE );");
3070 output.println(" }");
3071 output.println(" if( oldSrc != NULL ) {");
3072 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
3073 output.println(" }");
3074 output.println(" }");
3075 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
3078 // for each lhs that is dynamic from a non-dynamic source, set the
3079 // dynamic source vars to the current SESE
3080 dynItr = cp.getDynAssignCurr().iterator();
3081 while( dynItr.hasNext() ) {
3082 TempDescriptor dynVar = dynItr.next();
3083 assert currentSESE.getDynamicVarSet().contains( dynVar );
3085 // first release a reference to current record
3086 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3087 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
3088 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
3089 output.println(" }");
3090 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
3092 output.println(" "+dynVar+"_srcSESE = NULL;");
3096 // handling stall site
3097 if (state.OOOJAVA) {
3098 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(currentSESE);
3100 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
3101 Set<Analysis.OoOJava.WaitingElement> waitingElementSet =
3102 graph.getStallSiteWaitingElementSet(fn, seseLockSet);
3104 if(waitingElementSet.size()>0){
3105 output.println("// stall on parent's stall sites ");
3106 output.println(" {");
3107 output.println(" REntry* rentry;");
3109 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
3110 Analysis.OoOJava.WaitingElement waitingElement = (Analysis.OoOJava.WaitingElement) iterator.next();
3113 Analysis.OoOJava.ConflictGraph conflictGraph = graph;
3114 Hashtable<Taint, Set<Effect>> conflicts;
3115 ReachGraph rg = oooa.getDisjointAnalysis().getReachGraph(currentSESE.getmdEnclosing());
3116 if(rcr.cSideDebug) {
3117 rg.writeGraph("RCR_RG_STALLSITE_DEBUG");
3119 if((conflictGraph != null) &&
3120 (conflicts = graph.getConflictEffectSet(fn)) != null &&
3122 rcr.addToTraverseToDoList(fn, waitingElement.getTempDesc(), rg, conflicts);
3126 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3127 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", runningSESE);");
3129 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", runningSESE, (void*)&" +generateTemp(fm,waitingElement.getTempDesc(),lb)+ ");");
3131 output.println(" psem_init( &(rentry->parentStallSem) );");
3132 output.println(" rentry->queue=runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3133 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()
3134 + "],rentry)==NOTREADY){");
3135 if( state.COREPROF ) {
3136 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3137 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3138 output.println("#endif");
3140 output.println(" psem_take( &(rentry->parentStallSem) );");
3141 if( state.COREPROF ) {
3142 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3143 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3144 output.println("#endif");
3146 output.println(" } ");
3149 output.println(" "+rcr.getTraverserInvocation(waitingElement.getTempDesc(),
3150 generateTemp(fm, waitingElement.getTempDesc(), null), fn));
3153 output.println(" }");
3157 ParentChildConflictsMap conflictsMap = mlpa.getConflictsResults().get(fn);
3158 if (conflictsMap != null) {
3159 Set<Long> allocSet = conflictsMap.getAllocationSiteIDSetofStallSite();
3160 if (allocSet.size() > 0) {
3161 FlatNode enclosingFlatNode=null;
3162 if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
3163 enclosingFlatNode=currentSESE.getfmEnclosing();
3165 enclosingFlatNode=currentSESE;
3167 ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
3168 HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
3169 Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
3171 if(waitingElementSet.size()>0){
3172 output.println("// stall on parent's stall sites ");
3173 output.println(" {");
3174 output.println(" REntry* rentry;");
3176 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
3177 WaitingElement waitingElement = (WaitingElement) iterator.next();
3179 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3180 // HERE! a parent might conflict with a child
3181 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", runningSESE);");
3183 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", runningSESE, (void*)&___locals___."+ waitingElement.getDynID() + ");");
3185 output.println(" psem_init( &(rentry->parentStallSem) );");
3186 output.println(" rentry->queue=runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3188 .println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()
3189 + "],rentry)==NOTREADY){");
3190 if( state.COREPROF ) {
3191 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3192 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3193 output.println("#endif");
3195 output.println(" psem_take( &(rentry->parentStallSem) );");
3196 if( state.COREPROF ) {
3197 output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
3198 output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3199 output.println("#endif");
3201 output.println(" } ");
3203 output.println(" }");
3212 case FKind.FlatAtomicEnterNode:
3213 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
3216 case FKind.FlatAtomicExitNode:
3217 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
3220 case FKind.FlatInstanceOfNode:
3221 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
3224 case FKind.FlatSESEEnterNode:
3225 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
3228 case FKind.FlatSESEExitNode:
3229 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
3232 case FKind.FlatWriteDynamicVarNode:
3233 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
3236 case FKind.FlatGlobalConvNode:
3237 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
3240 case FKind.FlatTagDeclaration:
3241 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
3244 case FKind.FlatCall:
3245 generateFlatCall(fm, lb, (FlatCall) fn,output);
3248 case FKind.FlatFieldNode:
3249 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
3252 case FKind.FlatElementNode:
3253 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
3256 case FKind.FlatSetElementNode:
3257 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
3260 case FKind.FlatSetFieldNode:
3261 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
3265 generateFlatNew(fm, lb, (FlatNew) fn,output);
3268 case FKind.FlatOpNode:
3269 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
3272 case FKind.FlatCastNode:
3273 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
3276 case FKind.FlatLiteralNode:
3277 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
3280 case FKind.FlatReturnNode:
3281 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
3285 output.println("/* nop */");
3288 case FKind.FlatGenReachNode:
3289 // this node is just for generating a reach graph
3290 // in disjointness analysis at a particular program point
3293 case FKind.FlatExit:
3294 output.println("/* exit */");
3297 case FKind.FlatBackEdge:
3298 if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3299 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3301 if(state.DSM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3302 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3304 if (((state.MLP|| state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
3305 || (this.state.MULTICOREGC)) {
3306 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
3307 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
3308 } else if(this.state.MULTICOREGC) {
3309 output.println("if (gcflag) gc("+localsprefixaddr+");");
3311 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3314 output.println("/* nop */");
3317 case FKind.FlatCheckNode:
3318 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
3321 case FKind.FlatFlagActionNode:
3322 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
3325 case FKind.FlatPrefetchNode:
3326 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
3329 case FKind.FlatOffsetNode:
3330 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
3337 // insert post-node actions from the code-plan
3340 CodePlan cp = mlpa.getCodePlan( fn );
3348 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
3349 output.println("/* FlatOffsetNode */");
3350 FieldDescriptor fd=fofn.getField();
3351 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
3352 output.println("/* offset */");
3355 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
3356 if (state.PREFETCH) {
3357 Vector oids = new Vector();
3358 Vector fieldoffset = new Vector();
3359 Vector endoffset = new Vector();
3360 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
3361 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
3362 PrefetchPair pp = (PrefetchPair) it.next();
3363 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
3364 /* Find prefetches that can generate oid */
3365 if(statusbase == LocalityAnalysis.GLOBAL) {
3366 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
3368 } else if (statusbase == LocalityAnalysis.LOCAL) {
3369 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
3376 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
3377 output.println("{");
3378 output.println("/* prefetch */");
3379 output.println("/* prefetchid_" + fpn.siteid + " */");
3380 output.println("void * prefptr;");
3381 output.println("int tmpindex;");
3383 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
3384 /*Create C code for oid array */
3385 output.print(" unsigned int oidarray_[] = {");
3386 boolean needcomma=false;
3387 for (Iterator it = oids.iterator(); it.hasNext();) {
3390 output.print(it.next());
3393 output.println("};");
3395 /*Create C code for endoffset values */
3396 output.print(" unsigned short endoffsetarry_[] = {");
3398 for (Iterator it = endoffset.iterator(); it.hasNext();) {
3401 output.print(it.next());
3404 output.println("};");
3406 /*Create C code for Field Offset Values */
3407 output.print(" short fieldarry_[] = {");
3409 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
3412 output.print(it.next());
3415 output.println("};");
3416 /* make the prefetch call to Runtime */
3417 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
3418 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
3419 output.println(" }");
3420 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
3421 output.println(" } else {");
3422 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
3423 output.println(" }");
3424 output.println("}");
3428 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
3429 short offsetcount = 0;
3433 } else if (localbase) {
3434 for(; breakindex<pp.desc.size(); breakindex++) {
3435 Descriptor desc=pp.getDescAt(breakindex);
3436 if (desc instanceof FieldDescriptor) {
3437 FieldDescriptor fd=(FieldDescriptor)desc;
3438 if (fd.isGlobal()) {
3446 if (breakindex>pp.desc.size()) //all local
3449 TypeDescriptor lasttype=pp.base.getType();
3450 String basestr=generateTemp(fm, pp.base, lb);
3452 boolean maybenull=fm.getMethod().isStatic()||
3453 !pp.base.equals(fm.getParameter(0));
3455 for(int i=0; i<breakindex; i++) {
3456 String indexcheck="";
3458 Descriptor desc=pp.getDescAt(i);
3459 if (desc instanceof FieldDescriptor) {
3460 FieldDescriptor fd=(FieldDescriptor)desc;
3462 if (!teststr.equals(""))
3464 teststr+="((prefptr="+basestr+")!=NULL)";
3465 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3467 basestr=basestr+"->"+fd.getSafeSymbol();
3470 lasttype=fd.getType();
3472 IndexDescriptor id=(IndexDescriptor)desc;
3473 indexcheck="((tmpindex=";
3474 for(int j=0; j<id.tddesc.size(); j++) {
3475 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3477 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3479 if (!teststr.equals(""))
3481 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3482 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3484 lasttype=lasttype.dereference();
3489 if (teststr.equals("")) {
3490 oid="((unsigned int)"+basestr+")";
3492 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3496 for(int i = breakindex; i < pp.desc.size(); i++) {
3497 String newfieldoffset;
3498 Object desc = pp.getDescAt(i);
3499 if(desc instanceof FieldDescriptor) {
3500 FieldDescriptor fd=(FieldDescriptor)desc;
3501 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3502 lasttype=fd.getType();
3504 newfieldoffset = "";
3505 IndexDescriptor id=(IndexDescriptor)desc;
3506 for(int j = 0; j < id.tddesc.size(); j++) {
3507 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3509 newfieldoffset += id.offset.toString();
3510 lasttype=lasttype.dereference();
3512 fieldoffset.add(newfieldoffset);
3515 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3516 base+=pp.desc.size()-breakindex;
3517 endoffset.add(new Short((short)base));
3522 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3523 if (lb!=fgcn.getLocality())
3525 /* Have to generate flat globalconv */
3526 if (fgcn.getMakePtr()) {
3528 //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3529 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3531 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3532 //need to do translation
3533 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3534 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3535 if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3536 output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3538 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3542 /* Need to convert to OID */
3543 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3544 if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3545 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3547 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3553 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3555 if (fion.getType().isArray()) {
3556 type=state.getArrayNumber(fion.getType())+state.numClasses();
3558 type=fion.getType().getClassDesc().getId();
3561 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3562 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3564 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3567 int sandboxcounter=0;
3568 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3569 /* Check to see if we need to generate code for this atomic */
3570 if (locality==null) {
3571 if (GENERATEPRECISEGC) {
3572 output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3573 output.println("stopforgc((struct garbagelist *) &___locals___);");
3574 output.println("pthread_mutex_lock(&atomiclock);");
3575 output.println("restartaftergc();");
3576 output.println("}");
3578 output.println("pthread_mutex_lock(&atomiclock);");
3583 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3587 if (state.SANDBOX) {
3588 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3589 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3592 if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3593 AtomicRecord ar=atomicmethodmap.get(faen);
3595 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3596 TempDescriptor tmp=tmpit.next();
3597 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3600 //copy outs that depend on path
3601 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3602 TempDescriptor tmp=tmpit.next();
3603 if (!ar.livein.contains(tmp))
3604 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3608 /* Backup the temps. */
3609 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3610 TempDescriptor tmp=tmpit.next();
3611 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3614 output.println("goto transstart"+faen.getIdentifier()+";");
3616 /******* Print code to retry aborted transaction *******/
3617 output.println("transretry"+faen.getIdentifier()+":");
3620 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3621 TempDescriptor tmp=tmpit.next();
3622 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3626 /********* Need to revert local object store ********/
3627 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3629 output.println("while ("+revertptr+") {");
3630 output.println("struct ___Object___ * tmpptr;");
3631 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3632 output.println("REVERT_OBJ("+revertptr+");");
3633 output.println(revertptr+"=tmpptr;");
3634 output.println("}");
3636 /******* Tell the runtime to start the transaction *******/
3638 output.println("transstart"+faen.getIdentifier()+":");
3639 if (state.SANDBOX) {
3640 output.println("transaction_check_counter=*counter_reset_pointer;");
3643 output.println("transStart();");
3645 if (state.ABORTREADERS||state.SANDBOX) {
3647 output.println("abortenabled=1;");
3648 output.println("if (_setjmp(aborttrans)) {");
3649 output.println(" goto transretry"+faen.getIdentifier()+"; }");
3653 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3654 /* Check to see if we need to generate code for this atomic */
3655 if (locality==null) {
3656 output.println("pthread_mutex_unlock(&atomiclock);");
3659 if (locality.getAtomic(lb).get(faen).intValue()>0)
3661 //store the revert list before we lose the transaction object
3664 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3665 output.println(revertptr+"=revertlist;");
3666 output.println("if (transCommit()) {");
3667 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3668 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3669 output.println("} else {");
3670 /* Need to commit local object store */
3671 output.println("while ("+revertptr+") {");
3672 output.println("struct ___Object___ * tmpptr;");
3673 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3674 output.println("COMMIT_OBJ("+revertptr+");");
3675 output.println(revertptr+"=tmpptr;");
3676 output.println("}");
3677 output.println("}");
3681 if (!state.DELAYCOMP) {
3683 output.println("if (transCommit()) {");
3684 /* Transaction aborts if it returns true */
3685 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3686 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3687 output.println("}");
3689 if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
3690 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3691 output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3693 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3694 TempDescriptor tmp=tmpit.next();
3695 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3697 } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3698 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3700 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3701 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3702 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3703 output.println("}");
3705 output.println("else {");
3706 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3707 TempDescriptor tmp=tmpit.next();
3708 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3710 output.println("}");
3712 output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3713 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3714 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3715 output.println("}");
3720 public void generateFlatSESEEnterNode( FlatMethod fm,
3722 FlatSESEEnterNode fsen,
3723 PrintWriter output) {
3724 // if MLP flag is off, okay that SESE nodes are in IR graph,
3725 // just skip over them and code generates exactly the same
3726 if( !(state.MLP || state.OOOJAVA) ) {
3729 // there may be an SESE in an unreachable method, skip over
3730 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
3731 (state.OOOJAVA && !oooa.getAllSESEs().contains(fsen))
3736 // also, if we have encountered a placeholder, just skip it
3737 if( fsen.getIsCallerSESEplaceholder() ) {
3741 output.println(" {");
3743 if( state.COREPROF ) {
3744 output.println("#ifdef CP_EVENTID_TASKDISPATCH");
3745 output.println(" CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_BEGIN );");
3746 output.println("#endif");
3750 // before doing anything, lock your own record and increment the running children
3751 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3752 (state.OOOJAVA && fsen != oooa.getMainSESE())
3754 output.println(" atomic_inc(&(runningSESE->numRunningChildren));");
3757 // allocate the space for this record
3758 output.println( "#ifndef OOO_DISABLE_TASKMEMPOOL" );
3760 output.println( "#ifdef CP_EVENTID_POOLALLOC");
3761 output.println( " CP_LOGEVENT( CP_EVENTID_POOLALLOC, CP_EVENTTYPE_BEGIN );");
3762 output.println( "#endif");
3763 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3764 (state.OOOJAVA && fsen != oooa.getMainSESE())
3767 fsen.getSESErecordName()+"* seseToIssue = ("+
3768 fsen.getSESErecordName()+"*) poolalloc( runningSESE->taskRecordMemPool );");
3771 fsen.getSESErecordName()+"* seseToIssue = ("+
3772 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3773 fsen.getSESErecordName()+" ) );");
3775 output.println( "#ifdef CP_EVENTID_POOLALLOC");
3776 output.println( " CP_LOGEVENT( CP_EVENTID_POOLALLOC, CP_EVENTTYPE_END );");
3777 output.println( "#endif");
3779 output.println( "#else // OOO_DISABLE_TASKMEMPOOL" );
3781 fsen.getSESErecordName()+"* seseToIssue = ("+
3782 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3783 fsen.getSESErecordName()+" ) );");
3784 output.println( "#endif // OOO_DISABLE_TASKMEMPOOL" );
3787 // set up the SESE in-set and out-set objects, which look
3788 // like a garbage list
3789 output.println(" struct garbagelist * gl= (struct garbagelist *)&(((SESEcommon*)(seseToIssue))[1]);");
3790 output.println(" gl->size="+calculateSizeOfSESEParamList(fsen)+";");
3791 output.println(" gl->next = NULL;");
3793 // there are pointers to SESE records the newly-issued SESE
3794 // will use to get values it depends on them for--how many
3795 // are there, and what is the offset from the total SESE
3796 // record to the first dependent record pointer?
3797 output.println(" seseToIssue->common.numDependentSESErecords="+
3798 fsen.getNumDepRecs()+";");
3800 // we only need this (and it will only compile) when the number of dependent
3801 // SESE records is non-zero
3802 if( fsen.getFirstDepRecField() != null ) {
3803 output.println(" seseToIssue->common.offsetToDepSESErecords=(INTPTR)sizeof("+
3804 fsen.getSESErecordName()+") - (INTPTR)&((("+
3805 fsen.getSESErecordName()+"*)0)->"+fsen.getFirstDepRecField()+");"
3809 if (state.RCR&&fsen.getInVarsForDynamicCoarseConflictResolution().size()>0) {
3810 output.println(" seseToIssue->common.offsetToParamRecords=(INTPTR)sizeof("+fsen.getSESErecordName()+") - (INTPTR) & ((("+fsen.getSESErecordName()+"*)0)->rcrRecords);");
3813 // fill in common data
3814 output.println(" int localCount=0;");
3815 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3816 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
3817 output.println(" seseToIssue->common.forwardList = createQueue();");
3818 output.println(" seseToIssue->common.unresolvedDependencies = 10000;");
3819 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3820 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3821 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3822 output.println(" seseToIssue->common.numRunningChildren = 0;");
3823 output.println(" seseToIssue->common.parent = runningSESE;");
3824 // start with refCount = 2, one being the count that the child itself
3825 // will decrement when it retires, to say it is done using its own
3826 // record, and the other count is for the parent that will remember
3827 // the static name of this new child below
3828 output.println(" seseToIssue->common.refCount = 2;");
3830 // all READY in-vars should be copied now and be done with it
3831 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3832 while( tempItr.hasNext() ) {
3833 TempDescriptor temp = tempItr.next();
3835 // when we are issuing the main SESE or an SESE with placeholder
3836 // caller SESE as parent, generate temp child child's eclosing method,
3837 // otherwise use the parent's enclosing method as the context
3838 boolean useParentContext = false;
3840 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3841 (state.OOOJAVA && fsen != oooa.getMainSESE())
3843 assert fsen.getParent() != null;
3844 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3845 useParentContext = true;
3849 if( useParentContext ) {
3850 output.println(" seseToIssue->"+temp+" = "+
3851 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3853 output.println(" seseToIssue->"+temp+" = "+
3854 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3858 // before potentially adding this SESE to other forwarding lists,
3860 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3863 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3864 (state.OOOJAVA && fsen != oooa.getMainSESE())
3866 // count up outstanding dependencies, static first, then dynamic
3867 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3868 while( staticSrcsItr.hasNext() ) {
3869 SESEandAgePair srcPair = staticSrcsItr.next();
3870 output.println(" {");
3871 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3872 output.println(" pthread_mutex_lock( &(src->lock) );");
3874 output.println(" if( !src->doneExecuting ) {");
3875 output.println(" addNewItem( src->forwardList, seseToIssue );");
3876 output.println(" ++(localCount);");
3877 output.println(" }");
3878 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3879 output.println(" ADD_REFERENCE_TO( src );");
3880 output.println("#endif" );
3881 output.println(" pthread_mutex_unlock( &(src->lock) );");
3882 output.println(" }");
3884 // whether or not it is an outstanding dependency, make sure
3885 // to pass the static name to the child's record
3886 output.println(" seseToIssue->"+srcPair+" = "+
3887 "("+srcPair.getSESE().getSESErecordName()+"*)"+
3891 // dynamic sources might already be accounted for in the static list,
3892 // so only add them to forwarding lists if they're not already there
3893 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3894 while( dynVarsItr.hasNext() ) {
3895 TempDescriptor dynInVar = dynVarsItr.next();
3896 output.println(" {");
3897 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3899 // the dynamic source is NULL if it comes from your own space--you can't pass
3900 // the address off to the new child, because you're not done executing and
3901 // might change the variable, so copy it right now
3902 output.println(" if( src != NULL ) {");
3903 output.println(" pthread_mutex_lock( &(src->lock) );");
3907 output.println(" if( isEmpty( src->forwardList ) ||");
3908 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3909 output.println(" if( !src->doneExecuting ) {");
3910 output.println(" addNewItem( src->forwardList, seseToIssue );");
3911 output.println(" ++(localCount);");
3912 output.println(" }");
3913 output.println(" }");
3914 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3915 output.println(" ADD_REFERENCE_TO( src );");
3916 output.println("#endif" );
3917 output.println(" pthread_mutex_unlock( &(src->lock) );");
3918 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3919 output.println(" } else {");
3921 boolean useParentContext = false;
3922 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3923 (state.OOOJAVA && fsen != oooa.getMainSESE())
3925 assert fsen.getParent() != null;
3926 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3927 useParentContext = true;
3930 if( useParentContext ) {
3931 output.println(" seseToIssue->"+dynInVar+" = "+
3932 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3934 output.println(" seseToIssue->"+dynInVar+" = "+
3935 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3938 output.println(" }");
3939 output.println(" }");
3941 // even if the value is already copied, make sure your NULL source
3942 // gets passed so child knows it already has the dynamic value
3943 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3949 // maintain pointers for finding dynamic SESE
3950 // instances from static names
3951 SESEandAgePair pairNewest = new SESEandAgePair( fsen, 0 );
3952 SESEandAgePair pairOldest = new SESEandAgePair( fsen, fsen.getOldestAgeToTrack() );
3953 if( fsen.getParent() != null &&
3954 fsen.getParent().getNeededStaticNames().contains( pairNewest )
3956 output.println(" {");
3957 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3958 output.println(" SESEcommon* oldest = "+pairOldest+";");
3959 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
3961 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3962 SESEandAgePair pair1 = new SESEandAgePair( fsen, i );
3963 SESEandAgePair pair2 = new SESEandAgePair( fsen, i-1 );
3964 output.println(" "+pair1+" = "+pair2+";");
3966 output.println(" "+pairNewest+" = &(seseToIssue->common);");
3968 // no need to add a reference to whatever is the newest record, because
3969 // we initialized seseToIssue->refCount to *2*
3970 // but release a reference to whatever was the oldest BEFORE the shift
3971 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
3972 output.println(" if( oldest != NULL ) {");
3973 output.println(" RELEASE_REFERENCE_TO( oldest );");
3974 output.println(" }");
3975 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
3976 output.println(" }");
3981 if( state.COREPROF ) {
3982 output.println("#ifdef CP_EVENTID_PREPAREMEMQ");
3983 output.println(" CP_LOGEVENT( CP_EVENTID_PREPAREMEMQ, CP_EVENTTYPE_BEGIN );");
3984 output.println("#endif");
3989 // count up memory conflict dependencies,
3991 dispatchMEMRC(fm, lb, fsen, output);
3992 } else if(state.OOOJAVA){
3993 FlatSESEEnterNode parent = fsen.getParent();
3994 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(parent);
3995 if (graph != null && graph.hasConflictEdge()) {
3996 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
3998 output.println(" //add memory queue element");
3999 Analysis.OoOJava.SESEWaitingQueue seseWaitingQueue=
4000 graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet);
4001 if(seseWaitingQueue.getWaitingElementSize()>0) {
4002 output.println(" {");
4003 output.println(" REntry* rentry=NULL;");
4004 output.println(" INTPTR* pointer=NULL;");
4005 output.println(" seseToIssue->common.rentryIdx=0;");
4007 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
4008 for (Iterator iterator = queueIDSet.iterator(); iterator.hasNext();) {
4009 Integer key = (Integer) iterator.next();
4010 int queueID=key.intValue();
4011 Set<Analysis.OoOJava.WaitingElement> waitingQueueSet =
4012 seseWaitingQueue.getWaitingElementSet(queueID);
4013 int enqueueType=seseWaitingQueue.getType(queueID);
4014 if(enqueueType==SESEWaitingQueue.EXCEPTION) {
4015 output.println(" INITIALIZEBUF(runningSESE->memoryQueueArray[" + queueID+ "]);");
4017 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2.hasNext();) {
4018 Analysis.OoOJava.WaitingElement waitingElement
4019 = (Analysis.OoOJava.WaitingElement) iterator2.next();
4020 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
4021 output.println(" rentry=mlpCreateREntry("
4022 + waitingElement.getStatus()
4023 + ", &(seseToIssue->common));");
4025 TempDescriptor td = waitingElement.getTempDesc();
4026 // decide whether waiting element is dynamic or static
4027 if (fsen.getDynamicInVarSet().contains(td)) {
4028 // dynamic in-var case
4029 output.println(" pointer=seseToIssue->"
4030 + waitingElement.getDynID()
4031 + "_srcSESE+seseToIssue->"
4032 + waitingElement.getDynID()
4034 output.println(" rentry=mlpCreateFineREntry("
4035 + waitingElement.getStatus()
4036 + ", &(seseToIssue->common), pointer );");
4037 } else if (fsen.getStaticInVarSet().contains(td)) {
4038 // static in-var case
4039 VariableSourceToken vst = fsen.getStaticInVarSrc(td);
4042 String srcId = "SESE_" + vst.getSESE().getPrettyIdentifier()
4043 + vst.getSESE().getIdentifier()
4044 + "_" + vst.getAge();
4045 output.println(" pointer=(void*)&seseToIssue->"
4051 output.println(" rentry=mlpCreateFineREntry("
4052 + waitingElement.getStatus()
4053 + ", &(seseToIssue->common), pointer );");
4056 output.println(" rentry=mlpCreateFineREntry("
4057 + waitingElement.getStatus()
4058 + ", &(seseToIssue->common), (void*)&seseToIssue->"
4059 + waitingElement.getDynID()
4063 output.println(" rentry->queue=runningSESE->memoryQueueArray["
4064 + waitingElement.getQueueID()
4067 if(enqueueType==SESEWaitingQueue.NORMAL){
4068 output.println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4069 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["
4070 + waitingElement.getQueueID()
4071 + "],rentry)==NOTREADY) {");
4072 output.println(" localCount++;");
4073 output.println(" }");
4075 output.println(" ADDRENTRYTOBUF(runningSESE->memoryQueueArray[" + waitingElement.getQueueID() + "],rentry);");
4078 if(enqueueType!=SESEWaitingQueue.NORMAL){
4079 output.println(" localCount+=RESOLVEBUF(runningSESE->memoryQueueArray["
4080 + queueID+ "],&seseToIssue->common);");
4083 output.println(" }");
4088 ConflictGraph graph = null;
4089 FlatSESEEnterNode parent = fsen.getParent();
4090 if (parent != null) {
4091 if (parent.isCallerSESEplaceholder) {
4092 graph = mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
4094 graph = mlpa.getConflictGraphResults().get(parent);
4097 if (graph != null && graph.hasConflictEdge()) {
4098 HashSet<SESELock> seseLockSet = mlpa.getConflictGraphLockMap()
4101 output.println(" //add memory queue element");
4102 SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(fsen.getIdentifier(),
4104 if(seseWaitingQueue.getWaitingElementSize()>0){
4105 output.println(" {");
4106 output.println(" REntry* rentry=NULL;");
4107 output.println(" INTPTR* pointer=NULL;");
4108 output.println(" seseToIssue->common.rentryIdx=0;");
4110 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
4111 for (Iterator iterator = queueIDSet.iterator(); iterator
4113 Integer key = (Integer) iterator.next();
4114 int queueID=key.intValue();
4115 Set<WaitingElement> waitingQueueSet = seseWaitingQueue.getWaitingElementSet(queueID);
4116 int enqueueType=seseWaitingQueue.getType(queueID);
4117 if(enqueueType==SESEWaitingQueue.EXCEPTION){
4118 output.println(" INITIALIZEBUF(runningSESE->memoryQueueArray["
4121 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2
4123 WaitingElement waitingElement = (WaitingElement) iterator2
4125 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
4126 output.println(" rentry=mlpCreateREntry("
4127 + waitingElement.getStatus()
4128 + ", &(seseToIssue->common));");
4130 TempDescriptor td = waitingElement
4132 // decide whether waiting element is dynamic or
4134 if (fsen.getDynamicInVarSet().contains(td)) {
4135 // dynamic in-var case
4136 output.println(" pointer=seseToIssue->"
4137 + waitingElement.getDynID()
4138 + "_srcSESE+seseToIssue->"
4139 + waitingElement.getDynID()
4142 .println(" rentry=mlpCreateFineREntry("
4145 + ", &(seseToIssue->common), pointer );");
4146 } else if (fsen.getStaticInVarSet()
4148 // static in-var case
4149 VariableSourceToken vst = fsen
4150 .getStaticInVarSrc(td);
4153 String srcId = "SESE_"
4155 .getPrettyIdentifier()
4156 + vst.getSESE().getIdentifier()
4157 + "_" + vst.getAge();
4159 .println(" pointer=(void*)&seseToIssue->"
4166 .println(" rentry=mlpCreateFineREntry("
4169 + ", &(seseToIssue->common), pointer );");
4174 .println(" rentry=mlpCreateFineREntry("
4177 + ", &(seseToIssue->common), (void*)&seseToIssue->"
4178 + waitingElement.getDynID()
4183 .println(" rentry->queue=runningSESE->memoryQueueArray["
4184 + waitingElement.getQueueID()
4187 if(enqueueType==SESEWaitingQueue.NORMAL){
4189 .println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4191 .println(" if(ADDRENTRY(runningSESE->memoryQueueArray["
4192 + waitingElement.getQueueID()
4193 + "],rentry)==NOTREADY){");
4194 output.println(" ++(localCount);");
4195 output.println(" } ");
4198 .println(" ADDRENTRYTOBUF(runningSESE->memoryQueueArray["
4199 + waitingElement.getQueueID()
4203 if(enqueueType!=SESEWaitingQueue.NORMAL){
4204 output.println(" localCount+=RESOLVEBUF(runningSESE->memoryQueueArray["
4205 + queueID+ "],&seseToIssue->common);");
4208 output.println(" }");
4215 if( state.COREPROF ) {
4216 output.println("#ifdef CP_EVENTID_PREPAREMEMQ");
4217 output.println(" CP_LOGEVENT( CP_EVENTID_PREPAREMEMQ, CP_EVENTTYPE_END );");
4218 output.println("#endif");
4221 // Enqueue Task Record
4223 output.println(" enqueueTR(TRqueue, (void *)seseToIssue);");
4226 // if there were no outstanding dependencies, issue here
4227 output.println(" if( atomic_sub_and_test(10000-localCount,&(seseToIssue->common.unresolvedDependencies) ) ) {");
4228 output.println(" workScheduleSubmit( (void*)seseToIssue );");
4229 output.println(" }");
4233 if( state.COREPROF ) {
4234 output.println("#ifdef CP_EVENTID_TASKDISPATCH");
4235 output.println(" CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_END );");
4236 output.println("#endif");
4239 output.println(" }");
4243 void dispatchMEMRC(FlatMethod fm, LocalityBinding lb, FlatSESEEnterNode fsen, PrintWriter output) {
4244 FlatSESEEnterNode parent = fsen.getParent();
4245 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(parent);
4246 if (graph != null && graph.hasConflictEdge()) {
4247 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
4248 Analysis.OoOJava.SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet);
4249 if(seseWaitingQueue.getWaitingElementSize()>0) {
4250 output.println(" {");
4251 output.println(" REntry* rentry=NULL;");
4252 output.println(" INTPTR* pointer=NULL;");
4253 output.println(" seseToIssue->common.rentryIdx=0;");
4254 output.println(" int dispCount;");
4255 Vector<TempDescriptor> invars=fsen.getInVarsForDynamicCoarseConflictResolution();
4256 for(int i=0;i<invars.size();i++) {
4257 TempDescriptor td=invars.get(i);
4258 Set<Analysis.OoOJava.WaitingElement> weset=seseWaitingQueue.getWaitingElementSet(td);
4259 int numqueues=weset.size();
4260 output.println(" seseToIssue->rcrRecords["+i+"]="+numqueues+";");
4261 output.println(" dispCount=0;");
4262 for(Iterator<Analysis.OoOJava.WaitingElement> wtit=weset.iterator();wtit.hasNext();) {
4263 Analysis.OoOJava.WaitingElement waitingElement=wtit.next();
4264 int queueID=waitingElement.getQueueID();
4265 assert(waitingElement.getStatus()>=ConflictNode.COARSE);
4266 output.println(" rentry=mlpCreateREntry(" + waitingElement.getStatus() + ", &(seseToIssue->common));");
4267 output.println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4268 output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "],rentry)==READY) {");
4269 output.println(" dispCount++;");
4270 output.println(" }");
4272 output.println(" if(!dispCount || !atomic_sub_and_test(dispCount,&(seseToIssue->rcrRecords["+i+"])))");
4273 output.println(" localCount++;");
4274 if (fsen.getDynamicInVarSet().contains(td)) {
4275 // dynamic in-var case
4276 //output.println(" pointer=seseToIssue->" + waitingElement.getDynID()+ "_srcSESE+seseToIssue->"+ waitingElement.getDynID()+ "_srcOffset;");
4277 //output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", &(seseToIssue->common), pointer );");
4280 output.println(" }");
4285 public void generateFlatSESEExitNode( FlatMethod fm,
4287 FlatSESEExitNode fsexn,
4291 // if MLP flag is off, okay that SESE nodes are in IR graph,
4292 // just skip over them and code generates exactly the same
4293 if( ! (state.MLP || state.OOOJAVA) ) {
4297 // get the enter node for this exit that has meta data embedded
4298 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
4300 // there may be an SESE in an unreachable method, skip over
4301 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
4302 (state.OOOJAVA && !oooa.getAllSESEs().contains( fsen ))
4307 // also, if we have encountered a placeholder, just jump it
4308 if( fsen.getIsCallerSESEplaceholder() ) {
4312 if( state.COREPROF ) {
4313 output.println("#ifdef CP_EVENTID_TASKEXECUTE");
4314 output.println(" CP_LOGEVENT( CP_EVENTID_TASKEXECUTE, CP_EVENTTYPE_END );");
4315 output.println("#endif");
4318 output.println(" /* SESE exiting */");
4320 if( state.COREPROF ) {
4321 output.println("#ifdef CP_EVENTID_TASKRETIRE");
4322 output.println(" CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_BEGIN );");
4323 output.println("#endif");
4326 String com = paramsprefix+"->common";
4328 // this SESE cannot be done until all of its children are done
4329 // so grab your own lock with the condition variable for watching
4330 // that the number of your running children is greater than zero
4331 output.println(" pthread_mutex_lock( &("+com+".lock) );");
4332 output.println(" if ( "+com+".numRunningChildren > 0 ) {");
4333 output.println(" stopforgc((struct garbagelist *)&___locals___);");
4334 output.println(" do {");
4335 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
4336 output.println(" } while( "+com+".numRunningChildren > 0 );");
4337 output.println(" restartaftergc();");
4338 output.println(" }");
4341 // copy out-set from local temps into the sese record
4342 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
4343 while( itr.hasNext() ) {
4344 TempDescriptor temp = itr.next();
4346 // only have to do this for primitives non-arrays
4348 temp.getType().isPrimitive() && !temp.getType().isArray()
4354 // have to determine the context enclosing this sese
4355 boolean useParentContext = false;
4357 if( (state.MLP &&fsen != mlpa.getMainSESE()) ||
4358 (state.OOOJAVA &&fsen != oooa.getMainSESE())
4360 assert fsen.getParent() != null;
4361 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
4362 useParentContext = true;
4367 if( useParentContext ) {
4368 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
4370 from = generateTemp( fsen.getfmEnclosing(), temp, null );
4373 output.println(" "+paramsprefix+
4374 "->"+temp.getSafeSymbol()+
4378 // mark yourself done, your SESE data is now read-only
4379 output.println(" "+com+".doneExecuting = TRUE;");
4380 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
4381 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
4383 // decrement dependency count for all SESE's on your forwarding list
4386 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
4387 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
4390 output.println(" if(consumer->rentryIdx>0){");
4391 output.println(" // resolved null pointer");
4392 output.println(" int idx;");
4393 output.println(" for(idx=0;idx<consumer->rentryIdx;idx++){");
4394 output.println(" resolvePointer(consumer->rentryArray[idx]);");
4395 output.println(" }");
4396 output.println(" }");
4399 output.println(" if( atomic_sub_and_test(1, &(consumer->unresolvedDependencies)) ){");
4400 output.println(" workScheduleSubmit( (void*)consumer );");
4401 output.println(" }");
4402 output.println(" }");
4406 // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
4407 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4408 (state.OOOJAVA && fsen != oooa.getMainSESE())
4412 output.println(" /* check memory dependency*/");
4413 output.println(" {");
4414 output.println(" int idx;");
4415 output.println(" for(idx=0;idx<___params___->common.rentryIdx;idx++){");
4416 output.println(" REntry* re=___params___->common.rentryArray[idx];");
4417 output.println(" RETIRERENTRY(re->queue,re);");
4418 output.println(" }");
4419 output.println(" }");
4423 // if parent is stalling on you, let them know you're done
4424 if( (state.MLP && fsexn.getFlatEnter() != mlpa.getMainSESE()) ||
4425 (state.OOOJAVA && fsexn.getFlatEnter() != oooa.getMainSESE())
4427 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
4430 // last of all, decrement your parent's number of running children
4431 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
4432 output.println(" if (atomic_sub_and_test(1, &"+paramsprefix+"->common.parent->numRunningChildren)) {");
4433 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
4434 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
4435 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
4436 output.println(" }");
4437 output.println(" }");
4439 // a task has variables to track static/dynamic instances
4440 // that serve as sources, release the parent's ref of each
4441 // non-null var of these types
4442 output.println(" // releasing static SESEs");
4443 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4444 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
4445 while( pItr.hasNext() ) {
4446 SESEandAgePair pair = pItr.next();
4447 output.println(" if( "+pair+" != NULL ) {");
4448 output.println(" RELEASE_REFERENCE_TO( "+pair+" );");
4449 output.println(" }");
4451 output.println(" // releasing dynamic variable sources");
4452 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
4453 while( dynSrcItr.hasNext() ) {
4454 TempDescriptor dynSrcVar = dynSrcItr.next();
4455 output.println(" if( "+dynSrcVar+"_srcSESE != NULL ) {");
4456 output.println(" RELEASE_REFERENCE_TO( "+dynSrcVar+"_srcSESE );");
4457 output.println(" }");
4459 // destroy this task's mempool if it is not a leaf task
4460 if( !fsen.getIsLeafSESE() ) {
4461 output.println(" pooldestroy( runningSESE->taskRecordMemPool );");
4463 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4466 // if this is not the Main sese (which has no parent) then return
4467 // THIS task's record to the PARENT'S task record pool, and only if
4468 // the reference count is now zero
4469 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4470 (state.OOOJAVA && fsen != oooa.getMainSESE())
4472 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4473 output.println(" RELEASE_REFERENCE_TO( runningSESE );");
4474 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4476 // the main task has no parent, just free its record
4477 output.println(" mlpFreeSESErecord( runningSESE );");
4480 // as this thread is wrapping up the task, make sure the thread-local var
4481 // for the currently running task record references an invalid task
4482 output.println(" runningSESE = (SESEcommon*) 0x1;");
4484 if( state.COREPROF ) {
4485 output.println("#ifdef CP_EVENTID_TASKRETIRE");
4486 output.println(" CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_END );");
4487 output.println("#endif");
4491 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
4493 FlatWriteDynamicVarNode fwdvn,
4496 if( !(state.MLP || state.OOOJAVA) ) {
4497 // should node should not be in an IR graph if the
4498 // MLP flag is not set
4499 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
4502 Hashtable<TempDescriptor, VSTWrapper> writeDynamic = fwdvn.getVar2src();
4504 assert writeDynamic != null;
4506 Iterator wdItr = writeDynamic.entrySet().iterator();
4507 while( wdItr.hasNext() ) {
4508 Map.Entry me = (Map.Entry) wdItr.next();
4509 TempDescriptor refVar = (TempDescriptor) me.getKey();
4510 VSTWrapper vstW = (VSTWrapper) me.getValue();
4511 VariableSourceToken vst = vstW.vst;
4513 output.println(" {");
4514 output.println(" SESEcommon* oldSrc = "+refVar+"_srcSESE;");
4517 // if there is no given source, this variable is ready so
4518 // mark src pointer NULL to signify that the var is up-to-date
4519 output.println(" "+refVar+"_srcSESE = NULL;");
4521 // otherwise we track where it will come from
4522 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
4523 output.println(" "+refVar+"_srcSESE = "+instance+";");
4524 output.println(" "+refVar+"_srcOffset = (INTPTR) &((("+
4525 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
4528 // no matter what we did above, track reference count of whatever
4529 // this variable pointed to, do release last in case we're just
4530 // copying the same value in because 1->2->1 is safe but ref count
4531 // 1->0->1 has a window where it looks like it should be free'd
4532 output.println("#ifndef OOO_DISABLE_TASKMEMPOOL" );
4533 output.println(" if( "+refVar+"_srcSESE != NULL ) {");
4534 output.println(" ADD_REFERENCE_TO( "+refVar+"_srcSESE );");
4535 output.println(" }");
4536 output.println(" if( oldSrc != NULL ) {");
4537 output.println(" RELEASE_REFERENCE_TO( oldSrc );");
4538 output.println(" }");
4539 output.println("#endif // OOO_DISABLE_TASKMEMPOOL" );
4541 output.println(" }");
4546 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
4547 if (state.CONSCHECK) {
4548 String specname=fcn.getSpec();
4549 String varname="repairstate___";
4550 output.println("{");
4551 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
4553 TempDescriptor[] temps=fcn.getTemps();
4554 String[] vars=fcn.getVars();
4555 for(int i=0; i<temps.length; i++) {
4556 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
4559 output.println("if (doanalysis"+specname+"("+varname+")) {");
4560 output.println("free"+specname+"_state("+varname+");");
4561 output.println("} else {");
4562 output.println("/* Bad invariant */");
4563 output.println("free"+specname+"_state("+varname+");");
4564 output.println("abort_task();");
4565 output.println("}");
4566 output.println("}");
4570 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
4572 MethodDescriptor md=fc.getMethod();
4573 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
4574 ClassDescriptor cn=md.getClassDesc();
4575 output.println("{");
4576 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4578 LocalityBinding fclb=locality.getBinding(lb, fc);
4579 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4581 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4582 output.print(objectparams.numPointers());
4583 output.print(", "+localsprefixaddr);
4584 if (md.getThis()!=null) {
4586 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
4588 if (fc.getThis()!=null&&md.getThis()==null) {
4589 System.out.println("WARNING!!!!!!!!!!!!");
4590 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
4594 for(int i=0; i<fc.numArgs(); i++) {
4595 Descriptor var=md.getParameter(i);
4596 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4597 if (objectparams.isParamPtr(paramtemp)) {
4598 TempDescriptor targ=fc.getArg(i);
4600 TypeDescriptor td=md.getParamType(i);
4602 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4604 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4607 output.println("};");
4612 if (fc.getReturnTemp()!=null)
4613 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
4615 /* Do we need to do virtual dispatch? */
4616 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
4619 LocalityBinding fclb=locality.getBinding(lb, fc);
4620 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4622 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4627 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4628 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4630 output.print(md.getReturnType().getSafeSymbol()+" ");
4631 output.print("(*)(");
4633 boolean printcomma=false;
4634 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4636 LocalityBinding fclb=locality.getBinding(lb, fc);
4637 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4639 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4643 for(int i=0; i<objectparams.numPrimitives(); i++) {
4644 TempDescriptor temp=objectparams.getPrimitive(i);
4648 if (temp.getType().isClass()||temp.getType().isArray())
4649 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
4651 output.print(temp.getType().getSafeSymbol());
4656 LocalityBinding fclb=locality.getBinding(lb, fc);
4657 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
4659 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
4663 boolean needcomma=false;
4664 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4665 output.print("&__parameterlist__");
4669 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4670 if (fc.getThis()!=null) {
4671 TypeDescriptor ptd=null;
4672 if(md.getThis() != null) {
4673 ptd = md.getThis().getType();
4675 ptd = fc.getThis().getType();
4679 if (ptd.isClass()&&!ptd.isArray())
4680 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4681 output.print(generateTemp(fm,fc.getThis(),lb));
4686 for(int i=0; i<fc.numArgs(); i++) {
4687 Descriptor var=md.getParameter(i);
4688 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4689 if (objectparams.isParamPrim(paramtemp)) {
4690 TempDescriptor targ=fc.getArg(i);
4694 TypeDescriptor ptd=md.getParamType(i);
4695 if (ptd.isClass()&&!ptd.isArray())
4696 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4697 output.print(generateTemp(fm, targ,lb));
4701 output.println(");");
4702 output.println(" }");
4705 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
4706 Set subclasses=typeutil.getSubClasses(thiscd);
4707 if (subclasses==null)
4709 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
4710 ClassDescriptor cd=(ClassDescriptor)classit.next();
4711 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
4712 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
4713 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
4714 if (md.matches(matchmd))
4721 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
4722 if (state.SINGLETM) {
4723 //single machine transactional memory case
4724 String field=ffn.getField().getSafeSymbol();
4725 String src=generateTemp(fm, ffn.getSrc(),lb);
4726 String dst=generateTemp(fm, ffn.getDst(),lb);
4728 output.println(dst+"="+ src +"->"+field+ ";");
4729 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
4730 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
4731 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
4732 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
4733 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
4734 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
4735 if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
4736 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4738 output.println("TRANSREADRD("+dst+", "+dst+");");
4741 } else if (state.DSM) {
4742 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
4743 if (status==LocalityAnalysis.GLOBAL) {
4744 String field=ffn.getField().getSafeSymbol();
4745 String src=generateTemp(fm, ffn.getSrc(),lb);
4746 String dst=generateTemp(fm, ffn.getDst(),lb);
4748 if (ffn.getField().getType().isPtr()) {
4750 //TODO: Uncomment this when we have runtime support
4751 //if (ffn.getSrc()==ffn.getDst()) {
4752 //output.println("{");
4753 //output.println("void * temp="+src+";");
4754 //output.println("if (temp&0x1) {");
4755 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
4756 //output.println(src+"->"+field+"="+temp+";");
4757 //output.println("}");
4758 //output.println(dst+"=temp;");
4759 //output.println("}");
4761 output.println(dst+"="+ src +"->"+field+ ";");
4762 //output.println("if ("+dst+"&0x1) {");
4763 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4764 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4765 //output.println(src+"->"+field+"="+src+"->"+field+";");
4766 //output.println("}");
4769 output.println(dst+"="+ src+"->"+field+";");
4771 } else if (status==LocalityAnalysis.LOCAL) {
4772 if (ffn.getField().getType().isPtr()&&
4773 ffn.getField().isGlobal()) {
4774 String field=ffn.getField().getSafeSymbol();
4775 String src=generateTemp(fm, ffn.getSrc(),lb);
4776 String dst=generateTemp(fm, ffn.getDst(),lb);
4777 output.println(dst+"="+ src +"->"+field+ ";");
4778 if (locality.getAtomic(lb).get(ffn).intValue()>0)
4779 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4780 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4782 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4783 } else if (status==LocalityAnalysis.EITHER) {
4784 //Code is reading from a null pointer
4785 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
4786 output.println("#ifndef RAW");
4787 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4788 output.println("#endif");
4789 //This should throw a suitable null pointer error
4790 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4792 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4794 // DEBUG if(!ffn.getDst().getType().isPrimitive()){
4795 // DEBUG output.println("within((void*)"+generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+");");
4797 if(ffn.getField().isStatic()) {
4798 // static field, redirect to the global_defs_p structure
4799 if(ffn.getSrc().getType().isStatic()) {
4800 // reference to the static field with Class name
4801 output.println(generateTemp(fm, ffn.getDst(),lb)+"=global_defs_p->"+ ffn.getSrc().getType().getClassDesc().getSafeSymbol()+ffn.getField().getSafeSymbol()+";");
4803 output.println(generateTemp(fm, ffn.getDst(),lb)+"=*"+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4805 //output.println(generateTemp(fm, ffn.getDst(),lb)+"=global_defs_p->"+ffn.getSrc().getType().getClassDesc().getSafeSymbol()+"->"+ ffn.getField().getSafeSymbol()+";");
4807 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4813 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
4814 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
4815 throw new Error("Can't set array length");
4816 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4817 //Single Machine Transaction Case
4818 boolean srcptr=fsfn.getSrc().getType().isPtr();
4819 String src=generateTemp(fm,fsfn.getSrc(),lb);
4820 String dst=generateTemp(fm,fsfn.getDst(),lb);
4821 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
4822 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
4823 output.println("{");
4824 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
4825 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
4826 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4828 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4831 if (wb.needBarrier(fsfn)&&
4832 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
4833 if (state.EVENTMONITOR) {
4834 output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
4836 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
4838 if (srcptr&!fsfn.getSrc().getType().isNull()) {
4839 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4840 output.println("}");
4842 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4844 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4845 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
4846 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
4847 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4849 String src=generateTemp(fm,fsfn.getSrc(),lb);
4850 String dst=generateTemp(fm,fsfn.getDst(),lb);
4852 output.println("{");
4853 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4855 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
4858 if (wb.needBarrier(fsfn))
4859 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
4861 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4863 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4864 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
4865 /** Check if we need to copy */
4866 output.println("if(!"+dst+"->"+localcopystr+") {");
4867 /* Link object into list */
4868 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4869 output.println(revertptr+"=revertlist;");
4870 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4871 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4873 output.println("COPY_OBJ("+dst+");");
4874 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4875 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4876 output.println("}");
4878 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4880 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4881 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
4882 //writing to a null...bad
4883 output.println("if ("+dst+") {");
4884 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
4886 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4888 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4891 output.println("}");
4894 if (state.FASTCHECK) {
4895 String dst=generateTemp(fm, fsfn.getDst(),lb);
4896 output.println("if(!"+dst+"->"+localcopystr+") {");
4897 /* Link object into list */
4898 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4899 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4901 output.println("COPY_OBJ("+dst+");");
4902 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4903 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4904 output.println("}");
4907 // DEBUG if(!fsfn.getField().getType().isPrimitive()){
4908 // DEBUG output.println("within((void*)"+generateTemp(fm,fsfn.getSrc(),lb)+");");
4910 if(fsfn.getField().isStatic()) {
4911 // static field, redirect to the global_defs_p structure
4912 if(fsfn.getDst().getType().isStatic()) {
4913 // reference to the static field with Class name
4914 output.println("global_defs_p->" + fsfn.getDst().getType().getClassDesc().getSafeSymbol() + fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4916 output.println("*"+generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4919 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4924 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
4925 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
4928 if (elementtype.isArray()||elementtype.isClass())
4931 type=elementtype.getSafeSymbol()+" ";
4933 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
4934 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
4935 output.println("failedboundschk();");
4937 if (state.SINGLETM) {
4938 //Single machine transaction case
4939 String dst=generateTemp(fm, fen.getDst(),lb);
4940 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))) {
4941 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4943 output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
4946 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
4947 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
4948 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
4949 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
4950 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
4951 if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
4952 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4954 output.println("TRANSREADRD("+dst+", "+dst+");");
4957 } else if (state.DSM) {
4958 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
4959 if (status==LocalityAnalysis.GLOBAL) {
4960 String dst=generateTemp(fm, fen.getDst(),lb);
4961 if (elementtype.isPtr()) {
4962 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4963 //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
4964 output.println("TRANSREAD("+dst+", "+dst+");");
4966 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4968 } else if (status==LocalityAnalysis.LOCAL) {
4969 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4970 } else if (status==LocalityAnalysis.EITHER) {
4971 //Code is reading from a null pointer
4972 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
4973 output.println("#ifndef RAW");
4974 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4975 output.println("#endif");
4976 //This should throw a suitable null pointer error
4977 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4979 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4981 // DEBUG output.println("within((void*)"+generateTemp(fm,fen.getSrc(),lb)+");");
4982 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4986 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
4987 //TODO: need dynamic check to make sure this assignment is actually legal
4988 //Because Object[] could actually be something more specific...ie. Integer[]
4990 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
4993 if (elementtype.isArray()||elementtype.isClass())
4996 type=elementtype.getSafeSymbol()+" ";
4998 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
4999 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
5000 output.println("failedboundschk();");
5003 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
5004 //Transaction set element case
5005 if (wb.needBarrier(fsen)&&
5006 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
5007 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
5009 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
5010 output.println("{");
5011 String src=generateTemp(fm, fsen.getSrc(), lb);
5012 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
5013 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
5014 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
5016 output.println("INTPTR srcoid=(INTPTR)"+src+";");
5018 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
5019 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
5021 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
5023 output.println("}");
5025 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
5026 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
5028 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
5031 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
5032 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
5033 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
5034 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
5035 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
5036 boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
5039 if (wb.needBarrier(fsen))
5040 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
5041 } else if (dstlocal) {
5042 /** Check if we need to copy */
5043 String dst=generateTemp(fm, fsen.getDst(),lb);
5044 output.println("if(!"+dst+"->"+localcopystr+") {");
5045 /* Link object into list */
5046 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5047 output.println(revertptr+"=revertlist;");
5048 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
5049 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
5051 output.println("COPY_OBJ("+dst+");");
5052 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
5053 output.println("revertlist=(struct ___Object___ *)"+dst+";");
5054 output.println("}");
5056 System.out.println("Node: "+fsen);
5057 System.out.println(lb);
5058 System.out.println("statusdst="+statusdst);
5059 System.out.println(fm.printMethod());
5060 throw new Error("Unknown array type");
5063 output.println("{");
5064 String src=generateTemp(fm, fsen.getSrc(), lb);
5065 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
5066 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
5067 output.println("}");
5069 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
5072 if (state.FASTCHECK) {
5073 String dst=generateTemp(fm, fsen.getDst(),lb);
5074 output.println("if(!"+dst+"->"+localcopystr+") {");
5075 /* Link object into list */
5076 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
5077 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
5079 output.println("COPY_OBJ("+dst+");");
5080 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
5081 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
5082 output.println("}");
5084 // DEBUG output.println("within((void*)"+generateTemp(fm,fsen.getDst(),lb)+");");
5085 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
5089 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
5090 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
5091 //Stash pointer in case of GC
5092 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5093 output.println(revertptr+"=revertlist;");
5095 if (state.SINGLETM) {
5096 if (fn.getType().isArray()) {
5097 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
5098 if (locality.getAtomic(lb).get(fn).intValue()>0) {
5099 //inside transaction
5100 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5102 //outside transaction
5103 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5106 if (locality.getAtomic(lb).get(fn).intValue()>0) {
5107 //inside transaction
5108 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
5110 //outside transaction
5111 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
5114 } else if (fn.getType().isArray()) {
5115 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
5116 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
5117 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5118 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5119 if(this.state.MLP || state.OOOJAVA){
5120 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray_mlp("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
5121 output.println(" oid += numWorkers;");
5123 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5126 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
5129 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
5130 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
5131 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5132 if (this.state.MLP || state.OOOJAVA){
5133 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new_mlp("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
5134 output.println(" oid += numWorkers;");
5136 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
5139 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
5142 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
5143 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5144 String dst=generateTemp(fm,fn.getDst(),lb);
5145 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
5146 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
5147 output.println("revertlist=(struct ___Object___ *)"+dst+";");
5149 if (state.FASTCHECK) {
5150 String dst=generateTemp(fm,fn.getDst(),lb);
5151 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
5152 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
5153 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
5157 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
5158 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5159 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
5161 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
5165 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
5166 if (fon.getRight()!=null) {
5167 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
5168 if (fon.getLeft().getType().isLong())
5169 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
5171 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
5173 } else if (dc!=null) {
5174 output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
5175 if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
5176 output.print("(void *)");
5177 if (dc.getNeedLeftSrcTrans(lb, fon))
5178 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
5180 output.print(generateTemp(fm, fon.getLeft(),lb));
5181 output.print(")"+fon.getOp().toString()+"(");
5182 if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
5183 output.print("(void *)");
5184 if (dc.getNeedRightSrcTrans(lb, fon))
5185 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
5187 output.println(generateTemp(fm,fon.getRight(),lb)+");");
5189 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
5190 } else if (fon.getOp().getOp()==Operation.ASSIGN)
5191 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
5192 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
5193 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
5194 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
5195 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
5196 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
5197 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
5198 else if (fon.getOp().getOp()==Operation.COMP)
5199 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
5200 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
5201 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
5203 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
5206 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
5207 /* TODO: Do type check here */
5208 if (fcn.getType().isArray()) {
5209 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
5210 } else if (fcn.getType().isClass())
5211 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
5213 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
5216 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
5217 if (fln.getValue()==null)
5218 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
5219 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
5220 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5221 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
5222 //Stash pointer in case of GC
5223 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5224 output.println(revertptr+"=revertlist;");
5226 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
5227 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
5228 //Stash pointer in case of GC
5229 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
5230 output.println("revertlist="+revertptr+";");
5233 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
5235 } else if (fln.getType().isBoolean()) {
5236 if (((Boolean)fln.getValue()).booleanValue())
5237 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
5239 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
5240 } else if (fln.getType().isChar()) {
5241 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
5242 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
5243 } else if (fln.getType().isLong()) {
5244 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
5246 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
5249 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
5250 if (frn.getReturnTemp()!=null) {
5251 if (frn.getReturnTemp().getType().isPtr())
5252 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
5254 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
5256 output.println("return;");
5260 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
5263 //only record if this group has more than one exit
5264 if (branchanalysis.numJumps(fcb)>1) {
5265 left=branchanalysis.jumpValue(fcb, 0);
5266 right=branchanalysis.jumpValue(fcb, 1);
5268 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
5270 output.println("STOREBRANCH("+right+");");
5271 output.println("goto "+label+";");
5272 output.println("}");
5274 output.println("STOREBRANCH("+left+");");
5277 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
5278 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
5281 /** This method generates header information for the method or
5282 * task referenced by the Descriptor des. */
5283 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
5284 generateHeader(fm, lb, des, output, false);
5287 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
5289 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
5290 MethodDescriptor md=null;
5291 TaskDescriptor task=null;
5292 if (des instanceof MethodDescriptor)
5293 md=(MethodDescriptor) des;
5295 task=(TaskDescriptor) des;
5297 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
5299 if (md!=null&&md.getReturnType()!=null) {
5300 if (md.getReturnType().isClass()||md.getReturnType().isArray())
5301 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
5303 output.print(md.getReturnType().getSafeSymbol()+" ");
5305 //catch the constructor case
5306 output.print("void ");
5308 if (state.DSM||state.SINGLETM) {
5309 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5311 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5313 output.print(task.getSafeSymbol()+"(");
5315 boolean printcomma=false;
5316 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5318 if (state.DSM||state.SINGLETM) {
5319 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5321 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5323 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
5329 for(int i=0; i<objectparams.numPrimitives(); i++) {
5330 TempDescriptor temp=objectparams.getPrimitive(i);
5334 if (temp.getType().isClass()||temp.getType().isArray())
5335 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
5337 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
5339 output.println(") {");
5340 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
5341 /* Imprecise Task */
5342 output.println("void * parameterarray[]) {");
5343 /* Unpack variables */
5344 for(int i=0; i<objectparams.numPrimitives(); i++) {
5345 TempDescriptor temp=objectparams.getPrimitive(i);
5346 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
5348 for(int i=0; i<fm.numTags(); i++) {
5349 TempDescriptor temp=fm.getTag(i);
5350 int offset=i+objectparams.numPrimitives();
5351 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
5354 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
5355 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
5356 } else output.println(") {");
5359 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
5360 output.println("/* FlatFlagActionNode */");
5363 /* Process tag changes */
5364 Relation tagsettable=new Relation();
5365 Relation tagcleartable=new Relation();
5367 Iterator tagsit=ffan.getTempTagPairs();
5368 while (tagsit.hasNext()) {
5369 TempTagPair ttp=(TempTagPair) tagsit.next();
5370 TempDescriptor objtmp=ttp.getTemp();
5371 TagDescriptor tag=ttp.getTag();
5372 TempDescriptor tagtmp=ttp.getTagTemp();
5373 boolean tagstatus=ffan.getTagChange(ttp);
5375 tagsettable.put(objtmp, tagtmp);
5377 tagcleartable.put(objtmp, tagtmp);
5382 Hashtable flagandtable=new Hashtable();
5383 Hashtable flagortable=new Hashtable();
5385 /* Process flag changes */
5386 Iterator flagsit=ffan.getTempFlagPairs();
5387 while(flagsit.hasNext()) {
5388 TempFlagPair tfp=(TempFlagPair)flagsit.next();
5389 TempDescriptor temp=tfp.getTemp();
5390 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
5391 FlagDescriptor flag=tfp.getFlag();
5393 //Newly allocate objects that don't set any flags case
5394 if (flagortable.containsKey(temp)) {
5398 flagortable.put(temp,new Integer(mask));
5400 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
5401 boolean flagstatus=ffan.getFlagChange(tfp);
5404 if (flagortable.containsKey(temp)) {
5405 mask=((Integer)flagortable.get(temp)).intValue();
5408 flagortable.put(temp,new Integer(mask));
5410 int mask=0xFFFFFFFF;
5411 if (flagandtable.containsKey(temp)) {
5412 mask=((Integer)flagandtable.get(temp)).intValue();
5414 mask&=(0xFFFFFFFF^flagid);
5415 flagandtable.put(temp,new Integer(mask));
5421 HashSet flagtagset=new HashSet();
5422 flagtagset.addAll(flagortable.keySet());
5423 flagtagset.addAll(flagandtable.keySet());
5424 flagtagset.addAll(tagsettable.keySet());
5425 flagtagset.addAll(tagcleartable.keySet());
5427 Iterator ftit=flagtagset.iterator();
5428 while(ftit.hasNext()) {
5429 TempDescriptor temp=(TempDescriptor)ftit.next();
5432 Set tagtmps=tagcleartable.get(temp);
5433 if (tagtmps!=null) {
5434 Iterator tagit=tagtmps.iterator();
5435 while(tagit.hasNext()) {
5436 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5437 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5438 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5440 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5444 tagtmps=tagsettable.get(temp);
5445 if (tagtmps!=null) {
5446 Iterator tagit=tagtmps.iterator();
5447 while(tagit.hasNext()) {
5448 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5449 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5450 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5452 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
5457 int andmask=0xFFFFFFF;
5459 if (flagortable.containsKey(temp))
5460 ormask=((Integer)flagortable.get(temp)).intValue();
5461 if (flagandtable.containsKey(temp))
5462 andmask=((Integer)flagandtable.get(temp)).intValue();
5463 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
5464 generateObjectDistribute(ffan, fm, lb, temp, output);
5468 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
5469 PrintWriter output, int ormask, int andmask) {
5470 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
5471 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5473 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5477 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
5478 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
5481 void generateOptionalHeader(PrintWriter headers) {
5484 headers.println("#include \"task.h\"\n\n");
5485 headers.println("#ifndef _OPTIONAL_STRUCT_");
5486 headers.println("#define _OPTIONAL_STRUCT_");
5488 //STRUCT PREDICATEMEMBER
5489 headers.println("struct predicatemember{");
5490 headers.println("int type;");
5491 headers.println("int numdnfterms;");
5492 headers.println("int * flags;");
5493 headers.println("int numtags;");
5494 headers.println("int * tags;\n};\n\n");
5496 //STRUCT OPTIONALTASKDESCRIPTOR
5497 headers.println("struct optionaltaskdescriptor{");
5498 headers.println("struct taskdescriptor * task;");
5499 headers.println("int index;");
5500 headers.println("int numenterflags;");
5501 headers.println("int * enterflags;");
5502 headers.println("int numpredicatemembers;");
5503 headers.println("struct predicatemember ** predicatememberarray;");
5504 headers.println("};\n\n");
5506 //STRUCT TASKFAILURE
5507 headers.println("struct taskfailure {");
5508 headers.println("struct taskdescriptor * task;");
5509 headers.println("int index;");
5510 headers.println("int numoptionaltaskdescriptors;");
5511 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5513 //STRUCT FSANALYSISWRAPPER
5514 headers.println("struct fsanalysiswrapper{");
5515 headers.println("int flags;");
5516 headers.println("int numtags;");
5517 headers.println("int * tags;");
5518 headers.println("int numtaskfailures;");
5519 headers.println("struct taskfailure ** taskfailurearray;");
5520 headers.println("int numoptionaltaskdescriptors;");
5521 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5523 //STRUCT CLASSANALYSISWRAPPER
5524 headers.println("struct classanalysiswrapper{");
5525 headers.println("int type;");
5526 headers.println("int numotd;");
5527 headers.println("struct optionaltaskdescriptor ** otdarray;");
5528 headers.println("int numfsanalysiswrappers;");
5529 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
5531 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
5533 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
5534 while(taskit.hasNext()) {
5535 TaskDescriptor td=(TaskDescriptor)taskit.next();
5536 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
5541 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
5542 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
5543 int predicateindex = 0;
5544 //iterate through the classes concerned by the predicate
5545 Set c_vard = predicate.vardescriptors;
5546 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
5549 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
5550 VarDescriptor vard = (VarDescriptor)vard_it.next();
5551 TypeDescriptor typed = vard.getType();
5553 //generate for flags
5554 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
5555 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5557 if (fen_hashset!=null) {
5558 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
5559 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
5561 DNFFlag dflag=fen.getDNF();
5562 numberterms+=dflag.size();
5564 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
5566 for(int j=0; j<dflag.size(); j++) {
5568 output.println(",");
5569 Vector term=dflag.get(j);
5572 for(int k=0; k<term.size(); k++) {
5573 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
5574 FlagDescriptor fd=dfa.getFlag();
5575 boolean negated=dfa.getNegated();
5576 int flagid=1<<((Integer)flags.get(fd)).intValue();
5581 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
5586 output.println("};\n");
5589 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
5590 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5593 for(int j=0; j<tagel.numTags(); j++) {
5595 output.println(",");
5596 TempDescriptor tmp=tagel.getTemp(j);
5597 if (!slotnumber.containsKey(tmp)) {
5598 Integer slotint=new Integer(current_slot++);
5599 slotnumber.put(tmp,slotint);
5601 int slot=slotnumber.get(tmp).intValue();
5602 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
5604 numtags = tagel.numTags();
5606 output.println("};");
5608 //store the result into a predicatemember struct
5609 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5610 output.println("/*type*/"+typed.getClassDesc().getId()+",");
5611 output.println("/* number of dnf terms */"+numberterms+",");
5612 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5613 output.println("/* number of tag */"+numtags+",");
5614 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5615 output.println("};\n");
5620 //generate an array that stores the entire predicate
5621 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5622 for( int j = 0; j<predicateindex; j++) {
5623 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5624 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5626 output.println("};\n");
5627 return predicateindex;
5631 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
5632 generateOptionalHeader(headers);
5634 output.println("#include \"optionalstruct.h\"\n\n");
5635 output.println("#include \"stdlib.h\"\n");
5637 HashSet processedcd = new HashSet();
5639 Enumeration e = safeexecution.keys();
5640 while (e.hasMoreElements()) {
5643 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
5644 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
5646 //Generate the struct of optionals
5647 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5648 numotd = c_otd.size();
5649 if(maxotd<numotd) maxotd = numotd;
5650 if( !c_otd.isEmpty() ) {
5651 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5652 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5654 //generate the int arrays for the predicate
5655 Predicate predicate = otd.predicate;
5656 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
5657 TreeSet<Integer> fsset=new TreeSet<Integer>();
5658 //iterate through possible FSes corresponding to
5659 //the state when entering
5661 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
5662 FlagState fs = (FlagState)fses.next();
5664 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5665 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5666 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5669 fsset.add(new Integer(flagid));
5670 //tag information not needed because tag
5671 //changes are not tolerated.
5674 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5675 boolean needcomma=false;
5676 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
5679 output.println(it.next());
5682 output.println("};\n");
5685 //generate optionaltaskdescriptor that actually
5686 //includes exit fses, predicate and the task
5688 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5689 output.println("&task_"+otd.td.getSafeSymbol()+",");
5690 output.println("/*index*/"+otd.getIndex()+",");
5691 output.println("/*number of enter flags*/"+fsset.size()+",");
5692 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5693 output.println("/*number of members */"+predicateindex+",");
5694 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5695 output.println("};\n");
5699 // if there are no optionals, there is no need to build the rest of the struct
5701 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
5702 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5703 if( !c_otd.isEmpty() ) {
5704 boolean needcomma=false;
5705 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5706 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5708 output.println(",");
5710 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5713 output.println("};\n");
5715 //get all the possible flagstates reachable by an object
5716 Hashtable hashtbtemp = safeexecution.get(cdtemp);
5718 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
5719 fsts.addAll(hashtbtemp.keySet());
5720 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
5721 FlagState fs = (FlagState)fsit.next();
5724 //get the set of OptionalTaskDescriptors corresponding
5725 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
5726 //iterate through the OptionalTaskDescriptors and
5727 //store the pointers to the optionals struct (see on
5728 //top) into an array
5730 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
5731 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
5732 OptionalTaskDescriptor mm = mos.next();
5734 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
5736 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5739 output.println("};\n");
5741 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
5744 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5745 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5746 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5750 //process tag information
5753 boolean first = true;
5754 Enumeration tag_enum = fs.getTags();
5755 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5756 while(tag_enum.hasMoreElements()) {
5758 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
5762 output.println(", ");
5763 output.println("/*tagid*/"+state.getTagId(tagd));
5765 output.println("};");
5767 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
5768 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5769 TaskIndex ti=itti.next();
5773 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
5775 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
5776 boolean needcomma=false;
5777 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
5778 OptionalTaskDescriptor otd=otdit.next();
5782 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5784 output.println("};");
5786 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
5787 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
5788 output.print(ti.getIndex()+", ");
5789 output.print(otdset.size()+", ");
5790 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
5791 output.println("};");
5794 tiset=sa.getTaskIndex(fs);
5795 boolean needcomma=false;
5797 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5798 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5799 TaskIndex ti=itti.next();
5800 if (ti.isRuntime()) {
5807 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
5809 output.println("};\n");
5811 //Store the result in fsanalysiswrapper
5813 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
5814 output.println("/*flag*/"+flagid+",");
5815 output.println("/* number of tags*/"+tagcounter+",");
5816 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5817 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
5818 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5819 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
5820 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
5821 output.println("};\n");
5825 //Build the array of fsanalysiswrappers
5826 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
5827 boolean needcomma=false;
5828 for(int i = 0; i<fscounter; i++) {
5829 if (needcomma) output.print(",");
5830 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
5833 output.println("};");
5835 //Build the classanalysiswrapper referring to the previous array
5836 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
5837 output.println("/*type*/"+cdtemp.getId()+",");
5838 output.println("/*numotd*/"+numotd+",");
5839 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
5840 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
5841 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
5842 processedcd.add(cdtemp);
5845 //build an array containing every classes for which code has been build
5846 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
5847 for(int i=0; i<state.numClasses(); i++) {
5848 ClassDescriptor cn=cdarray[i];
5851 if ((cn != null) && (processedcd.contains(cn)))
5852 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
5854 output.print("NULL");
5856 output.println("};");
5858 output.println("#define MAXOTD "+maxotd);
5859 headers.println("#endif");
5862 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
5863 Relation r=new Relation();
5864 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
5865 OptionalTaskDescriptor otd=otdit.next();
5866 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
5870 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
5871 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
5872 Set s=r.get(it.next());
5873 for(Iterator it2=s.iterator(); it2.hasNext();) {
5874 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
5882 protected void outputTransCode(PrintWriter output) {
5885 private int calculateSizeOfSESEParamList(FlatSESEEnterNode fsen){
5887 Set<TempDescriptor> tdSet=new HashSet<TempDescriptor>();
5889 for (Iterator iterator = fsen.getInVarSet().iterator(); iterator.hasNext();) {
5890 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5891 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5892 tdSet.add(tempDescriptor);
5896 for (Iterator iterator = fsen.getOutVarSet().iterator(); iterator.hasNext();) {
5897 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5898 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5899 tdSet.add(tempDescriptor);
5903 return tdSet.size();
5906 private String calculateSizeOfSESEParamSize(FlatSESEEnterNode fsen){
5907 HashMap <String,Integer> map=new HashMap();
5908 HashSet <TempDescriptor> processed=new HashSet<TempDescriptor>();
5911 // space for all in and out set primitives
5912 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
5913 inSetAndOutSet.addAll( fsen.getInVarSet() );
5914 inSetAndOutSet.addAll( fsen.getOutVarSet() );
5916 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
5918 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
5919 while( itr.hasNext() ) {
5920 TempDescriptor temp = itr.next();
5921 TypeDescriptor type = temp.getType();
5922 if( !type.isPtr() ) {
5923 inSetAndOutSetPrims.add( temp );
5927 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
5928 while( itrPrims.hasNext() ) {
5929 TempDescriptor temp = itrPrims.next();
5930 TypeDescriptor type = temp.getType();
5931 if(type.isPrimitive()){
5932 Integer count=map.get(type.getSymbol());
5934 count=new Integer(1);
5935 map.put(type.getSymbol(), count);
5937 map.put(type.getSymbol(), new Integer(count.intValue()+1));
5942 Set<String> keySet=map.keySet();
5943 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
5944 String key = (String) iterator.next();
5945 rtr+="+sizeof("+key+")*"+map.get(key);