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;
13 import Analysis.TaskStateAnalysis.FlagState;
14 import Analysis.TaskStateAnalysis.FlagComparator;
15 import Analysis.TaskStateAnalysis.OptionalTaskDescriptor;
16 import Analysis.TaskStateAnalysis.Predicate;
17 import Analysis.TaskStateAnalysis.SafetyAnalysis;
18 import Analysis.TaskStateAnalysis.TaskIndex;
19 import Analysis.Locality.LocalityAnalysis;
20 import Analysis.Locality.LocalityBinding;
21 import Analysis.Locality.DiscoverConflicts;
22 import Analysis.Locality.DCWrapper;
23 import Analysis.Locality.DelayComputation;
24 import Analysis.Locality.BranchAnalysis;
25 import Analysis.CallGraph.CallGraph;
26 import Analysis.Disjoint.Effect;
27 import Analysis.Disjoint.ReachGraph;
28 import Analysis.Disjoint.Taint;
29 import Analysis.OoOJava.OoOJavaAnalysis;
30 import Analysis.Prefetch.*;
31 import Analysis.Loops.WriteBarrier;
32 import Analysis.Loops.GlobalFieldType;
33 import Analysis.Locality.TypeAnalysis;
34 import Analysis.MLP.ConflictGraph;
35 import Analysis.MLP.ConflictNode;
36 import Analysis.MLP.MLPAnalysis;
37 import Analysis.MLP.ParentChildConflictsMap;
38 import Analysis.MLP.SESELock;
39 import Analysis.MLP.SESEWaitingQueue;
40 import Analysis.MLP.VariableSourceToken;
41 import Analysis.MLP.VSTWrapper;
42 import Analysis.MLP.CodePlan;
43 import Analysis.MLP.SESEandAgePair;
44 import Analysis.MLP.WaitingElement;
46 public class BuildCode {
49 Hashtable paramstable;
54 String localsprefix="___locals___";
55 String localsprefixaddr="&"+localsprefix;
56 String localsprefixderef=localsprefix+".";
57 String fcrevert="___fcrevert___";
58 String paramsprefix="___params___";
59 String oidstr="___nextobject___";
60 String nextobjstr="___nextobject___";
61 String localcopystr="___localcopy___";
62 public static boolean GENERATEPRECISEGC=false;
63 public static String PREFIX="";
64 public static String arraytype="ArrayObject";
65 public static int flagcount = 0;
68 protected int maxtaskparams=0;
69 private int maxcount=0;
70 ClassDescriptor[] cdarray;
71 TypeDescriptor[] arraytable;
72 LocalityAnalysis locality;
73 Hashtable<LocalityBinding, TempDescriptor> reverttable;
74 Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>> backuptable;
79 String mlperrstr = "if(status != 0) { "+
80 "sprintf(errmsg, \"MLP error at %s:%d\", __FILE__, __LINE__); "+
81 "perror(errmsg); exit(-1); }";
82 boolean nonSESEpass=true;
85 DiscoverConflicts recorddc;
90 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa) {
91 this(st, temptovar, typeutil, null, sa, pa, null, null);
94 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
95 this(st, temptovar, typeutil, null, sa, pa, mlpa, oooa);
98 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
99 this(st, temptovar, typeutil, locality, null, pa, mlpa, oooa);
102 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
108 callgraph=new CallGraph(state);
110 oidstr="___objlocation___";
111 this.temptovar=temptovar;
112 paramstable=new Hashtable();
113 tempstable=new Hashtable();
114 fieldorder=new Hashtable();
115 flagorder=new Hashtable();
116 this.typeutil=typeutil;
117 virtualcalls=new Virtual(state,locality);
118 if (locality!=null) {
119 this.locality=locality;
120 this.reverttable=new Hashtable<LocalityBinding, TempDescriptor>();
121 this.backuptable=new Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>>();
122 this.wb=new WriteBarrier(locality, st);
124 if (state.SINGLETM&&state.DCOPTS) {
125 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
126 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
127 this.dc=new DiscoverConflicts(locality, st, typeanalysis, gft);
130 if (state.DELAYCOMP) {
131 //TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
132 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
133 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
134 delaycomp=new DCWrapper(locality, st, typeanalysis, gft);
135 dc=delaycomp.getConflicts();
136 recorddc=new DiscoverConflicts(locality, st, typeanalysis, delaycomp.getCannotDelayMap(), true, true, null);
137 recorddc.doAnalysis();
141 /** The buildCode method outputs C code for all the methods. The Flat
142 * versions of the methods must already be generated and stored in
143 * the State object. */
144 PrintWriter outsandbox=null;
146 public void buildCode() {
147 /* Create output streams to write to */
148 PrintWriter outclassdefs=null;
149 PrintWriter outstructs=null;
150 PrintWriter outrepairstructs=null;
151 PrintWriter outmethodheader=null;
152 PrintWriter outmethod=null;
153 PrintWriter outvirtual=null;
154 PrintWriter outtask=null;
155 PrintWriter outtaskdefs=null;
156 PrintWriter outoptionalarrays=null;
157 PrintWriter optionalheaders=null;
161 outsandbox=new PrintWriter(new FileOutputStream(PREFIX+"sandboxdefs.c"), true);
163 outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
164 outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
165 outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
166 outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
167 outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
169 outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
170 outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
171 if (state.OPTIONAL) {
172 outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
173 optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
176 if (state.structfile!=null) {
177 outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
179 } catch (Exception e) {
184 /* Build the virtual dispatch tables */
185 buildVirtualTables(outvirtual);
187 /* Output includes */
188 outmethodheader.println("#ifndef METHODHEADERS_H");
189 outmethodheader.println("#define METHODHEADERS_H");
190 outmethodheader.println("#include \"structdefs.h\"");
192 outmethodheader.println("#include \"dstm.h\"");
194 outmethodheader.println("#include \"sandbox.h\"");
196 if (state.EVENTMONITOR) {
197 outmethodheader.println("#include \"monitor.h\"");
199 if (state.SINGLETM) {
200 outmethodheader.println("#include \"tm.h\"");
201 outmethodheader.println("#include \"delaycomp.h\"");
202 outmethodheader.println("#include \"inlinestm.h\"");
204 if (state.ABORTREADERS) {
205 outmethodheader.println("#include \"abortreaders.h\"");
206 outmethodheader.println("#include <setjmp.h>");
208 if (state.MLP || state.OOOJAVA) {
209 outmethodheader.println("#include <stdlib.h>");
210 outmethodheader.println("#include <stdio.h>");
211 outmethodheader.println("#include <string.h>");
212 outmethodheader.println("#include \"mlp_runtime.h\"");
213 outmethodheader.println("#include \"psemaphore.h\"");
216 /* Output Structures */
217 outputStructs(outstructs);
219 // Output the C class declarations
220 // These could mutually reference each other
221 outputClassDeclarations(outclassdefs);
223 // Output function prototypes and structures for parameters
224 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
225 while(it.hasNext()) {
226 ClassDescriptor cn=(ClassDescriptor)it.next();
227 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader);
229 outclassdefs.close();
232 /* Map flags to integers */
233 /* The runtime keeps track of flags using these integers */
234 it=state.getClassSymbolTable().getDescriptorsIterator();
235 while(it.hasNext()) {
236 ClassDescriptor cn=(ClassDescriptor)it.next();
240 generateTaskStructs(outstructs, outmethodheader);
242 /* Outputs generic task structures if this is a task
244 outputTaskTypes(outtask);
247 if( state.MLP || state.OOOJAVA) {
248 // have to initialize some SESE compiler data before
249 // analyzing normal methods, which must happen before
250 // generating SESE internal code
252 Iterator<FlatSESEEnterNode> seseit;
254 seseit=mlpa.getAllSESEs().iterator();
256 seseit=oooa.getAllSESEs().iterator();
258 while(seseit.hasNext()){
259 FlatSESEEnterNode fsen = seseit.next();
260 initializeSESE( fsen );
264 if(!fsen.getIsCallerSESEplaceholder() && fsen.getParent()!=null){
266 FlatMethod fm=fsen.getfmEnclosing();
269 ReachGraph rg=oooa.getDisjointAnalysis().getReachGraph(fm.getMethod());
272 Hashtable<Taint, Set<Effect>> effects=oooa.getDisjointAnalysis().getEffectsAnalysis().get(fsen);
275 Analysis.OoOJava.ConflictGraph conflictGraph=oooa.getConflictGraph(fsen.getParent());
276 Hashtable<Taint, Set<Effect>> conflicts=conflictGraph.getConflictEffectSet(fsen);
284 /* Build the actual methods */
285 outputMethods(outmethod);
287 // Output function prototypes and structures for SESE's and code
288 if( state.MLP || state.OOOJAVA ) {
290 // used to differentiate, during code generation, whether we are
291 // passing over SESE body code, or non-SESE code
294 // first generate code for each sese's internals
295 Iterator<FlatSESEEnterNode> seseit;
297 seseit=mlpa.getAllSESEs().iterator();
299 seseit=oooa.getAllSESEs().iterator();
302 while(seseit.hasNext()) {
303 FlatSESEEnterNode fsen = seseit.next();
304 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
307 // then write the invokeSESE switch to decouple scheduler
308 // from having to do unique details of sese invocation
309 generateSESEinvocationMethod(outmethodheader, outmethod);
313 /* Output code for tasks */
314 outputTaskCode(outtaskdefs, outmethod);
316 /* Record maximum number of task parameters */
317 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
318 } else if (state.main!=null) {
319 /* Generate main method */
320 outputMainMethod(outmethod);
323 /* Generate information for task with optional parameters */
324 if (state.TASK&&state.OPTIONAL) {
325 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
326 outoptionalarrays.close();
329 /* Output structure definitions for repair tool */
330 if (state.structfile!=null) {
331 buildRepairStructs(outrepairstructs);
332 outrepairstructs.close();
336 outmethodheader.println("#endif");
337 outmethodheader.close();
339 outstructs.println("#endif");
344 /* This code just generates the main C method for java programs.
345 * The main C method packs up the arguments into a string array
346 * and passes it to the java main method. */
348 private void outputMainMethod(PrintWriter outmethod) {
349 outmethod.println("int main(int argc, const char *argv[]) {");
350 outmethod.println(" int i;");
352 if (state.MLP || state.OOOJAVA) {
353 //outmethod.println(" pthread_once( &mlpOnceObj, mlpInitOncePerThread );");
355 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
359 if (state.DSMRECOVERYSTATS) {
360 outmethod.println("#ifdef RECOVERYSTATS \n");
361 outmethod.println("handle();\n");
362 outmethod.println("#endif\n");
364 outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
365 outmethod.println("handle();\n");
366 outmethod.println("#endif\n");
370 if (state.THREAD||state.DSM||state.SINGLETM) {
371 outmethod.println("initializethreads();");
374 outmethod.println("if (dstmStartup(argv[1])) {");
375 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
376 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
378 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
381 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
382 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
384 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
388 outmethod.println(" for(i=2;i<argc;i++) {");
390 outmethod.println(" for(i=1;i<argc;i++) {");
391 outmethod.println(" int length=strlen(argv[i]);");
392 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
393 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
395 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
398 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
400 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
401 outmethod.println(" }");
403 MethodDescriptor md=typeutil.getMain();
404 ClassDescriptor cd=typeutil.getMainClass();
406 outmethod.println(" {");
407 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
408 if (state.DSM||state.SINGLETM) {
409 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
411 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
412 outmethod.println("1, NULL,"+"stringarray};");
413 if (state.DSM||state.SINGLETM)
414 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
416 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
418 if (state.DSM||state.SINGLETM)
419 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
421 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
423 outmethod.println(" }");
426 outmethod.println("}");
429 if (state.THREAD||state.DSM||state.SINGLETM) {
430 outmethod.println("pthread_mutex_lock(&gclistlock);");
431 outmethod.println("threadcount--;");
432 outmethod.println("pthread_cond_signal(&gccond);");
433 outmethod.println("pthread_mutex_unlock(&gclistlock);");
436 if (state.DSM||state.SINGLETM) {
437 //outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
438 outmethod.println("#if defined(TRANSSTATS) \n");
439 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
440 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
441 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
442 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
444 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
445 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
446 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
447 outmethod.println("printf(\"ndirtyCacheObj= %d\\n\", ndirtyCacheObj);");
448 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
449 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
450 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
451 outmethod.println("printf(\"totalObjSize= %d\\n\", totalObjSize);");
452 outmethod.println("printf(\"sendRemoteReq= %d\\n\", sendRemoteReq);");
453 outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
454 } else if (state.SINGLETM) {
455 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
456 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
457 outmethod.println("#ifdef STMSTATS\n");
458 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
459 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
460 outmethod.println("}\n");
461 outmethod.println("#endif\n");
462 outmethod.println("fflush(stdout);");
464 outmethod.println("#endif\n");
467 if (state.EVENTMONITOR) {
468 outmethod.println("dumpdata();");
471 if (state.THREAD||state.SINGLETM)
472 outmethod.println("pthread_exit(NULL);");
474 if (state.MLP || state.OOOJAVA ) {
475 outmethod.println(" workScheduleBegin();");
478 outmethod.println("}");
481 /* This method outputs code for each task. */
483 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
484 /* Compile task based program */
485 outtaskdefs.println("#include \"task.h\"");
486 outtaskdefs.println("#include \"methodheaders.h\"");
487 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
488 while(taskit.hasNext()) {
489 TaskDescriptor td=(TaskDescriptor)taskit.next();
490 FlatMethod fm=state.getMethodFlat(td);
491 generateFlatMethod(fm, null, outmethod);
492 generateTaskDescriptor(outtaskdefs, fm, td);
495 //Output task descriptors
496 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
497 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
499 while(taskit.hasNext()) {
500 TaskDescriptor td=(TaskDescriptor)taskit.next();
504 outtaskdefs.println(",");
505 outtaskdefs.print("&task_"+td.getSafeSymbol());
507 outtaskdefs.println("};");
509 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
512 /* This method outputs most of the methods.c file. This includes
513 * some standard includes and then an array with the sizes of
514 * objets and array that stores supertype and then the code for
515 * the Java methods.. */
517 protected void outputMethods(PrintWriter outmethod) {
518 outmethod.println("#include \"methodheaders.h\"");
519 outmethod.println("#include \"virtualtable.h\"");
520 outmethod.println("#include \"runtime.h\"");
522 outmethod.println("#include \"sandboxdefs.c\"");
525 outmethod.println("#include \"addPrefetchEnhance.h\"");
526 outmethod.println("#include \"localobjects.h\"");
528 if (state.FASTCHECK) {
529 outmethod.println("#include \"localobjects.h\"");
531 if(state.MULTICORE) {
532 outmethod.println("#include \"task.h\"");
533 outmethod.println("#include \"multicoreruntime.h\"");
534 outmethod.println("#include \"runtime_arch.h\"");
536 if (state.THREAD||state.DSM||state.SINGLETM)
537 outmethod.println("#include <thread.h>");
538 if (state.main!=null) {
539 outmethod.println("#include <string.h>");
541 if (state.CONSCHECK) {
542 outmethod.println("#include \"checkers.h\"");
544 if (state.MLP || state.OOOJAVA ) {
545 outmethod.println("#include <stdlib.h>");
546 outmethod.println("#include <stdio.h>");
547 outmethod.println("#include \"mlp_runtime.h\"");
548 outmethod.println("#include \"psemaphore.h\"");
550 if (state.COREPROF) {
551 outmethod.println("#include \"coreprof\\coreprof.h\"");
554 //Store the sizes of classes & array elements
555 generateSizeArray(outmethod);
557 //Store table of supertypes
558 generateSuperTypeTable(outmethod);
560 //Store the layout of classes
561 generateLayoutStructs(outmethod);
563 /* Generate code for methods */
564 if (state.DSM||state.SINGLETM) {
565 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
566 LocalityBinding lb=lbit.next();
567 MethodDescriptor md=lb.getMethod();
568 FlatMethod fm=state.getMethodFlat(md);
570 if (!md.getModifiers().isNative()) {
571 generateFlatMethod(fm, lb, outmethod);
572 //System.out.println("fm= " + fm + " md= " + md);
576 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
577 while(classit.hasNext()) {
578 ClassDescriptor cn=(ClassDescriptor)classit.next();
579 Iterator methodit=cn.getMethods();
580 while(methodit.hasNext()) {
581 /* Classify parameters */
582 MethodDescriptor md=(MethodDescriptor)methodit.next();
583 FlatMethod fm=state.getMethodFlat(md);
584 if (!md.getModifiers().isNative()) {
585 generateFlatMethod(fm, null, outmethod);
592 protected void outputStructs(PrintWriter outstructs) {
593 outstructs.println("#ifndef STRUCTDEFS_H");
594 outstructs.println("#define STRUCTDEFS_H");
595 outstructs.println("#include \"classdefs.h\"");
596 outstructs.println("#ifndef INTPTR");
597 outstructs.println("#ifdef BIT64");
598 outstructs.println("#define INTPTR long");
599 outstructs.println("#else");
600 outstructs.println("#define INTPTR int");
601 outstructs.println("#endif");
602 outstructs.println("#endif");
603 if( state.MLP || state.OOOJAVA ) {
604 outstructs.println("#include \"mlp_runtime.h\"");
605 outstructs.println("#include \"psemaphore.h\"");
608 /* Output #defines that the runtime uses to determine type
609 * numbers for various objects it needs */
610 outstructs.println("#define MAXCOUNT "+maxcount);
611 if (state.DSM||state.SINGLETM) {
612 LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
614 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
616 else if (state.SINGLETM) {
617 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
619 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
623 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
625 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
626 else if( state.SINGLETM)
627 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
628 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
631 outstructs.println("#define STRINGARRAYTYPE "+
632 (state.getArrayNumber(
633 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
635 outstructs.println("#define OBJECTARRAYTYPE "+
636 (state.getArrayNumber(
637 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
640 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
641 outstructs.println("#define CHARARRAYTYPE "+
642 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
644 outstructs.println("#define BYTEARRAYTYPE "+
645 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
647 outstructs.println("#define BYTEARRAYARRAYTYPE "+
648 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
650 outstructs.println("#define NUMCLASSES "+state.numClasses());
651 int totalClassSize = state.numClasses() + state.numArrays();
652 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
654 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
655 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
656 outstructs.println("#define TAGARRAYTYPE "+
657 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
661 protected void outputClassDeclarations(PrintWriter outclassdefs) {
662 if (state.THREAD||state.DSM||state.SINGLETM)
663 outclassdefs.println("#include <pthread.h>");
664 outclassdefs.println("#ifndef INTPTR");
665 outclassdefs.println("#ifdef BIT64");
666 outclassdefs.println("#define INTPTR long");
667 outclassdefs.println("#else");
668 outclassdefs.println("#define INTPTR int");
669 outclassdefs.println("#endif");
670 outclassdefs.println("#endif");
672 outclassdefs.println("#include \"optionalstruct.h\"");
673 outclassdefs.println("struct "+arraytype+";");
674 /* Start by declaring all structs */
675 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
676 while(it.hasNext()) {
677 ClassDescriptor cn=(ClassDescriptor)it.next();
678 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
680 outclassdefs.println("");
681 //Print out definition for array type
682 outclassdefs.println("struct "+arraytype+" {");
683 outclassdefs.println(" int type;");
684 if(state.MLP || state.OOOJAVA ){
685 outclassdefs.println(" int oid;");
686 outclassdefs.println(" int allocsite;");
688 if (state.EVENTMONITOR) {
689 outclassdefs.println(" int objuid;");
692 outclassdefs.println(" pthread_t tid;");
693 outclassdefs.println(" void * lockentry;");
694 outclassdefs.println(" int lockcount;");
697 outclassdefs.println(" int flag;");
698 if(!state.MULTICORE) {
699 outclassdefs.println(" void * flagptr;");
701 outclassdefs.println(" int version;");
702 outclassdefs.println(" int * lock;"); // lock entry for this obj
703 outclassdefs.println(" int mutex;");
704 outclassdefs.println(" int lockcount;");
705 if(state.MULTICOREGC) {
706 outclassdefs.println(" int marked;");
710 outclassdefs.println(" int numfses;");
711 outclassdefs.println(" int * fses;");
714 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
716 if (state.STMARRAY) {
717 outclassdefs.println(" int lowindex;");
718 outclassdefs.println(" int highindex;");
721 outclassdefs.println(" int paddingforarray;");
722 if (state.DUALVIEW) {
723 outclassdefs.println(" int arrayversion;");
726 outclassdefs.println(" int ___length___;");
727 outclassdefs.println("};\n");
728 outclassdefs.println("extern int classsize[];");
729 outclassdefs.println("extern int hasflags[];");
730 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
731 outclassdefs.println("extern int supertypes[];");
734 /** Prints out definitions for generic task structures */
736 private void outputTaskTypes(PrintWriter outtask) {
737 outtask.println("#ifndef _TASK_H");
738 outtask.println("#define _TASK_H");
739 outtask.println("struct parameterdescriptor {");
740 outtask.println("int type;");
741 outtask.println("int numberterms;");
742 outtask.println("int *intarray;");
743 outtask.println("void * queue;");
744 outtask.println("int numbertags;");
745 outtask.println("int *tagarray;");
746 outtask.println("};");
748 outtask.println("struct taskdescriptor {");
749 outtask.println("void * taskptr;");
750 outtask.println("int numParameters;");
751 outtask.println(" int numTotal;");
752 outtask.println("struct parameterdescriptor **descriptorarray;");
753 outtask.println("char * name;");
754 outtask.println("};");
755 outtask.println("extern struct taskdescriptor * taskarray[];");
756 outtask.println("extern numtasks;");
757 outtask.println("#endif");
761 private void buildRepairStructs(PrintWriter outrepairstructs) {
762 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
763 while(classit.hasNext()) {
764 ClassDescriptor cn=(ClassDescriptor)classit.next();
765 outrepairstructs.println("structure "+cn.getSymbol()+" {");
766 outrepairstructs.println(" int __type__;");
768 outrepairstructs.println(" int __flag__;");
769 if(!state.MULTICORE) {
770 outrepairstructs.println(" int __flagptr__;");
773 printRepairStruct(cn, outrepairstructs);
774 outrepairstructs.println("}\n");
777 for(int i=0; i<state.numArrays(); i++) {
778 TypeDescriptor tdarray=arraytable[i];
779 TypeDescriptor tdelement=tdarray.dereference();
780 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
781 outrepairstructs.println(" int __type__;");
782 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
783 outrepairstructs.println(" int length;");
785 // Need to add support to repair tool for this
786 if (tdelement.isClass()||tdelement.isArray())
787 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
789 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
791 outrepairstructs.println("}\n");
795 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
796 ClassDescriptor sp=cn.getSuperDesc();
798 printRepairStruct(sp, output);
800 Vector fields=(Vector)fieldorder.get(cn);
802 for(int i=0; i<fields.size(); i++) {
803 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
804 if (fd.getType().isArray()) {
805 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
806 } else if (fd.getType().isClass())
807 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
808 else if (fd.getType().isFloat())
809 output.println(" int "+fd.getSymbol()+"; /* really float */");
811 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
815 /** This method outputs TaskDescriptor information */
816 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
817 for (int i=0; i<task.numParameters(); i++) {
818 VarDescriptor param_var=task.getParameter(i);
819 TypeDescriptor param_type=task.getParamType(i);
820 FlagExpressionNode param_flag=task.getFlag(param_var);
821 TagExpressionList param_tag=task.getTag(param_var);
824 if (param_flag==null) {
825 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
826 output.println("0x0, 0x0 };");
829 DNFFlag dflag=param_flag.getDNF();
830 dnfterms=dflag.size();
832 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
833 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
834 for(int j=0; j<dflag.size(); j++) {
837 Vector term=dflag.get(j);
840 for(int k=0; k<term.size(); k++) {
841 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
842 FlagDescriptor fd=dfa.getFlag();
843 boolean negated=dfa.getNegated();
844 int flagid=1<<((Integer)flags.get(fd)).intValue();
849 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
851 output.println("};");
854 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
855 //BUG...added next line to fix, test with any task program
857 for(int j=0; j<param_tag.numTags(); j++) {
860 /* for each tag we need */
861 /* which slot it is */
862 /* what type it is */
863 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
864 TempDescriptor tmp=param_tag.getTemp(j);
865 int slot=fm.getTagInt(tmp);
866 output.println(slot+", "+state.getTagId(tvd.getTag()));
868 output.println("};");
870 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
871 output.println("/* type */"+param_type.getClassDesc().getId()+",");
872 output.println("/* number of DNF terms */"+dnfterms+",");
873 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
874 output.println("0,");
875 //BUG, added next line to fix and else statement...test
876 //with any task program
878 output.println("/* number of tags */"+param_tag.numTags()+",");
880 output.println("/* number of tags */ 0,");
881 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
882 output.println("};");
886 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
887 for (int i=0; i<task.numParameters(); i++) {
890 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
892 output.println("};");
894 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
895 output.println("&"+task.getSafeSymbol()+",");
896 output.println("/* number of parameters */" +task.numParameters() + ",");
897 int numtotal=task.numParameters()+fm.numTags();
898 output.println("/* number total parameters */" +numtotal + ",");
899 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
900 output.println("\""+task.getSymbol()+"\"");
901 output.println("};");
905 /** The buildVirtualTables method outputs the virtual dispatch
906 * tables for methods. */
908 protected void buildVirtualTables(PrintWriter outvirtual) {
909 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
910 while(classit.hasNext()) {
911 ClassDescriptor cd=(ClassDescriptor)classit.next();
912 if (virtualcalls.getMethodCount(cd)>maxcount)
913 maxcount=virtualcalls.getMethodCount(cd);
915 MethodDescriptor[][] virtualtable=null;
916 LocalityBinding[][] lbvirtualtable=null;
917 if (state.DSM||state.SINGLETM)
918 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
920 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
922 /* Fill in virtual table */
923 classit=state.getClassSymbolTable().getDescriptorsIterator();
924 while(classit.hasNext()) {
925 ClassDescriptor cd=(ClassDescriptor)classit.next();
926 if (state.DSM||state.SINGLETM)
927 fillinRow(cd, lbvirtualtable, cd.getId());
929 fillinRow(cd, virtualtable, cd.getId());
932 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
933 Iterator arrayit=state.getArrayIterator();
934 while(arrayit.hasNext()) {
935 TypeDescriptor td=(TypeDescriptor)arrayit.next();
936 int id=state.getArrayNumber(td);
937 if (state.DSM||state.SINGLETM)
938 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
940 fillinRow(objectcd, virtualtable, id+state.numClasses());
943 outvirtual.print("void * virtualtable[]={");
944 boolean needcomma=false;
945 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
946 for(int j=0; j<maxcount; j++) {
948 outvirtual.print(", ");
949 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
950 LocalityBinding lb=lbvirtualtable[i][j];
951 MethodDescriptor md=lb.getMethod();
952 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
953 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
954 MethodDescriptor md=virtualtable[i][j];
955 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
957 outvirtual.print("0");
961 outvirtual.println("");
963 outvirtual.println("};");
967 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
968 /* Get inherited methods */
969 if (cd.getSuperDesc()!=null)
970 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
971 /* Override them with our methods */
972 for(Iterator it=cd.getMethods(); it.hasNext();) {
973 MethodDescriptor md=(MethodDescriptor)it.next();
974 if (md.isStatic()||md.getReturnType()==null)
976 int methodnum=virtualcalls.getMethodNumber(md);
977 virtualtable[rownum][methodnum]=md;
981 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
982 /* Get inherited methods */
983 if (cd.getSuperDesc()!=null)
984 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
985 /* Override them with our methods */
986 if (locality.getClassBindings(cd)!=null)
987 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
988 LocalityBinding lb=lbit.next();
989 MethodDescriptor md=lb.getMethod();
990 //Is the method static or a constructor
991 if (md.isStatic()||md.getReturnType()==null)
993 int methodnum=virtualcalls.getLocalityNumber(lb);
994 virtualtable[rownum][methodnum]=lb;
998 /** Generate array that contains the sizes of class objects. The
999 * object allocation functions in the runtime use this
1002 private void generateSizeArray(PrintWriter outclassdefs) {
1003 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
1004 outclassdefs.print("#ifdef TRANSSTATS \n");
1005 outclassdefs.print("extern int numTransAbort;\n");
1006 outclassdefs.print("extern int numTransCommit;\n");
1007 outclassdefs.print("extern int nSoftAbort;\n");
1009 outclassdefs.print("extern int nchashSearch;\n");
1010 outclassdefs.print("extern int nmhashSearch;\n");
1011 outclassdefs.print("extern int nprehashSearch;\n");
1012 outclassdefs.print("extern int ndirtyCacheObj;\n");
1013 outclassdefs.print("extern int nRemoteSend;\n");
1014 outclassdefs.print("extern int sendRemoteReq;\n");
1015 outclassdefs.print("extern int getResponse;\n");
1016 outclassdefs.print("extern int bytesSent;\n");
1017 outclassdefs.print("extern int bytesRecv;\n");
1018 outclassdefs.print("extern int totalObjSize;\n");
1019 outclassdefs.print("extern void handle();\n");
1020 } else if (state.SINGLETM) {
1021 outclassdefs.println("extern int nSoftAbortAbort;");
1022 outclassdefs.println("extern int nSoftAbortCommit;");
1023 outclassdefs.println("#ifdef STMSTATS\n");
1024 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
1025 outclassdefs.println("#endif\n");
1027 outclassdefs.print("#endif\n");
1029 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
1030 if(this.state.MLP || state.OOOJAVA ){
1031 outclassdefs.print("extern __thread int oid;\n");
1032 outclassdefs.print("extern int numWorkers;\n");
1035 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1036 cdarray=new ClassDescriptor[state.numClasses()];
1038 while(it.hasNext()) {
1039 ClassDescriptor cd=(ClassDescriptor)it.next();
1040 cdarray[cd.getId()]=cd;
1043 arraytable=new TypeDescriptor[state.numArrays()];
1045 Iterator arrayit=state.getArrayIterator();
1046 while(arrayit.hasNext()) {
1047 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1048 int id=state.getArrayNumber(td);
1054 /* Print out types */
1055 outclassdefs.println("/* ");
1056 for(int i=0; i<state.numClasses(); i++) {
1057 ClassDescriptor cd=cdarray[i];
1059 outclassdefs.println("NULL " + i);
1061 outclassdefs.println(cd +" "+i);
1065 for(int i=0; i<state.numArrays(); i++) {
1066 TypeDescriptor arraytd=arraytable[i];
1067 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
1070 outclassdefs.println("*/");
1073 outclassdefs.print("int classsize[]={");
1075 boolean needcomma=false;
1076 for(int i=0; i<state.numClasses(); i++) {
1078 outclassdefs.print(", ");
1080 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1082 outclassdefs.print("0");
1088 for(int i=0; i<state.numArrays(); i++) {
1090 outclassdefs.print(", ");
1091 TypeDescriptor tdelement=arraytable[i].dereference();
1092 if (tdelement.isArray()||tdelement.isClass())
1093 outclassdefs.print("sizeof(void *)");
1095 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1099 outclassdefs.println("};");
1101 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1103 outclassdefs.print("int typearray[]={");
1104 for(int i=0; i<state.numClasses(); i++) {
1105 ClassDescriptor cd=cdarray[i];
1106 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1108 outclassdefs.print(", ");
1110 outclassdefs.print("-1");
1112 outclassdefs.print(supercd.getId());
1116 for(int i=0; i<state.numArrays(); i++) {
1117 TypeDescriptor arraytd=arraytable[i];
1118 ClassDescriptor arraycd=arraytd.getClassDesc();
1119 if (arraycd==null) {
1121 outclassdefs.print(", ");
1122 outclassdefs.print(objectclass.getId());
1126 ClassDescriptor cd=arraycd.getSuperDesc();
1129 TypeDescriptor supertd=new TypeDescriptor(cd);
1130 supertd.setArrayCount(arraytd.getArrayCount());
1131 type=state.getArrayNumber(supertd);
1133 type+=state.numClasses();
1136 cd=cd.getSuperDesc();
1139 outclassdefs.print(", ");
1140 outclassdefs.print(type);
1144 outclassdefs.println("};");
1149 outclassdefs.print("int typearray2[]={");
1150 for(int i=0; i<state.numArrays(); i++) {
1151 TypeDescriptor arraytd=arraytable[i];
1152 ClassDescriptor arraycd=arraytd.getClassDesc();
1153 if (arraycd==null) {
1155 outclassdefs.print(", ");
1156 outclassdefs.print("-1");
1160 ClassDescriptor cd=arraycd.getSuperDesc();
1161 int level=arraytd.getArrayCount()-1;
1163 for(; level>0; level--) {
1164 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1165 supertd.setArrayCount(level);
1166 type=state.getArrayNumber(supertd);
1168 type+=state.numClasses();
1173 outclassdefs.print(", ");
1174 outclassdefs.print(type);
1178 outclassdefs.println("};");
1181 /** Constructs params and temp objects for each method or task.
1182 * These objects tell the compiler which temps need to be
1185 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1186 MethodDescriptor md=fm.getMethod();
1187 TaskDescriptor task=fm.getTask();
1188 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1189 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1191 paramstable.put(lb, objectparams);
1192 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1193 } else if (md!=null)
1194 paramstable.put(md, objectparams);
1196 paramstable.put(task, objectparams);
1198 for(int i=0; i<fm.numParameters(); i++) {
1199 TempDescriptor temp=fm.getParameter(i);
1200 TypeDescriptor type=temp.getType();
1201 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1202 objectparams.addPtr(temp);
1204 objectparams.addPrim(temp);
1205 if(lb!=null&&saveset.contains(temp)) {
1206 backuptable.get(lb).put(temp, temp.createNew());
1210 for(int i=0; i<fm.numTags(); i++) {
1211 TempDescriptor temp=fm.getTag(i);
1212 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1213 objectparams.addPtr(temp);
1215 objectparams.addPrim(temp);
1218 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1220 tempstable.put(lb, objecttemps);
1222 tempstable.put(md, objecttemps);
1224 tempstable.put(task, objecttemps);
1226 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1227 FlatNode fn=(FlatNode)nodeit.next();
1228 TempDescriptor[] writes=fn.writesTemps();
1229 for(int i=0; i<writes.length; i++) {
1230 TempDescriptor temp=writes[i];
1231 TypeDescriptor type=temp.getType();
1232 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1233 objecttemps.addPtr(temp);
1235 objecttemps.addPrim(temp);
1236 if(lb!=null&&saveset.contains(temp)&&
1237 !backuptable.get(lb).containsKey(temp))
1238 backuptable.get(lb).put(temp, temp.createNew());
1242 /* Create backup temps */
1244 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1245 TempDescriptor tmp=tmpit.next();
1246 TypeDescriptor type=tmp.getType();
1247 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1248 objecttemps.addPtr(tmp);
1250 objecttemps.addPrim(tmp);
1252 /* Create temp to hold revert table */
1253 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1254 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1255 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1256 objecttemps.addPtr(reverttmp);
1258 objecttemps.addPrim(reverttmp);
1259 reverttable.put(lb, reverttmp);
1264 /** This method outputs the following information about classes
1266 * (1) For classes, what are the locations of pointers.
1267 * (2) For arrays, does the array contain pointers or primitives.
1268 * (3) For classes, does the class contain flags.
1271 private void generateLayoutStructs(PrintWriter output) {
1272 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1273 while(it.hasNext()) {
1274 ClassDescriptor cn=(ClassDescriptor)it.next();
1275 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1276 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1278 while(allit.hasNext()) {
1279 FieldDescriptor fd=(FieldDescriptor)allit.next();
1280 TypeDescriptor type=fd.getType();
1281 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1286 output.print(count);
1287 allit=cn.getFieldTable().getAllDescriptorsIterator();
1288 while(allit.hasNext()) {
1289 FieldDescriptor fd=(FieldDescriptor)allit.next();
1290 TypeDescriptor type=fd.getType();
1291 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1294 output.println(",");
1295 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1298 output.println("};");
1300 output.println("unsigned INTPTR * pointerarray[]={");
1301 boolean needcomma=false;
1302 for(int i=0; i<state.numClasses(); i++) {
1303 ClassDescriptor cn=cdarray[i];
1305 output.println(",");
1308 output.print(cn.getSafeSymbol()+"_pointers");
1310 output.print("NULL");
1314 for(int i=0; i<state.numArrays(); i++) {
1316 output.println(", ");
1317 TypeDescriptor tdelement=arraytable[i].dereference();
1318 if (tdelement.isArray()||tdelement.isClass())
1319 output.print("((unsigned INTPTR *)1)");
1325 output.println("};");
1327 output.println("int hasflags[]={");
1328 for(int i=0; i<state.numClasses(); i++) {
1329 ClassDescriptor cn=cdarray[i];
1331 output.println(", ");
1333 if ((cn != null) && (cn.hasFlags()))
1338 output.println("};");
1341 /** Print out table to give us supertypes */
1342 private void generateSuperTypeTable(PrintWriter output) {
1343 output.println("int supertypes[]={");
1344 boolean needcomma=false;
1345 for(int i=0; i<state.numClasses(); i++) {
1346 ClassDescriptor cn=cdarray[i];
1348 output.println(",");
1350 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1351 ClassDescriptor cdsuper=cn.getSuperDesc();
1352 output.print(cdsuper.getId());
1356 output.println("};");
1359 /** Force consistent field ordering between inherited classes. */
1361 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1363 ClassDescriptor sp=cn.getSuperDesc();
1365 printClassStruct(sp, classdefout);
1367 if (!fieldorder.containsKey(cn)) {
1368 Vector fields=new Vector();
1369 fieldorder.put(cn,fields);
1370 Vector fieldvec=cn.getFieldVec();
1371 for(int i=0;i<fieldvec.size();i++) {
1372 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1373 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1377 Vector fields=(Vector)fieldorder.get(cn);
1379 for(int i=0; i<fields.size(); i++) {
1380 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1381 if (fd.getType().isClass()||fd.getType().isArray())
1382 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1384 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1389 /* Map flags to integers consistently between inherited
1392 protected void mapFlags(ClassDescriptor cn) {
1393 ClassDescriptor sp=cn.getSuperDesc();
1397 if (!flagorder.containsKey(cn)) {
1398 Hashtable flags=new Hashtable();
1399 flagorder.put(cn,flags);
1401 Hashtable superflags=(Hashtable)flagorder.get(sp);
1402 Iterator superflagit=superflags.keySet().iterator();
1403 while(superflagit.hasNext()) {
1404 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1405 Integer number=(Integer)superflags.get(fd);
1406 flags.put(fd, number);
1407 if ((number.intValue()+1)>max)
1408 max=number.intValue()+1;
1412 Iterator flagit=cn.getFlags();
1413 while(flagit.hasNext()) {
1414 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1415 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1416 flags.put(fd, new Integer(max++));
1422 /** This function outputs (1) structures that parameters are
1423 * passed in (when PRECISE GC is enabled) and (2) function
1424 * prototypes for the methods */
1426 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1427 /* Output class structure */
1428 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1429 classdefout.println(" int type;");
1430 if(state.MLP || state.OOOJAVA){
1431 classdefout.println(" int oid;");
1432 classdefout.println(" int allocsite;");
1434 if (state.EVENTMONITOR) {
1435 classdefout.println(" int objuid;");
1438 classdefout.println(" pthread_t tid;");
1439 classdefout.println(" void * lockentry;");
1440 classdefout.println(" int lockcount;");
1444 classdefout.println(" int flag;");
1445 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1446 classdefout.println(" void * flagptr;");
1447 } else if (state.MULTICORE) {
1448 classdefout.println(" int version;");
1449 classdefout.println(" int * lock;"); // lock entry for this obj
1450 classdefout.println(" int mutex;");
1451 classdefout.println(" int lockcount;");
1452 if(state.MULTICOREGC) {
1453 classdefout.println(" int marked;");
1456 if (state.OPTIONAL) {
1457 classdefout.println(" int numfses;");
1458 classdefout.println(" int * fses;");
1461 printClassStruct(cn, classdefout);
1462 classdefout.println("};\n");
1464 if (state.DSM||state.SINGLETM) {
1465 /* Cycle through LocalityBindings */
1466 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1467 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1469 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1470 LocalityBinding lb=lbit.next();
1471 MethodDescriptor md=lb.getMethod();
1472 if (md.getModifiers().isNative()) {
1473 //make sure we only print a native method once
1474 if (nativemethods.contains(md)) {
1475 FlatMethod fm=state.getMethodFlat(md);
1476 generateTempStructs(fm, lb);
1479 nativemethods.add(md);
1481 generateMethod(cn, md, lb, headersout, output);
1484 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1485 MethodDescriptor md=(MethodDescriptor)methodit.next();
1486 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1487 //Need to build param structure for library code
1488 FlatMethod fm=state.getMethodFlat(md);
1489 generateTempStructs(fm, null);
1490 generateMethodParam(cn, md, null, output);
1495 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1496 MethodDescriptor md=(MethodDescriptor)methodit.next();
1497 generateMethod(cn, md, null, headersout, output);
1501 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1502 /* Output parameter structure */
1503 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1504 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1505 if ((state.DSM||state.SINGLETM)&&lb!=null)
1506 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1508 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1509 output.println(" int size;");
1510 output.println(" void * next;");
1511 for(int i=0; i<objectparams.numPointers(); i++) {
1512 TempDescriptor temp=objectparams.getPointer(i);
1513 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1515 output.println("};\n");
1519 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1520 FlatMethod fm=state.getMethodFlat(md);
1521 generateTempStructs(fm, lb);
1523 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1524 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1526 generateMethodParam(cn, md, lb, output);
1528 /* Output temp structure */
1529 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1530 if (state.DSM||state.SINGLETM)
1531 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1533 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1534 output.println(" int size;");
1535 output.println(" void * next;");
1536 for(int i=0; i<objecttemps.numPointers(); i++) {
1537 TempDescriptor temp=objecttemps.getPointer(i);
1538 if (temp.getType().isNull())
1539 output.println(" void * "+temp.getSafeSymbol()+";");
1541 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1543 output.println("};\n");
1546 /********* Output method declaration ***********/
1547 if (state.DSM||state.SINGLETM) {
1548 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1550 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1552 /* First the return type */
1553 if (md.getReturnType()!=null) {
1554 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1555 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1557 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1559 //catch the constructor case
1560 headersout.print("void ");
1562 /* Next the method name */
1563 if (state.DSM||state.SINGLETM) {
1564 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1566 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1568 boolean printcomma=false;
1569 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1570 if (state.DSM||state.SINGLETM) {
1571 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1573 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1577 /* Output parameter list*/
1578 for(int i=0; i<objectparams.numPrimitives(); i++) {
1579 TempDescriptor temp=objectparams.getPrimitive(i);
1581 headersout.print(", ");
1583 if (temp.getType().isClass()||temp.getType().isArray())
1584 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1586 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1588 headersout.println(");\n");
1592 /** This function outputs (1) structures that parameters are
1593 * passed in (when PRECISE GC is enabled) and (2) function
1594 * prototypes for the tasks */
1596 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1597 /* Cycle through tasks */
1598 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1600 while(taskit.hasNext()) {
1601 /* Classify parameters */
1602 TaskDescriptor task=(TaskDescriptor)taskit.next();
1603 FlatMethod fm=state.getMethodFlat(task);
1604 generateTempStructs(fm, null);
1606 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1607 TempObject objecttemps=(TempObject) tempstable.get(task);
1609 /* Output parameter structure */
1610 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1611 output.println("struct "+task.getSafeSymbol()+"_params {");
1612 output.println(" int size;");
1613 output.println(" void * next;");
1614 for(int i=0; i<objectparams.numPointers(); i++) {
1615 TempDescriptor temp=objectparams.getPointer(i);
1616 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1619 output.println("};\n");
1620 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1621 maxtaskparams=objectparams.numPointers()+fm.numTags();
1625 /* Output temp structure */
1626 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1627 output.println("struct "+task.getSafeSymbol()+"_locals {");
1628 output.println(" int size;");
1629 output.println(" void * next;");
1630 for(int i=0; i<objecttemps.numPointers(); i++) {
1631 TempDescriptor temp=objecttemps.getPointer(i);
1632 if (temp.getType().isNull())
1633 output.println(" void * "+temp.getSafeSymbol()+";");
1634 else if(temp.getType().isTag())
1635 output.println(" struct "+
1636 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1638 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1640 output.println("};\n");
1643 /* Output task declaration */
1644 headersout.print("void " + task.getSafeSymbol()+"(");
1646 boolean printcomma=false;
1647 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1648 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1650 headersout.print("void * parameterarray[]");
1651 headersout.println(");\n");
1655 /***** Generate code for FlatMethod fm. *****/
1657 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1658 static int atomicmethodcount=0;
1661 BranchAnalysis branchanalysis;
1662 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1663 if (State.PRINTFLAT)
1664 System.out.println(fm.printMethod());
1665 MethodDescriptor md=fm.getMethod();
1666 TaskDescriptor task=fm.getTask();
1667 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1668 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1670 HashSet<AtomicRecord> arset=null;
1671 branchanalysis=null;
1673 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1675 if (atomicmethodmap==null)
1676 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1678 //fix these so we get right strings for local variables
1679 localsprefixaddr=localsprefix;
1680 localsprefixderef=localsprefix+"->";
1681 arset=new HashSet<AtomicRecord>();
1683 //build branchanalysis
1684 branchanalysis=new BranchAnalysis(locality, lb, delaycomp.getNotReady(lb), delaycomp.livecode(lb), state);
1686 //Generate commit methods here
1687 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1688 FlatNode fn=fnit.next();
1689 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1690 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
1691 delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
1692 //We have an atomic enter
1693 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1694 Set<FlatNode> exitset=faen.getExits();
1696 String methodname=md.getSymbol()+(atomicmethodcount++);
1697 AtomicRecord ar=new AtomicRecord();
1701 atomicmethodmap.put(faen, ar);
1703 //build data structure declaration
1704 output.println("struct atomicprimitives_"+methodname+" {");
1706 Set<FlatNode> recordset=delaycomp.livecode(lb);
1707 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1708 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1709 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1711 ar.reallivein=new HashSet(liveinto);
1713 ar.liveoutvirtualread=liveoutvirtualread;
1716 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1717 TempDescriptor tmp=it.next();
1718 //remove the pointers
1719 if (tmp.getType().isPtr()) {
1722 //let's print it here
1723 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1726 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1727 TempDescriptor tmp=it.next();
1728 //remove the pointers
1729 if (tmp.getType().isPtr()) {
1731 } else if (!liveinto.contains(tmp)) {
1732 //let's print it here
1733 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1736 output.println("};");
1738 //print out method name
1739 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) {");
1740 //build code for commit method
1742 //first define local primitives
1743 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1744 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1745 TempDescriptor tmp=tmpit.next();
1746 if (!tmp.getType().isPtr()) {
1747 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1748 //read from live into set
1749 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1752 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1756 //turn off write barrier generation
1758 state.SINGLETM=false;
1759 generateCode(faen, fm, lb, exitset, output, false);
1760 state.SINGLETM=true;
1761 //turn on write barrier generation
1763 output.println("}\n\n");
1767 //redefine these back to normal
1769 localsprefixaddr="&"+localsprefix;
1770 localsprefixderef=localsprefix+".";
1772 generateHeader(fm, lb, md!=null ? md : task,output);
1773 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1775 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1776 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1777 AtomicRecord ar=arit.next();
1778 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1782 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1783 if (md!=null&&(state.DSM||state.SINGLETM))
1784 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1785 else if (md!=null&&!(state.DSM||state.SINGLETM))
1786 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1788 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1789 output.print(objecttemp.numPointers()+",");
1790 output.print(paramsprefix);
1791 for(int j=0; j<objecttemp.numPointers(); j++)
1792 output.print(", NULL");
1793 output.println("};");
1796 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1797 TempDescriptor td=objecttemp.getPrimitive(i);
1798 TypeDescriptor type=td.getType();
1800 output.println(" void * "+td.getSafeSymbol()+";");
1801 else if (type.isClass()||type.isArray())
1802 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1804 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1808 if( state.MLP || state.OOOJAVA ) {
1809 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1810 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1811 if( (state.MLP && callerSESEplaceholder != mlpa.getMainSESE()) ||
1812 (state.OOOJAVA && callerSESEplaceholder != oooa.getMainSESE())
1814 // declare variables for naming static SESE's
1815 output.println(" /* static SESE names */");
1816 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1817 while( pItr.hasNext() ) {
1818 SESEandAgePair pair = pItr.next();
1819 output.println(" void* "+pair+";");
1822 // declare variables for tracking dynamic sources
1823 output.println(" /* dynamic variable sources */");
1824 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1825 while( dynSrcItr.hasNext() ) {
1826 TempDescriptor dynSrcVar = dynSrcItr.next();
1827 output.println(" void* "+dynSrcVar+"_srcSESE;");
1828 output.println(" int "+dynSrcVar+"_srcOffset;");
1833 // set up related allocation sites's waiting queues
1836 ConflictGraph graph = null;
1837 graph = mlpa.getConflictGraphResults().get(fm);
1838 if (graph != null && graph.hasConflictEdge()) {
1839 output.println(" /* set up waiting queues */");
1840 output.println(" int numMemoryQueue=0;");
1841 output.println(" int memoryQueueItemID=0;");
1842 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
1844 System.out.println("#lockSet="+lockSet.hashCode());
1845 System.out.println("lockset="+lockSet);
1846 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1847 SESELock seseLock = (SESELock) iterator.next();
1848 System.out.println("id="+seseLock.getID());
1849 System.out.println("#="+seseLock);
1851 System.out.println("size="+lockSet.size());
1852 if (lockSet.size() > 0) {
1853 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1855 .println(" seseCaller->numMemoryQueue=numMemoryQueue;");
1857 .println(" seseCaller->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1862 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1863 if(callerSESEplaceholder!= oooa.getMainSESE()){
1864 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(callerSESEplaceholder);
1865 if (graph != null && graph.hasConflictEdge()) {
1866 output.println(" // set up waiting queues ");
1867 output.println(" int numMemoryQueue=0;");
1868 output.println(" int memoryQueueItemID=0;");
1869 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
1870 System.out.println("#lockSet="+lockSet.hashCode());
1871 System.out.println("lockset="+lockSet);
1872 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1873 Analysis.OoOJava.SESELock seseLock = (Analysis.OoOJava.SESELock) iterator.next();
1874 System.out.println("id="+seseLock.getID());
1875 System.out.println("#="+seseLock);
1877 System.out.println("size="+lockSet.size());
1878 if (lockSet.size() > 0) {
1879 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1881 .println(" seseCaller->numMemoryQueue=numMemoryQueue;");
1883 .println(" seseCaller->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1893 /* Check to see if we need to do a GC if this is a
1894 * multi-threaded program...*/
1896 if (((state.MLP||state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1897 || this.state.MULTICOREGC) {
1898 //Don't bother if we aren't in recursive methods...The loops case will catch it
1899 if (callgraph.getAllMethods(md).contains(md)) {
1900 if (state.DSM&&lb.isAtomic())
1901 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1902 else if (this.state.MULTICOREGC) {
1903 output.println("if(gcflag) gc("+localsprefixaddr+");");
1905 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1910 generateCode(fm.getNext(0), fm, lb, null, output, true);
1912 output.println("}\n\n");
1916 protected void initializeSESE( FlatSESEEnterNode fsen ) {
1918 FlatMethod fm = fsen.getfmEnclosing();
1919 MethodDescriptor md = fm.getMethod();
1920 ClassDescriptor cn = md.getClassDesc();
1923 // Creates bogus method descriptor to index into tables
1924 Modifiers modBogus = new Modifiers();
1925 MethodDescriptor mdBogus =
1926 new MethodDescriptor( modBogus,
1927 new TypeDescriptor( TypeDescriptor.VOID ),
1928 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1931 mdBogus.setClassDesc( fsen.getcdEnclosing() );
1932 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1933 fsen.setfmBogus( fmBogus );
1934 fsen.setmdBogus( mdBogus );
1936 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1937 inSetAndOutSet.addAll( fsen.getInVarSet() );
1938 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1940 // Build paramsobj for bogus method descriptor
1941 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
1942 paramstable.put( mdBogus, objectparams );
1944 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1945 while( itr.hasNext() ) {
1946 TempDescriptor temp = itr.next();
1947 TypeDescriptor type = temp.getType();
1948 if( type.isPtr() ) {
1949 objectparams.addPtr( temp );
1951 objectparams.addPrim( temp );
1955 // Build normal temp object for bogus method descriptor
1956 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
1957 tempstable.put( mdBogus, objecttemps );
1959 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
1960 FlatNode fn = (FlatNode)nodeit.next();
1961 TempDescriptor[] writes = fn.writesTemps();
1963 for( int i = 0; i < writes.length; i++ ) {
1964 TempDescriptor temp = writes[i];
1965 TypeDescriptor type = temp.getType();
1967 if( type.isPtr() ) {
1968 objecttemps.addPtr( temp );
1970 objecttemps.addPrim( temp );
1976 protected void generateMethodSESE(FlatSESEEnterNode fsen,
1978 PrintWriter outputStructs,
1979 PrintWriter outputMethHead,
1980 PrintWriter outputMethods
1983 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
1984 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
1986 // generate locals structure
1987 outputStructs.println("struct "+
1988 fsen.getcdEnclosing().getSafeSymbol()+
1989 fsen.getmdBogus().getSafeSymbol()+"_"+
1990 fsen.getmdBogus().getSafeMethodDescriptor()+
1992 outputStructs.println(" int size;");
1993 outputStructs.println(" void * next;");
1994 for(int i=0; i<objecttemps.numPointers(); i++) {
1995 TempDescriptor temp=objecttemps.getPointer(i);
1997 if (temp.getType().isNull())
1998 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
2000 outputStructs.println(" struct "+
2001 temp.getType().getSafeSymbol()+" * "+
2002 temp.getSafeSymbol()+";");
2004 outputStructs.println("};\n");
2007 // generate the SESE record structure
2008 outputStructs.println(fsen.getSESErecordName()+" {");
2010 // data common to any SESE, and it must be placed first so
2011 // a module that doesn't know what kind of SESE record this
2012 // is can cast the pointer to a common struct
2013 outputStructs.println(" SESEcommon common;");
2015 // then garbage list stuff
2016 outputStructs.println(" int size;");
2017 outputStructs.println(" void * next;");
2019 // DYNAMIC stuff was here
2021 // invar source taking was here
2023 // space for all in and out set primitives
2024 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
2025 inSetAndOutSet.addAll( fsen.getInVarSet() );
2026 inSetAndOutSet.addAll( fsen.getOutVarSet() );
2028 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
2030 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
2031 while( itr.hasNext() ) {
2032 TempDescriptor temp = itr.next();
2033 TypeDescriptor type = temp.getType();
2034 if( !type.isPtr() ) {
2035 inSetAndOutSetPrims.add( temp );
2039 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
2040 while( itrPrims.hasNext() ) {
2041 TempDescriptor temp = itrPrims.next();
2042 TypeDescriptor type = temp.getType();
2043 if(!type.isPrimitive()){
2044 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
2048 for(int i=0; i<objectparams.numPointers(); i++) {
2049 TempDescriptor temp=objectparams.getPointer(i);
2050 if (temp.getType().isNull())
2051 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
2053 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
2056 // DYNAMIC stuff needs a source SESE ptr and offset
2057 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
2058 while( itrDynInVars.hasNext() ) {
2059 TempDescriptor dynInVar = itrDynInVars.next();
2060 // outputStructs.println(" void* "+dynInVar+"_srcSESE;");
2061 outputStructs.println(" int "+dynInVar+"_srcOffset;");
2064 itrPrims = inSetAndOutSetPrims.iterator();
2065 while( itrPrims.hasNext() ) {
2066 TempDescriptor temp = itrPrims.next();
2067 TypeDescriptor type = temp.getType();
2068 if(type.isPrimitive()){
2069 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
2073 outputStructs.println(" int prevSESECount;");
2075 // DYNAMIC stuff needs a source SESE ptr and offset
2076 itrDynInVars = fsen.getDynamicInVarSet().iterator();
2077 while( itrDynInVars.hasNext() ) {
2078 TempDescriptor dynInVar = itrDynInVars.next();
2079 outputStructs.println(" void* "+dynInVar+"_srcSESE;");
2080 // outputStructs.println(" int "+dynInVar+"_srcOffset;");
2083 // in-set source tracking
2084 // in-vars that are READY come from parent, don't need anything
2085 // stuff STATIC needs a custom SESE pointer for each age pair
2086 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
2087 while( itrStaticInVarSrcs.hasNext() ) {
2088 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
2089 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
2092 outputStructs.println("};\n");
2095 // write method declaration to header file
2096 outputMethHead.print("void ");
2097 outputMethHead.print(fsen.getSESEmethodName()+"(");
2098 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
2099 outputMethHead.println(");\n");
2102 generateFlatMethodSESE( fsen.getfmBogus(),
2103 fsen.getcdEnclosing(),
2109 private void generateFlatMethodSESE(FlatMethod fm,
2111 FlatSESEEnterNode fsen,
2112 FlatSESEExitNode seseExit,
2116 MethodDescriptor md=fm.getMethod();
2118 output.print("void ");
2119 output.print(fsen.getSESEmethodName()+"(");
2120 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
2121 output.println("){\n");
2123 TempObject objecttemp=(TempObject) tempstable.get(md);
2125 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2126 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2127 output.print(objecttemp.numPointers()+",");
2128 output.print("&(((SESEcommon*)(___params___))[1])");
2129 for(int j=0; j<objecttemp.numPointers(); j++)
2130 output.print(", NULL");
2131 output.println("};");
2134 output.println(" /* regular local primitives */");
2135 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2136 TempDescriptor td=objecttemp.getPrimitive(i);
2137 TypeDescriptor type=td.getType();
2139 output.println(" void * "+td.getSafeSymbol()+";");
2140 else if (type.isClass()||type.isArray())
2141 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2143 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2147 // declare variables for naming static SESE's
2148 output.println(" /* static SESE names */");
2149 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
2150 while( pItr.hasNext() ) {
2151 SESEandAgePair pair = pItr.next();
2152 output.println(" void* "+pair+";");
2155 // declare variables for tracking dynamic sources
2156 output.println(" /* dynamic variable sources */");
2157 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
2158 while( dynSrcItr.hasNext() ) {
2159 TempDescriptor dynSrcVar = dynSrcItr.next();
2160 output.println(" void* "+dynSrcVar+"_srcSESE;");
2161 output.println(" int "+dynSrcVar+"_srcOffset;");
2164 // declare local temps for in-set primitives, and if it is
2165 // a ready-source variable, get the value from the record
2166 output.println(" /* local temps for in-set primitives */");
2167 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2168 while( itrInSet.hasNext() ) {
2169 TempDescriptor temp = itrInSet.next();
2170 TypeDescriptor type = temp.getType();
2171 if( !type.isPtr() ) {
2172 if( fsen.getReadyInVarSet().contains( temp ) ) {
2173 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2175 output.println(" "+type+" "+temp+";");
2180 // declare local temps for out-set primitives if its not already
2181 // in the in-set, and it's value will get written so no problem
2182 output.println(" /* local temp for out-set prim, not already in the in-set */");
2183 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2184 while( itrOutSet.hasNext() ) {
2185 TempDescriptor temp = itrOutSet.next();
2186 TypeDescriptor type = temp.getType();
2187 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2188 output.println(" "+type+" "+temp+";");
2192 // setup memory queue
2195 output.println(" // set up memory queues ");
2196 output.println(" int numMemoryQueue=0;");
2197 output.println(" int memoryQueueItemID=0;");
2198 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(fsen);
2199 if (graph != null && graph.hasConflictEdge()) {
2200 output.println(" {");
2202 .println(" SESEcommon* parentCommon = &(___params___->common);");
2203 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
2204 System.out.println("#lockSet="+lockSet);
2205 if (lockSet.size() > 0) {
2206 output.println(" numMemoryQueue=" + lockSet.size() + ";");
2208 .println(" parentCommon->numMemoryQueue=numMemoryQueue;");
2210 .println(" parentCommon->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2213 output.println(" }");
2216 output.println(" // set up memory queues ");
2217 output.println(" int numMemoryQueue=0;");
2218 output.println(" int memoryQueueItemID=0;");
2219 ConflictGraph graph = null;
2220 graph = mlpa.getConflictGraphResults().get(fsen);
2221 if (graph != null && graph.hasConflictEdge()) {
2222 output.println(" {");
2224 .println(" SESEcommon* parentCommon = &(___params___->common);");
2225 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
2227 System.out.println("#lockSet="+lockSet);
2229 if (lockSet.size() > 0) {
2230 output.println(" numMemoryQueue=" + lockSet.size() + "; ");
2232 .println(" parentCommon->numMemoryQueue=numMemoryQueue;");
2234 .println(" parentCommon->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2237 output.println(" }");
2243 // copy in-set into place, ready vars were already
2244 // copied when the SESE was issued
2245 Iterator<TempDescriptor> tempItr;
2247 // static vars are from a known SESE
2248 tempItr = fsen.getStaticInVarSet().iterator();
2249 while( tempItr.hasNext() ) {
2250 TempDescriptor temp = tempItr.next();
2251 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2252 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2254 // can't grab something from this source until it is done
2255 output.println(" {");
2257 If we are running, everything is done. This check is redundant.
2259 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+srcPair+";" );
2260 output.println(" pthread_mutex_lock( &(com->lock) );");
2261 output.println(" while( com->doneExecuting == FALSE ) {");
2262 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2263 output.println(" }");
2264 output.println(" pthread_mutex_unlock( &(com->lock) );");
2266 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2267 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2269 output.println(" }");
2272 // dynamic vars come from an SESE and src
2273 tempItr = fsen.getDynamicInVarSet().iterator();
2274 while( tempItr.hasNext() ) {
2275 TempDescriptor temp = tempItr.next();
2276 TypeDescriptor type = temp.getType();
2278 // go grab it from the SESE source
2279 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2281 // gotta wait until the source is done
2282 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+temp+"_srcSESE;" );
2284 If we are running, everything is done!
2285 output.println(" pthread_mutex_lock( &(com->lock) );");
2286 output.println(" while( com->doneExecuting == FALSE ) {");
2287 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2288 output.println(" }");
2289 output.println(" pthread_mutex_unlock( &(com->lock) );");
2293 if( type.isNull() ) {
2295 } else if( type.isClass() || type.isArray() ) {
2296 typeStr = "struct "+type.getSafeSymbol()+"*";
2298 typeStr = type.getSafeSymbol();
2301 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2302 " = *(("+typeStr+"*) ("+
2303 paramsprefix+"->"+temp+"_srcSESE + "+
2304 paramsprefix+"->"+temp+"_srcOffset));");
2306 // or if the source was our parent, its in the record to grab
2307 output.println(" } else {");
2308 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2309 " = "+paramsprefix+"->"+temp+";");
2310 output.println(" }");
2313 // Check to see if we need to do a GC if this is a
2314 // multi-threaded program...
2315 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2316 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2317 //Don't bother if we aren't in recursive methods...The loops case will catch it
2318 // if (callgraph.getAllMethods(md).contains(md)) {
2319 // if(this.state.MULTICOREGC) {
2320 // output.println("if(gcflag) gc("+localsprefixaddr+");");
2322 // output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2327 // initialize thread-local var to a non-zero, invalid address
2328 output.println(" seseCaller = (SESEcommon*) 0x2;");
2329 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2330 exitset.add(seseExit);
2331 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2332 output.println("}\n\n");
2337 // when a new mlp thread is created for an issued SESE, it is started
2338 // by running this method which blocks on a cond variable until
2339 // it is allowed to transition to execute. Then a case statement
2340 // allows it to invoke the method with the proper SESE body, and after
2341 // exiting the SESE method, executes proper SESE exit code before the
2342 // thread can be destroyed
2343 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2344 PrintWriter outmethod
2347 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2348 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2349 outmethod.println( " int status;");
2350 outmethod.println( " char errmsg[128];");
2352 // generate a case for each SESE class that can be invoked
2353 outmethod.println( " switch( *((int*)seseRecord) ) {");
2354 outmethod.println( " ");
2355 Iterator<FlatSESEEnterNode> seseit;
2357 seseit=mlpa.getAllSESEs().iterator();
2359 seseit=oooa.getAllSESEs().iterator();
2361 while(seseit.hasNext()){
2362 FlatSESEEnterNode fsen = seseit.next();
2364 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2365 outmethod.println( " case "+fsen.getIdentifier()+":");
2366 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2368 if( (state.MLP && fsen.equals( mlpa.getMainSESE() )) ||
2369 (state.OOOJAVA && fsen.equals( oooa.getMainSESE() ))
2371 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2372 if (state.COREPROF) {
2373 outmethod.println("CP_EXIT();");
2374 outmethod.println("CP_DUMP();");
2376 outmethod.println( " exit( 0 );");
2379 outmethod.println( " break;");
2380 outmethod.println( "");
2383 // default case should never be taken, error out
2384 outmethod.println( " default:");
2385 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2386 outmethod.println( " exit(-30);");
2387 outmethod.println( " break;");
2388 outmethod.println( " }");
2389 outmethod.println( " return NULL;");
2390 outmethod.println( "}\n\n");
2394 protected void generateCode(FlatNode first,
2397 Set<FlatNode> stopset,
2398 PrintWriter output, boolean firstpass) {
2400 /* Assign labels to FlatNode's if necessary.*/
2402 Hashtable<FlatNode, Integer> nodetolabel;
2404 if (state.DELAYCOMP&&!firstpass)
2405 nodetolabel=dcassignLabels(first, stopset);
2407 nodetolabel=assignLabels(first, stopset);
2409 Set<FlatNode> storeset=null;
2410 HashSet<FlatNode> genset=null;
2411 HashSet<FlatNode> refset=null;
2412 Set<FlatNode> unionset=null;
2414 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2415 storeset=delaycomp.livecode(lb);
2416 genset=new HashSet<FlatNode>();
2417 if (state.STMARRAY&&!state.DUALVIEW) {
2418 refset=new HashSet<FlatNode>();
2419 refset.addAll(delaycomp.getDeref(lb));
2420 refset.removeAll(delaycomp.getCannotDelay(lb));
2421 refset.removeAll(delaycomp.getOther(lb));
2424 genset.addAll(delaycomp.getCannotDelay(lb));
2425 genset.addAll(delaycomp.getOther(lb));
2427 genset.addAll(delaycomp.getNotReady(lb));
2428 if (state.STMARRAY&&!state.DUALVIEW) {
2429 genset.removeAll(refset);
2432 unionset=new HashSet<FlatNode>();
2433 unionset.addAll(storeset);
2434 unionset.addAll(genset);
2435 if (state.STMARRAY&&!state.DUALVIEW)
2436 unionset.addAll(refset);
2439 /* Do the actual code generation */
2440 FlatNode current_node=null;
2441 HashSet tovisit=new HashSet();
2442 HashSet visited=new HashSet();
2444 tovisit.add(first.getNext(0));
2447 while(current_node!=null||!tovisit.isEmpty()) {
2448 if (current_node==null) {
2449 current_node=(FlatNode)tovisit.iterator().next();
2450 tovisit.remove(current_node);
2451 } else if (tovisit.contains(current_node)) {
2452 tovisit.remove(current_node);
2454 visited.add(current_node);
2455 if (nodetolabel.containsKey(current_node)) {
2456 output.println("L"+nodetolabel.get(current_node)+":");
2458 if (state.INSTRUCTIONFAILURE) {
2459 if (state.THREAD||state.DSM||state.SINGLETM) {
2460 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2462 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2464 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2466 if (!state.DELAYCOMP||firstpass) {
2467 generateFlatNode(fm, lb, current_node, output);
2469 //store primitive variables in out set
2470 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2471 Set<TempDescriptor> liveout=ar.liveout;
2472 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2473 TempDescriptor tmp=tmpit.next();
2474 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2477 if ((state.MLP || state.OOOJAVA) && stopset!=null) {
2478 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2479 assert current_node instanceof FlatSESEExitNode;
2480 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2481 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2482 assert fsen.getFlatExit().equals( fsxn );
2483 assert fsxn.getFlatEnter().equals( fsen );
2485 if (current_node.kind()!=FKind.FlatReturnNode) {
2486 output.println(" return;");
2489 } else if(current_node.numNext()==1) {
2491 if ((state.MLP|| state.OOOJAVA) &&
2492 current_node.kind()==FKind.FlatSESEEnterNode &&
2493 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2495 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2496 generateFlatNode(fm, lb, current_node, output);
2497 nextnode=fsen.getFlatExit().getNext(0);
2498 } else if (state.DELAYCOMP) {
2499 boolean specialprimitive=false;
2500 //skip literals...no need to add extra overhead
2501 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2502 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2503 if (!typedesc.isClass()&&!typedesc.isArray()) {
2504 specialprimitive=true;
2508 if (genset==null||genset.contains(current_node)||specialprimitive)
2509 generateFlatNode(fm, lb, current_node, output);
2510 if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2511 //need to acquire lock
2512 handleArrayDeref(fm, lb, current_node, output, firstpass);
2514 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2515 TempDescriptor wrtmp=current_node.writesTemps()[0];
2517 //need to store value written by previous node
2518 if (wrtmp.getType().isPtr()) {
2519 //only lock the objects that may actually need locking
2520 if (recorddc.getNeedTrans(lb, current_node)&&
2521 (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2522 wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2523 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2525 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2528 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2531 //need to read value read by previous node
2532 if (wrtmp.getType().isPtr()) {
2533 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2535 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");
2539 nextnode=current_node.getNext(0);
2542 generateFlatNode(fm, lb, current_node, output);
2543 nextnode=current_node.getNext(0);
2545 if (visited.contains(nextnode)) {
2546 output.println("goto L"+nodetolabel.get(nextnode)+";");
2549 current_node=nextnode;
2550 } else if (current_node.numNext()==2) {
2552 if (state.DELAYCOMP) {
2553 boolean computeside=false;
2555 //need to record which way it should go
2556 if (genset==null||genset.contains(current_node)) {
2557 if (storeset!=null&&storeset.contains(current_node)) {
2558 //need to store which way branch goes
2559 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2561 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2563 //which side to execute
2567 if (genset.contains(current_node)) {
2568 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2569 } else if (storeset.contains(current_node)) {
2571 branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2573 //which side to execute
2578 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2580 if (leftset.size()==0)
2582 if (visited.contains(current_node.getNext(branch))) {
2583 //already visited -- build jump
2584 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2587 current_node=current_node.getNext(branch);
2590 if (!visited.contains(current_node.getNext(1)))
2591 tovisit.add(current_node.getNext(1));
2592 if (visited.contains(current_node.getNext(0))) {
2593 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2596 current_node=current_node.getNext(0);
2600 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2601 if (!visited.contains(current_node.getNext(1)))
2602 tovisit.add(current_node.getNext(1));
2603 if (visited.contains(current_node.getNext(0))) {
2604 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2607 current_node=current_node.getNext(0);
2609 } else throw new Error();
2613 protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2614 if (fn.kind()==FKind.FlatSetElementNode) {
2615 FlatSetElementNode fsen=(FlatSetElementNode) fn;
2616 String dst=generateTemp(fm, fsen.getDst(), lb);
2617 String src=generateTemp(fm, fsen.getSrc(), lb);
2618 String index=generateTemp(fm, fsen.getIndex(), lb);
2619 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2621 if (elementtype.isArray()||elementtype.isClass())
2624 type=elementtype.getSafeSymbol()+" ";
2626 output.println("STOREARRAY("+dst+","+index+","+type+")");
2628 output.println("{");
2629 output.println(" struct ArrayObject *array;");
2630 output.println(" int index;");
2631 output.println(" RESTOREARRAY(array,index);");
2632 output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2633 output.println("}");
2635 } else if (fn.kind()==FKind.FlatElementNode) {
2636 FlatElementNode fen=(FlatElementNode) fn;
2637 String src=generateTemp(fm, fen.getSrc(), lb);
2638 String index=generateTemp(fm, fen.getIndex(), lb);
2639 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2640 String dst=generateTemp(fm, fen.getDst(), lb);
2642 if (elementtype.isArray()||elementtype.isClass())
2645 type=elementtype.getSafeSymbol()+" ";
2647 output.println("STOREARRAY("+src+","+index+","+type+")");
2649 output.println("{");
2650 output.println(" struct ArrayObject *array;");
2651 output.println(" int index;");
2652 output.println(" RESTOREARRAY(array,index);");
2653 output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2654 output.println("}");
2658 /** Special label assignment for delaycomputation */
2659 protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2660 HashSet tovisit=new HashSet();
2661 HashSet visited=new HashSet();
2663 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2665 //Label targets of branches
2666 Set<FlatNode> targets=branchanalysis.getTargets();
2667 for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2668 nodetolabel.put(it.next(), new Integer(labelindex++));
2673 /*Assign labels first. A node needs a label if the previous
2674 * node has two exits or this node is a join point. */
2676 while(!tovisit.isEmpty()) {
2677 FlatNode fn=(FlatNode)tovisit.iterator().next();
2682 if(lastset!=null&&lastset.contains(fn)) {
2683 // if last is not null and matches, don't go
2684 // any further for assigning labels
2688 for(int i=0; i<fn.numNext(); i++) {
2689 FlatNode nn=fn.getNext(i);
2692 //1) Edge >1 of node
2693 nodetolabel.put(nn,new Integer(labelindex++));
2695 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2699 nodetolabel.put(nn,new Integer(labelindex++));
2707 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2708 return assignLabels(first, null);
2711 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2712 HashSet tovisit=new HashSet();
2713 HashSet visited=new HashSet();
2715 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2718 /*Assign labels first. A node needs a label if the previous
2719 * node has two exits or this node is a join point. */
2721 while(!tovisit.isEmpty()) {
2722 FlatNode fn=(FlatNode)tovisit.iterator().next();
2727 if(lastset!=null&&lastset.contains(fn)) {
2728 // if last is not null and matches, don't go
2729 // any further for assigning labels
2733 for(int i=0; i<fn.numNext(); i++) {
2734 FlatNode nn=fn.getNext(i);
2737 //1) Edge >1 of node
2738 nodetolabel.put(nn,new Integer(labelindex++));
2740 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2744 nodetolabel.put(nn,new Integer(labelindex++));
2752 /** Generate text string that corresponds to the TempDescriptor td. */
2753 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2754 MethodDescriptor md=fm.getMethod();
2755 TaskDescriptor task=fm.getTask();
2756 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2758 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2759 return td.getSafeSymbol();
2762 if (objecttemps.isLocalPtr(td)) {
2763 return localsprefixderef+td.getSafeSymbol();
2766 if (objecttemps.isParamPtr(td)) {
2767 return paramsprefix+"->"+td.getSafeSymbol();
2773 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2775 // insert pre-node actions from the code plan
2776 if( state.MLP|| state.OOOJAVA ) {
2780 cp = mlpa.getCodePlan( fn );
2782 cp = oooa.getCodePlan(fn);
2787 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2789 // for each sese and age pair that this parent statement
2790 // must stall on, take that child's stall semaphore, the
2791 // copying of values comes after the statement
2792 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2793 while( vstItr.hasNext() ) {
2794 VariableSourceToken vst = vstItr.next();
2796 SESEandAgePair pair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2798 output.println(" {");
2799 output.println(" SESEcommon* common = (SESEcommon*) "+pair+";");
2800 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
2801 output.println(" pthread_mutex_lock( &(common->lock) );");
2802 output.println(" while( common->doneExecuting == FALSE ) {");
2803 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2804 output.println(" }");
2805 output.println(" pthread_mutex_unlock( &(common->lock) );");
2807 // copy things we might have stalled for
2808 output.println(" "+pair.getSESE().getSESErecordName()+"* child = ("+
2809 pair.getSESE().getSESErecordName()+"*) "+pair+";");
2811 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2812 while( tdItr.hasNext() ) {
2813 TempDescriptor td = tdItr.next();
2814 FlatMethod fmContext;
2815 if( currentSESE.getIsCallerSESEplaceholder() ) {
2816 fmContext = currentSESE.getfmEnclosing();
2818 fmContext = currentSESE.getfmBogus();
2820 output.println(" "+generateTemp( fmContext, td, null )+
2821 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2824 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
2825 output.println(" }");
2828 // for each variable with a dynamic source, stall just for that variable
2829 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2830 while( dynItr.hasNext() ) {
2831 TempDescriptor dynVar = dynItr.next();
2833 // only stall if the dynamic source is not yourself, denoted by src==NULL
2834 // otherwise the dynamic write nodes will have the local var up-to-date
2835 output.println(" {");
2836 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2837 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
2838 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2839 output.println(" psem_take( &(common->stallSem) );");
2841 FlatMethod fmContext;
2842 if( currentSESE.getIsCallerSESEplaceholder() ) {
2843 fmContext = currentSESE.getfmEnclosing();
2845 fmContext = currentSESE.getfmBogus();
2848 TypeDescriptor type=dynVar.getType();
2850 if( type.isNull() ) {
2852 } else if( type.isClass() || type.isArray() ) {
2853 typeStr = "struct "+type.getSafeSymbol()+"*";
2855 typeStr = type.getSafeSymbol();
2858 output.println(" "+generateTemp( fmContext, dynVar, null )+
2859 " = *(("+typeStr+"*) ("+
2860 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2861 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
2862 output.println(" }");
2863 output.println(" }");
2866 // for each assignment of a variable to rhs that has a dynamic source,
2867 // copy the dynamic sources
2868 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2869 while( dynAssignItr.hasNext() ) {
2870 Map.Entry me = (Map.Entry) dynAssignItr.next();
2871 TempDescriptor lhs = (TempDescriptor) me.getKey();
2872 TempDescriptor rhs = (TempDescriptor) me.getValue();
2873 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
2874 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2877 // for each lhs that is dynamic from a non-dynamic source, set the
2878 // dynamic source vars to the current SESE
2879 dynItr = cp.getDynAssignCurr().iterator();
2880 while( dynItr.hasNext() ) {
2881 TempDescriptor dynVar = dynItr.next();
2882 assert currentSESE.getDynamicVarSet().contains( dynVar );
2883 output.println(" "+dynVar+"_srcSESE = NULL;");
2887 // handling stall site
2888 if (state.OOOJAVA) {
2889 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(currentSESE);
2891 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
2892 Set<Analysis.OoOJava.WaitingElement> waitingElementSet =
2893 graph.getStallSiteWaitingElementSet(fn, seseLockSet);
2895 if(waitingElementSet.size()>0){
2896 output.println("// stall on parent's stall sites ");
2897 output.println(" {");
2898 output.println(" REntry* rentry;");
2900 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
2901 Analysis.OoOJava.WaitingElement waitingElement = (Analysis.OoOJava.WaitingElement) iterator.next();
2903 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
2904 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", seseCaller);");
2906 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller, (void*)&" +generateTemp(fm,waitingElement.getTempDesc(),lb)+ ");");
2908 output.println(" psem_init( &(rentry->parentStallSem) );");
2909 output.println(" rentry->queue=seseCaller->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
2911 .println(" if(ADDRENTRY(seseCaller->memoryQueueArray["+ waitingElement.getQueueID()
2912 + "],rentry)==NOTREADY){");
2913 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
2914 output.println(" psem_take( &(rentry->parentStallSem) );");
2915 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
2916 output.println(" } ");
2918 output.println(" }");
2922 ParentChildConflictsMap conflictsMap = mlpa.getConflictsResults().get(fn);
2923 if (conflictsMap != null) {
2924 Set<Long> allocSet = conflictsMap.getAllocationSiteIDSetofStallSite();
2925 if (allocSet.size() > 0) {
2926 FlatNode enclosingFlatNode=null;
2927 if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
2928 enclosingFlatNode=currentSESE.getfmEnclosing();
2930 enclosingFlatNode=currentSESE;
2932 ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
2933 HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
2934 Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
2936 if(waitingElementSet.size()>0){
2937 output.println("// stall on parent's stall sites ");
2938 output.println(" {");
2939 output.println(" REntry* rentry;");
2941 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
2942 WaitingElement waitingElement = (WaitingElement) iterator.next();
2944 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
2945 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", seseCaller);");
2947 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller, (void*)&___locals___."+ waitingElement.getDynID() + ");");
2948 // output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller, ___locals___."+ waitingElement.getDynID() + "->oid);");
2950 output.println(" psem_init( &(rentry->parentStallSem) );");
2951 output.println(" rentry->queue=seseCaller->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
2953 .println(" if(ADDRENTRY(seseCaller->memoryQueueArray["+ waitingElement.getQueueID()
2954 + "],rentry)==NOTREADY){");
2955 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
2956 output.println(" psem_take( &(rentry->parentStallSem) );");
2957 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
2958 output.println(" } ");
2960 output.println(" }");
2969 case FKind.FlatAtomicEnterNode:
2970 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
2973 case FKind.FlatAtomicExitNode:
2974 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
2977 case FKind.FlatInstanceOfNode:
2978 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
2981 case FKind.FlatSESEEnterNode:
2982 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
2985 case FKind.FlatSESEExitNode:
2986 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
2989 case FKind.FlatWriteDynamicVarNode:
2990 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
2993 case FKind.FlatGlobalConvNode:
2994 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
2997 case FKind.FlatTagDeclaration:
2998 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
3001 case FKind.FlatCall:
3002 generateFlatCall(fm, lb, (FlatCall) fn,output);
3005 case FKind.FlatFieldNode:
3006 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
3009 case FKind.FlatElementNode:
3010 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
3013 case FKind.FlatSetElementNode:
3014 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
3017 case FKind.FlatSetFieldNode:
3018 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
3022 generateFlatNew(fm, lb, (FlatNew) fn,output);
3025 case FKind.FlatOpNode:
3026 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
3029 case FKind.FlatCastNode:
3030 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
3033 case FKind.FlatLiteralNode:
3034 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
3037 case FKind.FlatReturnNode:
3038 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
3042 output.println("/* nop */");
3045 case FKind.FlatExit:
3046 output.println("/* exit */");
3049 case FKind.FlatBackEdge:
3050 if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3051 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3053 if(state.DSM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3054 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3056 if (((state.MLP|| state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
3057 || (this.state.MULTICOREGC)) {
3058 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
3059 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
3060 } else if(this.state.MULTICOREGC) {
3061 output.println("if (gcflag) gc("+localsprefixaddr+");");
3063 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3066 output.println("/* nop */");
3069 case FKind.FlatCheckNode:
3070 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
3073 case FKind.FlatFlagActionNode:
3074 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
3077 case FKind.FlatPrefetchNode:
3078 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
3081 case FKind.FlatOffsetNode:
3082 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
3089 // insert post-node actions from the code-plan
3092 CodePlan cp = mlpa.getCodePlan( fn );
3100 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
3101 output.println("/* FlatOffsetNode */");
3102 FieldDescriptor fd=fofn.getField();
3103 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
3104 output.println("/* offset */");
3107 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
3108 if (state.PREFETCH) {
3109 Vector oids = new Vector();
3110 Vector fieldoffset = new Vector();
3111 Vector endoffset = new Vector();
3112 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
3113 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
3114 PrefetchPair pp = (PrefetchPair) it.next();
3115 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
3116 /* Find prefetches that can generate oid */
3117 if(statusbase == LocalityAnalysis.GLOBAL) {
3118 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
3120 } else if (statusbase == LocalityAnalysis.LOCAL) {
3121 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
3128 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
3129 output.println("{");
3130 output.println("/* prefetch */");
3131 output.println("/* prefetchid_" + fpn.siteid + " */");
3132 output.println("void * prefptr;");
3133 output.println("int tmpindex;");
3135 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
3136 /*Create C code for oid array */
3137 output.print(" unsigned int oidarray_[] = {");
3138 boolean needcomma=false;
3139 for (Iterator it = oids.iterator(); it.hasNext();) {
3142 output.print(it.next());
3145 output.println("};");
3147 /*Create C code for endoffset values */
3148 output.print(" unsigned short endoffsetarry_[] = {");
3150 for (Iterator it = endoffset.iterator(); it.hasNext();) {
3153 output.print(it.next());
3156 output.println("};");
3158 /*Create C code for Field Offset Values */
3159 output.print(" short fieldarry_[] = {");
3161 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
3164 output.print(it.next());
3167 output.println("};");
3168 /* make the prefetch call to Runtime */
3169 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
3170 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
3171 output.println(" }");
3172 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
3173 output.println(" } else {");
3174 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
3175 output.println(" }");
3176 output.println("}");
3180 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
3181 short offsetcount = 0;
3185 } else if (localbase) {
3186 for(; breakindex<pp.desc.size(); breakindex++) {
3187 Descriptor desc=pp.getDescAt(breakindex);
3188 if (desc instanceof FieldDescriptor) {
3189 FieldDescriptor fd=(FieldDescriptor)desc;
3190 if (fd.isGlobal()) {
3198 if (breakindex>pp.desc.size()) //all local
3201 TypeDescriptor lasttype=pp.base.getType();
3202 String basestr=generateTemp(fm, pp.base, lb);
3204 boolean maybenull=fm.getMethod().isStatic()||
3205 !pp.base.equals(fm.getParameter(0));
3207 for(int i=0; i<breakindex; i++) {
3208 String indexcheck="";
3210 Descriptor desc=pp.getDescAt(i);
3211 if (desc instanceof FieldDescriptor) {
3212 FieldDescriptor fd=(FieldDescriptor)desc;
3214 if (!teststr.equals(""))
3216 teststr+="((prefptr="+basestr+")!=NULL)";
3217 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3219 basestr=basestr+"->"+fd.getSafeSymbol();
3222 lasttype=fd.getType();
3224 IndexDescriptor id=(IndexDescriptor)desc;
3225 indexcheck="((tmpindex=";
3226 for(int j=0; j<id.tddesc.size(); j++) {
3227 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3229 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3231 if (!teststr.equals(""))
3233 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3234 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3236 lasttype=lasttype.dereference();
3241 if (teststr.equals("")) {
3242 oid="((unsigned int)"+basestr+")";
3244 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3248 for(int i = breakindex; i < pp.desc.size(); i++) {
3249 String newfieldoffset;
3250 Object desc = pp.getDescAt(i);
3251 if(desc instanceof FieldDescriptor) {
3252 FieldDescriptor fd=(FieldDescriptor)desc;
3253 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3254 lasttype=fd.getType();
3256 newfieldoffset = "";
3257 IndexDescriptor id=(IndexDescriptor)desc;
3258 for(int j = 0; j < id.tddesc.size(); j++) {
3259 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3261 newfieldoffset += id.offset.toString();
3262 lasttype=lasttype.dereference();
3264 fieldoffset.add(newfieldoffset);
3267 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3268 base+=pp.desc.size()-breakindex;
3269 endoffset.add(new Short((short)base));
3274 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3275 if (lb!=fgcn.getLocality())
3277 /* Have to generate flat globalconv */
3278 if (fgcn.getMakePtr()) {
3280 //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3281 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3283 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3284 //need to do translation
3285 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3286 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3287 if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3288 output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3290 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3294 /* Need to convert to OID */
3295 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3296 if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3297 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3299 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3305 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3307 if (fion.getType().isArray()) {
3308 type=state.getArrayNumber(fion.getType())+state.numClasses();
3310 type=fion.getType().getClassDesc().getId();
3313 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3314 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3316 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3319 int sandboxcounter=0;
3320 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3321 /* Check to see if we need to generate code for this atomic */
3322 if (locality==null) {
3323 if (GENERATEPRECISEGC) {
3324 output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3325 output.println("stopforgc((struct garbagelist *) &___locals___);");
3326 output.println("pthread_mutex_lock(&atomiclock);");
3327 output.println("restartaftergc();");
3328 output.println("}");
3330 output.println("pthread_mutex_lock(&atomiclock);");
3335 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3339 if (state.SANDBOX) {
3340 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3341 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3344 if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3345 AtomicRecord ar=atomicmethodmap.get(faen);
3347 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3348 TempDescriptor tmp=tmpit.next();
3349 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3352 //copy outs that depend on path
3353 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3354 TempDescriptor tmp=tmpit.next();
3355 if (!ar.livein.contains(tmp))
3356 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3360 /* Backup the temps. */
3361 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3362 TempDescriptor tmp=tmpit.next();
3363 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3366 output.println("goto transstart"+faen.getIdentifier()+";");
3368 /******* Print code to retry aborted transaction *******/
3369 output.println("transretry"+faen.getIdentifier()+":");
3372 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3373 TempDescriptor tmp=tmpit.next();
3374 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3378 /********* Need to revert local object store ********/
3379 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3381 output.println("while ("+revertptr+") {");
3382 output.println("struct ___Object___ * tmpptr;");
3383 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3384 output.println("REVERT_OBJ("+revertptr+");");
3385 output.println(revertptr+"=tmpptr;");
3386 output.println("}");
3388 /******* Tell the runtime to start the transaction *******/
3390 output.println("transstart"+faen.getIdentifier()+":");
3391 if (state.SANDBOX) {
3392 output.println("transaction_check_counter=*counter_reset_pointer;");
3395 output.println("transStart();");
3397 if (state.ABORTREADERS||state.SANDBOX) {
3399 output.println("abortenabled=1;");
3400 output.println("if (_setjmp(aborttrans)) {");
3401 output.println(" goto transretry"+faen.getIdentifier()+"; }");
3405 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3406 /* Check to see if we need to generate code for this atomic */
3407 if (locality==null) {
3408 output.println("pthread_mutex_unlock(&atomiclock);");
3411 if (locality.getAtomic(lb).get(faen).intValue()>0)
3413 //store the revert list before we lose the transaction object
3416 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3417 output.println(revertptr+"=revertlist;");
3418 output.println("if (transCommit()) {");
3419 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3420 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3421 output.println("} else {");
3422 /* Need to commit local object store */
3423 output.println("while ("+revertptr+") {");
3424 output.println("struct ___Object___ * tmpptr;");
3425 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3426 output.println("COMMIT_OBJ("+revertptr+");");
3427 output.println(revertptr+"=tmpptr;");
3428 output.println("}");
3429 output.println("}");
3433 if (!state.DELAYCOMP) {
3435 output.println("if (transCommit()) {");
3436 /* Transaction aborts if it returns true */
3437 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3438 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3439 output.println("}");
3441 if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
3442 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3443 output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3445 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3446 TempDescriptor tmp=tmpit.next();
3447 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3449 } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3450 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3452 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3453 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3454 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3455 output.println("}");
3457 output.println("else {");
3458 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3459 TempDescriptor tmp=tmpit.next();
3460 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3462 output.println("}");
3464 output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3465 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3466 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3467 output.println("}");
3472 public void generateFlatSESEEnterNode( FlatMethod fm,
3474 FlatSESEEnterNode fsen,
3477 // if MLP flag is off, okay that SESE nodes are in IR graph,
3478 // just skip over them and code generates exactly the same
3479 if( !(state.MLP || state.OOOJAVA) ) {
3482 // there may be an SESE in an unreachable method, skip over
3483 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
3484 (state.OOOJAVA && !oooa.getAllSESEs().contains(fsen))
3489 // also, if we have encountered a placeholder, just skip it
3490 if( fsen.getIsCallerSESEplaceholder() ) {
3494 output.println(" {");
3497 //output.println("CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_BEGIN );");
3499 // set up the parent
3500 if( (state.MLP && fsen == mlpa.getMainSESE()) ||
3501 (state.OOOJAVA && fsen == oooa.getMainSESE())
3503 output.println(" SESEcommon* parentCommon = NULL;");
3505 if( fsen.getParent() == null ) {
3506 System.out.println( "in "+fm+", "+fsen+" has null parent" );
3508 assert fsen.getParent() != null;
3509 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3510 output.println(" SESEcommon* parentCommon = &("+paramsprefix+"->common);");
3512 //output.println(" SESEcommon* parentCommon = (SESEcommon*) peekItem( seseCallStack );");
3513 output.println(" SESEcommon* parentCommon = seseCaller;");
3517 // before doing anything, lock your own record and increment the running children
3518 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3519 (state.OOOJAVA && fsen != oooa.getMainSESE())
3521 output.println(" atomic_inc(&parentCommon->numRunningChildren);");
3524 // just allocate the space for this record
3525 output.println(" "+fsen.getSESErecordName()+"* seseToIssue = ("+
3526 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3527 fsen.getSESErecordName()+" ) );");
3528 //eomgc need to set next, size
3529 // output.println(" struct garbagelist * gl= (struct garbagelist *)&(((SESEcommon*)(seseToIssue))[1]);");
3530 output.println(" struct garbagelist * gl= (struct garbagelist *)&(((SESEcommon*)(seseToIssue))[1]);");
3531 // sizeof(int)*2 + sizeof(void*)*calculateSizeOfSESEParamList(fsen)
3532 //output.println(" // sizeof(int)*2+sizeof(void*)*"+calculateSizeOfSESEParamList(fsen));
3533 //output.println(" // blah="+calculateSizeOfSESEParamSize(fsen));
3534 output.println(" (seseToIssue->common).offsetsize=sizeof(int)+sizeof(void*)+sizeof(void*)*"+calculateSizeOfSESEParamList(fsen)+calculateSizeOfSESEParamSize(fsen)+";");
3535 output.println(" gl->size="+calculateSizeOfSESEParamList(fsen)+";");
3536 // output.println(" gl->next = (struct garbagelist *)&___locals___;");
3537 output.println(" seseToIssue->prevSESECount="+calculatePrevSESECount(fsen)+";");
3538 // output.println(" seseToIssue->prevSESECount=50;");
3539 output.println(" gl->next = NULL;");
3540 // output.println(" seseToIssue->size = "+calculateSizeOfSESEParamList(fsen)+";");
3541 // output.println(" seseToIssue->next = &___locals___;");
3544 // and keep the thread-local sese stack up to date
3545 //output.println(" addNewItem( seseCallStack, (void*) seseToIssue);");
3547 // fill in common data
3548 output.println(" int localCount=0;");
3549 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3550 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
3552 output.println(" seseToIssue->common.forwardList = createQueue();");
3553 output.println(" seseToIssue->common.unresolvedDependencies = 10000;");
3554 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3555 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3556 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3557 output.println(" seseToIssue->common.numRunningChildren = 0;");
3558 output.println(" seseToIssue->common.parent = parentCommon;");
3560 // all READY in-vars should be copied now and be done with it
3561 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3562 while( tempItr.hasNext() ) {
3563 TempDescriptor temp = tempItr.next();
3565 // when we are issuing the main SESE or an SESE with placeholder
3566 // caller SESE as parent, generate temp child child's eclosing method,
3567 // otherwise use the parent's enclosing method as the context
3568 boolean useParentContext = false;
3570 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3571 (state.OOOJAVA && fsen != oooa.getMainSESE())
3573 assert fsen.getParent() != null;
3574 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3575 useParentContext = true;
3579 if( useParentContext ) {
3580 output.println(" seseToIssue->"+temp+" = "+
3581 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3583 output.println(" seseToIssue->"+temp+" = "+
3584 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3588 // before potentially adding this SESE to other forwarding lists,
3589 // create it's lock and take it immediately
3590 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3591 // output.println(" pthread_mutex_lock( &(seseToIssue->common.lock) );");
3593 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3594 (state.OOOJAVA && fsen != oooa.getMainSESE())
3596 // count up outstanding dependencies, static first, then dynamic
3597 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3598 while( staticSrcsItr.hasNext() ) {
3599 SESEandAgePair srcPair = staticSrcsItr.next();
3600 output.println(" {");
3601 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3603 if(GENERATEPRECISEGC){
3604 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3606 output.println(" pthread_mutex_lock( &(src->lock) );");
3607 if(GENERATEPRECISEGC){
3608 output.println(" restartaftergc();");
3610 output.println(" if( !isEmpty( src->forwardList ) &&");
3611 output.println(" seseToIssue == peekItem( src->forwardList ) ) {");
3612 output.println(" printf( \"This shouldnt already be here\\n\");");
3613 output.println(" exit( -1 );");
3614 output.println(" }");
3615 output.println(" if( !src->doneExecuting ) {");
3616 output.println(" addNewItem( src->forwardList, seseToIssue );");
3617 // output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3618 output.println(" ++(localCount);");
3619 output.println(" }");
3620 output.println(" pthread_mutex_unlock( &(src->lock) );");
3621 output.println(" }");
3623 // whether or not it is an outstanding dependency, make sure
3624 // to pass the static name to the child's record
3625 output.println(" seseToIssue->"+srcPair+" = "+srcPair+";");
3628 // dynamic sources might already be accounted for in the static list,
3629 // so only add them to forwarding lists if they're not already there
3630 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3631 while( dynVarsItr.hasNext() ) {
3632 TempDescriptor dynInVar = dynVarsItr.next();
3633 output.println(" {");
3634 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3636 // the dynamic source is NULL if it comes from your own space--you can't pass
3637 // the address off to the new child, because you're not done executing and
3638 // might change the variable, so copy it right now
3639 output.println(" if( src != NULL ) {");
3641 if(GENERATEPRECISEGC){
3642 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3644 output.println(" pthread_mutex_lock( &(src->lock) );");
3645 if(GENERATEPRECISEGC){
3646 output.println(" restartaftergc();");
3648 output.println(" if( isEmpty( src->forwardList ) ||");
3649 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3650 output.println(" if( !src->doneExecuting ) {");
3651 output.println(" addNewItem( src->forwardList, seseToIssue );");
3652 // output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3653 output.println(" ++(localCount);");
3654 output.println(" }");
3655 output.println(" }");
3656 output.println(" pthread_mutex_unlock( &(src->lock) );");
3657 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3658 output.println(" } else {");
3660 boolean useParentContext = false;
3661 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3662 (state.OOOJAVA && fsen != oooa.getMainSESE())
3664 assert fsen.getParent() != null;
3665 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3666 useParentContext = true;
3669 if( useParentContext ) {
3670 output.println(" seseToIssue->"+dynInVar+" = "+
3671 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3673 output.println(" seseToIssue->"+dynInVar+" = "+
3674 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3677 output.println(" }");
3678 output.println(" }");
3680 // even if the value is already copied, make sure your NULL source
3681 // gets passed so child knows it already has the dynamic value
3682 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3685 // maintain pointers for finding dynamic SESE
3686 // instances from static names
3687 SESEandAgePair pair = new SESEandAgePair( fsen, 0 );
3688 if( fsen.getParent() != null &&
3689 //!fsen.getParent().getIsCallerSESEplaceholder() &&
3690 fsen.getParent().getNeededStaticNames().contains( pair )
3693 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3694 SESEandAgePair pair1 = new SESEandAgePair( fsen, i );
3695 SESEandAgePair pair2 = new SESEandAgePair( fsen, i-1 );
3696 output.println(" "+pair1+" = "+pair2+";");
3698 output.println(" "+pair+" = seseToIssue;");
3702 // count up memory conflict dependencies,
3706 FlatSESEEnterNode parent = fsen.getParent();
3707 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(parent);
3708 if (graph != null && graph.hasConflictEdge()) {
3709 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
3711 output.println(" //add memory queue element");
3712 Analysis.OoOJava.SESEWaitingQueue seseWaitingQueue=
3713 graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet);
3714 if(seseWaitingQueue.getWaitingElementSize()>0){
3715 output.println(" {");
3716 output.println(" REntry* rentry=NULL;");
3717 output.println(" INTPTR* pointer=NULL;");
3718 output.println(" seseToIssue->common.rentryIdx=0;");
3720 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
3721 for (Iterator iterator = queueIDSet.iterator(); iterator
3723 Integer key = (Integer) iterator.next();
3724 int queueID=key.intValue();
3725 Set<Analysis.OoOJava.WaitingElement> waitingQueueSet =
3726 seseWaitingQueue.getWaitingElementSet(queueID);
3727 int enqueueType=seseWaitingQueue.getType(queueID);
3728 if(enqueueType==SESEWaitingQueue.EXCEPTION){
3729 output.println(" INITIALIZEBUF(parentCommon->memoryQueueArray["
3732 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2
3734 Analysis.OoOJava.WaitingElement waitingElement
3735 = (Analysis.OoOJava.WaitingElement) iterator2.next();
3736 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
3737 output.println(" rentry=mlpCreateREntry("
3738 + waitingElement.getStatus()
3739 + ", seseToIssue);");
3741 TempDescriptor td = waitingElement
3743 // decide whether waiting element is dynamic or static
3744 if (fsen.getDynamicInVarSet().contains(td)) {
3745 // dynamic in-var case
3746 output.println(" pointer=seseToIssue->"
3747 + waitingElement.getDynID()
3748 + "_srcSESE+seseToIssue->"
3749 + waitingElement.getDynID()
3752 .println(" rentry=mlpCreateFineREntry("
3755 + ", seseToIssue, pointer );");
3756 } else if (fsen.getStaticInVarSet()
3758 // static in-var case
3759 VariableSourceToken vst = fsen
3760 .getStaticInVarSrc(td);
3763 String srcId = "SESE_"
3765 .getPrettyIdentifier()
3766 + vst.getSESE().getIdentifier()
3767 + "_" + vst.getAge();
3769 .println(" pointer=(void*)&seseToIssue->"
3776 .println(" rentry=mlpCreateFineREntry("
3779 + ", seseToIssue, pointer );");
3784 .println(" rentry=mlpCreateFineREntry("
3787 + ", seseToIssue, (void*)&seseToIssue->"
3788 + waitingElement.getDynID()
3793 .println(" rentry->queue=parentCommon->memoryQueueArray["
3794 + waitingElement.getQueueID()
3797 if(enqueueType==SESEWaitingQueue.NORMAL){
3799 .println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
3801 .println(" if(ADDRENTRY(parentCommon->memoryQueueArray["
3802 + waitingElement.getQueueID()
3803 + "],rentry)==NOTREADY){");
3804 output.println(" ++(localCount);");
3805 output.println(" }");
3808 .println(" ADDRENTRYTOBUF(parentCommon->memoryQueueArray["
3809 + waitingElement.getQueueID()
3813 if(enqueueType!=SESEWaitingQueue.NORMAL){
3814 output.println(" localCount+=RESOLVEBUF(parentCommon->memoryQueueArray["
3815 + queueID+ "],&seseToIssue->common);");
3818 output.println(" }");
3824 ConflictGraph graph = null;
3825 FlatSESEEnterNode parent = fsen.getParent();
3826 if (parent != null) {
3827 if (parent.isCallerSESEplaceholder) {
3828 graph = mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
3830 graph = mlpa.getConflictGraphResults().get(parent);
3833 if (graph != null && graph.hasConflictEdge()) {
3834 HashSet<SESELock> seseLockSet = mlpa.getConflictGraphLockMap()
3837 output.println(" //add memory queue element");
3838 SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(fsen.getIdentifier(),
3840 if(seseWaitingQueue.getWaitingElementSize()>0){
3841 output.println(" {");
3842 output.println(" REntry* rentry=NULL;");
3843 output.println(" INTPTR* pointer=NULL;");
3844 output.println(" seseToIssue->common.rentryIdx=0;");
3846 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
3847 for (Iterator iterator = queueIDSet.iterator(); iterator
3849 Integer key = (Integer) iterator.next();
3850 int queueID=key.intValue();
3851 Set<WaitingElement> waitingQueueSet = seseWaitingQueue.getWaitingElementSet(queueID);
3852 int enqueueType=seseWaitingQueue.getType(queueID);
3853 if(enqueueType==SESEWaitingQueue.EXCEPTION){
3854 output.println(" INITIALIZEBUF(parentCommon->memoryQueueArray["
3857 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2
3859 WaitingElement waitingElement = (WaitingElement) iterator2
3861 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
3862 output.println(" rentry=mlpCreateREntry("
3863 + waitingElement.getStatus()
3864 + ", seseToIssue);");
3866 TempDescriptor td = waitingElement
3868 // decide whether waiting element is dynamic or
3870 if (fsen.getDynamicInVarSet().contains(td)) {
3871 // dynamic in-var case
3872 output.println(" pointer=seseToIssue->"
3873 + waitingElement.getDynID()
3874 + "_srcSESE+seseToIssue->"
3875 + waitingElement.getDynID()
3878 .println(" rentry=mlpCreateFineREntry("
3881 + ", seseToIssue, pointer );");
3882 } else if (fsen.getStaticInVarSet()
3884 // static in-var case
3885 VariableSourceToken vst = fsen
3886 .getStaticInVarSrc(td);
3889 String srcId = "SESE_"
3891 .getPrettyIdentifier()
3892 + vst.getSESE().getIdentifier()
3893 + "_" + vst.getAge();
3895 .println(" pointer=(void*)&seseToIssue->"
3902 .println(" rentry=mlpCreateFineREntry("
3905 + ", seseToIssue, pointer );");
3910 .println(" rentry=mlpCreateFineREntry("
3913 + ", seseToIssue, (void*)&seseToIssue->"
3914 + waitingElement.getDynID()
3919 .println(" rentry->queue=parentCommon->memoryQueueArray["
3920 + waitingElement.getQueueID()
3923 if(enqueueType==SESEWaitingQueue.NORMAL){
3925 .println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
3927 .println(" if(ADDRENTRY(parentCommon->memoryQueueArray["
3928 + waitingElement.getQueueID()
3929 + "],rentry)==NOTREADY){");
3930 output.println(" ++(localCount);");
3931 output.println(" } ");
3934 .println(" ADDRENTRYTOBUF(parentCommon->memoryQueueArray["
3935 + waitingElement.getQueueID()
3939 if(enqueueType!=SESEWaitingQueue.NORMAL){
3940 output.println(" localCount+=RESOLVEBUF(parentCommon->memoryQueueArray["
3941 + queueID+ "],&seseToIssue->common);");
3944 output.println(" }");
3952 // release this SESE for siblings to update its dependencies or,
3953 // eventually, for it to mark itself finished
3954 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3956 // if there were no outstanding dependencies, issue here
3957 output.println(" if( atomic_sub_and_test(10000-localCount,&(seseToIssue->common.unresolvedDependencies) ) ) {");
3958 output.println(" workScheduleSubmit( (void*)seseToIssue );");
3959 output.println(" }");
3961 output.println(" if( seseToIssue->common.unresolvedDependencies == 0 ) {");
3962 output.println(" workScheduleSubmit( (void*)seseToIssue );");
3963 output.println(" }");
3965 // release this SESE for siblings to update its dependencies or,
3966 // eventually, for it to mark itself finished
3967 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3970 //output.println("CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_END );");
3972 output.println(" }");
3976 public void generateFlatSESEExitNode( FlatMethod fm,
3978 FlatSESEExitNode fsexn,
3982 // if MLP flag is off, okay that SESE nodes are in IR graph,
3983 // just skip over them and code generates exactly the same
3984 if( ! (state.MLP || state.OOOJAVA) ) {
3988 //output.println("CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_BEGIN );");
3990 // get the enter node for this exit that has meta data embedded
3991 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
3993 // there may be an SESE in an unreachable method, skip over
3994 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
3995 (state.OOOJAVA && !oooa.getAllSESEs().contains( fsen ))
4000 // also, if we have encountered a placeholder, just jump it
4001 if( fsen.getIsCallerSESEplaceholder() ) {
4005 output.println(" /* SESE exiting */");
4007 String com = paramsprefix+"->common";
4009 // this SESE cannot be done until all of its children are done
4010 // so grab your own lock with the condition variable for watching
4011 // that the number of your running children is greater than zero
4012 if (GENERATEPRECISEGC){
4013 output.println(" stopforgc((struct garbagelist *)&___locals___);");
4015 output.println(" pthread_mutex_lock( &("+com+".lock) );");
4016 if (GENERATEPRECISEGC){
4017 output.println(" restartaftergc();");
4019 output.println(" while( "+com+".numRunningChildren > 0 ) {");
4020 if (GENERATEPRECISEGC){
4021 // output.println(" stopforgc((struct garbagelist *)&(((SESEcommon*)(___params___))[1]));");
4022 output.println(" stopforgc((struct garbagelist *)&___locals___);");
4024 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
4025 if (GENERATEPRECISEGC){
4026 output.println(" restartaftergc();");
4028 output.println(" }");
4031 // copy out-set from local temps into the sese record
4032 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
4033 while( itr.hasNext() ) {
4034 TempDescriptor temp = itr.next();
4036 // only have to do this for primitives non-arrays
4038 temp.getType().isPrimitive() && !temp.getType().isArray()
4044 // have to determine the context enclosing this sese
4045 boolean useParentContext = false;
4047 if( (state.MLP &&fsen != mlpa.getMainSESE()) ||
4048 (state.OOOJAVA &&fsen != oooa.getMainSESE())
4050 assert fsen.getParent() != null;
4051 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
4052 useParentContext = true;
4057 if( useParentContext ) {
4058 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
4060 from = generateTemp( fsen.getfmEnclosing(), temp, null );
4063 output.println(" "+paramsprefix+
4064 "->"+temp.getSafeSymbol()+
4068 // mark yourself done, your SESE data is now read-only
4069 output.println(" "+com+".doneExecuting = TRUE;");
4070 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
4071 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
4073 // decrement dependency count for all SESE's on your forwarding list
4074 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
4075 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
4078 output.println(" if(consumer->rentryIdx>0){");
4079 output.println(" // resolved null pointer");
4080 output.println(" int idx;");
4081 output.println(" for(idx=0;idx<consumer->rentryIdx;idx++){");
4082 output.println(" resolvePointer(consumer->rentryArray[idx]);");
4083 output.println(" }");
4084 output.println(" }");
4087 // output.println(" pthread_mutex_lock( &(consumer->lock) );");
4088 // output.println(" --(consumer->unresolvedDependencies);");
4089 // output.println(" if( consumer->unresolvedDependencies == 0 ) {");
4090 output.println(" if( atomic_sub_and_test(1, &(consumer->unresolvedDependencies)) ){");
4091 output.println(" workScheduleSubmit( (void*)consumer );");
4092 output.println(" }");
4093 // output.println(" pthread_mutex_unlock( &(consumer->lock) );");
4094 output.println(" }");
4098 // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
4099 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4100 (state.OOOJAVA && fsen != oooa.getMainSESE())
4104 output.println(" /* check memory dependency*/");
4105 output.println(" {");
4106 output.println(" int idx;");
4107 output.println(" for(idx=0;idx<___params___->common.rentryIdx;idx++){");
4108 output.println(" REntry* re=___params___->common.rentryArray[idx];");
4109 output.println(" RETIRERENTRY(re->queue,re);");
4110 output.println(" }");
4111 output.println(" }");
4115 // if parent is stalling on you, let them know you're done
4116 if( (state.MLP && fsexn.getFlatEnter() != mlpa.getMainSESE()) ||
4117 (state.OOOJAVA && fsexn.getFlatEnter() != oooa.getMainSESE())
4119 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
4122 // last of all, decrement your parent's number of running children
4123 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
4124 output.println(" if (atomic_sub_and_test(1, &"+paramsprefix+"->common.parent->numRunningChildren)) {");
4125 if (GENERATEPRECISEGC){
4126 output.println(" stopforgc((struct garbagelist *)&___locals___);");
4128 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
4129 if (GENERATEPRECISEGC){
4130 output.println(" restartaftergc();");
4132 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
4133 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
4134 output.println(" }");
4135 output.println(" }");
4137 // this is a thread-only variable that can be handled when critical sese-to-sese
4138 // data has been taken care of--set sese pointer to remember self over method
4139 // calls to a non-zero, invalid address
4140 output.println(" seseCaller = (SESEcommon*) 0x1;");
4143 //output.println("CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_END );");
4146 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
4148 FlatWriteDynamicVarNode fwdvn,
4151 if( !(state.MLP || state.OOOJAVA) ) {
4152 // should node should not be in an IR graph if the
4153 // MLP flag is not set
4154 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
4157 Hashtable<TempDescriptor, VSTWrapper> writeDynamic = fwdvn.getVar2src();
4159 assert writeDynamic != null;
4161 Iterator wdItr = writeDynamic.entrySet().iterator();
4162 while( wdItr.hasNext() ) {
4163 Map.Entry me = (Map.Entry) wdItr.next();
4164 TempDescriptor refVar = (TempDescriptor) me.getKey();
4165 VSTWrapper vstW = (VSTWrapper) me.getValue();
4166 VariableSourceToken vst = vstW.vst;
4169 // only do this if the variable in question should be tracked,
4170 // meaning that it was explicitly added to the dynamic var set
4171 if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
4177 // if there is no given source, this variable is ready so
4178 // mark src pointer NULL to signify that the var is up-to-date
4179 output.println(" "+refVar+"_srcSESE = NULL;");
4183 // otherwise we track where it will come from
4184 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
4185 output.println(" "+refVar+"_srcSESE = "+instance+";");
4186 output.println(" "+refVar+"_srcOffset = (int) &((("+
4187 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
4192 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
4193 if (state.CONSCHECK) {
4194 String specname=fcn.getSpec();
4195 String varname="repairstate___";
4196 output.println("{");
4197 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
4199 TempDescriptor[] temps=fcn.getTemps();
4200 String[] vars=fcn.getVars();
4201 for(int i=0; i<temps.length; i++) {
4202 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
4205 output.println("if (doanalysis"+specname+"("+varname+")) {");
4206 output.println("free"+specname+"_state("+varname+");");
4207 output.println("} else {");
4208 output.println("/* Bad invariant */");
4209 output.println("free"+specname+"_state("+varname+");");
4210 output.println("abort_task();");
4211 output.println("}");
4212 output.println("}");
4216 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
4218 if( (state.MLP && !nonSESEpass) ||
4219 (state.OOOJAVA && !nonSESEpass)
4221 output.println(" seseCaller = (SESEcommon*)"+paramsprefix+";");
4224 MethodDescriptor md=fc.getMethod();
4225 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
4226 ClassDescriptor cn=md.getClassDesc();
4227 output.println("{");
4228 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4230 LocalityBinding fclb=locality.getBinding(lb, fc);
4231 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4233 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4234 output.print(objectparams.numPointers());
4235 output.print(", "+localsprefixaddr);
4236 if (md.getThis()!=null) {
4238 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
4240 if (fc.getThis()!=null&&md.getThis()==null) {
4241 System.out.println("WARNING!!!!!!!!!!!!");
4242 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
4246 for(int i=0; i<fc.numArgs(); i++) {
4247 Descriptor var=md.getParameter(i);
4248 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4249 if (objectparams.isParamPtr(paramtemp)) {
4250 TempDescriptor targ=fc.getArg(i);
4252 TypeDescriptor td=md.getParamType(i);
4254 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4256 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4259 output.println("};");
4264 if (fc.getReturnTemp()!=null)
4265 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
4267 /* Do we need to do virtual dispatch? */
4268 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
4271 LocalityBinding fclb=locality.getBinding(lb, fc);
4272 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4274 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4279 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4280 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4282 output.print(md.getReturnType().getSafeSymbol()+" ");
4283 output.print("(*)(");
4285 boolean printcomma=false;
4286 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4288 LocalityBinding fclb=locality.getBinding(lb, fc);
4289 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4291 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4295 for(int i=0; i<objectparams.numPrimitives(); i++) {
4296 TempDescriptor temp=objectparams.getPrimitive(i);
4300 if (temp.getType().isClass()||temp.getType().isArray())
4301 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
4303 output.print(temp.getType().getSafeSymbol());
4308 LocalityBinding fclb=locality.getBinding(lb, fc);
4309 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
4311 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
4315 boolean needcomma=false;
4316 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4317 output.print("&__parameterlist__");
4321 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4322 if (fc.getThis()!=null) {
4323 TypeDescriptor ptd=md.getThis().getType();
4326 if (ptd.isClass()&&!ptd.isArray())
4327 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4328 output.print(generateTemp(fm,fc.getThis(),lb));
4333 for(int i=0; i<fc.numArgs(); i++) {
4334 Descriptor var=md.getParameter(i);
4335 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4336 if (objectparams.isParamPrim(paramtemp)) {
4337 TempDescriptor targ=fc.getArg(i);
4341 TypeDescriptor ptd=md.getParamType(i);
4342 if (ptd.isClass()&&!ptd.isArray())
4343 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4344 output.print(generateTemp(fm, targ,lb));
4348 output.println(");");
4349 output.println(" }");
4352 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
4353 Set subclasses=typeutil.getSubClasses(thiscd);
4354 if (subclasses==null)
4356 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
4357 ClassDescriptor cd=(ClassDescriptor)classit.next();
4358 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
4359 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
4360 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
4361 if (md.matches(matchmd))
4368 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
4369 if (state.SINGLETM) {
4370 //single machine transactional memory case
4371 String field=ffn.getField().getSafeSymbol();
4372 String src=generateTemp(fm, ffn.getSrc(),lb);
4373 String dst=generateTemp(fm, ffn.getDst(),lb);
4375 output.println(dst+"="+ src +"->"+field+ ";");
4376 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
4377 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
4378 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
4379 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
4380 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
4381 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
4382 if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
4383 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4385 output.println("TRANSREADRD("+dst+", "+dst+");");
4388 } else if (state.DSM) {
4389 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
4390 if (status==LocalityAnalysis.GLOBAL) {
4391 String field=ffn.getField().getSafeSymbol();
4392 String src=generateTemp(fm, ffn.getSrc(),lb);
4393 String dst=generateTemp(fm, ffn.getDst(),lb);
4395 if (ffn.getField().getType().isPtr()) {
4397 //TODO: Uncomment this when we have runtime support
4398 //if (ffn.getSrc()==ffn.getDst()) {
4399 //output.println("{");
4400 //output.println("void * temp="+src+";");
4401 //output.println("if (temp&0x1) {");
4402 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
4403 //output.println(src+"->"+field+"="+temp+";");
4404 //output.println("}");
4405 //output.println(dst+"=temp;");
4406 //output.println("}");
4408 output.println(dst+"="+ src +"->"+field+ ";");
4409 //output.println("if ("+dst+"&0x1) {");
4410 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4411 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4412 //output.println(src+"->"+field+"="+src+"->"+field+";");
4413 //output.println("}");
4416 output.println(dst+"="+ src+"->"+field+";");
4418 } else if (status==LocalityAnalysis.LOCAL) {
4419 if (ffn.getField().getType().isPtr()&&
4420 ffn.getField().isGlobal()) {
4421 String field=ffn.getField().getSafeSymbol();
4422 String src=generateTemp(fm, ffn.getSrc(),lb);
4423 String dst=generateTemp(fm, ffn.getDst(),lb);
4424 output.println(dst+"="+ src +"->"+field+ ";");
4425 if (locality.getAtomic(lb).get(ffn).intValue()>0)
4426 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4427 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4429 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4430 } else if (status==LocalityAnalysis.EITHER) {
4431 //Code is reading from a null pointer
4432 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
4433 output.println("#ifndef RAW");
4434 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4435 output.println("#endif");
4436 //This should throw a suitable null pointer error
4437 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4439 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4441 // DEBUG if(!ffn.getDst().getType().isPrimitive()){
4442 // DEBUG output.println("within((void*)"+generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+");");
4444 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4449 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
4450 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
4451 throw new Error("Can't set array length");
4452 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4453 //Single Machine Transaction Case
4454 boolean srcptr=fsfn.getSrc().getType().isPtr();
4455 String src=generateTemp(fm,fsfn.getSrc(),lb);
4456 String dst=generateTemp(fm,fsfn.getDst(),lb);
4457 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
4458 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
4459 output.println("{");
4460 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
4461 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
4462 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4464 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4467 if (wb.needBarrier(fsfn)&&
4468 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
4469 if (state.EVENTMONITOR) {
4470 output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
4472 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
4474 if (srcptr&!fsfn.getSrc().getType().isNull()) {
4475 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4476 output.println("}");
4478 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4480 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4481 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
4482 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
4483 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4485 String src=generateTemp(fm,fsfn.getSrc(),lb);
4486 String dst=generateTemp(fm,fsfn.getDst(),lb);
4488 output.println("{");
4489 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4491 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
4494 if (wb.needBarrier(fsfn))
4495 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
4497 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4499 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4500 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
4501 /** Check if we need to copy */
4502 output.println("if(!"+dst+"->"+localcopystr+") {");
4503 /* Link object into list */
4504 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4505 output.println(revertptr+"=revertlist;");
4506 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4507 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4509 output.println("COPY_OBJ("+dst+");");
4510 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4511 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4512 output.println("}");
4514 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4516 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4517 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
4518 //writing to a null...bad
4519 output.println("if ("+dst+") {");
4520 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
4522 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4524 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4527 output.println("}");
4530 if (state.FASTCHECK) {
4531 String dst=generateTemp(fm, fsfn.getDst(),lb);
4532 output.println("if(!"+dst+"->"+localcopystr+") {");
4533 /* Link object into list */
4534 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4535 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4537 output.println("COPY_OBJ("+dst+");");
4538 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4539 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4540 output.println("}");
4543 // DEBUG if(!fsfn.getField().getType().isPrimitive()){
4544 // DEBUG output.println("within((void*)"+generateTemp(fm,fsfn.getSrc(),lb)+");");
4546 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4550 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
4551 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
4554 if (elementtype.isArray()||elementtype.isClass())
4557 type=elementtype.getSafeSymbol()+" ";
4559 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
4560 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
4561 output.println("failedboundschk();");
4563 if (state.SINGLETM) {
4564 //Single machine transaction case
4565 String dst=generateTemp(fm, fen.getDst(),lb);
4566 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))) {
4567 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4569 output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
4572 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
4573 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
4574 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
4575 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
4576 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
4577 if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
4578 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4580 output.println("TRANSREADRD("+dst+", "+dst+");");
4583 } else if (state.DSM) {
4584 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
4585 if (status==LocalityAnalysis.GLOBAL) {
4586 String dst=generateTemp(fm, fen.getDst(),lb);
4587 if (elementtype.isPtr()) {
4588 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4589 //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
4590 output.println("TRANSREAD("+dst+", "+dst+");");
4592 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4594 } else if (status==LocalityAnalysis.LOCAL) {
4595 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4596 } else if (status==LocalityAnalysis.EITHER) {
4597 //Code is reading from a null pointer
4598 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
4599 output.println("#ifndef RAW");
4600 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4601 output.println("#endif");
4602 //This should throw a suitable null pointer error
4603 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4605 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4607 // DEBUG output.println("within((void*)"+generateTemp(fm,fen.getSrc(),lb)+");");
4608 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4612 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
4613 //TODO: need dynamic check to make sure this assignment is actually legal
4614 //Because Object[] could actually be something more specific...ie. Integer[]
4616 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
4619 if (elementtype.isArray()||elementtype.isClass())
4622 type=elementtype.getSafeSymbol()+" ";
4624 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
4625 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
4626 output.println("failedboundschk();");
4629 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4630 //Transaction set element case
4631 if (wb.needBarrier(fsen)&&
4632 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
4633 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
4635 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
4636 output.println("{");
4637 String src=generateTemp(fm, fsen.getSrc(), lb);
4638 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
4639 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
4640 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4642 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4644 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4645 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
4647 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4649 output.println("}");
4651 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4652 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
4654 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4657 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4658 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
4659 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
4660 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4661 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
4662 boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
4665 if (wb.needBarrier(fsen))
4666 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
4667 } else if (dstlocal) {
4668 /** Check if we need to copy */
4669 String dst=generateTemp(fm, fsen.getDst(),lb);
4670 output.println("if(!"+dst+"->"+localcopystr+") {");
4671 /* Link object into list */
4672 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4673 output.println(revertptr+"=revertlist;");
4674 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
4675 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4677 output.println("COPY_OBJ("+dst+");");
4678 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4679 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4680 output.println("}");
4682 System.out.println("Node: "+fsen);
4683 System.out.println(lb);
4684 System.out.println("statusdst="+statusdst);
4685 System.out.println(fm.printMethod());
4686 throw new Error("Unknown array type");
4689 output.println("{");
4690 String src=generateTemp(fm, fsen.getSrc(), lb);
4691 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4692 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4693 output.println("}");
4695 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4698 if (state.FASTCHECK) {
4699 String dst=generateTemp(fm, fsen.getDst(),lb);
4700 output.println("if(!"+dst+"->"+localcopystr+") {");
4701 /* Link object into list */
4702 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4703 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4705 output.println("COPY_OBJ("+dst+");");
4706 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4707 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4708 output.println("}");
4710 // DEBUG output.println("within((void*)"+generateTemp(fm,fsen.getDst(),lb)+");");
4711 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4715 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
4716 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4717 //Stash pointer in case of GC
4718 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4719 output.println(revertptr+"=revertlist;");
4721 if (state.SINGLETM) {
4722 if (fn.getType().isArray()) {
4723 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4724 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4725 //inside transaction
4726 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4728 //outside transaction
4729 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4732 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4733 //inside transaction
4734 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4736 //outside transaction
4737 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4740 } else if (fn.getType().isArray()) {
4741 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4742 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4743 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4744 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4745 if(this.state.MLP || state.OOOJAVA){
4746 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray_mlp("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
4747 output.println(" oid += numWorkers;");
4749 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4752 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4755 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4756 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
4757 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4758 if (this.state.MLP || state.OOOJAVA){
4759 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new_mlp("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
4760 output.println(" oid += numWorkers;");
4762 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4765 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
4768 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4769 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4770 String dst=generateTemp(fm,fn.getDst(),lb);
4771 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4772 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4773 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4775 if (state.FASTCHECK) {
4776 String dst=generateTemp(fm,fn.getDst(),lb);
4777 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4778 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4779 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4783 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
4784 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4785 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
4787 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
4791 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
4792 if (fon.getRight()!=null) {
4793 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
4794 if (fon.getLeft().getType().isLong())
4795 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4797 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4799 } else if (dc!=null) {
4800 output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
4801 if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4802 output.print("(void *)");
4803 if (dc.getNeedLeftSrcTrans(lb, fon))
4804 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
4806 output.print(generateTemp(fm, fon.getLeft(),lb));
4807 output.print(")"+fon.getOp().toString()+"(");
4808 if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4809 output.print("(void *)");
4810 if (dc.getNeedRightSrcTrans(lb, fon))
4811 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
4813 output.println(generateTemp(fm,fon.getRight(),lb)+");");
4815 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
4816 } else if (fon.getOp().getOp()==Operation.ASSIGN)
4817 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4818 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
4819 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4820 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
4821 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
4822 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
4823 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
4824 else if (fon.getOp().getOp()==Operation.COMP)
4825 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
4826 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
4827 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
4829 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
4832 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
4833 /* TODO: Do type check here */
4834 if (fcn.getType().isArray()) {
4835 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4836 } else if (fcn.getType().isClass())
4837 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4839 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
4842 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
4843 if (fln.getValue()==null)
4844 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4845 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
4846 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4847 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4848 //Stash pointer in case of GC
4849 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4850 output.println(revertptr+"=revertlist;");
4852 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4853 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4854 //Stash pointer in case of GC
4855 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4856 output.println("revertlist="+revertptr+";");
4859 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4861 } else if (fln.getType().isBoolean()) {
4862 if (((Boolean)fln.getValue()).booleanValue())
4863 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
4865 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4866 } else if (fln.getType().isChar()) {
4867 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
4868 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
4869 } else if (fln.getType().isLong()) {
4870 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
4872 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
4875 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
4876 if (frn.getReturnTemp()!=null) {
4877 if (frn.getReturnTemp().getType().isPtr())
4878 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4880 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4882 output.println("return;");
4886 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4889 //only record if this group has more than one exit
4890 if (branchanalysis.numJumps(fcb)>1) {
4891 left=branchanalysis.jumpValue(fcb, 0);
4892 right=branchanalysis.jumpValue(fcb, 1);
4894 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
4896 output.println("STOREBRANCH("+right+");");
4897 output.println("goto "+label+";");
4898 output.println("}");
4900 output.println("STOREBRANCH("+left+");");
4903 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4904 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
4907 /** This method generates header information for the method or
4908 * task referenced by the Descriptor des. */
4909 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
4910 generateHeader(fm, lb, des, output, false);
4913 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
4915 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
4916 MethodDescriptor md=null;
4917 TaskDescriptor task=null;
4918 if (des instanceof MethodDescriptor)
4919 md=(MethodDescriptor) des;
4921 task=(TaskDescriptor) des;
4923 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
4925 if (md!=null&&md.getReturnType()!=null) {
4926 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4927 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4929 output.print(md.getReturnType().getSafeSymbol()+" ");
4931 //catch the constructor case
4932 output.print("void ");
4934 if (state.DSM||state.SINGLETM) {
4935 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4937 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4939 output.print(task.getSafeSymbol()+"(");
4941 boolean printcomma=false;
4942 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4944 if (state.DSM||state.SINGLETM) {
4945 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4947 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4949 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
4955 for(int i=0; i<objectparams.numPrimitives(); i++) {
4956 TempDescriptor temp=objectparams.getPrimitive(i);
4960 if (temp.getType().isClass()||temp.getType().isArray())
4961 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
4963 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
4965 output.println(") {");
4966 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4967 /* Imprecise Task */
4968 output.println("void * parameterarray[]) {");
4969 /* Unpack variables */
4970 for(int i=0; i<objectparams.numPrimitives(); i++) {
4971 TempDescriptor temp=objectparams.getPrimitive(i);
4972 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
4974 for(int i=0; i<fm.numTags(); i++) {
4975 TempDescriptor temp=fm.getTag(i);
4976 int offset=i+objectparams.numPrimitives();
4977 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
4980 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
4981 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
4982 } else output.println(") {");
4985 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
4986 output.println("/* FlatFlagActionNode */");
4989 /* Process tag changes */
4990 Relation tagsettable=new Relation();
4991 Relation tagcleartable=new Relation();
4993 Iterator tagsit=ffan.getTempTagPairs();
4994 while (tagsit.hasNext()) {
4995 TempTagPair ttp=(TempTagPair) tagsit.next();
4996 TempDescriptor objtmp=ttp.getTemp();
4997 TagDescriptor tag=ttp.getTag();
4998 TempDescriptor tagtmp=ttp.getTagTemp();
4999 boolean tagstatus=ffan.getTagChange(ttp);
5001 tagsettable.put(objtmp, tagtmp);
5003 tagcleartable.put(objtmp, tagtmp);
5008 Hashtable flagandtable=new Hashtable();
5009 Hashtable flagortable=new Hashtable();
5011 /* Process flag changes */
5012 Iterator flagsit=ffan.getTempFlagPairs();
5013 while(flagsit.hasNext()) {
5014 TempFlagPair tfp=(TempFlagPair)flagsit.next();
5015 TempDescriptor temp=tfp.getTemp();
5016 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
5017 FlagDescriptor flag=tfp.getFlag();
5019 //Newly allocate objects that don't set any flags case
5020 if (flagortable.containsKey(temp)) {
5024 flagortable.put(temp,new Integer(mask));
5026 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
5027 boolean flagstatus=ffan.getFlagChange(tfp);
5030 if (flagortable.containsKey(temp)) {
5031 mask=((Integer)flagortable.get(temp)).intValue();
5034 flagortable.put(temp,new Integer(mask));
5036 int mask=0xFFFFFFFF;
5037 if (flagandtable.containsKey(temp)) {
5038 mask=((Integer)flagandtable.get(temp)).intValue();
5040 mask&=(0xFFFFFFFF^flagid);
5041 flagandtable.put(temp,new Integer(mask));
5047 HashSet flagtagset=new HashSet();
5048 flagtagset.addAll(flagortable.keySet());
5049 flagtagset.addAll(flagandtable.keySet());
5050 flagtagset.addAll(tagsettable.keySet());
5051 flagtagset.addAll(tagcleartable.keySet());
5053 Iterator ftit=flagtagset.iterator();
5054 while(ftit.hasNext()) {
5055 TempDescriptor temp=(TempDescriptor)ftit.next();
5058 Set tagtmps=tagcleartable.get(temp);
5059 if (tagtmps!=null) {
5060 Iterator tagit=tagtmps.iterator();
5061 while(tagit.hasNext()) {
5062 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5063 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5064 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5066 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5070 tagtmps=tagsettable.get(temp);
5071 if (tagtmps!=null) {
5072 Iterator tagit=tagtmps.iterator();
5073 while(tagit.hasNext()) {
5074 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5075 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5076 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5078 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
5083 int andmask=0xFFFFFFF;
5085 if (flagortable.containsKey(temp))
5086 ormask=((Integer)flagortable.get(temp)).intValue();
5087 if (flagandtable.containsKey(temp))
5088 andmask=((Integer)flagandtable.get(temp)).intValue();
5089 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
5090 generateObjectDistribute(ffan, fm, lb, temp, output);
5094 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
5095 PrintWriter output, int ormask, int andmask) {
5096 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
5097 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5099 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5103 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
5104 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
5107 void generateOptionalHeader(PrintWriter headers) {
5110 headers.println("#include \"task.h\"\n\n");
5111 headers.println("#ifndef _OPTIONAL_STRUCT_");
5112 headers.println("#define _OPTIONAL_STRUCT_");
5114 //STRUCT PREDICATEMEMBER
5115 headers.println("struct predicatemember{");
5116 headers.println("int type;");
5117 headers.println("int numdnfterms;");
5118 headers.println("int * flags;");
5119 headers.println("int numtags;");
5120 headers.println("int * tags;\n};\n\n");
5122 //STRUCT OPTIONALTASKDESCRIPTOR
5123 headers.println("struct optionaltaskdescriptor{");
5124 headers.println("struct taskdescriptor * task;");
5125 headers.println("int index;");
5126 headers.println("int numenterflags;");
5127 headers.println("int * enterflags;");
5128 headers.println("int numpredicatemembers;");
5129 headers.println("struct predicatemember ** predicatememberarray;");
5130 headers.println("};\n\n");
5132 //STRUCT TASKFAILURE
5133 headers.println("struct taskfailure {");
5134 headers.println("struct taskdescriptor * task;");
5135 headers.println("int index;");
5136 headers.println("int numoptionaltaskdescriptors;");
5137 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5139 //STRUCT FSANALYSISWRAPPER
5140 headers.println("struct fsanalysiswrapper{");
5141 headers.println("int flags;");
5142 headers.println("int numtags;");
5143 headers.println("int * tags;");
5144 headers.println("int numtaskfailures;");
5145 headers.println("struct taskfailure ** taskfailurearray;");
5146 headers.println("int numoptionaltaskdescriptors;");
5147 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5149 //STRUCT CLASSANALYSISWRAPPER
5150 headers.println("struct classanalysiswrapper{");
5151 headers.println("int type;");
5152 headers.println("int numotd;");
5153 headers.println("struct optionaltaskdescriptor ** otdarray;");
5154 headers.println("int numfsanalysiswrappers;");
5155 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
5157 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
5159 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
5160 while(taskit.hasNext()) {
5161 TaskDescriptor td=(TaskDescriptor)taskit.next();
5162 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
5167 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
5168 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
5169 int predicateindex = 0;
5170 //iterate through the classes concerned by the predicate
5171 Set c_vard = predicate.vardescriptors;
5172 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
5175 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
5176 VarDescriptor vard = (VarDescriptor)vard_it.next();
5177 TypeDescriptor typed = vard.getType();
5179 //generate for flags
5180 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
5181 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5183 if (fen_hashset!=null) {
5184 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
5185 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
5187 DNFFlag dflag=fen.getDNF();
5188 numberterms+=dflag.size();
5190 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
5192 for(int j=0; j<dflag.size(); j++) {
5194 output.println(",");
5195 Vector term=dflag.get(j);
5198 for(int k=0; k<term.size(); k++) {
5199 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
5200 FlagDescriptor fd=dfa.getFlag();
5201 boolean negated=dfa.getNegated();
5202 int flagid=1<<((Integer)flags.get(fd)).intValue();
5207 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
5212 output.println("};\n");
5215 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
5216 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5219 for(int j=0; j<tagel.numTags(); j++) {
5221 output.println(",");
5222 TempDescriptor tmp=tagel.getTemp(j);
5223 if (!slotnumber.containsKey(tmp)) {
5224 Integer slotint=new Integer(current_slot++);
5225 slotnumber.put(tmp,slotint);
5227 int slot=slotnumber.get(tmp).intValue();
5228 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
5230 numtags = tagel.numTags();
5232 output.println("};");
5234 //store the result into a predicatemember struct
5235 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5236 output.println("/*type*/"+typed.getClassDesc().getId()+",");
5237 output.println("/* number of dnf terms */"+numberterms+",");
5238 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5239 output.println("/* number of tag */"+numtags+",");
5240 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5241 output.println("};\n");
5246 //generate an array that stores the entire predicate
5247 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5248 for( int j = 0; j<predicateindex; j++) {
5249 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5250 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5252 output.println("};\n");
5253 return predicateindex;
5257 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
5258 generateOptionalHeader(headers);
5260 output.println("#include \"optionalstruct.h\"\n\n");
5261 output.println("#include \"stdlib.h\"\n");
5263 HashSet processedcd = new HashSet();
5265 Enumeration e = safeexecution.keys();
5266 while (e.hasMoreElements()) {
5269 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
5270 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
5272 //Generate the struct of optionals
5273 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5274 numotd = c_otd.size();
5275 if(maxotd<numotd) maxotd = numotd;
5276 if( !c_otd.isEmpty() ) {
5277 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5278 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5280 //generate the int arrays for the predicate
5281 Predicate predicate = otd.predicate;
5282 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
5283 TreeSet<Integer> fsset=new TreeSet<Integer>();
5284 //iterate through possible FSes corresponding to
5285 //the state when entering
5287 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
5288 FlagState fs = (FlagState)fses.next();
5290 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5291 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5292 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5295 fsset.add(new Integer(flagid));
5296 //tag information not needed because tag
5297 //changes are not tolerated.
5300 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5301 boolean needcomma=false;
5302 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
5305 output.println(it.next());
5308 output.println("};\n");
5311 //generate optionaltaskdescriptor that actually
5312 //includes exit fses, predicate and the task
5314 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5315 output.println("&task_"+otd.td.getSafeSymbol()+",");
5316 output.println("/*index*/"+otd.getIndex()+",");
5317 output.println("/*number of enter flags*/"+fsset.size()+",");
5318 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5319 output.println("/*number of members */"+predicateindex+",");
5320 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5321 output.println("};\n");
5325 // if there are no optionals, there is no need to build the rest of the struct
5327 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
5328 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5329 if( !c_otd.isEmpty() ) {
5330 boolean needcomma=false;
5331 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5332 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5334 output.println(",");
5336 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5339 output.println("};\n");
5341 //get all the possible flagstates reachable by an object
5342 Hashtable hashtbtemp = safeexecution.get(cdtemp);
5344 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
5345 fsts.addAll(hashtbtemp.keySet());
5346 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
5347 FlagState fs = (FlagState)fsit.next();
5350 //get the set of OptionalTaskDescriptors corresponding
5351 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
5352 //iterate through the OptionalTaskDescriptors and
5353 //store the pointers to the optionals struct (see on
5354 //top) into an array
5356 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
5357 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
5358 OptionalTaskDescriptor mm = mos.next();
5360 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
5362 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5365 output.println("};\n");
5367 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
5370 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5371 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5372 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5376 //process tag information
5379 boolean first = true;
5380 Enumeration tag_enum = fs.getTags();
5381 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5382 while(tag_enum.hasMoreElements()) {
5384 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
5388 output.println(", ");
5389 output.println("/*tagid*/"+state.getTagId(tagd));
5391 output.println("};");
5393 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
5394 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5395 TaskIndex ti=itti.next();
5399 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
5401 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
5402 boolean needcomma=false;
5403 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
5404 OptionalTaskDescriptor otd=otdit.next();
5408 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5410 output.println("};");
5412 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
5413 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
5414 output.print(ti.getIndex()+", ");
5415 output.print(otdset.size()+", ");
5416 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
5417 output.println("};");
5420 tiset=sa.getTaskIndex(fs);
5421 boolean needcomma=false;
5423 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5424 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5425 TaskIndex ti=itti.next();
5426 if (ti.isRuntime()) {
5433 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
5435 output.println("};\n");
5437 //Store the result in fsanalysiswrapper
5439 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
5440 output.println("/*flag*/"+flagid+",");
5441 output.println("/* number of tags*/"+tagcounter+",");
5442 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5443 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
5444 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5445 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
5446 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
5447 output.println("};\n");
5451 //Build the array of fsanalysiswrappers
5452 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
5453 boolean needcomma=false;
5454 for(int i = 0; i<fscounter; i++) {
5455 if (needcomma) output.print(",");
5456 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
5459 output.println("};");
5461 //Build the classanalysiswrapper referring to the previous array
5462 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
5463 output.println("/*type*/"+cdtemp.getId()+",");
5464 output.println("/*numotd*/"+numotd+",");
5465 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
5466 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
5467 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
5468 processedcd.add(cdtemp);
5471 //build an array containing every classes for which code has been build
5472 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
5473 for(int i=0; i<state.numClasses(); i++) {
5474 ClassDescriptor cn=cdarray[i];
5477 if ((cn != null) && (processedcd.contains(cn)))
5478 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
5480 output.print("NULL");
5482 output.println("};");
5484 output.println("#define MAXOTD "+maxotd);
5485 headers.println("#endif");
5488 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
5489 Relation r=new Relation();
5490 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
5491 OptionalTaskDescriptor otd=otdit.next();
5492 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
5496 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
5497 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
5498 Set s=r.get(it.next());
5499 for(Iterator it2=s.iterator(); it2.hasNext();) {
5500 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
5508 protected void outputTransCode(PrintWriter output) {
5511 private int calculateSizeOfSESEParamList(FlatSESEEnterNode fsen){
5513 Set<TempDescriptor> tdSet=new HashSet<TempDescriptor>();
5515 for (Iterator iterator = fsen.getInVarSet().iterator(); iterator.hasNext();) {
5516 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5517 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5518 tdSet.add(tempDescriptor);
5522 for (Iterator iterator = fsen.getOutVarSet().iterator(); iterator.hasNext();) {
5523 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5524 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5525 tdSet.add(tempDescriptor);
5529 return tdSet.size();
5532 private String calculateSizeOfSESEParamSize(FlatSESEEnterNode fsen){
5533 HashMap <String,Integer> map=new HashMap();
5534 HashSet <TempDescriptor> processed=new HashSet<TempDescriptor>();
5537 // space for all in and out set primitives
5538 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
5539 inSetAndOutSet.addAll( fsen.getInVarSet() );
5540 inSetAndOutSet.addAll( fsen.getOutVarSet() );
5542 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
5544 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
5545 while( itr.hasNext() ) {
5546 TempDescriptor temp = itr.next();
5547 TypeDescriptor type = temp.getType();
5548 if( !type.isPtr() ) {
5549 inSetAndOutSetPrims.add( temp );
5553 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
5554 while( itrPrims.hasNext() ) {
5555 TempDescriptor temp = itrPrims.next();
5556 TypeDescriptor type = temp.getType();
5557 if(type.isPrimitive()){
5558 Integer count=map.get(type.getSymbol());
5560 count=new Integer(1);
5561 map.put(type.getSymbol(), count);
5563 map.put(type.getSymbol(), new Integer(count.intValue()+1));
5568 Set<String> keySet=map.keySet();
5569 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
5570 String key = (String) iterator.next();
5571 rtr+="+sizeof("+key+")*"+map.get(key);
5576 private int calculatePrevSESECount(FlatSESEEnterNode fsen){
5580 Iterator<TempDescriptor>itrDynInVars = fsen.getDynamicInVarSet().iterator();
5581 while( itrDynInVars.hasNext() ) {
5582 TempDescriptor dynInVar = itrDynInVars.next();
5586 // in-set source tracking
5587 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
5588 while( itrStaticInVarSrcs.hasNext() ) {
5589 SESEandAgePair srcPair = itrStaticInVarSrcs.next();