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.ReachGraph;
27 import Analysis.OoOJava.OoOJavaAnalysis;
28 import Analysis.Prefetch.*;
29 import Analysis.Loops.WriteBarrier;
30 import Analysis.Loops.GlobalFieldType;
31 import Analysis.Locality.TypeAnalysis;
32 import Analysis.MLP.ConflictGraph;
33 import Analysis.MLP.ConflictNode;
34 import Analysis.MLP.MLPAnalysis;
35 import Analysis.MLP.ParentChildConflictsMap;
36 import Analysis.MLP.SESELock;
37 import Analysis.MLP.SESEWaitingQueue;
38 import Analysis.MLP.VariableSourceToken;
39 import Analysis.MLP.VSTWrapper;
40 import Analysis.MLP.CodePlan;
41 import Analysis.MLP.SESEandAgePair;
42 import Analysis.MLP.WaitingElement;
44 public class BuildCode {
47 Hashtable paramstable;
52 String localsprefix="___locals___";
53 String localsprefixaddr="&"+localsprefix;
54 String localsprefixderef=localsprefix+".";
55 String fcrevert="___fcrevert___";
56 String paramsprefix="___params___";
57 String oidstr="___nextobject___";
58 String nextobjstr="___nextobject___";
59 String localcopystr="___localcopy___";
60 public static boolean GENERATEPRECISEGC=false;
61 public static String PREFIX="";
62 public static String arraytype="ArrayObject";
63 public static int flagcount = 0;
66 protected int maxtaskparams=0;
67 private int maxcount=0;
68 ClassDescriptor[] cdarray;
69 TypeDescriptor[] arraytable;
70 LocalityAnalysis locality;
71 Hashtable<LocalityBinding, TempDescriptor> reverttable;
72 Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>> backuptable;
77 String mlperrstr = "if(status != 0) { "+
78 "sprintf(errmsg, \"MLP error at %s:%d\", __FILE__, __LINE__); "+
79 "perror(errmsg); exit(-1); }";
80 boolean nonSESEpass=true;
83 DiscoverConflicts recorddc;
88 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa) {
89 this(st, temptovar, typeutil, null, sa, pa, null, null);
92 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
93 this(st, temptovar, typeutil, null, sa, pa, mlpa, oooa);
96 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
97 this(st, temptovar, typeutil, locality, null, pa, mlpa, oooa);
100 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
106 callgraph=new CallGraph(state);
108 oidstr="___objlocation___";
109 this.temptovar=temptovar;
110 paramstable=new Hashtable();
111 tempstable=new Hashtable();
112 fieldorder=new Hashtable();
113 flagorder=new Hashtable();
114 this.typeutil=typeutil;
115 virtualcalls=new Virtual(state,locality);
116 if (locality!=null) {
117 this.locality=locality;
118 this.reverttable=new Hashtable<LocalityBinding, TempDescriptor>();
119 this.backuptable=new Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>>();
120 this.wb=new WriteBarrier(locality, st);
122 if (state.SINGLETM&&state.DCOPTS) {
123 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
124 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
125 this.dc=new DiscoverConflicts(locality, st, typeanalysis, gft);
128 if (state.DELAYCOMP) {
129 //TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
130 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
131 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
132 delaycomp=new DCWrapper(locality, st, typeanalysis, gft);
133 dc=delaycomp.getConflicts();
134 recorddc=new DiscoverConflicts(locality, st, typeanalysis, delaycomp.getCannotDelayMap(), true, true, null);
135 recorddc.doAnalysis();
139 /** The buildCode method outputs C code for all the methods. The Flat
140 * versions of the methods must already be generated and stored in
141 * the State object. */
142 PrintWriter outsandbox=null;
144 public void buildCode() {
145 /* Create output streams to write to */
146 PrintWriter outclassdefs=null;
147 PrintWriter outstructs=null;
148 PrintWriter outrepairstructs=null;
149 PrintWriter outmethodheader=null;
150 PrintWriter outmethod=null;
151 PrintWriter outvirtual=null;
152 PrintWriter outtask=null;
153 PrintWriter outtaskdefs=null;
154 PrintWriter outoptionalarrays=null;
155 PrintWriter optionalheaders=null;
159 outsandbox=new PrintWriter(new FileOutputStream(PREFIX+"sandboxdefs.c"), true);
161 outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
162 outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
163 outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
164 outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
165 outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
167 outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
168 outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
169 if (state.OPTIONAL) {
170 outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
171 optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
174 if (state.structfile!=null) {
175 outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
177 } catch (Exception e) {
182 /* Build the virtual dispatch tables */
183 buildVirtualTables(outvirtual);
185 /* Output includes */
186 outmethodheader.println("#ifndef METHODHEADERS_H");
187 outmethodheader.println("#define METHODHEADERS_H");
188 outmethodheader.println("#include \"structdefs.h\"");
190 outmethodheader.println("#include \"dstm.h\"");
192 outmethodheader.println("#include \"sandbox.h\"");
194 if (state.EVENTMONITOR) {
195 outmethodheader.println("#include \"monitor.h\"");
197 if (state.SINGLETM) {
198 outmethodheader.println("#include \"tm.h\"");
199 outmethodheader.println("#include \"delaycomp.h\"");
200 outmethodheader.println("#include \"inlinestm.h\"");
202 if (state.ABORTREADERS) {
203 outmethodheader.println("#include \"abortreaders.h\"");
204 outmethodheader.println("#include <setjmp.h>");
206 if (state.MLP || state.OOOJAVA) {
207 outmethodheader.println("#include <stdlib.h>");
208 outmethodheader.println("#include <stdio.h>");
209 outmethodheader.println("#include <string.h>");
210 outmethodheader.println("#include \"mlp_runtime.h\"");
211 outmethodheader.println("#include \"psemaphore.h\"");
214 /* Output Structures */
215 outputStructs(outstructs);
217 // Output the C class declarations
218 // These could mutually reference each other
219 outputClassDeclarations(outclassdefs);
221 // Output function prototypes and structures for parameters
222 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
223 while(it.hasNext()) {
224 ClassDescriptor cn=(ClassDescriptor)it.next();
225 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader);
227 outclassdefs.close();
230 /* Map flags to integers */
231 /* The runtime keeps track of flags using these integers */
232 it=state.getClassSymbolTable().getDescriptorsIterator();
233 while(it.hasNext()) {
234 ClassDescriptor cn=(ClassDescriptor)it.next();
238 generateTaskStructs(outstructs, outmethodheader);
240 /* Outputs generic task structures if this is a task
242 outputTaskTypes(outtask);
245 if( state.MLP || state.OOOJAVA) {
246 // have to initialize some SESE compiler data before
247 // analyzing normal methods, which must happen before
248 // generating SESE internal code
250 Iterator<FlatSESEEnterNode> seseit;
252 seseit=mlpa.getAllSESEs().iterator();
254 seseit=oooa.getAllSESEs().iterator();
256 while(seseit.hasNext()){
257 FlatSESEEnterNode fsen = seseit.next();
258 initializeSESE( fsen );
262 // FlatMethod fm=fsen.getfmEnclosing();
263 // ReachGraph rg=oooa.getDisjointAnalysis().getReachGraph(fm.getMethod());
270 /* Build the actual methods */
271 outputMethods(outmethod);
273 // Output function prototypes and structures for SESE's and code
274 if( state.MLP || state.OOOJAVA ) {
276 // used to differentiate, during code generation, whether we are
277 // passing over SESE body code, or non-SESE code
280 // first generate code for each sese's internals
281 Iterator<FlatSESEEnterNode> seseit;
283 seseit=mlpa.getAllSESEs().iterator();
285 seseit=oooa.getAllSESEs().iterator();
288 while(seseit.hasNext()) {
289 FlatSESEEnterNode fsen = seseit.next();
290 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
293 // then write the invokeSESE switch to decouple scheduler
294 // from having to do unique details of sese invocation
295 generateSESEinvocationMethod(outmethodheader, outmethod);
299 /* Output code for tasks */
300 outputTaskCode(outtaskdefs, outmethod);
302 /* Record maximum number of task parameters */
303 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
304 } else if (state.main!=null) {
305 /* Generate main method */
306 outputMainMethod(outmethod);
309 /* Generate information for task with optional parameters */
310 if (state.TASK&&state.OPTIONAL) {
311 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
312 outoptionalarrays.close();
315 /* Output structure definitions for repair tool */
316 if (state.structfile!=null) {
317 buildRepairStructs(outrepairstructs);
318 outrepairstructs.close();
322 outmethodheader.println("#endif");
323 outmethodheader.close();
325 outstructs.println("#endif");
330 /* This code just generates the main C method for java programs.
331 * The main C method packs up the arguments into a string array
332 * and passes it to the java main method. */
334 private void outputMainMethod(PrintWriter outmethod) {
335 outmethod.println("int main(int argc, const char *argv[]) {");
336 outmethod.println(" int i;");
338 if (state.MLP || state.OOOJAVA) {
339 //outmethod.println(" pthread_once( &mlpOnceObj, mlpInitOncePerThread );");
341 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
345 if (state.DSMRECOVERYSTATS) {
346 outmethod.println("#ifdef RECOVERYSTATS \n");
347 outmethod.println("handle();\n");
348 outmethod.println("#endif\n");
350 outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
351 outmethod.println("handle();\n");
352 outmethod.println("#endif\n");
356 if (state.THREAD||state.DSM||state.SINGLETM) {
357 outmethod.println("initializethreads();");
360 outmethod.println("if (dstmStartup(argv[1])) {");
361 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
362 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
364 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
367 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
368 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
370 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
374 outmethod.println(" for(i=2;i<argc;i++) {");
376 outmethod.println(" for(i=1;i<argc;i++) {");
377 outmethod.println(" int length=strlen(argv[i]);");
378 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
379 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
381 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
384 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
386 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
387 outmethod.println(" }");
389 MethodDescriptor md=typeutil.getMain();
390 ClassDescriptor cd=typeutil.getMainClass();
392 outmethod.println(" {");
393 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
394 if (state.DSM||state.SINGLETM) {
395 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
397 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
398 outmethod.println("1, NULL,"+"stringarray};");
399 if (state.DSM||state.SINGLETM)
400 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
402 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
404 if (state.DSM||state.SINGLETM)
405 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
407 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
409 outmethod.println(" }");
412 outmethod.println("}");
415 if (state.THREAD||state.DSM||state.SINGLETM) {
416 outmethod.println("pthread_mutex_lock(&gclistlock);");
417 outmethod.println("threadcount--;");
418 outmethod.println("pthread_cond_signal(&gccond);");
419 outmethod.println("pthread_mutex_unlock(&gclistlock);");
422 if (state.DSM||state.SINGLETM) {
423 //outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
424 outmethod.println("#if defined(TRANSSTATS) \n");
425 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
426 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
427 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
428 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
430 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
431 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
432 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
433 outmethod.println("printf(\"ndirtyCacheObj= %d\\n\", ndirtyCacheObj);");
434 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
435 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
436 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
437 outmethod.println("printf(\"totalObjSize= %d\\n\", totalObjSize);");
438 outmethod.println("printf(\"sendRemoteReq= %d\\n\", sendRemoteReq);");
439 outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
440 } else if (state.SINGLETM) {
441 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
442 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
443 outmethod.println("#ifdef STMSTATS\n");
444 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
445 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
446 outmethod.println("}\n");
447 outmethod.println("#endif\n");
448 outmethod.println("fflush(stdout);");
450 outmethod.println("#endif\n");
453 if (state.EVENTMONITOR) {
454 outmethod.println("dumpdata();");
457 if (state.THREAD||state.SINGLETM)
458 outmethod.println("pthread_exit(NULL);");
460 if (state.MLP || state.OOOJAVA ) {
461 outmethod.println(" workScheduleBegin();");
464 outmethod.println("}");
467 /* This method outputs code for each task. */
469 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
470 /* Compile task based program */
471 outtaskdefs.println("#include \"task.h\"");
472 outtaskdefs.println("#include \"methodheaders.h\"");
473 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
474 while(taskit.hasNext()) {
475 TaskDescriptor td=(TaskDescriptor)taskit.next();
476 FlatMethod fm=state.getMethodFlat(td);
477 generateFlatMethod(fm, null, outmethod);
478 generateTaskDescriptor(outtaskdefs, fm, td);
481 //Output task descriptors
482 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
483 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
485 while(taskit.hasNext()) {
486 TaskDescriptor td=(TaskDescriptor)taskit.next();
490 outtaskdefs.println(",");
491 outtaskdefs.print("&task_"+td.getSafeSymbol());
493 outtaskdefs.println("};");
495 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
498 /* This method outputs most of the methods.c file. This includes
499 * some standard includes and then an array with the sizes of
500 * objets and array that stores supertype and then the code for
501 * the Java methods.. */
503 protected void outputMethods(PrintWriter outmethod) {
504 outmethod.println("#include \"methodheaders.h\"");
505 outmethod.println("#include \"virtualtable.h\"");
506 outmethod.println("#include \"runtime.h\"");
508 outmethod.println("#include \"sandboxdefs.c\"");
511 outmethod.println("#include \"addPrefetchEnhance.h\"");
512 outmethod.println("#include \"localobjects.h\"");
514 if (state.FASTCHECK) {
515 outmethod.println("#include \"localobjects.h\"");
517 if(state.MULTICORE) {
518 outmethod.println("#include \"task.h\"");
519 outmethod.println("#include \"multicoreruntime.h\"");
520 outmethod.println("#include \"runtime_arch.h\"");
522 if (state.THREAD||state.DSM||state.SINGLETM)
523 outmethod.println("#include <thread.h>");
524 if (state.main!=null) {
525 outmethod.println("#include <string.h>");
527 if (state.CONSCHECK) {
528 outmethod.println("#include \"checkers.h\"");
530 if (state.MLP || state.OOOJAVA ) {
531 outmethod.println("#include <stdlib.h>");
532 outmethod.println("#include <stdio.h>");
533 outmethod.println("#include \"mlp_runtime.h\"");
534 outmethod.println("#include \"psemaphore.h\"");
536 if (state.COREPROF) {
537 outmethod.println("#include \"coreprof\\coreprof.h\"");
540 //Store the sizes of classes & array elements
541 generateSizeArray(outmethod);
543 //Store table of supertypes
544 generateSuperTypeTable(outmethod);
546 //Store the layout of classes
547 generateLayoutStructs(outmethod);
549 /* Generate code for methods */
550 if (state.DSM||state.SINGLETM) {
551 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
552 LocalityBinding lb=lbit.next();
553 MethodDescriptor md=lb.getMethod();
554 FlatMethod fm=state.getMethodFlat(md);
556 if (!md.getModifiers().isNative()) {
557 generateFlatMethod(fm, lb, outmethod);
558 //System.out.println("fm= " + fm + " md= " + md);
562 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
563 while(classit.hasNext()) {
564 ClassDescriptor cn=(ClassDescriptor)classit.next();
565 Iterator methodit=cn.getMethods();
566 while(methodit.hasNext()) {
567 /* Classify parameters */
568 MethodDescriptor md=(MethodDescriptor)methodit.next();
569 FlatMethod fm=state.getMethodFlat(md);
570 if (!md.getModifiers().isNative()) {
571 generateFlatMethod(fm, null, outmethod);
578 protected void outputStructs(PrintWriter outstructs) {
579 outstructs.println("#ifndef STRUCTDEFS_H");
580 outstructs.println("#define STRUCTDEFS_H");
581 outstructs.println("#include \"classdefs.h\"");
582 outstructs.println("#ifndef INTPTR");
583 outstructs.println("#ifdef BIT64");
584 outstructs.println("#define INTPTR long");
585 outstructs.println("#else");
586 outstructs.println("#define INTPTR int");
587 outstructs.println("#endif");
588 outstructs.println("#endif");
589 if( state.MLP || state.OOOJAVA ) {
590 outstructs.println("#include \"mlp_runtime.h\"");
591 outstructs.println("#include \"psemaphore.h\"");
594 /* Output #defines that the runtime uses to determine type
595 * numbers for various objects it needs */
596 outstructs.println("#define MAXCOUNT "+maxcount);
597 if (state.DSM||state.SINGLETM) {
598 LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
600 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
602 else if (state.SINGLETM) {
603 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
605 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
609 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
611 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
612 else if( state.SINGLETM)
613 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
614 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
617 outstructs.println("#define STRINGARRAYTYPE "+
618 (state.getArrayNumber(
619 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
621 outstructs.println("#define OBJECTARRAYTYPE "+
622 (state.getArrayNumber(
623 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
626 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
627 outstructs.println("#define CHARARRAYTYPE "+
628 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
630 outstructs.println("#define BYTEARRAYTYPE "+
631 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
633 outstructs.println("#define BYTEARRAYARRAYTYPE "+
634 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
636 outstructs.println("#define NUMCLASSES "+state.numClasses());
637 int totalClassSize = state.numClasses() + state.numArrays();
638 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
640 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
641 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
642 outstructs.println("#define TAGARRAYTYPE "+
643 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
647 protected void outputClassDeclarations(PrintWriter outclassdefs) {
648 if (state.THREAD||state.DSM||state.SINGLETM)
649 outclassdefs.println("#include <pthread.h>");
650 outclassdefs.println("#ifndef INTPTR");
651 outclassdefs.println("#ifdef BIT64");
652 outclassdefs.println("#define INTPTR long");
653 outclassdefs.println("#else");
654 outclassdefs.println("#define INTPTR int");
655 outclassdefs.println("#endif");
656 outclassdefs.println("#endif");
658 outclassdefs.println("#include \"optionalstruct.h\"");
659 outclassdefs.println("struct "+arraytype+";");
660 /* Start by declaring all structs */
661 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
662 while(it.hasNext()) {
663 ClassDescriptor cn=(ClassDescriptor)it.next();
664 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
666 outclassdefs.println("");
667 //Print out definition for array type
668 outclassdefs.println("struct "+arraytype+" {");
669 outclassdefs.println(" int type;");
670 if(state.MLP || state.OOOJAVA ){
671 outclassdefs.println(" int oid;");
673 if (state.EVENTMONITOR) {
674 outclassdefs.println(" int objuid;");
677 outclassdefs.println(" pthread_t tid;");
678 outclassdefs.println(" void * lockentry;");
679 outclassdefs.println(" int lockcount;");
682 outclassdefs.println(" int flag;");
683 if(!state.MULTICORE) {
684 outclassdefs.println(" void * flagptr;");
686 outclassdefs.println(" int version;");
687 outclassdefs.println(" int * lock;"); // lock entry for this obj
688 outclassdefs.println(" int mutex;");
689 outclassdefs.println(" int lockcount;");
690 if(state.MULTICOREGC) {
691 outclassdefs.println(" int marked;");
695 outclassdefs.println(" int numfses;");
696 outclassdefs.println(" int * fses;");
699 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
701 if (state.STMARRAY) {
702 outclassdefs.println(" int lowindex;");
703 outclassdefs.println(" int highindex;");
706 outclassdefs.println(" int paddingforarray;");
707 if (state.DUALVIEW) {
708 outclassdefs.println(" int arrayversion;");
711 outclassdefs.println(" int ___length___;");
712 outclassdefs.println("};\n");
713 outclassdefs.println("extern int classsize[];");
714 outclassdefs.println("extern int hasflags[];");
715 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
716 outclassdefs.println("extern int supertypes[];");
719 /** Prints out definitions for generic task structures */
721 private void outputTaskTypes(PrintWriter outtask) {
722 outtask.println("#ifndef _TASK_H");
723 outtask.println("#define _TASK_H");
724 outtask.println("struct parameterdescriptor {");
725 outtask.println("int type;");
726 outtask.println("int numberterms;");
727 outtask.println("int *intarray;");
728 outtask.println("void * queue;");
729 outtask.println("int numbertags;");
730 outtask.println("int *tagarray;");
731 outtask.println("};");
733 outtask.println("struct taskdescriptor {");
734 outtask.println("void * taskptr;");
735 outtask.println("int numParameters;");
736 outtask.println(" int numTotal;");
737 outtask.println("struct parameterdescriptor **descriptorarray;");
738 outtask.println("char * name;");
739 outtask.println("};");
740 outtask.println("extern struct taskdescriptor * taskarray[];");
741 outtask.println("extern numtasks;");
742 outtask.println("#endif");
746 private void buildRepairStructs(PrintWriter outrepairstructs) {
747 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
748 while(classit.hasNext()) {
749 ClassDescriptor cn=(ClassDescriptor)classit.next();
750 outrepairstructs.println("structure "+cn.getSymbol()+" {");
751 outrepairstructs.println(" int __type__;");
753 outrepairstructs.println(" int __flag__;");
754 if(!state.MULTICORE) {
755 outrepairstructs.println(" int __flagptr__;");
758 printRepairStruct(cn, outrepairstructs);
759 outrepairstructs.println("}\n");
762 for(int i=0; i<state.numArrays(); i++) {
763 TypeDescriptor tdarray=arraytable[i];
764 TypeDescriptor tdelement=tdarray.dereference();
765 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
766 outrepairstructs.println(" int __type__;");
767 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
768 outrepairstructs.println(" int length;");
770 // Need to add support to repair tool for this
771 if (tdelement.isClass()||tdelement.isArray())
772 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
774 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
776 outrepairstructs.println("}\n");
780 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
781 ClassDescriptor sp=cn.getSuperDesc();
783 printRepairStruct(sp, output);
785 Vector fields=(Vector)fieldorder.get(cn);
787 for(int i=0; i<fields.size(); i++) {
788 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
789 if (fd.getType().isArray()) {
790 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
791 } else if (fd.getType().isClass())
792 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
793 else if (fd.getType().isFloat())
794 output.println(" int "+fd.getSymbol()+"; /* really float */");
796 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
800 /** This method outputs TaskDescriptor information */
801 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
802 for (int i=0; i<task.numParameters(); i++) {
803 VarDescriptor param_var=task.getParameter(i);
804 TypeDescriptor param_type=task.getParamType(i);
805 FlagExpressionNode param_flag=task.getFlag(param_var);
806 TagExpressionList param_tag=task.getTag(param_var);
809 if (param_flag==null) {
810 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
811 output.println("0x0, 0x0 };");
814 DNFFlag dflag=param_flag.getDNF();
815 dnfterms=dflag.size();
817 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
818 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
819 for(int j=0; j<dflag.size(); j++) {
822 Vector term=dflag.get(j);
825 for(int k=0; k<term.size(); k++) {
826 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
827 FlagDescriptor fd=dfa.getFlag();
828 boolean negated=dfa.getNegated();
829 int flagid=1<<((Integer)flags.get(fd)).intValue();
834 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
836 output.println("};");
839 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
840 //BUG...added next line to fix, test with any task program
842 for(int j=0; j<param_tag.numTags(); j++) {
845 /* for each tag we need */
846 /* which slot it is */
847 /* what type it is */
848 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
849 TempDescriptor tmp=param_tag.getTemp(j);
850 int slot=fm.getTagInt(tmp);
851 output.println(slot+", "+state.getTagId(tvd.getTag()));
853 output.println("};");
855 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
856 output.println("/* type */"+param_type.getClassDesc().getId()+",");
857 output.println("/* number of DNF terms */"+dnfterms+",");
858 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
859 output.println("0,");
860 //BUG, added next line to fix and else statement...test
861 //with any task program
863 output.println("/* number of tags */"+param_tag.numTags()+",");
865 output.println("/* number of tags */ 0,");
866 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
867 output.println("};");
871 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
872 for (int i=0; i<task.numParameters(); i++) {
875 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
877 output.println("};");
879 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
880 output.println("&"+task.getSafeSymbol()+",");
881 output.println("/* number of parameters */" +task.numParameters() + ",");
882 int numtotal=task.numParameters()+fm.numTags();
883 output.println("/* number total parameters */" +numtotal + ",");
884 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
885 output.println("\""+task.getSymbol()+"\"");
886 output.println("};");
890 /** The buildVirtualTables method outputs the virtual dispatch
891 * tables for methods. */
893 protected void buildVirtualTables(PrintWriter outvirtual) {
894 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
895 while(classit.hasNext()) {
896 ClassDescriptor cd=(ClassDescriptor)classit.next();
897 if (virtualcalls.getMethodCount(cd)>maxcount)
898 maxcount=virtualcalls.getMethodCount(cd);
900 MethodDescriptor[][] virtualtable=null;
901 LocalityBinding[][] lbvirtualtable=null;
902 if (state.DSM||state.SINGLETM)
903 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
905 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
907 /* Fill in virtual table */
908 classit=state.getClassSymbolTable().getDescriptorsIterator();
909 while(classit.hasNext()) {
910 ClassDescriptor cd=(ClassDescriptor)classit.next();
911 if (state.DSM||state.SINGLETM)
912 fillinRow(cd, lbvirtualtable, cd.getId());
914 fillinRow(cd, virtualtable, cd.getId());
917 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
918 Iterator arrayit=state.getArrayIterator();
919 while(arrayit.hasNext()) {
920 TypeDescriptor td=(TypeDescriptor)arrayit.next();
921 int id=state.getArrayNumber(td);
922 if (state.DSM||state.SINGLETM)
923 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
925 fillinRow(objectcd, virtualtable, id+state.numClasses());
928 outvirtual.print("void * virtualtable[]={");
929 boolean needcomma=false;
930 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
931 for(int j=0; j<maxcount; j++) {
933 outvirtual.print(", ");
934 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
935 LocalityBinding lb=lbvirtualtable[i][j];
936 MethodDescriptor md=lb.getMethod();
937 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
938 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
939 MethodDescriptor md=virtualtable[i][j];
940 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
942 outvirtual.print("0");
946 outvirtual.println("");
948 outvirtual.println("};");
952 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
953 /* Get inherited methods */
954 if (cd.getSuperDesc()!=null)
955 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
956 /* Override them with our methods */
957 for(Iterator it=cd.getMethods(); it.hasNext();) {
958 MethodDescriptor md=(MethodDescriptor)it.next();
959 if (md.isStatic()||md.getReturnType()==null)
961 int methodnum=virtualcalls.getMethodNumber(md);
962 virtualtable[rownum][methodnum]=md;
966 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
967 /* Get inherited methods */
968 if (cd.getSuperDesc()!=null)
969 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
970 /* Override them with our methods */
971 if (locality.getClassBindings(cd)!=null)
972 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
973 LocalityBinding lb=lbit.next();
974 MethodDescriptor md=lb.getMethod();
975 //Is the method static or a constructor
976 if (md.isStatic()||md.getReturnType()==null)
978 int methodnum=virtualcalls.getLocalityNumber(lb);
979 virtualtable[rownum][methodnum]=lb;
983 /** Generate array that contains the sizes of class objects. The
984 * object allocation functions in the runtime use this
987 private void generateSizeArray(PrintWriter outclassdefs) {
988 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
989 outclassdefs.print("#ifdef TRANSSTATS \n");
990 outclassdefs.print("extern int numTransAbort;\n");
991 outclassdefs.print("extern int numTransCommit;\n");
992 outclassdefs.print("extern int nSoftAbort;\n");
994 outclassdefs.print("extern int nchashSearch;\n");
995 outclassdefs.print("extern int nmhashSearch;\n");
996 outclassdefs.print("extern int nprehashSearch;\n");
997 outclassdefs.print("extern int ndirtyCacheObj;\n");
998 outclassdefs.print("extern int nRemoteSend;\n");
999 outclassdefs.print("extern int sendRemoteReq;\n");
1000 outclassdefs.print("extern int getResponse;\n");
1001 outclassdefs.print("extern int bytesSent;\n");
1002 outclassdefs.print("extern int bytesRecv;\n");
1003 outclassdefs.print("extern int totalObjSize;\n");
1004 outclassdefs.print("extern void handle();\n");
1005 } else if (state.SINGLETM) {
1006 outclassdefs.println("extern int nSoftAbortAbort;");
1007 outclassdefs.println("extern int nSoftAbortCommit;");
1008 outclassdefs.println("#ifdef STMSTATS\n");
1009 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
1010 outclassdefs.println("#endif\n");
1012 outclassdefs.print("#endif\n");
1014 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
1015 if(this.state.MLP || state.OOOJAVA ){
1016 outclassdefs.print("extern __thread int oid;\n");
1017 outclassdefs.print("extern int numWorkers;\n");
1020 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1021 cdarray=new ClassDescriptor[state.numClasses()];
1023 while(it.hasNext()) {
1024 ClassDescriptor cd=(ClassDescriptor)it.next();
1025 cdarray[cd.getId()]=cd;
1028 arraytable=new TypeDescriptor[state.numArrays()];
1030 Iterator arrayit=state.getArrayIterator();
1031 while(arrayit.hasNext()) {
1032 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1033 int id=state.getArrayNumber(td);
1039 /* Print out types */
1040 outclassdefs.println("/* ");
1041 for(int i=0; i<state.numClasses(); i++) {
1042 ClassDescriptor cd=cdarray[i];
1044 outclassdefs.println("NULL " + i);
1046 outclassdefs.println(cd +" "+i);
1050 for(int i=0; i<state.numArrays(); i++) {
1051 TypeDescriptor arraytd=arraytable[i];
1052 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
1055 outclassdefs.println("*/");
1058 outclassdefs.print("int classsize[]={");
1060 boolean needcomma=false;
1061 for(int i=0; i<state.numClasses(); i++) {
1063 outclassdefs.print(", ");
1065 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1067 outclassdefs.print("0");
1073 for(int i=0; i<state.numArrays(); i++) {
1075 outclassdefs.print(", ");
1076 TypeDescriptor tdelement=arraytable[i].dereference();
1077 if (tdelement.isArray()||tdelement.isClass())
1078 outclassdefs.print("sizeof(void *)");
1080 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1084 outclassdefs.println("};");
1086 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1088 outclassdefs.print("int typearray[]={");
1089 for(int i=0; i<state.numClasses(); i++) {
1090 ClassDescriptor cd=cdarray[i];
1091 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1093 outclassdefs.print(", ");
1095 outclassdefs.print("-1");
1097 outclassdefs.print(supercd.getId());
1101 for(int i=0; i<state.numArrays(); i++) {
1102 TypeDescriptor arraytd=arraytable[i];
1103 ClassDescriptor arraycd=arraytd.getClassDesc();
1104 if (arraycd==null) {
1106 outclassdefs.print(", ");
1107 outclassdefs.print(objectclass.getId());
1111 ClassDescriptor cd=arraycd.getSuperDesc();
1114 TypeDescriptor supertd=new TypeDescriptor(cd);
1115 supertd.setArrayCount(arraytd.getArrayCount());
1116 type=state.getArrayNumber(supertd);
1118 type+=state.numClasses();
1121 cd=cd.getSuperDesc();
1124 outclassdefs.print(", ");
1125 outclassdefs.print(type);
1129 outclassdefs.println("};");
1134 outclassdefs.print("int typearray2[]={");
1135 for(int i=0; i<state.numArrays(); i++) {
1136 TypeDescriptor arraytd=arraytable[i];
1137 ClassDescriptor arraycd=arraytd.getClassDesc();
1138 if (arraycd==null) {
1140 outclassdefs.print(", ");
1141 outclassdefs.print("-1");
1145 ClassDescriptor cd=arraycd.getSuperDesc();
1146 int level=arraytd.getArrayCount()-1;
1148 for(; level>0; level--) {
1149 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1150 supertd.setArrayCount(level);
1151 type=state.getArrayNumber(supertd);
1153 type+=state.numClasses();
1158 outclassdefs.print(", ");
1159 outclassdefs.print(type);
1163 outclassdefs.println("};");
1166 /** Constructs params and temp objects for each method or task.
1167 * These objects tell the compiler which temps need to be
1170 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1171 MethodDescriptor md=fm.getMethod();
1172 TaskDescriptor task=fm.getTask();
1173 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1174 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1176 paramstable.put(lb, objectparams);
1177 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1178 } else if (md!=null)
1179 paramstable.put(md, objectparams);
1181 paramstable.put(task, objectparams);
1183 for(int i=0; i<fm.numParameters(); i++) {
1184 TempDescriptor temp=fm.getParameter(i);
1185 TypeDescriptor type=temp.getType();
1186 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1187 objectparams.addPtr(temp);
1189 objectparams.addPrim(temp);
1190 if(lb!=null&&saveset.contains(temp)) {
1191 backuptable.get(lb).put(temp, temp.createNew());
1195 for(int i=0; i<fm.numTags(); i++) {
1196 TempDescriptor temp=fm.getTag(i);
1197 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1198 objectparams.addPtr(temp);
1200 objectparams.addPrim(temp);
1203 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1205 tempstable.put(lb, objecttemps);
1207 tempstable.put(md, objecttemps);
1209 tempstable.put(task, objecttemps);
1211 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1212 FlatNode fn=(FlatNode)nodeit.next();
1213 TempDescriptor[] writes=fn.writesTemps();
1214 for(int i=0; i<writes.length; i++) {
1215 TempDescriptor temp=writes[i];
1216 TypeDescriptor type=temp.getType();
1217 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1218 objecttemps.addPtr(temp);
1220 objecttemps.addPrim(temp);
1221 if(lb!=null&&saveset.contains(temp)&&
1222 !backuptable.get(lb).containsKey(temp))
1223 backuptable.get(lb).put(temp, temp.createNew());
1227 /* Create backup temps */
1229 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1230 TempDescriptor tmp=tmpit.next();
1231 TypeDescriptor type=tmp.getType();
1232 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1233 objecttemps.addPtr(tmp);
1235 objecttemps.addPrim(tmp);
1237 /* Create temp to hold revert table */
1238 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1239 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1240 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1241 objecttemps.addPtr(reverttmp);
1243 objecttemps.addPrim(reverttmp);
1244 reverttable.put(lb, reverttmp);
1249 /** This method outputs the following information about classes
1251 * (1) For classes, what are the locations of pointers.
1252 * (2) For arrays, does the array contain pointers or primitives.
1253 * (3) For classes, does the class contain flags.
1256 private void generateLayoutStructs(PrintWriter output) {
1257 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1258 while(it.hasNext()) {
1259 ClassDescriptor cn=(ClassDescriptor)it.next();
1260 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1261 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1263 while(allit.hasNext()) {
1264 FieldDescriptor fd=(FieldDescriptor)allit.next();
1265 TypeDescriptor type=fd.getType();
1266 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1271 output.print(count);
1272 allit=cn.getFieldTable().getAllDescriptorsIterator();
1273 while(allit.hasNext()) {
1274 FieldDescriptor fd=(FieldDescriptor)allit.next();
1275 TypeDescriptor type=fd.getType();
1276 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1279 output.println(",");
1280 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1283 output.println("};");
1285 output.println("unsigned INTPTR * pointerarray[]={");
1286 boolean needcomma=false;
1287 for(int i=0; i<state.numClasses(); i++) {
1288 ClassDescriptor cn=cdarray[i];
1290 output.println(",");
1293 output.print(cn.getSafeSymbol()+"_pointers");
1295 output.print("NULL");
1299 for(int i=0; i<state.numArrays(); i++) {
1301 output.println(", ");
1302 TypeDescriptor tdelement=arraytable[i].dereference();
1303 if (tdelement.isArray()||tdelement.isClass())
1304 output.print("((unsigned INTPTR *)1)");
1310 output.println("};");
1312 output.println("int hasflags[]={");
1313 for(int i=0; i<state.numClasses(); i++) {
1314 ClassDescriptor cn=cdarray[i];
1316 output.println(", ");
1318 if ((cn != null) && (cn.hasFlags()))
1323 output.println("};");
1326 /** Print out table to give us supertypes */
1327 private void generateSuperTypeTable(PrintWriter output) {
1328 output.println("int supertypes[]={");
1329 boolean needcomma=false;
1330 for(int i=0; i<state.numClasses(); i++) {
1331 ClassDescriptor cn=cdarray[i];
1333 output.println(",");
1335 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1336 ClassDescriptor cdsuper=cn.getSuperDesc();
1337 output.print(cdsuper.getId());
1341 output.println("};");
1344 /** Force consistent field ordering between inherited classes. */
1346 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1348 ClassDescriptor sp=cn.getSuperDesc();
1350 printClassStruct(sp, classdefout);
1352 if (!fieldorder.containsKey(cn)) {
1353 Vector fields=new Vector();
1354 fieldorder.put(cn,fields);
1355 Vector fieldvec=cn.getFieldVec();
1356 for(int i=0;i<fieldvec.size();i++) {
1357 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1358 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1362 Vector fields=(Vector)fieldorder.get(cn);
1364 for(int i=0; i<fields.size(); i++) {
1365 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1366 if (fd.getType().isClass()||fd.getType().isArray())
1367 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1369 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1374 /* Map flags to integers consistently between inherited
1377 protected void mapFlags(ClassDescriptor cn) {
1378 ClassDescriptor sp=cn.getSuperDesc();
1382 if (!flagorder.containsKey(cn)) {
1383 Hashtable flags=new Hashtable();
1384 flagorder.put(cn,flags);
1386 Hashtable superflags=(Hashtable)flagorder.get(sp);
1387 Iterator superflagit=superflags.keySet().iterator();
1388 while(superflagit.hasNext()) {
1389 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1390 Integer number=(Integer)superflags.get(fd);
1391 flags.put(fd, number);
1392 if ((number.intValue()+1)>max)
1393 max=number.intValue()+1;
1397 Iterator flagit=cn.getFlags();
1398 while(flagit.hasNext()) {
1399 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1400 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1401 flags.put(fd, new Integer(max++));
1407 /** This function outputs (1) structures that parameters are
1408 * passed in (when PRECISE GC is enabled) and (2) function
1409 * prototypes for the methods */
1411 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1412 /* Output class structure */
1413 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1414 classdefout.println(" int type;");
1415 if(state.MLP || state.OOOJAVA){
1416 classdefout.println(" int oid;");
1418 if (state.EVENTMONITOR) {
1419 classdefout.println(" int objuid;");
1422 classdefout.println(" pthread_t tid;");
1423 classdefout.println(" void * lockentry;");
1424 classdefout.println(" int lockcount;");
1428 classdefout.println(" int flag;");
1429 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1430 classdefout.println(" void * flagptr;");
1431 } else if (state.MULTICORE) {
1432 classdefout.println(" int version;");
1433 classdefout.println(" int * lock;"); // lock entry for this obj
1434 classdefout.println(" int mutex;");
1435 classdefout.println(" int lockcount;");
1436 if(state.MULTICOREGC) {
1437 classdefout.println(" int marked;");
1440 if (state.OPTIONAL) {
1441 classdefout.println(" int numfses;");
1442 classdefout.println(" int * fses;");
1445 printClassStruct(cn, classdefout);
1446 classdefout.println("};\n");
1448 if (state.DSM||state.SINGLETM) {
1449 /* Cycle through LocalityBindings */
1450 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1451 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1453 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1454 LocalityBinding lb=lbit.next();
1455 MethodDescriptor md=lb.getMethod();
1456 if (md.getModifiers().isNative()) {
1457 //make sure we only print a native method once
1458 if (nativemethods.contains(md)) {
1459 FlatMethod fm=state.getMethodFlat(md);
1460 generateTempStructs(fm, lb);
1463 nativemethods.add(md);
1465 generateMethod(cn, md, lb, headersout, output);
1468 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1469 MethodDescriptor md=(MethodDescriptor)methodit.next();
1470 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1471 //Need to build param structure for library code
1472 FlatMethod fm=state.getMethodFlat(md);
1473 generateTempStructs(fm, null);
1474 generateMethodParam(cn, md, null, output);
1479 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1480 MethodDescriptor md=(MethodDescriptor)methodit.next();
1481 generateMethod(cn, md, null, headersout, output);
1485 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1486 /* Output parameter structure */
1487 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1488 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1489 if ((state.DSM||state.SINGLETM)&&lb!=null)
1490 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1492 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1493 output.println(" int size;");
1494 output.println(" void * next;");
1495 for(int i=0; i<objectparams.numPointers(); i++) {
1496 TempDescriptor temp=objectparams.getPointer(i);
1497 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1499 output.println("};\n");
1503 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1504 FlatMethod fm=state.getMethodFlat(md);
1505 generateTempStructs(fm, lb);
1507 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1508 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1510 generateMethodParam(cn, md, lb, output);
1512 /* Output temp structure */
1513 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1514 if (state.DSM||state.SINGLETM)
1515 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1517 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1518 output.println(" int size;");
1519 output.println(" void * next;");
1520 for(int i=0; i<objecttemps.numPointers(); i++) {
1521 TempDescriptor temp=objecttemps.getPointer(i);
1522 if (temp.getType().isNull())
1523 output.println(" void * "+temp.getSafeSymbol()+";");
1525 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1527 output.println("};\n");
1530 /********* Output method declaration ***********/
1531 if (state.DSM||state.SINGLETM) {
1532 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1534 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1536 /* First the return type */
1537 if (md.getReturnType()!=null) {
1538 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1539 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1541 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1543 //catch the constructor case
1544 headersout.print("void ");
1546 /* Next the method name */
1547 if (state.DSM||state.SINGLETM) {
1548 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1550 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1552 boolean printcomma=false;
1553 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1554 if (state.DSM||state.SINGLETM) {
1555 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1557 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1561 /* Output parameter list*/
1562 for(int i=0; i<objectparams.numPrimitives(); i++) {
1563 TempDescriptor temp=objectparams.getPrimitive(i);
1565 headersout.print(", ");
1567 if (temp.getType().isClass()||temp.getType().isArray())
1568 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1570 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1572 headersout.println(");\n");
1576 /** This function outputs (1) structures that parameters are
1577 * passed in (when PRECISE GC is enabled) and (2) function
1578 * prototypes for the tasks */
1580 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1581 /* Cycle through tasks */
1582 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1584 while(taskit.hasNext()) {
1585 /* Classify parameters */
1586 TaskDescriptor task=(TaskDescriptor)taskit.next();
1587 FlatMethod fm=state.getMethodFlat(task);
1588 generateTempStructs(fm, null);
1590 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1591 TempObject objecttemps=(TempObject) tempstable.get(task);
1593 /* Output parameter structure */
1594 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1595 output.println("struct "+task.getSafeSymbol()+"_params {");
1596 output.println(" int size;");
1597 output.println(" void * next;");
1598 for(int i=0; i<objectparams.numPointers(); i++) {
1599 TempDescriptor temp=objectparams.getPointer(i);
1600 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1603 output.println("};\n");
1604 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1605 maxtaskparams=objectparams.numPointers()+fm.numTags();
1609 /* Output temp structure */
1610 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1611 output.println("struct "+task.getSafeSymbol()+"_locals {");
1612 output.println(" int size;");
1613 output.println(" void * next;");
1614 for(int i=0; i<objecttemps.numPointers(); i++) {
1615 TempDescriptor temp=objecttemps.getPointer(i);
1616 if (temp.getType().isNull())
1617 output.println(" void * "+temp.getSafeSymbol()+";");
1618 else if(temp.getType().isTag())
1619 output.println(" struct "+
1620 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1622 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1624 output.println("};\n");
1627 /* Output task declaration */
1628 headersout.print("void " + task.getSafeSymbol()+"(");
1630 boolean printcomma=false;
1631 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1632 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1634 headersout.print("void * parameterarray[]");
1635 headersout.println(");\n");
1639 /***** Generate code for FlatMethod fm. *****/
1641 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1642 static int atomicmethodcount=0;
1645 BranchAnalysis branchanalysis;
1646 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1647 if (State.PRINTFLAT)
1648 System.out.println(fm.printMethod());
1649 MethodDescriptor md=fm.getMethod();
1650 TaskDescriptor task=fm.getTask();
1651 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1652 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1654 HashSet<AtomicRecord> arset=null;
1655 branchanalysis=null;
1657 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1659 if (atomicmethodmap==null)
1660 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1662 //fix these so we get right strings for local variables
1663 localsprefixaddr=localsprefix;
1664 localsprefixderef=localsprefix+"->";
1665 arset=new HashSet<AtomicRecord>();
1667 //build branchanalysis
1668 branchanalysis=new BranchAnalysis(locality, lb, delaycomp.getNotReady(lb), delaycomp.livecode(lb), state);
1670 //Generate commit methods here
1671 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1672 FlatNode fn=fnit.next();
1673 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1674 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
1675 delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
1676 //We have an atomic enter
1677 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1678 Set<FlatNode> exitset=faen.getExits();
1680 String methodname=md.getSymbol()+(atomicmethodcount++);
1681 AtomicRecord ar=new AtomicRecord();
1685 atomicmethodmap.put(faen, ar);
1687 //build data structure declaration
1688 output.println("struct atomicprimitives_"+methodname+" {");
1690 Set<FlatNode> recordset=delaycomp.livecode(lb);
1691 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1692 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1693 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1695 ar.reallivein=new HashSet(liveinto);
1697 ar.liveoutvirtualread=liveoutvirtualread;
1700 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1701 TempDescriptor tmp=it.next();
1702 //remove the pointers
1703 if (tmp.getType().isPtr()) {
1706 //let's print it here
1707 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1710 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1711 TempDescriptor tmp=it.next();
1712 //remove the pointers
1713 if (tmp.getType().isPtr()) {
1715 } else if (!liveinto.contains(tmp)) {
1716 //let's print it here
1717 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1720 output.println("};");
1722 //print out method name
1723 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) {");
1724 //build code for commit method
1726 //first define local primitives
1727 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1728 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1729 TempDescriptor tmp=tmpit.next();
1730 if (!tmp.getType().isPtr()) {
1731 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1732 //read from live into set
1733 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1736 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1740 //turn off write barrier generation
1742 state.SINGLETM=false;
1743 generateCode(faen, fm, lb, exitset, output, false);
1744 state.SINGLETM=true;
1745 //turn on write barrier generation
1747 output.println("}\n\n");
1751 //redefine these back to normal
1753 localsprefixaddr="&"+localsprefix;
1754 localsprefixderef=localsprefix+".";
1756 generateHeader(fm, lb, md!=null ? md : task,output);
1757 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1759 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1760 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1761 AtomicRecord ar=arit.next();
1762 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1766 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1767 if (md!=null&&(state.DSM||state.SINGLETM))
1768 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1769 else if (md!=null&&!(state.DSM||state.SINGLETM))
1770 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1772 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1773 output.print(objecttemp.numPointers()+",");
1774 output.print(paramsprefix);
1775 for(int j=0; j<objecttemp.numPointers(); j++)
1776 output.print(", NULL");
1777 output.println("};");
1780 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1781 TempDescriptor td=objecttemp.getPrimitive(i);
1782 TypeDescriptor type=td.getType();
1784 output.println(" void * "+td.getSafeSymbol()+";");
1785 else if (type.isClass()||type.isArray())
1786 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1788 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1792 if( state.MLP || state.OOOJAVA ) {
1793 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1794 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1795 if( (state.MLP && callerSESEplaceholder != mlpa.getMainSESE()) ||
1796 (state.OOOJAVA && callerSESEplaceholder != oooa.getMainSESE())
1798 // declare variables for naming static SESE's
1799 output.println(" /* static SESE names */");
1800 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1801 while( pItr.hasNext() ) {
1802 SESEandAgePair pair = pItr.next();
1803 output.println(" void* "+pair+";");
1806 // declare variables for tracking dynamic sources
1807 output.println(" /* dynamic variable sources */");
1808 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1809 while( dynSrcItr.hasNext() ) {
1810 TempDescriptor dynSrcVar = dynSrcItr.next();
1811 output.println(" void* "+dynSrcVar+"_srcSESE;");
1812 output.println(" int "+dynSrcVar+"_srcOffset;");
1817 // set up related allocation sites's waiting queues
1820 ConflictGraph graph = null;
1821 graph = mlpa.getConflictGraphResults().get(fm);
1822 if (graph != null && graph.hasConflictEdge()) {
1823 output.println(" /* set up waiting queues */");
1824 output.println(" int numMemoryQueue=0;");
1825 output.println(" int memoryQueueItemID=0;");
1826 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
1828 System.out.println("#lockSet="+lockSet.hashCode());
1829 System.out.println("lockset="+lockSet);
1830 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1831 SESELock seseLock = (SESELock) iterator.next();
1832 System.out.println("id="+seseLock.getID());
1833 System.out.println("#="+seseLock);
1835 System.out.println("size="+lockSet.size());
1836 if (lockSet.size() > 0) {
1837 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1839 .println(" seseCaller->numMemoryQueue=numMemoryQueue;");
1841 .println(" seseCaller->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1846 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1847 if(callerSESEplaceholder!= oooa.getMainSESE()){
1848 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(callerSESEplaceholder);
1849 if (graph != null && graph.hasConflictEdge()) {
1850 output.println(" // set up waiting queues ");
1851 output.println(" int numMemoryQueue=0;");
1852 output.println(" int memoryQueueItemID=0;");
1853 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
1854 System.out.println("#lockSet="+lockSet.hashCode());
1855 System.out.println("lockset="+lockSet);
1856 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1857 Analysis.OoOJava.SESELock seseLock = (Analysis.OoOJava.SESELock) iterator.next();
1858 System.out.println("id="+seseLock.getID());
1859 System.out.println("#="+seseLock);
1861 System.out.println("size="+lockSet.size());
1862 if (lockSet.size() > 0) {
1863 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1865 .println(" seseCaller->numMemoryQueue=numMemoryQueue;");
1867 .println(" seseCaller->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1877 /* Check to see if we need to do a GC if this is a
1878 * multi-threaded program...*/
1880 if (((state.MLP||state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1881 || this.state.MULTICOREGC) {
1882 //Don't bother if we aren't in recursive methods...The loops case will catch it
1883 if (callgraph.getAllMethods(md).contains(md)) {
1884 if (state.DSM&&lb.isAtomic())
1885 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1886 else if (this.state.MULTICOREGC) {
1887 output.println("if(gcflag) gc("+localsprefixaddr+");");
1889 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1894 generateCode(fm.getNext(0), fm, lb, null, output, true);
1896 output.println("}\n\n");
1900 protected void initializeSESE( FlatSESEEnterNode fsen ) {
1902 FlatMethod fm = fsen.getfmEnclosing();
1903 MethodDescriptor md = fm.getMethod();
1904 ClassDescriptor cn = md.getClassDesc();
1907 // Creates bogus method descriptor to index into tables
1908 Modifiers modBogus = new Modifiers();
1909 MethodDescriptor mdBogus =
1910 new MethodDescriptor( modBogus,
1911 new TypeDescriptor( TypeDescriptor.VOID ),
1912 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1915 mdBogus.setClassDesc( fsen.getcdEnclosing() );
1916 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1917 fsen.setfmBogus( fmBogus );
1918 fsen.setmdBogus( mdBogus );
1920 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1921 inSetAndOutSet.addAll( fsen.getInVarSet() );
1922 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1924 // Build paramsobj for bogus method descriptor
1925 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
1926 paramstable.put( mdBogus, objectparams );
1928 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1929 while( itr.hasNext() ) {
1930 TempDescriptor temp = itr.next();
1931 TypeDescriptor type = temp.getType();
1932 if( type.isPtr() ) {
1933 objectparams.addPtr( temp );
1935 objectparams.addPrim( temp );
1939 // Build normal temp object for bogus method descriptor
1940 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
1941 tempstable.put( mdBogus, objecttemps );
1943 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
1944 FlatNode fn = (FlatNode)nodeit.next();
1945 TempDescriptor[] writes = fn.writesTemps();
1947 for( int i = 0; i < writes.length; i++ ) {
1948 TempDescriptor temp = writes[i];
1949 TypeDescriptor type = temp.getType();
1951 if( type.isPtr() ) {
1952 objecttemps.addPtr( temp );
1954 objecttemps.addPrim( temp );
1960 protected void generateMethodSESE(FlatSESEEnterNode fsen,
1962 PrintWriter outputStructs,
1963 PrintWriter outputMethHead,
1964 PrintWriter outputMethods
1967 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
1968 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
1970 // generate locals structure
1971 outputStructs.println("struct "+
1972 fsen.getcdEnclosing().getSafeSymbol()+
1973 fsen.getmdBogus().getSafeSymbol()+"_"+
1974 fsen.getmdBogus().getSafeMethodDescriptor()+
1976 outputStructs.println(" int size;");
1977 outputStructs.println(" void * next;");
1978 for(int i=0; i<objecttemps.numPointers(); i++) {
1979 TempDescriptor temp=objecttemps.getPointer(i);
1981 if (temp.getType().isNull())
1982 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1984 outputStructs.println(" struct "+
1985 temp.getType().getSafeSymbol()+" * "+
1986 temp.getSafeSymbol()+";");
1988 outputStructs.println("};\n");
1991 // generate the SESE record structure
1992 outputStructs.println(fsen.getSESErecordName()+" {");
1994 // data common to any SESE, and it must be placed first so
1995 // a module that doesn't know what kind of SESE record this
1996 // is can cast the pointer to a common struct
1997 outputStructs.println(" SESEcommon common;");
1999 // then garbage list stuff
2000 outputStructs.println(" int size;");
2001 outputStructs.println(" void * next;");
2003 // DYNAMIC stuff was here
2005 // invar source taking was here
2007 // space for all in and out set primitives
2008 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
2009 inSetAndOutSet.addAll( fsen.getInVarSet() );
2010 inSetAndOutSet.addAll( fsen.getOutVarSet() );
2012 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
2014 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
2015 while( itr.hasNext() ) {
2016 TempDescriptor temp = itr.next();
2017 TypeDescriptor type = temp.getType();
2018 if( !type.isPtr() ) {
2019 inSetAndOutSetPrims.add( temp );
2023 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
2024 while( itrPrims.hasNext() ) {
2025 TempDescriptor temp = itrPrims.next();
2026 TypeDescriptor type = temp.getType();
2027 if(!type.isPrimitive()){
2028 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
2032 for(int i=0; i<objectparams.numPointers(); i++) {
2033 TempDescriptor temp=objectparams.getPointer(i);
2034 if (temp.getType().isNull())
2035 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
2037 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
2040 // DYNAMIC stuff needs a source SESE ptr and offset
2041 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
2042 while( itrDynInVars.hasNext() ) {
2043 TempDescriptor dynInVar = itrDynInVars.next();
2044 // outputStructs.println(" void* "+dynInVar+"_srcSESE;");
2045 outputStructs.println(" int "+dynInVar+"_srcOffset;");
2048 itrPrims = inSetAndOutSetPrims.iterator();
2049 while( itrPrims.hasNext() ) {
2050 TempDescriptor temp = itrPrims.next();
2051 TypeDescriptor type = temp.getType();
2052 if(type.isPrimitive()){
2053 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
2057 outputStructs.println(" int prevSESECount;");
2059 // DYNAMIC stuff needs a source SESE ptr and offset
2060 itrDynInVars = fsen.getDynamicInVarSet().iterator();
2061 while( itrDynInVars.hasNext() ) {
2062 TempDescriptor dynInVar = itrDynInVars.next();
2063 outputStructs.println(" void* "+dynInVar+"_srcSESE;");
2064 // outputStructs.println(" int "+dynInVar+"_srcOffset;");
2067 // in-set source tracking
2068 // in-vars that are READY come from parent, don't need anything
2069 // stuff STATIC needs a custom SESE pointer for each age pair
2070 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
2071 while( itrStaticInVarSrcs.hasNext() ) {
2072 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
2073 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
2076 outputStructs.println("};\n");
2079 // write method declaration to header file
2080 outputMethHead.print("void ");
2081 outputMethHead.print(fsen.getSESEmethodName()+"(");
2082 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
2083 outputMethHead.println(");\n");
2086 generateFlatMethodSESE( fsen.getfmBogus(),
2087 fsen.getcdEnclosing(),
2093 private void generateFlatMethodSESE(FlatMethod fm,
2095 FlatSESEEnterNode fsen,
2096 FlatSESEExitNode seseExit,
2100 MethodDescriptor md=fm.getMethod();
2102 output.print("void ");
2103 output.print(fsen.getSESEmethodName()+"(");
2104 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
2105 output.println("){\n");
2107 TempObject objecttemp=(TempObject) tempstable.get(md);
2109 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2110 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2111 output.print(objecttemp.numPointers()+",");
2112 output.print("&(((SESEcommon*)(___params___))[1])");
2113 for(int j=0; j<objecttemp.numPointers(); j++)
2114 output.print(", NULL");
2115 output.println("};");
2118 output.println(" /* regular local primitives */");
2119 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2120 TempDescriptor td=objecttemp.getPrimitive(i);
2121 TypeDescriptor type=td.getType();
2123 output.println(" void * "+td.getSafeSymbol()+";");
2124 else if (type.isClass()||type.isArray())
2125 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2127 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2131 // declare variables for naming static SESE's
2132 output.println(" /* static SESE names */");
2133 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
2134 while( pItr.hasNext() ) {
2135 SESEandAgePair pair = pItr.next();
2136 output.println(" void* "+pair+";");
2139 // declare variables for tracking dynamic sources
2140 output.println(" /* dynamic variable sources */");
2141 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
2142 while( dynSrcItr.hasNext() ) {
2143 TempDescriptor dynSrcVar = dynSrcItr.next();
2144 output.println(" void* "+dynSrcVar+"_srcSESE;");
2145 output.println(" int "+dynSrcVar+"_srcOffset;");
2148 // declare local temps for in-set primitives, and if it is
2149 // a ready-source variable, get the value from the record
2150 output.println(" /* local temps for in-set primitives */");
2151 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2152 while( itrInSet.hasNext() ) {
2153 TempDescriptor temp = itrInSet.next();
2154 TypeDescriptor type = temp.getType();
2155 if( !type.isPtr() ) {
2156 if( fsen.getReadyInVarSet().contains( temp ) ) {
2157 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2159 output.println(" "+type+" "+temp+";");
2164 // declare local temps for out-set primitives if its not already
2165 // in the in-set, and it's value will get written so no problem
2166 output.println(" /* local temp for out-set prim, not already in the in-set */");
2167 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2168 while( itrOutSet.hasNext() ) {
2169 TempDescriptor temp = itrOutSet.next();
2170 TypeDescriptor type = temp.getType();
2171 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2172 output.println(" "+type+" "+temp+";");
2176 // setup memory queue
2179 output.println(" // set up memory queues ");
2180 output.println(" int numMemoryQueue=0;");
2181 output.println(" int memoryQueueItemID=0;");
2182 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(fsen);
2183 if (graph != null && graph.hasConflictEdge()) {
2184 output.println(" {");
2186 .println(" SESEcommon* parentCommon = &(___params___->common);");
2187 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
2188 System.out.println("#lockSet="+lockSet);
2189 if (lockSet.size() > 0) {
2190 output.println(" numMemoryQueue=" + lockSet.size() + ";");
2192 .println(" parentCommon->numMemoryQueue=numMemoryQueue;");
2194 .println(" parentCommon->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2197 output.println(" }");
2200 output.println(" // set up memory queues ");
2201 output.println(" int numMemoryQueue=0;");
2202 output.println(" int memoryQueueItemID=0;");
2203 ConflictGraph graph = null;
2204 graph = mlpa.getConflictGraphResults().get(fsen);
2205 if (graph != null && graph.hasConflictEdge()) {
2206 output.println(" {");
2208 .println(" SESEcommon* parentCommon = &(___params___->common);");
2209 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
2211 System.out.println("#lockSet="+lockSet);
2213 if (lockSet.size() > 0) {
2214 output.println(" numMemoryQueue=" + lockSet.size() + "; ");
2216 .println(" parentCommon->numMemoryQueue=numMemoryQueue;");
2218 .println(" parentCommon->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2221 output.println(" }");
2227 // copy in-set into place, ready vars were already
2228 // copied when the SESE was issued
2229 Iterator<TempDescriptor> tempItr;
2231 // static vars are from a known SESE
2232 tempItr = fsen.getStaticInVarSet().iterator();
2233 while( tempItr.hasNext() ) {
2234 TempDescriptor temp = tempItr.next();
2235 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2236 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2238 // can't grab something from this source until it is done
2239 output.println(" {");
2241 If we are running, everything is done. This check is redundant.
2243 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+srcPair+";" );
2244 output.println(" pthread_mutex_lock( &(com->lock) );");
2245 output.println(" while( com->doneExecuting == FALSE ) {");
2246 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2247 output.println(" }");
2248 output.println(" pthread_mutex_unlock( &(com->lock) );");
2250 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2251 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2253 output.println(" }");
2256 // dynamic vars come from an SESE and src
2257 tempItr = fsen.getDynamicInVarSet().iterator();
2258 while( tempItr.hasNext() ) {
2259 TempDescriptor temp = tempItr.next();
2260 TypeDescriptor type = temp.getType();
2262 // go grab it from the SESE source
2263 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2265 // gotta wait until the source is done
2266 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+temp+"_srcSESE;" );
2268 If we are running, everything is done!
2269 output.println(" pthread_mutex_lock( &(com->lock) );");
2270 output.println(" while( com->doneExecuting == FALSE ) {");
2271 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2272 output.println(" }");
2273 output.println(" pthread_mutex_unlock( &(com->lock) );");
2277 if( type.isNull() ) {
2279 } else if( type.isClass() || type.isArray() ) {
2280 typeStr = "struct "+type.getSafeSymbol()+"*";
2282 typeStr = type.getSafeSymbol();
2285 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2286 " = *(("+typeStr+"*) ("+
2287 paramsprefix+"->"+temp+"_srcSESE + "+
2288 paramsprefix+"->"+temp+"_srcOffset));");
2290 // or if the source was our parent, its in the record to grab
2291 output.println(" } else {");
2292 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2293 " = "+paramsprefix+"->"+temp+";");
2294 output.println(" }");
2297 // Check to see if we need to do a GC if this is a
2298 // multi-threaded program...
2299 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2300 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2301 //Don't bother if we aren't in recursive methods...The loops case will catch it
2302 // if (callgraph.getAllMethods(md).contains(md)) {
2303 // if(this.state.MULTICOREGC) {
2304 // output.println("if(gcflag) gc("+localsprefixaddr+");");
2306 // output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2311 // initialize thread-local var to a non-zero, invalid address
2312 output.println(" seseCaller = (SESEcommon*) 0x2;");
2313 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2314 exitset.add(seseExit);
2315 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2316 output.println("}\n\n");
2321 // when a new mlp thread is created for an issued SESE, it is started
2322 // by running this method which blocks on a cond variable until
2323 // it is allowed to transition to execute. Then a case statement
2324 // allows it to invoke the method with the proper SESE body, and after
2325 // exiting the SESE method, executes proper SESE exit code before the
2326 // thread can be destroyed
2327 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2328 PrintWriter outmethod
2331 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2332 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2333 outmethod.println( " int status;");
2334 outmethod.println( " char errmsg[128];");
2336 // generate a case for each SESE class that can be invoked
2337 outmethod.println( " switch( *((int*)seseRecord) ) {");
2338 outmethod.println( " ");
2339 Iterator<FlatSESEEnterNode> seseit;
2341 seseit=mlpa.getAllSESEs().iterator();
2343 seseit=oooa.getAllSESEs().iterator();
2345 while(seseit.hasNext()){
2346 FlatSESEEnterNode fsen = seseit.next();
2348 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2349 outmethod.println( " case "+fsen.getIdentifier()+":");
2350 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2352 if( (state.MLP && fsen.equals( mlpa.getMainSESE() )) ||
2353 (state.OOOJAVA && fsen.equals( oooa.getMainSESE() ))
2355 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2356 if (state.COREPROF) {
2357 outmethod.println("EXITPROFILER();");
2358 outmethod.println("DUMPPROFILER();");
2360 outmethod.println( " exit( 0 );");
2363 outmethod.println( " break;");
2364 outmethod.println( "");
2367 // default case should never be taken, error out
2368 outmethod.println( " default:");
2369 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2370 outmethod.println( " exit(-30);");
2371 outmethod.println( " break;");
2372 outmethod.println( " }");
2373 outmethod.println( " return NULL;");
2374 outmethod.println( "}\n\n");
2378 protected void generateCode(FlatNode first,
2381 Set<FlatNode> stopset,
2382 PrintWriter output, boolean firstpass) {
2384 /* Assign labels to FlatNode's if necessary.*/
2386 Hashtable<FlatNode, Integer> nodetolabel;
2388 if (state.DELAYCOMP&&!firstpass)
2389 nodetolabel=dcassignLabels(first, stopset);
2391 nodetolabel=assignLabels(first, stopset);
2393 Set<FlatNode> storeset=null;
2394 HashSet<FlatNode> genset=null;
2395 HashSet<FlatNode> refset=null;
2396 Set<FlatNode> unionset=null;
2398 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2399 storeset=delaycomp.livecode(lb);
2400 genset=new HashSet<FlatNode>();
2401 if (state.STMARRAY&&!state.DUALVIEW) {
2402 refset=new HashSet<FlatNode>();
2403 refset.addAll(delaycomp.getDeref(lb));
2404 refset.removeAll(delaycomp.getCannotDelay(lb));
2405 refset.removeAll(delaycomp.getOther(lb));
2408 genset.addAll(delaycomp.getCannotDelay(lb));
2409 genset.addAll(delaycomp.getOther(lb));
2411 genset.addAll(delaycomp.getNotReady(lb));
2412 if (state.STMARRAY&&!state.DUALVIEW) {
2413 genset.removeAll(refset);
2416 unionset=new HashSet<FlatNode>();
2417 unionset.addAll(storeset);
2418 unionset.addAll(genset);
2419 if (state.STMARRAY&&!state.DUALVIEW)
2420 unionset.addAll(refset);
2423 /* Do the actual code generation */
2424 FlatNode current_node=null;
2425 HashSet tovisit=new HashSet();
2426 HashSet visited=new HashSet();
2428 tovisit.add(first.getNext(0));
2431 while(current_node!=null||!tovisit.isEmpty()) {
2432 if (current_node==null) {
2433 current_node=(FlatNode)tovisit.iterator().next();
2434 tovisit.remove(current_node);
2435 } else if (tovisit.contains(current_node)) {
2436 tovisit.remove(current_node);
2438 visited.add(current_node);
2439 if (nodetolabel.containsKey(current_node)) {
2440 output.println("L"+nodetolabel.get(current_node)+":");
2442 if (state.INSTRUCTIONFAILURE) {
2443 if (state.THREAD||state.DSM||state.SINGLETM) {
2444 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2446 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2448 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2450 if (!state.DELAYCOMP||firstpass) {
2451 generateFlatNode(fm, lb, current_node, output);
2453 //store primitive variables in out set
2454 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2455 Set<TempDescriptor> liveout=ar.liveout;
2456 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2457 TempDescriptor tmp=tmpit.next();
2458 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2461 if ((state.MLP || state.OOOJAVA) && stopset!=null) {
2462 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2463 assert current_node instanceof FlatSESEExitNode;
2464 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2465 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2466 assert fsen.getFlatExit().equals( fsxn );
2467 assert fsxn.getFlatEnter().equals( fsen );
2469 if (current_node.kind()!=FKind.FlatReturnNode) {
2470 output.println(" return;");
2473 } else if(current_node.numNext()==1) {
2475 if ((state.MLP|| state.OOOJAVA) &&
2476 current_node.kind()==FKind.FlatSESEEnterNode &&
2477 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2479 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2480 generateFlatNode(fm, lb, current_node, output);
2481 nextnode=fsen.getFlatExit().getNext(0);
2482 } else if (state.DELAYCOMP) {
2483 boolean specialprimitive=false;
2484 //skip literals...no need to add extra overhead
2485 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2486 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2487 if (!typedesc.isClass()&&!typedesc.isArray()) {
2488 specialprimitive=true;
2492 if (genset==null||genset.contains(current_node)||specialprimitive)
2493 generateFlatNode(fm, lb, current_node, output);
2494 if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2495 //need to acquire lock
2496 handleArrayDeref(fm, lb, current_node, output, firstpass);
2498 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2499 TempDescriptor wrtmp=current_node.writesTemps()[0];
2501 //need to store value written by previous node
2502 if (wrtmp.getType().isPtr()) {
2503 //only lock the objects that may actually need locking
2504 if (recorddc.getNeedTrans(lb, current_node)&&
2505 (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2506 wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2507 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2509 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2512 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2515 //need to read value read by previous node
2516 if (wrtmp.getType().isPtr()) {
2517 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2519 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");
2523 nextnode=current_node.getNext(0);
2526 generateFlatNode(fm, lb, current_node, output);
2527 nextnode=current_node.getNext(0);
2529 if (visited.contains(nextnode)) {
2530 output.println("goto L"+nodetolabel.get(nextnode)+";");
2533 current_node=nextnode;
2534 } else if (current_node.numNext()==2) {
2536 if (state.DELAYCOMP) {
2537 boolean computeside=false;
2539 //need to record which way it should go
2540 if (genset==null||genset.contains(current_node)) {
2541 if (storeset!=null&&storeset.contains(current_node)) {
2542 //need to store which way branch goes
2543 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2545 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2547 //which side to execute
2551 if (genset.contains(current_node)) {
2552 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2553 } else if (storeset.contains(current_node)) {
2555 branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2557 //which side to execute
2562 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2564 if (leftset.size()==0)
2566 if (visited.contains(current_node.getNext(branch))) {
2567 //already visited -- build jump
2568 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2571 current_node=current_node.getNext(branch);
2574 if (!visited.contains(current_node.getNext(1)))
2575 tovisit.add(current_node.getNext(1));
2576 if (visited.contains(current_node.getNext(0))) {
2577 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2580 current_node=current_node.getNext(0);
2584 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2585 if (!visited.contains(current_node.getNext(1)))
2586 tovisit.add(current_node.getNext(1));
2587 if (visited.contains(current_node.getNext(0))) {
2588 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2591 current_node=current_node.getNext(0);
2593 } else throw new Error();
2597 protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2598 if (fn.kind()==FKind.FlatSetElementNode) {
2599 FlatSetElementNode fsen=(FlatSetElementNode) fn;
2600 String dst=generateTemp(fm, fsen.getDst(), lb);
2601 String src=generateTemp(fm, fsen.getSrc(), lb);
2602 String index=generateTemp(fm, fsen.getIndex(), lb);
2603 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2605 if (elementtype.isArray()||elementtype.isClass())
2608 type=elementtype.getSafeSymbol()+" ";
2610 output.println("STOREARRAY("+dst+","+index+","+type+")");
2612 output.println("{");
2613 output.println(" struct ArrayObject *array;");
2614 output.println(" int index;");
2615 output.println(" RESTOREARRAY(array,index);");
2616 output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2617 output.println("}");
2619 } else if (fn.kind()==FKind.FlatElementNode) {
2620 FlatElementNode fen=(FlatElementNode) fn;
2621 String src=generateTemp(fm, fen.getSrc(), lb);
2622 String index=generateTemp(fm, fen.getIndex(), lb);
2623 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2624 String dst=generateTemp(fm, fen.getDst(), lb);
2626 if (elementtype.isArray()||elementtype.isClass())
2629 type=elementtype.getSafeSymbol()+" ";
2631 output.println("STOREARRAY("+src+","+index+","+type+")");
2633 output.println("{");
2634 output.println(" struct ArrayObject *array;");
2635 output.println(" int index;");
2636 output.println(" RESTOREARRAY(array,index);");
2637 output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2638 output.println("}");
2642 /** Special label assignment for delaycomputation */
2643 protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2644 HashSet tovisit=new HashSet();
2645 HashSet visited=new HashSet();
2647 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2649 //Label targets of branches
2650 Set<FlatNode> targets=branchanalysis.getTargets();
2651 for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2652 nodetolabel.put(it.next(), new Integer(labelindex++));
2657 /*Assign labels first. A node needs a label if the previous
2658 * node has two exits or this node is a join point. */
2660 while(!tovisit.isEmpty()) {
2661 FlatNode fn=(FlatNode)tovisit.iterator().next();
2666 if(lastset!=null&&lastset.contains(fn)) {
2667 // if last is not null and matches, don't go
2668 // any further for assigning labels
2672 for(int i=0; i<fn.numNext(); i++) {
2673 FlatNode nn=fn.getNext(i);
2676 //1) Edge >1 of node
2677 nodetolabel.put(nn,new Integer(labelindex++));
2679 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2683 nodetolabel.put(nn,new Integer(labelindex++));
2691 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2692 return assignLabels(first, null);
2695 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2696 HashSet tovisit=new HashSet();
2697 HashSet visited=new HashSet();
2699 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2702 /*Assign labels first. A node needs a label if the previous
2703 * node has two exits or this node is a join point. */
2705 while(!tovisit.isEmpty()) {
2706 FlatNode fn=(FlatNode)tovisit.iterator().next();
2711 if(lastset!=null&&lastset.contains(fn)) {
2712 // if last is not null and matches, don't go
2713 // any further for assigning labels
2717 for(int i=0; i<fn.numNext(); i++) {
2718 FlatNode nn=fn.getNext(i);
2721 //1) Edge >1 of node
2722 nodetolabel.put(nn,new Integer(labelindex++));
2724 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2728 nodetolabel.put(nn,new Integer(labelindex++));
2736 /** Generate text string that corresponds to the TempDescriptor td. */
2737 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2738 MethodDescriptor md=fm.getMethod();
2739 TaskDescriptor task=fm.getTask();
2740 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2742 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2743 return td.getSafeSymbol();
2746 if (objecttemps.isLocalPtr(td)) {
2747 return localsprefixderef+td.getSafeSymbol();
2750 if (objecttemps.isParamPtr(td)) {
2751 return paramsprefix+"->"+td.getSafeSymbol();
2757 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2759 // insert pre-node actions from the code plan
2760 if( state.MLP|| state.OOOJAVA ) {
2764 cp = mlpa.getCodePlan( fn );
2766 cp = oooa.getCodePlan(fn);
2771 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2773 // for each sese and age pair that this parent statement
2774 // must stall on, take that child's stall semaphore, the
2775 // copying of values comes after the statement
2776 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2777 while( vstItr.hasNext() ) {
2778 VariableSourceToken vst = vstItr.next();
2780 SESEandAgePair pair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2782 output.println(" {");
2783 output.println(" SESEcommon* common = (SESEcommon*) "+pair+";");
2785 output.println(" pthread_mutex_lock( &(common->lock) );");
2786 output.println(" while( common->doneExecuting == FALSE ) {");
2787 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2788 output.println(" }");
2789 output.println(" pthread_mutex_unlock( &(common->lock) );");
2791 // copy things we might have stalled for
2792 output.println(" "+pair.getSESE().getSESErecordName()+"* child = ("+
2793 pair.getSESE().getSESErecordName()+"*) "+pair+";");
2795 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2796 while( tdItr.hasNext() ) {
2797 TempDescriptor td = tdItr.next();
2798 FlatMethod fmContext;
2799 if( currentSESE.getIsCallerSESEplaceholder() ) {
2800 fmContext = currentSESE.getfmEnclosing();
2802 fmContext = currentSESE.getfmBogus();
2804 output.println(" "+generateTemp( fmContext, td, null )+
2805 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2808 output.println(" }");
2811 // for each variable with a dynamic source, stall just for that variable
2812 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2813 while( dynItr.hasNext() ) {
2814 TempDescriptor dynVar = dynItr.next();
2816 // only stall if the dynamic source is not yourself, denoted by src==NULL
2817 // otherwise the dynamic write nodes will have the local var up-to-date
2818 output.println(" {");
2819 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2820 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2821 output.println(" psem_take( &(common->stallSem) );");
2823 FlatMethod fmContext;
2824 if( currentSESE.getIsCallerSESEplaceholder() ) {
2825 fmContext = currentSESE.getfmEnclosing();
2827 fmContext = currentSESE.getfmBogus();
2830 TypeDescriptor type=dynVar.getType();
2832 if( type.isNull() ) {
2834 } else if( type.isClass() || type.isArray() ) {
2835 typeStr = "struct "+type.getSafeSymbol()+"*";
2837 typeStr = type.getSafeSymbol();
2840 output.println(" "+generateTemp( fmContext, dynVar, null )+
2841 " = *(("+typeStr+"*) ("+
2842 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2844 output.println(" }");
2845 output.println(" }");
2848 // for each assignment of a variable to rhs that has a dynamic source,
2849 // copy the dynamic sources
2850 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2851 while( dynAssignItr.hasNext() ) {
2852 Map.Entry me = (Map.Entry) dynAssignItr.next();
2853 TempDescriptor lhs = (TempDescriptor) me.getKey();
2854 TempDescriptor rhs = (TempDescriptor) me.getValue();
2855 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
2856 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2859 // for each lhs that is dynamic from a non-dynamic source, set the
2860 // dynamic source vars to the current SESE
2861 dynItr = cp.getDynAssignCurr().iterator();
2862 while( dynItr.hasNext() ) {
2863 TempDescriptor dynVar = dynItr.next();
2864 assert currentSESE.getDynamicVarSet().contains( dynVar );
2865 output.println(" "+dynVar+"_srcSESE = NULL;");
2869 // handling stall site
2870 if (state.OOOJAVA) {
2871 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(currentSESE);
2873 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
2874 Set<Analysis.OoOJava.WaitingElement> waitingElementSet =
2875 graph.getStallSiteWaitingElementSet(fn, seseLockSet);
2877 if(waitingElementSet.size()>0){
2878 output.println("// stall on parent's stall sites ");
2879 output.println(" {");
2880 output.println(" REntry* rentry;");
2882 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
2883 Analysis.OoOJava.WaitingElement waitingElement = (Analysis.OoOJava.WaitingElement) iterator.next();
2885 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
2886 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", seseCaller);");
2888 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller, (void*)&" +generateTemp(fm,waitingElement.getTempDesc(),lb)+ ");");
2890 output.println(" psem_init( &(rentry->parentStallSem) );");
2891 output.println(" rentry->queue=seseCaller->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
2893 .println(" if(ADDRENTRY(seseCaller->memoryQueueArray["+ waitingElement.getQueueID()
2894 + "],rentry)==NOTREADY){");
2895 output.println(" psem_take( &(rentry->parentStallSem) );");
2896 output.println(" } ");
2898 output.println(" }");
2902 ParentChildConflictsMap conflictsMap = mlpa.getConflictsResults().get(fn);
2903 if (conflictsMap != null) {
2904 Set<Long> allocSet = conflictsMap.getAllocationSiteIDSetofStallSite();
2905 if (allocSet.size() > 0) {
2906 FlatNode enclosingFlatNode=null;
2907 if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
2908 enclosingFlatNode=currentSESE.getfmEnclosing();
2910 enclosingFlatNode=currentSESE;
2912 ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
2913 HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
2914 Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
2916 if(waitingElementSet.size()>0){
2917 output.println("// stall on parent's stall sites ");
2918 output.println(" {");
2919 output.println(" REntry* rentry;");
2921 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
2922 WaitingElement waitingElement = (WaitingElement) iterator.next();
2924 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
2925 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", seseCaller);");
2927 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller, (void*)&___locals___."+ waitingElement.getDynID() + ");");
2928 // output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller, ___locals___."+ waitingElement.getDynID() + "->oid);");
2930 output.println(" psem_init( &(rentry->parentStallSem) );");
2931 output.println(" rentry->queue=seseCaller->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
2933 .println(" if(ADDRENTRY(seseCaller->memoryQueueArray["+ waitingElement.getQueueID()
2934 + "],rentry)==NOTREADY){");
2935 output.println(" psem_take( &(rentry->parentStallSem) );");
2936 output.println(" } ");
2938 output.println(" }");
2949 case FKind.FlatAtomicEnterNode:
2950 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
2953 case FKind.FlatAtomicExitNode:
2954 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
2957 case FKind.FlatInstanceOfNode:
2958 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
2961 case FKind.FlatSESEEnterNode:
2962 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
2965 case FKind.FlatSESEExitNode:
2966 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
2969 case FKind.FlatWriteDynamicVarNode:
2970 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
2973 case FKind.FlatGlobalConvNode:
2974 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
2977 case FKind.FlatTagDeclaration:
2978 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
2981 case FKind.FlatCall:
2982 generateFlatCall(fm, lb, (FlatCall) fn,output);
2985 case FKind.FlatFieldNode:
2986 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
2989 case FKind.FlatElementNode:
2990 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
2993 case FKind.FlatSetElementNode:
2994 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
2997 case FKind.FlatSetFieldNode:
2998 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
3002 generateFlatNew(fm, lb, (FlatNew) fn,output);
3005 case FKind.FlatOpNode:
3006 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
3009 case FKind.FlatCastNode:
3010 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
3013 case FKind.FlatLiteralNode:
3014 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
3017 case FKind.FlatReturnNode:
3018 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
3022 output.println("/* nop */");
3025 case FKind.FlatExit:
3026 output.println("/* exit */");
3029 case FKind.FlatBackEdge:
3030 if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3031 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3033 if(state.DSM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3034 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3036 if (((state.MLP|| state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
3037 || (this.state.MULTICOREGC)) {
3038 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
3039 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
3040 } else if(this.state.MULTICOREGC) {
3041 output.println("if (gcflag) gc("+localsprefixaddr+");");
3043 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3046 output.println("/* nop */");
3049 case FKind.FlatCheckNode:
3050 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
3053 case FKind.FlatFlagActionNode:
3054 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
3057 case FKind.FlatPrefetchNode:
3058 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
3061 case FKind.FlatOffsetNode:
3062 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
3069 // insert post-node actions from the code-plan
3072 CodePlan cp = mlpa.getCodePlan( fn );
3080 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
3081 output.println("/* FlatOffsetNode */");
3082 FieldDescriptor fd=fofn.getField();
3083 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
3084 output.println("/* offset */");
3087 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
3088 if (state.PREFETCH) {
3089 Vector oids = new Vector();
3090 Vector fieldoffset = new Vector();
3091 Vector endoffset = new Vector();
3092 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
3093 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
3094 PrefetchPair pp = (PrefetchPair) it.next();
3095 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
3096 /* Find prefetches that can generate oid */
3097 if(statusbase == LocalityAnalysis.GLOBAL) {
3098 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
3100 } else if (statusbase == LocalityAnalysis.LOCAL) {
3101 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
3108 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
3109 output.println("{");
3110 output.println("/* prefetch */");
3111 output.println("/* prefetchid_" + fpn.siteid + " */");
3112 output.println("void * prefptr;");
3113 output.println("int tmpindex;");
3115 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
3116 /*Create C code for oid array */
3117 output.print(" unsigned int oidarray_[] = {");
3118 boolean needcomma=false;
3119 for (Iterator it = oids.iterator(); it.hasNext();) {
3122 output.print(it.next());
3125 output.println("};");
3127 /*Create C code for endoffset values */
3128 output.print(" unsigned short endoffsetarry_[] = {");
3130 for (Iterator it = endoffset.iterator(); it.hasNext();) {
3133 output.print(it.next());
3136 output.println("};");
3138 /*Create C code for Field Offset Values */
3139 output.print(" short fieldarry_[] = {");
3141 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
3144 output.print(it.next());
3147 output.println("};");
3148 /* make the prefetch call to Runtime */
3149 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
3150 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
3151 output.println(" }");
3152 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
3153 output.println(" } else {");
3154 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
3155 output.println(" }");
3156 output.println("}");
3160 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
3161 short offsetcount = 0;
3165 } else if (localbase) {
3166 for(; breakindex<pp.desc.size(); breakindex++) {
3167 Descriptor desc=pp.getDescAt(breakindex);
3168 if (desc instanceof FieldDescriptor) {
3169 FieldDescriptor fd=(FieldDescriptor)desc;
3170 if (fd.isGlobal()) {
3178 if (breakindex>pp.desc.size()) //all local
3181 TypeDescriptor lasttype=pp.base.getType();
3182 String basestr=generateTemp(fm, pp.base, lb);
3184 boolean maybenull=fm.getMethod().isStatic()||
3185 !pp.base.equals(fm.getParameter(0));
3187 for(int i=0; i<breakindex; i++) {
3188 String indexcheck="";
3190 Descriptor desc=pp.getDescAt(i);
3191 if (desc instanceof FieldDescriptor) {
3192 FieldDescriptor fd=(FieldDescriptor)desc;
3194 if (!teststr.equals(""))
3196 teststr+="((prefptr="+basestr+")!=NULL)";
3197 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3199 basestr=basestr+"->"+fd.getSafeSymbol();
3202 lasttype=fd.getType();
3204 IndexDescriptor id=(IndexDescriptor)desc;
3205 indexcheck="((tmpindex=";
3206 for(int j=0; j<id.tddesc.size(); j++) {
3207 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3209 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3211 if (!teststr.equals(""))
3213 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3214 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3216 lasttype=lasttype.dereference();
3221 if (teststr.equals("")) {
3222 oid="((unsigned int)"+basestr+")";
3224 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3228 for(int i = breakindex; i < pp.desc.size(); i++) {
3229 String newfieldoffset;
3230 Object desc = pp.getDescAt(i);
3231 if(desc instanceof FieldDescriptor) {
3232 FieldDescriptor fd=(FieldDescriptor)desc;
3233 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3234 lasttype=fd.getType();
3236 newfieldoffset = "";
3237 IndexDescriptor id=(IndexDescriptor)desc;
3238 for(int j = 0; j < id.tddesc.size(); j++) {
3239 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3241 newfieldoffset += id.offset.toString();
3242 lasttype=lasttype.dereference();
3244 fieldoffset.add(newfieldoffset);
3247 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3248 base+=pp.desc.size()-breakindex;
3249 endoffset.add(new Short((short)base));
3254 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3255 if (lb!=fgcn.getLocality())
3257 /* Have to generate flat globalconv */
3258 if (fgcn.getMakePtr()) {
3260 //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3261 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3263 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3264 //need to do translation
3265 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3266 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3267 if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3268 output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3270 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3274 /* Need to convert to OID */
3275 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3276 if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3277 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3279 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3285 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3287 if (fion.getType().isArray()) {
3288 type=state.getArrayNumber(fion.getType())+state.numClasses();
3290 type=fion.getType().getClassDesc().getId();
3293 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3294 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3296 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3299 int sandboxcounter=0;
3300 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3301 /* Check to see if we need to generate code for this atomic */
3302 if (locality==null) {
3303 if (GENERATEPRECISEGC) {
3304 output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3305 output.println("stopforgc((struct garbagelist *) &___locals___);");
3306 output.println("pthread_mutex_lock(&atomiclock);");
3307 output.println("restartaftergc();");
3308 output.println("}");
3310 output.println("pthread_mutex_lock(&atomiclock);");
3315 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3319 if (state.SANDBOX) {
3320 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3321 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3324 if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3325 AtomicRecord ar=atomicmethodmap.get(faen);
3327 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3328 TempDescriptor tmp=tmpit.next();
3329 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3332 //copy outs that depend on path
3333 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3334 TempDescriptor tmp=tmpit.next();
3335 if (!ar.livein.contains(tmp))
3336 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3340 /* Backup the temps. */
3341 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3342 TempDescriptor tmp=tmpit.next();
3343 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3346 output.println("goto transstart"+faen.getIdentifier()+";");
3348 /******* Print code to retry aborted transaction *******/
3349 output.println("transretry"+faen.getIdentifier()+":");
3352 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3353 TempDescriptor tmp=tmpit.next();
3354 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3358 /********* Need to revert local object store ********/
3359 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3361 output.println("while ("+revertptr+") {");
3362 output.println("struct ___Object___ * tmpptr;");
3363 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3364 output.println("REVERT_OBJ("+revertptr+");");
3365 output.println(revertptr+"=tmpptr;");
3366 output.println("}");
3368 /******* Tell the runtime to start the transaction *******/
3370 output.println("transstart"+faen.getIdentifier()+":");
3371 if (state.SANDBOX) {
3372 output.println("transaction_check_counter=*counter_reset_pointer;");
3375 output.println("transStart();");
3377 if (state.ABORTREADERS||state.SANDBOX) {
3379 output.println("abortenabled=1;");
3380 output.println("if (_setjmp(aborttrans)) {");
3381 output.println(" goto transretry"+faen.getIdentifier()+"; }");
3385 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3386 /* Check to see if we need to generate code for this atomic */
3387 if (locality==null) {
3388 output.println("pthread_mutex_unlock(&atomiclock);");
3391 if (locality.getAtomic(lb).get(faen).intValue()>0)
3393 //store the revert list before we lose the transaction object
3396 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3397 output.println(revertptr+"=revertlist;");
3398 output.println("if (transCommit()) {");
3399 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3400 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3401 output.println("} else {");
3402 /* Need to commit local object store */
3403 output.println("while ("+revertptr+") {");
3404 output.println("struct ___Object___ * tmpptr;");
3405 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3406 output.println("COMMIT_OBJ("+revertptr+");");
3407 output.println(revertptr+"=tmpptr;");
3408 output.println("}");
3409 output.println("}");
3413 if (!state.DELAYCOMP) {
3415 output.println("if (transCommit()) {");
3416 /* Transaction aborts if it returns true */
3417 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3418 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3419 output.println("}");
3421 if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
3422 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3423 output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3425 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3426 TempDescriptor tmp=tmpit.next();
3427 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3429 } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3430 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3432 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3433 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3434 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3435 output.println("}");
3437 output.println("else {");
3438 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3439 TempDescriptor tmp=tmpit.next();
3440 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3442 output.println("}");
3444 output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3445 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3446 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3447 output.println("}");
3452 public void generateFlatSESEEnterNode( FlatMethod fm,
3454 FlatSESEEnterNode fsen,
3457 // if MLP flag is off, okay that SESE nodes are in IR graph,
3458 // just skip over them and code generates exactly the same
3459 if( !(state.MLP || state.OOOJAVA) ) {
3462 // there may be an SESE in an unreachable method, skip over
3463 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
3464 (state.OOOJAVA && !oooa.getAllSESEs().contains(fsen))
3469 // also, if we have encountered a placeholder, just skip it
3470 if( fsen.getIsCallerSESEplaceholder() ) {
3474 output.println(" {");
3476 // set up the parent
3477 if( (state.MLP && fsen == mlpa.getMainSESE()) ||
3478 (state.OOOJAVA && fsen == oooa.getMainSESE())
3480 output.println(" SESEcommon* parentCommon = NULL;");
3482 if( fsen.getParent() == null ) {
3483 System.out.println( "in "+fm+", "+fsen+" has null parent" );
3485 assert fsen.getParent() != null;
3486 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3487 output.println(" SESEcommon* parentCommon = &("+paramsprefix+"->common);");
3489 //output.println(" SESEcommon* parentCommon = (SESEcommon*) peekItem( seseCallStack );");
3490 output.println(" SESEcommon* parentCommon = seseCaller;");
3494 // before doing anything, lock your own record and increment the running children
3495 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3496 (state.OOOJAVA && fsen != oooa.getMainSESE())
3498 output.println(" atomic_inc(&parentCommon->numRunningChildren);");
3501 // just allocate the space for this record
3502 output.println(" "+fsen.getSESErecordName()+"* seseToIssue = ("+
3503 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3504 fsen.getSESErecordName()+" ) );");
3505 //eomgc need to set next, size
3506 // output.println(" struct garbagelist * gl= (struct garbagelist *)&(((SESEcommon*)(seseToIssue))[1]);");
3507 output.println(" struct garbagelist * gl= (struct garbagelist *)&(((SESEcommon*)(seseToIssue))[1]);");
3508 // sizeof(int)*2 + sizeof(void*)*calculateSizeOfSESEParamList(fsen)
3509 //output.println(" // sizeof(int)*2+sizeof(void*)*"+calculateSizeOfSESEParamList(fsen));
3510 //output.println(" // blah="+calculateSizeOfSESEParamSize(fsen));
3511 output.println(" (seseToIssue->common).offsetsize=sizeof(int)+sizeof(void*)+sizeof(void*)*"+calculateSizeOfSESEParamList(fsen)+calculateSizeOfSESEParamSize(fsen)+";");
3512 output.println(" gl->size="+calculateSizeOfSESEParamList(fsen)+";");
3513 // output.println(" gl->next = (struct garbagelist *)&___locals___;");
3514 output.println(" seseToIssue->prevSESECount="+calculatePrevSESECount(fsen)+";");
3515 // output.println(" seseToIssue->prevSESECount=50;");
3516 output.println(" gl->next = NULL;");
3517 // output.println(" seseToIssue->size = "+calculateSizeOfSESEParamList(fsen)+";");
3518 // output.println(" seseToIssue->next = &___locals___;");
3521 // and keep the thread-local sese stack up to date
3522 //output.println(" addNewItem( seseCallStack, (void*) seseToIssue);");
3524 // fill in common data
3525 output.println(" int localCount=0;");
3526 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3527 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
3529 output.println(" seseToIssue->common.forwardList = createQueue();");
3530 output.println(" seseToIssue->common.unresolvedDependencies = 10000;");
3531 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3532 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3533 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3534 output.println(" seseToIssue->common.numRunningChildren = 0;");
3535 output.println(" seseToIssue->common.parent = parentCommon;");
3537 // all READY in-vars should be copied now and be done with it
3538 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3539 while( tempItr.hasNext() ) {
3540 TempDescriptor temp = tempItr.next();
3542 // when we are issuing the main SESE or an SESE with placeholder
3543 // caller SESE as parent, generate temp child child's eclosing method,
3544 // otherwise use the parent's enclosing method as the context
3545 boolean useParentContext = false;
3547 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3548 (state.OOOJAVA && fsen != oooa.getMainSESE())
3550 assert fsen.getParent() != null;
3551 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3552 useParentContext = true;
3556 if( useParentContext ) {
3557 output.println(" seseToIssue->"+temp+" = "+
3558 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3560 output.println(" seseToIssue->"+temp+" = "+
3561 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3565 // before potentially adding this SESE to other forwarding lists,
3566 // create it's lock and take it immediately
3567 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3568 // output.println(" pthread_mutex_lock( &(seseToIssue->common.lock) );");
3570 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3571 (state.OOOJAVA && fsen != oooa.getMainSESE())
3573 // count up outstanding dependencies, static first, then dynamic
3574 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3575 while( staticSrcsItr.hasNext() ) {
3576 SESEandAgePair srcPair = staticSrcsItr.next();
3577 output.println(" {");
3578 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3580 if(GENERATEPRECISEGC){
3581 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3583 output.println(" pthread_mutex_lock( &(src->lock) );");
3584 if(GENERATEPRECISEGC){
3585 output.println(" restartaftergc();");
3587 output.println(" if( !isEmpty( src->forwardList ) &&");
3588 output.println(" seseToIssue == peekItem( src->forwardList ) ) {");
3589 output.println(" printf( \"This shouldnt already be here\\n\");");
3590 output.println(" exit( -1 );");
3591 output.println(" }");
3592 output.println(" if( !src->doneExecuting ) {");
3593 output.println(" addNewItem( src->forwardList, seseToIssue );");
3594 // output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3595 output.println(" ++(localCount);");
3596 output.println(" }");
3597 output.println(" pthread_mutex_unlock( &(src->lock) );");
3598 output.println(" }");
3600 // whether or not it is an outstanding dependency, make sure
3601 // to pass the static name to the child's record
3602 output.println(" seseToIssue->"+srcPair+" = "+srcPair+";");
3605 // dynamic sources might already be accounted for in the static list,
3606 // so only add them to forwarding lists if they're not already there
3607 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3608 while( dynVarsItr.hasNext() ) {
3609 TempDescriptor dynInVar = dynVarsItr.next();
3610 output.println(" {");
3611 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3613 // the dynamic source is NULL if it comes from your own space--you can't pass
3614 // the address off to the new child, because you're not done executing and
3615 // might change the variable, so copy it right now
3616 output.println(" if( src != NULL ) {");
3618 if(GENERATEPRECISEGC){
3619 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3621 output.println(" pthread_mutex_lock( &(src->lock) );");
3622 if(GENERATEPRECISEGC){
3623 output.println(" restartaftergc();");
3625 output.println(" if( isEmpty( src->forwardList ) ||");
3626 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3627 output.println(" if( !src->doneExecuting ) {");
3628 output.println(" addNewItem( src->forwardList, seseToIssue );");
3629 // output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3630 output.println(" ++(localCount);");
3631 output.println(" }");
3632 output.println(" }");
3633 output.println(" pthread_mutex_unlock( &(src->lock) );");
3634 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3635 output.println(" } else {");
3637 boolean useParentContext = false;
3638 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3639 (state.OOOJAVA && fsen != oooa.getMainSESE())
3641 assert fsen.getParent() != null;
3642 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3643 useParentContext = true;
3646 if( useParentContext ) {
3647 output.println(" seseToIssue->"+dynInVar+" = "+
3648 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3650 output.println(" seseToIssue->"+dynInVar+" = "+
3651 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3654 output.println(" }");
3655 output.println(" }");
3657 // even if the value is already copied, make sure your NULL source
3658 // gets passed so child knows it already has the dynamic value
3659 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3662 // maintain pointers for finding dynamic SESE
3663 // instances from static names
3664 SESEandAgePair pair = new SESEandAgePair( fsen, 0 );
3665 if( fsen.getParent() != null &&
3666 //!fsen.getParent().getIsCallerSESEplaceholder() &&
3667 fsen.getParent().getNeededStaticNames().contains( pair )
3670 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3671 SESEandAgePair pair1 = new SESEandAgePair( fsen, i );
3672 SESEandAgePair pair2 = new SESEandAgePair( fsen, i-1 );
3673 output.println(" "+pair1+" = "+pair2+";");
3675 output.println(" "+pair+" = seseToIssue;");
3679 // count up memory conflict dependencies,
3683 FlatSESEEnterNode parent = fsen.getParent();
3684 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(parent);
3685 if (graph != null && graph.hasConflictEdge()) {
3686 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
3688 output.println(" //add memory queue element");
3689 Analysis.OoOJava.SESEWaitingQueue seseWaitingQueue=
3690 graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet);
3691 if(seseWaitingQueue.getWaitingElementSize()>0){
3692 output.println(" {");
3693 output.println(" REntry* rentry=NULL;");
3694 output.println(" INTPTR* pointer=NULL;");
3695 output.println(" seseToIssue->common.rentryIdx=0;");
3697 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
3698 for (Iterator iterator = queueIDSet.iterator(); iterator
3700 Integer key = (Integer) iterator.next();
3701 int queueID=key.intValue();
3702 Set<Analysis.OoOJava.WaitingElement> waitingQueueSet =
3703 seseWaitingQueue.getWaitingElementSet(queueID);
3704 int enqueueType=seseWaitingQueue.getType(queueID);
3705 if(enqueueType==SESEWaitingQueue.EXCEPTION){
3706 output.println(" INITIALIZEBUF(parentCommon->memoryQueueArray["
3709 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2
3711 Analysis.OoOJava.WaitingElement waitingElement
3712 = (Analysis.OoOJava.WaitingElement) iterator2.next();
3713 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
3714 output.println(" rentry=mlpCreateREntry("
3715 + waitingElement.getStatus()
3716 + ", seseToIssue);");
3718 TempDescriptor td = waitingElement
3720 // decide whether waiting element is dynamic or static
3721 if (fsen.getDynamicInVarSet().contains(td)) {
3722 // dynamic in-var case
3723 output.println(" pointer=seseToIssue->"
3724 + waitingElement.getDynID()
3725 + "_srcSESE+seseToIssue->"
3726 + waitingElement.getDynID()
3729 .println(" rentry=mlpCreateFineREntry("
3732 + ", seseToIssue, pointer );");
3733 } else if (fsen.getStaticInVarSet()
3735 // static in-var case
3736 VariableSourceToken vst = fsen
3737 .getStaticInVarSrc(td);
3740 String srcId = "SESE_"
3742 .getPrettyIdentifier()
3743 + vst.getSESE().getIdentifier()
3744 + "_" + vst.getAge();
3746 .println(" pointer=(void*)&seseToIssue->"
3753 .println(" rentry=mlpCreateFineREntry("
3756 + ", seseToIssue, pointer );");
3761 .println(" rentry=mlpCreateFineREntry("
3764 + ", seseToIssue, (void*)&seseToIssue->"
3765 + waitingElement.getDynID()
3770 .println(" rentry->queue=parentCommon->memoryQueueArray["
3771 + waitingElement.getQueueID()
3774 if(enqueueType==SESEWaitingQueue.NORMAL){
3776 .println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
3778 .println(" if(ADDRENTRY(parentCommon->memoryQueueArray["
3779 + waitingElement.getQueueID()
3780 + "],rentry)==NOTREADY){");
3781 output.println(" ++(localCount);");
3782 output.println(" }");
3785 .println(" ADDRENTRYTOBUF(parentCommon->memoryQueueArray["
3786 + waitingElement.getQueueID()
3790 if(enqueueType!=SESEWaitingQueue.NORMAL){
3791 output.println(" localCount+=RESOLVEBUF(parentCommon->memoryQueueArray["
3792 + queueID+ "],&seseToIssue->common);");
3795 output.println(" }");
3801 ConflictGraph graph = null;
3802 FlatSESEEnterNode parent = fsen.getParent();
3803 if (parent != null) {
3804 if (parent.isCallerSESEplaceholder) {
3805 graph = mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
3807 graph = mlpa.getConflictGraphResults().get(parent);
3810 if (graph != null && graph.hasConflictEdge()) {
3811 HashSet<SESELock> seseLockSet = mlpa.getConflictGraphLockMap()
3814 output.println(" //add memory queue element");
3815 SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(fsen.getIdentifier(),
3817 if(seseWaitingQueue.getWaitingElementSize()>0){
3818 output.println(" {");
3819 output.println(" REntry* rentry=NULL;");
3820 output.println(" INTPTR* pointer=NULL;");
3821 output.println(" seseToIssue->common.rentryIdx=0;");
3823 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
3824 for (Iterator iterator = queueIDSet.iterator(); iterator
3826 Integer key = (Integer) iterator.next();
3827 int queueID=key.intValue();
3828 Set<WaitingElement> waitingQueueSet = seseWaitingQueue.getWaitingElementSet(queueID);
3829 int enqueueType=seseWaitingQueue.getType(queueID);
3830 if(enqueueType==SESEWaitingQueue.EXCEPTION){
3831 output.println(" INITIALIZEBUF(parentCommon->memoryQueueArray["
3834 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2
3836 WaitingElement waitingElement = (WaitingElement) iterator2
3838 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
3839 output.println(" rentry=mlpCreateREntry("
3840 + waitingElement.getStatus()
3841 + ", seseToIssue);");
3843 TempDescriptor td = waitingElement
3845 // decide whether waiting element is dynamic or
3847 if (fsen.getDynamicInVarSet().contains(td)) {
3848 // dynamic in-var case
3849 output.println(" pointer=seseToIssue->"
3850 + waitingElement.getDynID()
3851 + "_srcSESE+seseToIssue->"
3852 + waitingElement.getDynID()
3855 .println(" rentry=mlpCreateFineREntry("
3858 + ", seseToIssue, pointer );");
3859 } else if (fsen.getStaticInVarSet()
3861 // static in-var case
3862 VariableSourceToken vst = fsen
3863 .getStaticInVarSrc(td);
3866 String srcId = "SESE_"
3868 .getPrettyIdentifier()
3869 + vst.getSESE().getIdentifier()
3870 + "_" + vst.getAge();
3872 .println(" pointer=(void*)&seseToIssue->"
3879 .println(" rentry=mlpCreateFineREntry("
3882 + ", seseToIssue, pointer );");
3887 .println(" rentry=mlpCreateFineREntry("
3890 + ", seseToIssue, (void*)&seseToIssue->"
3891 + waitingElement.getDynID()
3896 .println(" rentry->queue=parentCommon->memoryQueueArray["
3897 + waitingElement.getQueueID()
3900 if(enqueueType==SESEWaitingQueue.NORMAL){
3902 .println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
3904 .println(" if(ADDRENTRY(parentCommon->memoryQueueArray["
3905 + waitingElement.getQueueID()
3906 + "],rentry)==NOTREADY){");
3907 output.println(" ++(localCount);");
3908 output.println(" } ");
3911 .println(" ADDRENTRYTOBUF(parentCommon->memoryQueueArray["
3912 + waitingElement.getQueueID()
3916 if(enqueueType!=SESEWaitingQueue.NORMAL){
3917 output.println(" localCount+=RESOLVEBUF(parentCommon->memoryQueueArray["
3918 + queueID+ "],&seseToIssue->common);");
3921 output.println(" }");
3929 // release this SESE for siblings to update its dependencies or,
3930 // eventually, for it to mark itself finished
3931 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3933 // if there were no outstanding dependencies, issue here
3934 output.println(" if( atomic_sub_and_test(10000-localCount,&(seseToIssue->common.unresolvedDependencies) ) ) {");
3935 output.println(" workScheduleSubmit( (void*)seseToIssue );");
3936 output.println(" }");
3938 output.println(" if( seseToIssue->common.unresolvedDependencies == 0 ) {");
3939 output.println(" workScheduleSubmit( (void*)seseToIssue );");
3940 output.println(" }");
3942 // release this SESE for siblings to update its dependencies or,
3943 // eventually, for it to mark itself finished
3944 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3945 output.println(" }");
3949 public void generateFlatSESEExitNode( FlatMethod fm,
3951 FlatSESEExitNode fsexn,
3955 // if MLP flag is off, okay that SESE nodes are in IR graph,
3956 // just skip over them and code generates exactly the same
3957 if( ! (state.MLP || state.OOOJAVA) ) {
3961 // get the enter node for this exit that has meta data embedded
3962 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
3964 // there may be an SESE in an unreachable method, skip over
3965 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
3966 (state.OOOJAVA && !oooa.getAllSESEs().contains( fsen ))
3971 // also, if we have encountered a placeholder, just jump it
3972 if( fsen.getIsCallerSESEplaceholder() ) {
3976 output.println(" /* SESE exiting */");
3978 String com = paramsprefix+"->common";
3980 // this SESE cannot be done until all of its children are done
3981 // so grab your own lock with the condition variable for watching
3982 // that the number of your running children is greater than zero
3983 if (GENERATEPRECISEGC){
3984 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3986 output.println(" pthread_mutex_lock( &("+com+".lock) );");
3987 if (GENERATEPRECISEGC){
3988 output.println(" restartaftergc();");
3990 output.println(" while( "+com+".numRunningChildren > 0 ) {");
3991 if (GENERATEPRECISEGC){
3992 // output.println(" stopforgc((struct garbagelist *)&(((SESEcommon*)(___params___))[1]));");
3993 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3995 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
3996 if (GENERATEPRECISEGC){
3997 output.println(" restartaftergc();");
3999 output.println(" }");
4002 // copy out-set from local temps into the sese record
4003 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
4004 while( itr.hasNext() ) {
4005 TempDescriptor temp = itr.next();
4007 // only have to do this for primitives non-arrays
4009 temp.getType().isPrimitive() && !temp.getType().isArray()
4015 // have to determine the context enclosing this sese
4016 boolean useParentContext = false;
4018 if( (state.MLP &&fsen != mlpa.getMainSESE()) ||
4019 (state.OOOJAVA &&fsen != oooa.getMainSESE())
4021 assert fsen.getParent() != null;
4022 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
4023 useParentContext = true;
4028 if( useParentContext ) {
4029 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
4031 from = generateTemp( fsen.getfmEnclosing(), temp, null );
4034 output.println(" "+paramsprefix+
4035 "->"+temp.getSafeSymbol()+
4039 // mark yourself done, your SESE data is now read-only
4040 output.println(" "+com+".doneExecuting = TRUE;");
4041 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
4042 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
4044 // decrement dependency count for all SESE's on your forwarding list
4045 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
4046 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
4049 output.println(" if(consumer->rentryIdx>0){");
4050 output.println(" // resolved null pointer");
4051 output.println(" int idx;");
4052 output.println(" for(idx=0;idx<consumer->rentryIdx;idx++){");
4053 output.println(" resolvePointer(consumer->rentryArray[idx]);");
4054 output.println(" }");
4055 output.println(" }");
4058 // output.println(" pthread_mutex_lock( &(consumer->lock) );");
4059 // output.println(" --(consumer->unresolvedDependencies);");
4060 // output.println(" if( consumer->unresolvedDependencies == 0 ) {");
4061 output.println(" if( atomic_sub_and_test(1, &(consumer->unresolvedDependencies)) ){");
4062 output.println(" workScheduleSubmit( (void*)consumer );");
4063 output.println(" }");
4064 // output.println(" pthread_mutex_unlock( &(consumer->lock) );");
4065 output.println(" }");
4069 // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
4070 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4071 (state.OOOJAVA && fsen != oooa.getMainSESE())
4075 output.println(" /* check memory dependency*/");
4076 output.println(" {");
4077 output.println(" int idx;");
4078 output.println(" for(idx=0;idx<___params___->common.rentryIdx;idx++){");
4079 output.println(" REntry* re=___params___->common.rentryArray[idx];");
4080 output.println(" RETIRERENTRY(re->queue,re);");
4081 output.println(" }");
4082 output.println(" }");
4086 // if parent is stalling on you, let them know you're done
4087 if( (state.MLP && fsexn.getFlatEnter() != mlpa.getMainSESE()) ||
4088 (state.OOOJAVA && fsexn.getFlatEnter() != oooa.getMainSESE())
4090 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
4093 // last of all, decrement your parent's number of running children
4094 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
4095 output.println(" if (atomic_sub_and_test(1, &"+paramsprefix+"->common.parent->numRunningChildren)) {");
4096 if (GENERATEPRECISEGC){
4097 output.println(" stopforgc((struct garbagelist *)&___locals___);");
4099 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
4100 if (GENERATEPRECISEGC){
4101 output.println(" restartaftergc();");
4103 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
4104 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
4105 output.println(" }");
4106 output.println(" }");
4108 // this is a thread-only variable that can be handled when critical sese-to-sese
4109 // data has been taken care of--set sese pointer to remember self over method
4110 // calls to a non-zero, invalid address
4111 output.println(" seseCaller = (SESEcommon*) 0x1;");
4115 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
4117 FlatWriteDynamicVarNode fwdvn,
4120 if( !(state.MLP || state.OOOJAVA) ) {
4121 // should node should not be in an IR graph if the
4122 // MLP flag is not set
4123 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
4126 Hashtable<TempDescriptor, VSTWrapper> writeDynamic = fwdvn.getVar2src();
4128 assert writeDynamic != null;
4130 Iterator wdItr = writeDynamic.entrySet().iterator();
4131 while( wdItr.hasNext() ) {
4132 Map.Entry me = (Map.Entry) wdItr.next();
4133 TempDescriptor refVar = (TempDescriptor) me.getKey();
4134 VSTWrapper vstW = (VSTWrapper) me.getValue();
4135 VariableSourceToken vst = vstW.vst;
4138 // only do this if the variable in question should be tracked,
4139 // meaning that it was explicitly added to the dynamic var set
4140 if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
4146 // if there is no given source, this variable is ready so
4147 // mark src pointer NULL to signify that the var is up-to-date
4148 output.println(" "+refVar+"_srcSESE = NULL;");
4152 // otherwise we track where it will come from
4153 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
4154 output.println(" "+refVar+"_srcSESE = "+instance+";");
4155 output.println(" "+refVar+"_srcOffset = (int) &((("+
4156 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
4161 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
4162 if (state.CONSCHECK) {
4163 String specname=fcn.getSpec();
4164 String varname="repairstate___";
4165 output.println("{");
4166 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
4168 TempDescriptor[] temps=fcn.getTemps();
4169 String[] vars=fcn.getVars();
4170 for(int i=0; i<temps.length; i++) {
4171 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
4174 output.println("if (doanalysis"+specname+"("+varname+")) {");
4175 output.println("free"+specname+"_state("+varname+");");
4176 output.println("} else {");
4177 output.println("/* Bad invariant */");
4178 output.println("free"+specname+"_state("+varname+");");
4179 output.println("abort_task();");
4180 output.println("}");
4181 output.println("}");
4185 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
4187 if( (state.MLP && !nonSESEpass) ||
4188 (state.OOOJAVA && !nonSESEpass)
4190 output.println(" seseCaller = (SESEcommon*)"+paramsprefix+";");
4193 MethodDescriptor md=fc.getMethod();
4194 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
4195 ClassDescriptor cn=md.getClassDesc();
4196 output.println("{");
4197 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4199 LocalityBinding fclb=locality.getBinding(lb, fc);
4200 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4202 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4203 output.print(objectparams.numPointers());
4204 output.print(", "+localsprefixaddr);
4205 if (md.getThis()!=null) {
4207 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
4209 if (fc.getThis()!=null&&md.getThis()==null) {
4210 System.out.println("WARNING!!!!!!!!!!!!");
4211 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
4215 for(int i=0; i<fc.numArgs(); i++) {
4216 Descriptor var=md.getParameter(i);
4217 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4218 if (objectparams.isParamPtr(paramtemp)) {
4219 TempDescriptor targ=fc.getArg(i);
4221 TypeDescriptor td=md.getParamType(i);
4223 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4225 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4228 output.println("};");
4233 if (fc.getReturnTemp()!=null)
4234 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
4236 /* Do we need to do virtual dispatch? */
4237 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
4240 LocalityBinding fclb=locality.getBinding(lb, fc);
4241 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4243 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4248 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4249 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4251 output.print(md.getReturnType().getSafeSymbol()+" ");
4252 output.print("(*)(");
4254 boolean printcomma=false;
4255 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4257 LocalityBinding fclb=locality.getBinding(lb, fc);
4258 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4260 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4264 for(int i=0; i<objectparams.numPrimitives(); i++) {
4265 TempDescriptor temp=objectparams.getPrimitive(i);
4269 if (temp.getType().isClass()||temp.getType().isArray())
4270 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
4272 output.print(temp.getType().getSafeSymbol());
4277 LocalityBinding fclb=locality.getBinding(lb, fc);
4278 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
4280 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
4284 boolean needcomma=false;
4285 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4286 output.print("&__parameterlist__");
4290 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4291 if (fc.getThis()!=null) {
4292 TypeDescriptor ptd=md.getThis().getType();
4295 if (ptd.isClass()&&!ptd.isArray())
4296 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4297 output.print(generateTemp(fm,fc.getThis(),lb));
4302 for(int i=0; i<fc.numArgs(); i++) {
4303 Descriptor var=md.getParameter(i);
4304 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4305 if (objectparams.isParamPrim(paramtemp)) {
4306 TempDescriptor targ=fc.getArg(i);
4310 TypeDescriptor ptd=md.getParamType(i);
4311 if (ptd.isClass()&&!ptd.isArray())
4312 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4313 output.print(generateTemp(fm, targ,lb));
4317 output.println(");");
4318 output.println(" }");
4321 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
4322 Set subclasses=typeutil.getSubClasses(thiscd);
4323 if (subclasses==null)
4325 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
4326 ClassDescriptor cd=(ClassDescriptor)classit.next();
4327 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
4328 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
4329 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
4330 if (md.matches(matchmd))
4337 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
4338 if (state.SINGLETM) {
4339 //single machine transactional memory case
4340 String field=ffn.getField().getSafeSymbol();
4341 String src=generateTemp(fm, ffn.getSrc(),lb);
4342 String dst=generateTemp(fm, ffn.getDst(),lb);
4344 output.println(dst+"="+ src +"->"+field+ ";");
4345 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
4346 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
4347 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
4348 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
4349 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
4350 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
4351 if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
4352 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4354 output.println("TRANSREADRD("+dst+", "+dst+");");
4357 } else if (state.DSM) {
4358 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
4359 if (status==LocalityAnalysis.GLOBAL) {
4360 String field=ffn.getField().getSafeSymbol();
4361 String src=generateTemp(fm, ffn.getSrc(),lb);
4362 String dst=generateTemp(fm, ffn.getDst(),lb);
4364 if (ffn.getField().getType().isPtr()) {
4366 //TODO: Uncomment this when we have runtime support
4367 //if (ffn.getSrc()==ffn.getDst()) {
4368 //output.println("{");
4369 //output.println("void * temp="+src+";");
4370 //output.println("if (temp&0x1) {");
4371 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
4372 //output.println(src+"->"+field+"="+temp+";");
4373 //output.println("}");
4374 //output.println(dst+"=temp;");
4375 //output.println("}");
4377 output.println(dst+"="+ src +"->"+field+ ";");
4378 //output.println("if ("+dst+"&0x1) {");
4379 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4380 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4381 //output.println(src+"->"+field+"="+src+"->"+field+";");
4382 //output.println("}");
4385 output.println(dst+"="+ src+"->"+field+";");
4387 } else if (status==LocalityAnalysis.LOCAL) {
4388 if (ffn.getField().getType().isPtr()&&
4389 ffn.getField().isGlobal()) {
4390 String field=ffn.getField().getSafeSymbol();
4391 String src=generateTemp(fm, ffn.getSrc(),lb);
4392 String dst=generateTemp(fm, ffn.getDst(),lb);
4393 output.println(dst+"="+ src +"->"+field+ ";");
4394 if (locality.getAtomic(lb).get(ffn).intValue()>0)
4395 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4396 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4398 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4399 } else if (status==LocalityAnalysis.EITHER) {
4400 //Code is reading from a null pointer
4401 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
4402 output.println("#ifndef RAW");
4403 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4404 output.println("#endif");
4405 //This should throw a suitable null pointer error
4406 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4408 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4410 // DEBUG if(!ffn.getDst().getType().isPrimitive()){
4411 // DEBUG output.println("within((void*)"+generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+");");
4413 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4418 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
4419 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
4420 throw new Error("Can't set array length");
4421 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4422 //Single Machine Transaction Case
4423 boolean srcptr=fsfn.getSrc().getType().isPtr();
4424 String src=generateTemp(fm,fsfn.getSrc(),lb);
4425 String dst=generateTemp(fm,fsfn.getDst(),lb);
4426 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
4427 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
4428 output.println("{");
4429 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
4430 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
4431 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4433 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4436 if (wb.needBarrier(fsfn)&&
4437 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
4438 if (state.EVENTMONITOR) {
4439 output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
4441 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
4443 if (srcptr&!fsfn.getSrc().getType().isNull()) {
4444 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4445 output.println("}");
4447 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4449 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4450 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
4451 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
4452 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4454 String src=generateTemp(fm,fsfn.getSrc(),lb);
4455 String dst=generateTemp(fm,fsfn.getDst(),lb);
4457 output.println("{");
4458 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4460 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
4463 if (wb.needBarrier(fsfn))
4464 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
4466 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4468 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4469 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
4470 /** Check if we need to copy */
4471 output.println("if(!"+dst+"->"+localcopystr+") {");
4472 /* Link object into list */
4473 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4474 output.println(revertptr+"=revertlist;");
4475 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4476 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4478 output.println("COPY_OBJ("+dst+");");
4479 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4480 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4481 output.println("}");
4483 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4485 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4486 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
4487 //writing to a null...bad
4488 output.println("if ("+dst+") {");
4489 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
4491 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4493 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4496 output.println("}");
4499 if (state.FASTCHECK) {
4500 String dst=generateTemp(fm, fsfn.getDst(),lb);
4501 output.println("if(!"+dst+"->"+localcopystr+") {");
4502 /* Link object into list */
4503 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4504 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4506 output.println("COPY_OBJ("+dst+");");
4507 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4508 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4509 output.println("}");
4512 // DEBUG if(!fsfn.getField().getType().isPrimitive()){
4513 // DEBUG output.println("within((void*)"+generateTemp(fm,fsfn.getSrc(),lb)+");");
4515 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4519 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
4520 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
4523 if (elementtype.isArray()||elementtype.isClass())
4526 type=elementtype.getSafeSymbol()+" ";
4528 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
4529 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
4530 output.println("failedboundschk();");
4532 if (state.SINGLETM) {
4533 //Single machine transaction case
4534 String dst=generateTemp(fm, fen.getDst(),lb);
4535 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))) {
4536 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4538 output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
4541 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
4542 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
4543 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
4544 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
4545 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
4546 if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
4547 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4549 output.println("TRANSREADRD("+dst+", "+dst+");");
4552 } else if (state.DSM) {
4553 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
4554 if (status==LocalityAnalysis.GLOBAL) {
4555 String dst=generateTemp(fm, fen.getDst(),lb);
4556 if (elementtype.isPtr()) {
4557 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4558 //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
4559 output.println("TRANSREAD("+dst+", "+dst+");");
4561 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4563 } else if (status==LocalityAnalysis.LOCAL) {
4564 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4565 } else if (status==LocalityAnalysis.EITHER) {
4566 //Code is reading from a null pointer
4567 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
4568 output.println("#ifndef RAW");
4569 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4570 output.println("#endif");
4571 //This should throw a suitable null pointer error
4572 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4574 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4576 // DEBUG output.println("within((void*)"+generateTemp(fm,fen.getSrc(),lb)+");");
4577 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4581 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
4582 //TODO: need dynamic check to make sure this assignment is actually legal
4583 //Because Object[] could actually be something more specific...ie. Integer[]
4585 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
4588 if (elementtype.isArray()||elementtype.isClass())
4591 type=elementtype.getSafeSymbol()+" ";
4593 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
4594 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
4595 output.println("failedboundschk();");
4598 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4599 //Transaction set element case
4600 if (wb.needBarrier(fsen)&&
4601 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
4602 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
4604 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
4605 output.println("{");
4606 String src=generateTemp(fm, fsen.getSrc(), lb);
4607 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
4608 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
4609 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4611 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4613 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4614 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
4616 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4618 output.println("}");
4620 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4621 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
4623 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4626 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4627 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
4628 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
4629 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4630 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
4631 boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
4634 if (wb.needBarrier(fsen))
4635 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
4636 } else if (dstlocal) {
4637 /** Check if we need to copy */
4638 String dst=generateTemp(fm, fsen.getDst(),lb);
4639 output.println("if(!"+dst+"->"+localcopystr+") {");
4640 /* Link object into list */
4641 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4642 output.println(revertptr+"=revertlist;");
4643 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
4644 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4646 output.println("COPY_OBJ("+dst+");");
4647 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4648 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4649 output.println("}");
4651 System.out.println("Node: "+fsen);
4652 System.out.println(lb);
4653 System.out.println("statusdst="+statusdst);
4654 System.out.println(fm.printMethod());
4655 throw new Error("Unknown array type");
4658 output.println("{");
4659 String src=generateTemp(fm, fsen.getSrc(), lb);
4660 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4661 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4662 output.println("}");
4664 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4667 if (state.FASTCHECK) {
4668 String dst=generateTemp(fm, fsen.getDst(),lb);
4669 output.println("if(!"+dst+"->"+localcopystr+") {");
4670 /* Link object into list */
4671 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4672 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4674 output.println("COPY_OBJ("+dst+");");
4675 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4676 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4677 output.println("}");
4679 // DEBUG output.println("within((void*)"+generateTemp(fm,fsen.getDst(),lb)+");");
4680 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4684 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
4685 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4686 //Stash pointer in case of GC
4687 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4688 output.println(revertptr+"=revertlist;");
4690 if (state.SINGLETM) {
4691 if (fn.getType().isArray()) {
4692 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4693 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4694 //inside transaction
4695 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4697 //outside transaction
4698 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4701 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4702 //inside transaction
4703 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4705 //outside transaction
4706 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4709 } else if (fn.getType().isArray()) {
4710 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4711 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4712 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4713 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4714 if(this.state.MLP || state.OOOJAVA){
4715 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray_oid("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+", oid);");
4716 output.println(" oid += numWorkers;");
4718 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4721 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4724 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4725 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
4726 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4727 if (this.state.MLP || state.OOOJAVA){
4728 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new_oid("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+", oid);");
4729 output.println(" oid += numWorkers;");
4731 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4734 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
4737 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4738 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4739 String dst=generateTemp(fm,fn.getDst(),lb);
4740 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4741 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4742 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4744 if (state.FASTCHECK) {
4745 String dst=generateTemp(fm,fn.getDst(),lb);
4746 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4747 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4748 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4752 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
4753 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4754 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
4756 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
4760 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
4761 if (fon.getRight()!=null) {
4762 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
4763 if (fon.getLeft().getType().isLong())
4764 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4766 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4768 } else if (dc!=null) {
4769 output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
4770 if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4771 output.print("(void *)");
4772 if (dc.getNeedLeftSrcTrans(lb, fon))
4773 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
4775 output.print(generateTemp(fm, fon.getLeft(),lb));
4776 output.print(")"+fon.getOp().toString()+"(");
4777 if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4778 output.print("(void *)");
4779 if (dc.getNeedRightSrcTrans(lb, fon))
4780 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
4782 output.println(generateTemp(fm,fon.getRight(),lb)+");");
4784 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
4785 } else if (fon.getOp().getOp()==Operation.ASSIGN)
4786 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4787 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
4788 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4789 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
4790 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
4791 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
4792 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
4793 else if (fon.getOp().getOp()==Operation.COMP)
4794 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
4795 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
4796 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
4798 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
4801 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
4802 /* TODO: Do type check here */
4803 if (fcn.getType().isArray()) {
4804 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4805 } else if (fcn.getType().isClass())
4806 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4808 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
4811 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
4812 if (fln.getValue()==null)
4813 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4814 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
4815 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4816 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4817 //Stash pointer in case of GC
4818 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4819 output.println(revertptr+"=revertlist;");
4821 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4822 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4823 //Stash pointer in case of GC
4824 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4825 output.println("revertlist="+revertptr+";");
4828 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4830 } else if (fln.getType().isBoolean()) {
4831 if (((Boolean)fln.getValue()).booleanValue())
4832 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
4834 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4835 } else if (fln.getType().isChar()) {
4836 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
4837 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
4838 } else if (fln.getType().isLong()) {
4839 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
4841 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
4844 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
4845 if (frn.getReturnTemp()!=null) {
4846 if (frn.getReturnTemp().getType().isPtr())
4847 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4849 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4851 output.println("return;");
4855 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4858 //only record if this group has more than one exit
4859 if (branchanalysis.numJumps(fcb)>1) {
4860 left=branchanalysis.jumpValue(fcb, 0);
4861 right=branchanalysis.jumpValue(fcb, 1);
4863 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
4865 output.println("STOREBRANCH("+right+");");
4866 output.println("goto "+label+";");
4867 output.println("}");
4869 output.println("STOREBRANCH("+left+");");
4872 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4873 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
4876 /** This method generates header information for the method or
4877 * task referenced by the Descriptor des. */
4878 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
4879 generateHeader(fm, lb, des, output, false);
4882 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
4884 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
4885 MethodDescriptor md=null;
4886 TaskDescriptor task=null;
4887 if (des instanceof MethodDescriptor)
4888 md=(MethodDescriptor) des;
4890 task=(TaskDescriptor) des;
4892 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
4894 if (md!=null&&md.getReturnType()!=null) {
4895 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4896 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4898 output.print(md.getReturnType().getSafeSymbol()+" ");
4900 //catch the constructor case
4901 output.print("void ");
4903 if (state.DSM||state.SINGLETM) {
4904 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4906 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4908 output.print(task.getSafeSymbol()+"(");
4910 boolean printcomma=false;
4911 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4913 if (state.DSM||state.SINGLETM) {
4914 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4916 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4918 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
4924 for(int i=0; i<objectparams.numPrimitives(); i++) {
4925 TempDescriptor temp=objectparams.getPrimitive(i);
4929 if (temp.getType().isClass()||temp.getType().isArray())
4930 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
4932 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
4934 output.println(") {");
4935 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4936 /* Imprecise Task */
4937 output.println("void * parameterarray[]) {");
4938 /* Unpack variables */
4939 for(int i=0; i<objectparams.numPrimitives(); i++) {
4940 TempDescriptor temp=objectparams.getPrimitive(i);
4941 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
4943 for(int i=0; i<fm.numTags(); i++) {
4944 TempDescriptor temp=fm.getTag(i);
4945 int offset=i+objectparams.numPrimitives();
4946 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
4949 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
4950 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
4951 } else output.println(") {");
4954 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
4955 output.println("/* FlatFlagActionNode */");
4958 /* Process tag changes */
4959 Relation tagsettable=new Relation();
4960 Relation tagcleartable=new Relation();
4962 Iterator tagsit=ffan.getTempTagPairs();
4963 while (tagsit.hasNext()) {
4964 TempTagPair ttp=(TempTagPair) tagsit.next();
4965 TempDescriptor objtmp=ttp.getTemp();
4966 TagDescriptor tag=ttp.getTag();
4967 TempDescriptor tagtmp=ttp.getTagTemp();
4968 boolean tagstatus=ffan.getTagChange(ttp);
4970 tagsettable.put(objtmp, tagtmp);
4972 tagcleartable.put(objtmp, tagtmp);
4977 Hashtable flagandtable=new Hashtable();
4978 Hashtable flagortable=new Hashtable();
4980 /* Process flag changes */
4981 Iterator flagsit=ffan.getTempFlagPairs();
4982 while(flagsit.hasNext()) {
4983 TempFlagPair tfp=(TempFlagPair)flagsit.next();
4984 TempDescriptor temp=tfp.getTemp();
4985 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
4986 FlagDescriptor flag=tfp.getFlag();
4988 //Newly allocate objects that don't set any flags case
4989 if (flagortable.containsKey(temp)) {
4993 flagortable.put(temp,new Integer(mask));
4995 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
4996 boolean flagstatus=ffan.getFlagChange(tfp);
4999 if (flagortable.containsKey(temp)) {
5000 mask=((Integer)flagortable.get(temp)).intValue();
5003 flagortable.put(temp,new Integer(mask));
5005 int mask=0xFFFFFFFF;
5006 if (flagandtable.containsKey(temp)) {
5007 mask=((Integer)flagandtable.get(temp)).intValue();
5009 mask&=(0xFFFFFFFF^flagid);
5010 flagandtable.put(temp,new Integer(mask));
5016 HashSet flagtagset=new HashSet();
5017 flagtagset.addAll(flagortable.keySet());
5018 flagtagset.addAll(flagandtable.keySet());
5019 flagtagset.addAll(tagsettable.keySet());
5020 flagtagset.addAll(tagcleartable.keySet());
5022 Iterator ftit=flagtagset.iterator();
5023 while(ftit.hasNext()) {
5024 TempDescriptor temp=(TempDescriptor)ftit.next();
5027 Set tagtmps=tagcleartable.get(temp);
5028 if (tagtmps!=null) {
5029 Iterator tagit=tagtmps.iterator();
5030 while(tagit.hasNext()) {
5031 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5032 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5033 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5035 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5039 tagtmps=tagsettable.get(temp);
5040 if (tagtmps!=null) {
5041 Iterator tagit=tagtmps.iterator();
5042 while(tagit.hasNext()) {
5043 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5044 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5045 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5047 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
5052 int andmask=0xFFFFFFF;
5054 if (flagortable.containsKey(temp))
5055 ormask=((Integer)flagortable.get(temp)).intValue();
5056 if (flagandtable.containsKey(temp))
5057 andmask=((Integer)flagandtable.get(temp)).intValue();
5058 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
5059 generateObjectDistribute(ffan, fm, lb, temp, output);
5063 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
5064 PrintWriter output, int ormask, int andmask) {
5065 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
5066 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5068 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5072 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
5073 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
5076 void generateOptionalHeader(PrintWriter headers) {
5079 headers.println("#include \"task.h\"\n\n");
5080 headers.println("#ifndef _OPTIONAL_STRUCT_");
5081 headers.println("#define _OPTIONAL_STRUCT_");
5083 //STRUCT PREDICATEMEMBER
5084 headers.println("struct predicatemember{");
5085 headers.println("int type;");
5086 headers.println("int numdnfterms;");
5087 headers.println("int * flags;");
5088 headers.println("int numtags;");
5089 headers.println("int * tags;\n};\n\n");
5091 //STRUCT OPTIONALTASKDESCRIPTOR
5092 headers.println("struct optionaltaskdescriptor{");
5093 headers.println("struct taskdescriptor * task;");
5094 headers.println("int index;");
5095 headers.println("int numenterflags;");
5096 headers.println("int * enterflags;");
5097 headers.println("int numpredicatemembers;");
5098 headers.println("struct predicatemember ** predicatememberarray;");
5099 headers.println("};\n\n");
5101 //STRUCT TASKFAILURE
5102 headers.println("struct taskfailure {");
5103 headers.println("struct taskdescriptor * task;");
5104 headers.println("int index;");
5105 headers.println("int numoptionaltaskdescriptors;");
5106 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5108 //STRUCT FSANALYSISWRAPPER
5109 headers.println("struct fsanalysiswrapper{");
5110 headers.println("int flags;");
5111 headers.println("int numtags;");
5112 headers.println("int * tags;");
5113 headers.println("int numtaskfailures;");
5114 headers.println("struct taskfailure ** taskfailurearray;");
5115 headers.println("int numoptionaltaskdescriptors;");
5116 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5118 //STRUCT CLASSANALYSISWRAPPER
5119 headers.println("struct classanalysiswrapper{");
5120 headers.println("int type;");
5121 headers.println("int numotd;");
5122 headers.println("struct optionaltaskdescriptor ** otdarray;");
5123 headers.println("int numfsanalysiswrappers;");
5124 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
5126 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
5128 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
5129 while(taskit.hasNext()) {
5130 TaskDescriptor td=(TaskDescriptor)taskit.next();
5131 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
5136 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
5137 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
5138 int predicateindex = 0;
5139 //iterate through the classes concerned by the predicate
5140 Set c_vard = predicate.vardescriptors;
5141 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
5144 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
5145 VarDescriptor vard = (VarDescriptor)vard_it.next();
5146 TypeDescriptor typed = vard.getType();
5148 //generate for flags
5149 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
5150 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5152 if (fen_hashset!=null) {
5153 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
5154 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
5156 DNFFlag dflag=fen.getDNF();
5157 numberterms+=dflag.size();
5159 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
5161 for(int j=0; j<dflag.size(); j++) {
5163 output.println(",");
5164 Vector term=dflag.get(j);
5167 for(int k=0; k<term.size(); k++) {
5168 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
5169 FlagDescriptor fd=dfa.getFlag();
5170 boolean negated=dfa.getNegated();
5171 int flagid=1<<((Integer)flags.get(fd)).intValue();
5176 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
5181 output.println("};\n");
5184 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
5185 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5188 for(int j=0; j<tagel.numTags(); j++) {
5190 output.println(",");
5191 TempDescriptor tmp=tagel.getTemp(j);
5192 if (!slotnumber.containsKey(tmp)) {
5193 Integer slotint=new Integer(current_slot++);
5194 slotnumber.put(tmp,slotint);
5196 int slot=slotnumber.get(tmp).intValue();
5197 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
5199 numtags = tagel.numTags();
5201 output.println("};");
5203 //store the result into a predicatemember struct
5204 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5205 output.println("/*type*/"+typed.getClassDesc().getId()+",");
5206 output.println("/* number of dnf terms */"+numberterms+",");
5207 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5208 output.println("/* number of tag */"+numtags+",");
5209 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5210 output.println("};\n");
5215 //generate an array that stores the entire predicate
5216 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5217 for( int j = 0; j<predicateindex; j++) {
5218 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5219 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5221 output.println("};\n");
5222 return predicateindex;
5226 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
5227 generateOptionalHeader(headers);
5229 output.println("#include \"optionalstruct.h\"\n\n");
5230 output.println("#include \"stdlib.h\"\n");
5232 HashSet processedcd = new HashSet();
5234 Enumeration e = safeexecution.keys();
5235 while (e.hasMoreElements()) {
5238 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
5239 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
5241 //Generate the struct of optionals
5242 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5243 numotd = c_otd.size();
5244 if(maxotd<numotd) maxotd = numotd;
5245 if( !c_otd.isEmpty() ) {
5246 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5247 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5249 //generate the int arrays for the predicate
5250 Predicate predicate = otd.predicate;
5251 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
5252 TreeSet<Integer> fsset=new TreeSet<Integer>();
5253 //iterate through possible FSes corresponding to
5254 //the state when entering
5256 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
5257 FlagState fs = (FlagState)fses.next();
5259 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5260 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5261 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5264 fsset.add(new Integer(flagid));
5265 //tag information not needed because tag
5266 //changes are not tolerated.
5269 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5270 boolean needcomma=false;
5271 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
5274 output.println(it.next());
5277 output.println("};\n");
5280 //generate optionaltaskdescriptor that actually
5281 //includes exit fses, predicate and the task
5283 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5284 output.println("&task_"+otd.td.getSafeSymbol()+",");
5285 output.println("/*index*/"+otd.getIndex()+",");
5286 output.println("/*number of enter flags*/"+fsset.size()+",");
5287 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5288 output.println("/*number of members */"+predicateindex+",");
5289 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5290 output.println("};\n");
5294 // if there are no optionals, there is no need to build the rest of the struct
5296 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
5297 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5298 if( !c_otd.isEmpty() ) {
5299 boolean needcomma=false;
5300 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5301 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5303 output.println(",");
5305 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5308 output.println("};\n");
5310 //get all the possible flagstates reachable by an object
5311 Hashtable hashtbtemp = safeexecution.get(cdtemp);
5313 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
5314 fsts.addAll(hashtbtemp.keySet());
5315 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
5316 FlagState fs = (FlagState)fsit.next();
5319 //get the set of OptionalTaskDescriptors corresponding
5320 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
5321 //iterate through the OptionalTaskDescriptors and
5322 //store the pointers to the optionals struct (see on
5323 //top) into an array
5325 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
5326 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
5327 OptionalTaskDescriptor mm = mos.next();
5329 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
5331 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5334 output.println("};\n");
5336 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
5339 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5340 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5341 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5345 //process tag information
5348 boolean first = true;
5349 Enumeration tag_enum = fs.getTags();
5350 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5351 while(tag_enum.hasMoreElements()) {
5353 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
5357 output.println(", ");
5358 output.println("/*tagid*/"+state.getTagId(tagd));
5360 output.println("};");
5362 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
5363 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5364 TaskIndex ti=itti.next();
5368 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
5370 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
5371 boolean needcomma=false;
5372 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
5373 OptionalTaskDescriptor otd=otdit.next();
5377 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5379 output.println("};");
5381 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
5382 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
5383 output.print(ti.getIndex()+", ");
5384 output.print(otdset.size()+", ");
5385 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
5386 output.println("};");
5389 tiset=sa.getTaskIndex(fs);
5390 boolean needcomma=false;
5392 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5393 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5394 TaskIndex ti=itti.next();
5395 if (ti.isRuntime()) {
5402 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
5404 output.println("};\n");
5406 //Store the result in fsanalysiswrapper
5408 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
5409 output.println("/*flag*/"+flagid+",");
5410 output.println("/* number of tags*/"+tagcounter+",");
5411 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5412 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
5413 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5414 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
5415 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
5416 output.println("};\n");
5420 //Build the array of fsanalysiswrappers
5421 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
5422 boolean needcomma=false;
5423 for(int i = 0; i<fscounter; i++) {
5424 if (needcomma) output.print(",");
5425 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
5428 output.println("};");
5430 //Build the classanalysiswrapper referring to the previous array
5431 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
5432 output.println("/*type*/"+cdtemp.getId()+",");
5433 output.println("/*numotd*/"+numotd+",");
5434 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
5435 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
5436 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
5437 processedcd.add(cdtemp);
5440 //build an array containing every classes for which code has been build
5441 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
5442 for(int i=0; i<state.numClasses(); i++) {
5443 ClassDescriptor cn=cdarray[i];
5446 if ((cn != null) && (processedcd.contains(cn)))
5447 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
5449 output.print("NULL");
5451 output.println("};");
5453 output.println("#define MAXOTD "+maxotd);
5454 headers.println("#endif");
5457 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
5458 Relation r=new Relation();
5459 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
5460 OptionalTaskDescriptor otd=otdit.next();
5461 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
5465 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
5466 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
5467 Set s=r.get(it.next());
5468 for(Iterator it2=s.iterator(); it2.hasNext();) {
5469 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
5477 protected void outputTransCode(PrintWriter output) {
5480 private int calculateSizeOfSESEParamList(FlatSESEEnterNode fsen){
5482 Set<TempDescriptor> tdSet=new HashSet<TempDescriptor>();
5484 for (Iterator iterator = fsen.getInVarSet().iterator(); iterator.hasNext();) {
5485 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5486 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5487 tdSet.add(tempDescriptor);
5491 for (Iterator iterator = fsen.getOutVarSet().iterator(); iterator.hasNext();) {
5492 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5493 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5494 tdSet.add(tempDescriptor);
5498 return tdSet.size();
5501 private String calculateSizeOfSESEParamSize(FlatSESEEnterNode fsen){
5502 HashMap <String,Integer> map=new HashMap();
5503 HashSet <TempDescriptor> processed=new HashSet<TempDescriptor>();
5506 // space for all in and out set primitives
5507 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
5508 inSetAndOutSet.addAll( fsen.getInVarSet() );
5509 inSetAndOutSet.addAll( fsen.getOutVarSet() );
5511 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
5513 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
5514 while( itr.hasNext() ) {
5515 TempDescriptor temp = itr.next();
5516 TypeDescriptor type = temp.getType();
5517 if( !type.isPtr() ) {
5518 inSetAndOutSetPrims.add( temp );
5522 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
5523 while( itrPrims.hasNext() ) {
5524 TempDescriptor temp = itrPrims.next();
5525 TypeDescriptor type = temp.getType();
5526 if(type.isPrimitive()){
5527 Integer count=map.get(type.getSymbol());
5529 count=new Integer(1);
5530 map.put(type.getSymbol(), count);
5532 map.put(type.getSymbol(), new Integer(count.intValue()+1));
5537 Set<String> keySet=map.keySet();
5538 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
5539 String key = (String) iterator.next();
5540 rtr+="+sizeof("+key+")*"+map.get(key);
5545 private int calculatePrevSESECount(FlatSESEEnterNode fsen){
5549 Iterator<TempDescriptor>itrDynInVars = fsen.getDynamicInVarSet().iterator();
5550 while( itrDynInVars.hasNext() ) {
5551 TempDescriptor dynInVar = itrDynInVars.next();
5555 // in-set source tracking
5556 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
5557 while( itrStaticInVarSrcs.hasNext() ) {
5558 SESEandAgePair srcPair = itrStaticInVarSrcs.next();