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.Prefetch.*;
27 import Analysis.Loops.WriteBarrier;
28 import Analysis.Loops.GlobalFieldType;
29 import Analysis.Locality.TypeAnalysis;
30 import Analysis.MLP.ConflictGraph;
31 import Analysis.MLP.ConflictNode;
32 import Analysis.MLP.MLPAnalysis;
33 import Analysis.MLP.ParentChildConflictsMap;
34 import Analysis.MLP.SESELock;
35 import Analysis.MLP.VariableSourceToken;
36 import Analysis.MLP.VSTWrapper;
37 import Analysis.MLP.CodePlan;
38 import Analysis.MLP.SESEandAgePair;
39 import Analysis.MLP.WaitingElement;
41 public class BuildCode {
44 Hashtable paramstable;
49 String localsprefix="___locals___";
50 String localsprefixaddr="&"+localsprefix;
51 String localsprefixderef=localsprefix+".";
52 String fcrevert="___fcrevert___";
53 String paramsprefix="___params___";
54 String oidstr="___nextobject___";
55 String nextobjstr="___nextobject___";
56 String localcopystr="___localcopy___";
57 public static boolean GENERATEPRECISEGC=false;
58 public static String PREFIX="";
59 public static String arraytype="ArrayObject";
60 public static int flagcount = 0;
63 protected int maxtaskparams=0;
64 private int maxcount=0;
65 ClassDescriptor[] cdarray;
66 TypeDescriptor[] arraytable;
67 LocalityAnalysis locality;
68 Hashtable<LocalityBinding, TempDescriptor> reverttable;
69 Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>> backuptable;
73 String mlperrstr = "if(status != 0) { "+
74 "sprintf(errmsg, \"MLP error at %s:%d\", __FILE__, __LINE__); "+
75 "perror(errmsg); exit(-1); }";
76 boolean nonSESEpass=true;
79 DiscoverConflicts recorddc;
84 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa) {
85 this(st, temptovar, typeutil, null, sa, pa, null);
88 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa) {
89 this(st, temptovar, typeutil, null, sa, pa, mlpa);
92 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, PrefetchAnalysis pa, MLPAnalysis mlpa) {
93 this(st, temptovar, typeutil, locality, null, pa, mlpa);
96 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa) {
101 callgraph=new CallGraph(state);
103 oidstr="___objlocation___";
104 this.temptovar=temptovar;
105 paramstable=new Hashtable();
106 tempstable=new Hashtable();
107 fieldorder=new Hashtable();
108 flagorder=new Hashtable();
109 this.typeutil=typeutil;
110 virtualcalls=new Virtual(state,locality);
111 if (locality!=null) {
112 this.locality=locality;
113 this.reverttable=new Hashtable<LocalityBinding, TempDescriptor>();
114 this.backuptable=new Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>>();
115 this.wb=new WriteBarrier(locality, st);
117 if (state.SINGLETM&&state.DCOPTS) {
118 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
119 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
120 this.dc=new DiscoverConflicts(locality, st, typeanalysis, gft);
123 if (state.DELAYCOMP) {
124 //TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
125 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
126 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
127 delaycomp=new DCWrapper(locality, st, typeanalysis, gft);
128 dc=delaycomp.getConflicts();
129 recorddc=new DiscoverConflicts(locality, st, typeanalysis, delaycomp.getCannotDelayMap(), true, true, null);
130 recorddc.doAnalysis();
134 /** The buildCode method outputs C code for all the methods. The Flat
135 * versions of the methods must already be generated and stored in
136 * the State object. */
137 PrintWriter outsandbox=null;
139 public void buildCode() {
140 /* Create output streams to write to */
141 PrintWriter outclassdefs=null;
142 PrintWriter outstructs=null;
143 PrintWriter outrepairstructs=null;
144 PrintWriter outmethodheader=null;
145 PrintWriter outmethod=null;
146 PrintWriter outvirtual=null;
147 PrintWriter outtask=null;
148 PrintWriter outtaskdefs=null;
149 PrintWriter outoptionalarrays=null;
150 PrintWriter optionalheaders=null;
154 outsandbox=new PrintWriter(new FileOutputStream(PREFIX+"sandboxdefs.c"), true);
156 outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
157 outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
158 outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
159 outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
160 outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
162 outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
163 outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
164 if (state.OPTIONAL) {
165 outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
166 optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
169 if (state.structfile!=null) {
170 outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
172 } catch (Exception e) {
177 /* Build the virtual dispatch tables */
178 buildVirtualTables(outvirtual);
180 /* Output includes */
181 outmethodheader.println("#ifndef METHODHEADERS_H");
182 outmethodheader.println("#define METHODHEADERS_H");
183 outmethodheader.println("#include \"structdefs.h\"");
185 outmethodheader.println("#include \"dstm.h\"");
187 outmethodheader.println("#include \"sandbox.h\"");
189 if (state.EVENTMONITOR) {
190 outmethodheader.println("#include \"monitor.h\"");
192 if (state.SINGLETM) {
193 outmethodheader.println("#include \"tm.h\"");
194 outmethodheader.println("#include \"delaycomp.h\"");
195 outmethodheader.println("#include \"inlinestm.h\"");
197 if (state.ABORTREADERS) {
198 outmethodheader.println("#include \"abortreaders.h\"");
199 outmethodheader.println("#include <setjmp.h>");
202 outmethodheader.println("#include <stdlib.h>");
203 outmethodheader.println("#include <stdio.h>");
204 outmethodheader.println("#include <string.h>");
205 outmethodheader.println("#include \"mlp_runtime.h\"");
206 outmethodheader.println("#include \"psemaphore.h\"");
209 /* Output Structures */
210 outputStructs(outstructs);
212 // Output the C class declarations
213 // These could mutually reference each other
214 outputClassDeclarations(outclassdefs);
216 // Output function prototypes and structures for parameters
217 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
218 while(it.hasNext()) {
219 ClassDescriptor cn=(ClassDescriptor)it.next();
220 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader);
222 outclassdefs.close();
225 /* Map flags to integers */
226 /* The runtime keeps track of flags using these integers */
227 it=state.getClassSymbolTable().getDescriptorsIterator();
228 while(it.hasNext()) {
229 ClassDescriptor cn=(ClassDescriptor)it.next();
233 generateTaskStructs(outstructs, outmethodheader);
235 /* Outputs generic task structures if this is a task
237 outputTaskTypes(outtask);
241 // have to initialize some SESE compiler data before
242 // analyzing normal methods, which must happen before
243 // generating SESE internal code
244 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
245 FlatSESEEnterNode fsen = seseit.next();
246 initializeSESE( fsen );
250 /* Build the actual methods */
251 outputMethods(outmethod);
253 // Output function prototypes and structures for SESE's and code
256 // used to differentiate, during code generation, whether we are
257 // passing over SESE body code, or non-SESE code
260 // first generate code for each sese's internals
261 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
262 FlatSESEEnterNode fsen = seseit.next();
263 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
266 // then write the invokeSESE switch to decouple scheduler
267 // from having to do unique details of sese invocation
268 generateSESEinvocationMethod(outmethodheader, outmethod);
272 /* Output code for tasks */
273 outputTaskCode(outtaskdefs, outmethod);
275 /* Record maximum number of task parameters */
276 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
277 } else if (state.main!=null) {
278 /* Generate main method */
279 outputMainMethod(outmethod);
282 /* Generate information for task with optional parameters */
283 if (state.TASK&&state.OPTIONAL) {
284 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
285 outoptionalarrays.close();
288 /* Output structure definitions for repair tool */
289 if (state.structfile!=null) {
290 buildRepairStructs(outrepairstructs);
291 outrepairstructs.close();
295 outmethodheader.println("#endif");
296 outmethodheader.close();
298 outstructs.println("#endif");
303 /* This code just generates the main C method for java programs.
304 * The main C method packs up the arguments into a string array
305 * and passes it to the java main method. */
307 private void outputMainMethod(PrintWriter outmethod) {
308 outmethod.println("int main(int argc, const char *argv[]) {");
309 outmethod.println(" int i;");
312 //outmethod.println(" pthread_once( &mlpOnceObj, mlpInitOncePerThread );");
313 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
317 if (state.DSMRECOVERYSTATS) {
318 outmethod.println("#ifdef RECOVERYSTATS \n");
319 outmethod.println("handle();\n");
320 outmethod.println("#endif\n");
322 outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
323 outmethod.println("handle();\n");
324 outmethod.println("#endif\n");
328 if (state.THREAD||state.DSM||state.SINGLETM) {
329 outmethod.println("initializethreads();");
332 outmethod.println("if (dstmStartup(argv[1])) {");
333 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
334 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
336 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
339 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
340 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
342 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
346 outmethod.println(" for(i=2;i<argc;i++) {");
348 outmethod.println(" for(i=1;i<argc;i++) {");
349 outmethod.println(" int length=strlen(argv[i]);");
350 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
351 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
353 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
356 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
358 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
359 outmethod.println(" }");
361 MethodDescriptor md=typeutil.getMain();
362 ClassDescriptor cd=typeutil.getMainClass();
364 outmethod.println(" {");
365 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
366 if (state.DSM||state.SINGLETM) {
367 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
369 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
370 outmethod.println("1, NULL,"+"stringarray};");
371 if (state.DSM||state.SINGLETM)
372 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
374 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
376 if (state.DSM||state.SINGLETM)
377 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
379 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
381 outmethod.println(" }");
384 outmethod.println("}");
387 if (state.THREAD||state.DSM||state.SINGLETM) {
388 outmethod.println("pthread_mutex_lock(&gclistlock);");
389 outmethod.println("threadcount--;");
390 outmethod.println("pthread_cond_signal(&gccond);");
391 outmethod.println("pthread_mutex_unlock(&gclistlock);");
394 if (state.DSM||state.SINGLETM) {
395 //outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
396 outmethod.println("#if defined(TRANSSTATS) \n");
397 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
398 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
399 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
400 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
402 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
403 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
404 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
405 outmethod.println("printf(\"ndirtyCacheObj= %d\\n\", ndirtyCacheObj);");
406 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
407 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
408 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
409 outmethod.println("printf(\"totalObjSize= %d\\n\", totalObjSize);");
410 outmethod.println("printf(\"sendRemoteReq= %d\\n\", sendRemoteReq);");
411 outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
412 } else if (state.SINGLETM) {
413 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
414 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
415 outmethod.println("#ifdef STMSTATS\n");
416 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
417 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
418 outmethod.println("}\n");
419 outmethod.println("#endif\n");
420 outmethod.println("fflush(stdout);");
422 outmethod.println("#endif\n");
425 if (state.EVENTMONITOR) {
426 outmethod.println("dumpdata();");
429 if (state.THREAD||state.SINGLETM)
430 outmethod.println("pthread_exit(NULL);");
433 outmethod.println(" workScheduleBegin();");
436 outmethod.println("}");
439 /* This method outputs code for each task. */
441 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
442 /* Compile task based program */
443 outtaskdefs.println("#include \"task.h\"");
444 outtaskdefs.println("#include \"methodheaders.h\"");
445 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
446 while(taskit.hasNext()) {
447 TaskDescriptor td=(TaskDescriptor)taskit.next();
448 FlatMethod fm=state.getMethodFlat(td);
449 generateFlatMethod(fm, null, outmethod);
450 generateTaskDescriptor(outtaskdefs, fm, td);
453 //Output task descriptors
454 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
455 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
457 while(taskit.hasNext()) {
458 TaskDescriptor td=(TaskDescriptor)taskit.next();
462 outtaskdefs.println(",");
463 outtaskdefs.print("&task_"+td.getSafeSymbol());
465 outtaskdefs.println("};");
467 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
470 /* This method outputs most of the methods.c file. This includes
471 * some standard includes and then an array with the sizes of
472 * objets and array that stores supertype and then the code for
473 * the Java methods.. */
475 protected void outputMethods(PrintWriter outmethod) {
476 outmethod.println("#include \"methodheaders.h\"");
477 outmethod.println("#include \"virtualtable.h\"");
478 outmethod.println("#include \"runtime.h\"");
480 outmethod.println("#include \"sandboxdefs.c\"");
483 outmethod.println("#include \"addPrefetchEnhance.h\"");
484 outmethod.println("#include \"localobjects.h\"");
486 if (state.FASTCHECK) {
487 outmethod.println("#include \"localobjects.h\"");
489 if(state.MULTICORE) {
490 outmethod.println("#include \"task.h\"");
491 outmethod.println("#include \"multicoreruntime.h\"");
492 outmethod.println("#include \"runtime_arch.h\"");
494 if (state.THREAD||state.DSM||state.SINGLETM)
495 outmethod.println("#include <thread.h>");
496 if (state.main!=null) {
497 outmethod.println("#include <string.h>");
499 if (state.CONSCHECK) {
500 outmethod.println("#include \"checkers.h\"");
503 outmethod.println("#include <stdlib.h>");
504 outmethod.println("#include <stdio.h>");
505 outmethod.println("#include \"mlp_runtime.h\"");
506 outmethod.println("#include \"psemaphore.h\"");
510 //Store the sizes of classes & array elements
511 generateSizeArray(outmethod);
513 //Store table of supertypes
514 generateSuperTypeTable(outmethod);
516 //Store the layout of classes
517 generateLayoutStructs(outmethod);
519 /* Generate code for methods */
520 if (state.DSM||state.SINGLETM) {
521 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
522 LocalityBinding lb=lbit.next();
523 MethodDescriptor md=lb.getMethod();
524 FlatMethod fm=state.getMethodFlat(md);
526 if (!md.getModifiers().isNative()) {
527 generateFlatMethod(fm, lb, outmethod);
528 //System.out.println("fm= " + fm + " md= " + md);
532 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
533 while(classit.hasNext()) {
534 ClassDescriptor cn=(ClassDescriptor)classit.next();
535 Iterator methodit=cn.getMethods();
536 while(methodit.hasNext()) {
537 /* Classify parameters */
538 MethodDescriptor md=(MethodDescriptor)methodit.next();
539 FlatMethod fm=state.getMethodFlat(md);
540 if (!md.getModifiers().isNative()) {
541 generateFlatMethod(fm, null, outmethod);
548 protected void outputStructs(PrintWriter outstructs) {
549 outstructs.println("#ifndef STRUCTDEFS_H");
550 outstructs.println("#define STRUCTDEFS_H");
551 outstructs.println("#include \"classdefs.h\"");
552 outstructs.println("#ifndef INTPTR");
553 outstructs.println("#ifdef BIT64");
554 outstructs.println("#define INTPTR long");
555 outstructs.println("#else");
556 outstructs.println("#define INTPTR int");
557 outstructs.println("#endif");
558 outstructs.println("#endif");
560 outstructs.println("#include \"mlp_runtime.h\"");
561 outstructs.println("#include \"psemaphore.h\"");
564 /* Output #defines that the runtime uses to determine type
565 * numbers for various objects it needs */
566 outstructs.println("#define MAXCOUNT "+maxcount);
567 if (state.DSM||state.SINGLETM) {
568 LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
570 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
572 else if (state.SINGLETM) {
573 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
575 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
579 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
581 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
582 else if( state.SINGLETM)
583 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
584 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
587 outstructs.println("#define STRINGARRAYTYPE "+
588 (state.getArrayNumber(
589 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
591 outstructs.println("#define OBJECTARRAYTYPE "+
592 (state.getArrayNumber(
593 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
596 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
597 outstructs.println("#define CHARARRAYTYPE "+
598 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
600 outstructs.println("#define BYTEARRAYTYPE "+
601 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
603 outstructs.println("#define BYTEARRAYARRAYTYPE "+
604 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
606 outstructs.println("#define NUMCLASSES "+state.numClasses());
607 int totalClassSize = state.numClasses() + state.numArrays();
608 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
610 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
611 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
612 outstructs.println("#define TAGARRAYTYPE "+
613 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
617 protected void outputClassDeclarations(PrintWriter outclassdefs) {
618 if (state.THREAD||state.DSM||state.SINGLETM)
619 outclassdefs.println("#include <pthread.h>");
620 outclassdefs.println("#ifndef INTPTR");
621 outclassdefs.println("#ifdef BIT64");
622 outclassdefs.println("#define INTPTR long");
623 outclassdefs.println("#else");
624 outclassdefs.println("#define INTPTR int");
625 outclassdefs.println("#endif");
626 outclassdefs.println("#endif");
628 outclassdefs.println("#include \"optionalstruct.h\"");
629 outclassdefs.println("struct "+arraytype+";");
630 /* Start by declaring all structs */
631 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
632 while(it.hasNext()) {
633 ClassDescriptor cn=(ClassDescriptor)it.next();
634 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
636 outclassdefs.println("");
637 //Print out definition for array type
638 outclassdefs.println("struct "+arraytype+" {");
639 outclassdefs.println(" int type;");
640 outclassdefs.println(" int oid;");
641 if (state.EVENTMONITOR) {
642 outclassdefs.println(" int objuid;");
645 outclassdefs.println(" pthread_t tid;");
646 outclassdefs.println(" void * lockentry;");
647 outclassdefs.println(" int lockcount;");
650 outclassdefs.println(" int flag;");
651 if(!state.MULTICORE) {
652 outclassdefs.println(" void * flagptr;");
654 outclassdefs.println(" int version;");
655 outclassdefs.println(" int * lock;"); // lock entry for this obj
656 outclassdefs.println(" int mutex;");
657 outclassdefs.println(" int lockcount;");
658 if(state.MULTICOREGC) {
659 outclassdefs.println(" int marked;");
663 outclassdefs.println(" int numfses;");
664 outclassdefs.println(" int * fses;");
667 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
669 if (state.STMARRAY) {
670 outclassdefs.println(" int lowindex;");
671 outclassdefs.println(" int highindex;");
674 outclassdefs.println(" int paddingforarray;");
675 if (state.DUALVIEW) {
676 outclassdefs.println(" int arrayversion;");
679 outclassdefs.println(" int ___length___;");
680 outclassdefs.println("};\n");
681 outclassdefs.println("extern int classsize[];");
682 outclassdefs.println("extern int hasflags[];");
683 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
684 outclassdefs.println("extern int supertypes[];");
687 /** Prints out definitions for generic task structures */
689 private void outputTaskTypes(PrintWriter outtask) {
690 outtask.println("#ifndef _TASK_H");
691 outtask.println("#define _TASK_H");
692 outtask.println("struct parameterdescriptor {");
693 outtask.println("int type;");
694 outtask.println("int numberterms;");
695 outtask.println("int *intarray;");
696 outtask.println("void * queue;");
697 outtask.println("int numbertags;");
698 outtask.println("int *tagarray;");
699 outtask.println("};");
701 outtask.println("struct taskdescriptor {");
702 outtask.println("void * taskptr;");
703 outtask.println("int numParameters;");
704 outtask.println(" int numTotal;");
705 outtask.println("struct parameterdescriptor **descriptorarray;");
706 outtask.println("char * name;");
707 outtask.println("};");
708 outtask.println("extern struct taskdescriptor * taskarray[];");
709 outtask.println("extern numtasks;");
710 outtask.println("#endif");
714 private void buildRepairStructs(PrintWriter outrepairstructs) {
715 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
716 while(classit.hasNext()) {
717 ClassDescriptor cn=(ClassDescriptor)classit.next();
718 outrepairstructs.println("structure "+cn.getSymbol()+" {");
719 outrepairstructs.println(" int __type__;");
721 outrepairstructs.println(" int __flag__;");
722 if(!state.MULTICORE) {
723 outrepairstructs.println(" int __flagptr__;");
726 printRepairStruct(cn, outrepairstructs);
727 outrepairstructs.println("}\n");
730 for(int i=0; i<state.numArrays(); i++) {
731 TypeDescriptor tdarray=arraytable[i];
732 TypeDescriptor tdelement=tdarray.dereference();
733 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
734 outrepairstructs.println(" int __type__;");
735 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
736 outrepairstructs.println(" int length;");
738 // Need to add support to repair tool for this
739 if (tdelement.isClass()||tdelement.isArray())
740 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
742 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
744 outrepairstructs.println("}\n");
748 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
749 ClassDescriptor sp=cn.getSuperDesc();
751 printRepairStruct(sp, output);
753 Vector fields=(Vector)fieldorder.get(cn);
755 for(int i=0; i<fields.size(); i++) {
756 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
757 if (fd.getType().isArray()) {
758 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
759 } else if (fd.getType().isClass())
760 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
761 else if (fd.getType().isFloat())
762 output.println(" int "+fd.getSymbol()+"; /* really float */");
764 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
768 /** This method outputs TaskDescriptor information */
769 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
770 for (int i=0; i<task.numParameters(); i++) {
771 VarDescriptor param_var=task.getParameter(i);
772 TypeDescriptor param_type=task.getParamType(i);
773 FlagExpressionNode param_flag=task.getFlag(param_var);
774 TagExpressionList param_tag=task.getTag(param_var);
777 if (param_flag==null) {
778 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
779 output.println("0x0, 0x0 };");
782 DNFFlag dflag=param_flag.getDNF();
783 dnfterms=dflag.size();
785 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
786 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
787 for(int j=0; j<dflag.size(); j++) {
790 Vector term=dflag.get(j);
793 for(int k=0; k<term.size(); k++) {
794 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
795 FlagDescriptor fd=dfa.getFlag();
796 boolean negated=dfa.getNegated();
797 int flagid=1<<((Integer)flags.get(fd)).intValue();
802 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
804 output.println("};");
807 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
808 //BUG...added next line to fix, test with any task program
810 for(int j=0; j<param_tag.numTags(); j++) {
813 /* for each tag we need */
814 /* which slot it is */
815 /* what type it is */
816 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
817 TempDescriptor tmp=param_tag.getTemp(j);
818 int slot=fm.getTagInt(tmp);
819 output.println(slot+", "+state.getTagId(tvd.getTag()));
821 output.println("};");
823 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
824 output.println("/* type */"+param_type.getClassDesc().getId()+",");
825 output.println("/* number of DNF terms */"+dnfterms+",");
826 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
827 output.println("0,");
828 //BUG, added next line to fix and else statement...test
829 //with any task program
831 output.println("/* number of tags */"+param_tag.numTags()+",");
833 output.println("/* number of tags */ 0,");
834 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
835 output.println("};");
839 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
840 for (int i=0; i<task.numParameters(); i++) {
843 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
845 output.println("};");
847 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
848 output.println("&"+task.getSafeSymbol()+",");
849 output.println("/* number of parameters */" +task.numParameters() + ",");
850 int numtotal=task.numParameters()+fm.numTags();
851 output.println("/* number total parameters */" +numtotal + ",");
852 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
853 output.println("\""+task.getSymbol()+"\"");
854 output.println("};");
858 /** The buildVirtualTables method outputs the virtual dispatch
859 * tables for methods. */
861 protected void buildVirtualTables(PrintWriter outvirtual) {
862 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
863 while(classit.hasNext()) {
864 ClassDescriptor cd=(ClassDescriptor)classit.next();
865 if (virtualcalls.getMethodCount(cd)>maxcount)
866 maxcount=virtualcalls.getMethodCount(cd);
868 MethodDescriptor[][] virtualtable=null;
869 LocalityBinding[][] lbvirtualtable=null;
870 if (state.DSM||state.SINGLETM)
871 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
873 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
875 /* Fill in virtual table */
876 classit=state.getClassSymbolTable().getDescriptorsIterator();
877 while(classit.hasNext()) {
878 ClassDescriptor cd=(ClassDescriptor)classit.next();
879 if (state.DSM||state.SINGLETM)
880 fillinRow(cd, lbvirtualtable, cd.getId());
882 fillinRow(cd, virtualtable, cd.getId());
885 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
886 Iterator arrayit=state.getArrayIterator();
887 while(arrayit.hasNext()) {
888 TypeDescriptor td=(TypeDescriptor)arrayit.next();
889 int id=state.getArrayNumber(td);
890 if (state.DSM||state.SINGLETM)
891 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
893 fillinRow(objectcd, virtualtable, id+state.numClasses());
896 outvirtual.print("void * virtualtable[]={");
897 boolean needcomma=false;
898 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
899 for(int j=0; j<maxcount; j++) {
901 outvirtual.print(", ");
902 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
903 LocalityBinding lb=lbvirtualtable[i][j];
904 MethodDescriptor md=lb.getMethod();
905 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
906 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
907 MethodDescriptor md=virtualtable[i][j];
908 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
910 outvirtual.print("0");
914 outvirtual.println("");
916 outvirtual.println("};");
920 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
921 /* Get inherited methods */
922 if (cd.getSuperDesc()!=null)
923 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
924 /* Override them with our methods */
925 for(Iterator it=cd.getMethods(); it.hasNext();) {
926 MethodDescriptor md=(MethodDescriptor)it.next();
927 if (md.isStatic()||md.getReturnType()==null)
929 int methodnum=virtualcalls.getMethodNumber(md);
930 virtualtable[rownum][methodnum]=md;
934 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
935 /* Get inherited methods */
936 if (cd.getSuperDesc()!=null)
937 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
938 /* Override them with our methods */
939 if (locality.getClassBindings(cd)!=null)
940 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
941 LocalityBinding lb=lbit.next();
942 MethodDescriptor md=lb.getMethod();
943 //Is the method static or a constructor
944 if (md.isStatic()||md.getReturnType()==null)
946 int methodnum=virtualcalls.getLocalityNumber(lb);
947 virtualtable[rownum][methodnum]=lb;
951 /** Generate array that contains the sizes of class objects. The
952 * object allocation functions in the runtime use this
955 private void generateSizeArray(PrintWriter outclassdefs) {
956 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
957 outclassdefs.print("#ifdef TRANSSTATS \n");
958 outclassdefs.print("extern int numTransAbort;\n");
959 outclassdefs.print("extern int numTransCommit;\n");
960 outclassdefs.print("extern int nSoftAbort;\n");
962 outclassdefs.print("extern int nchashSearch;\n");
963 outclassdefs.print("extern int nmhashSearch;\n");
964 outclassdefs.print("extern int nprehashSearch;\n");
965 outclassdefs.print("extern int ndirtyCacheObj;\n");
966 outclassdefs.print("extern int nRemoteSend;\n");
967 outclassdefs.print("extern int sendRemoteReq;\n");
968 outclassdefs.print("extern int getResponse;\n");
969 outclassdefs.print("extern int bytesSent;\n");
970 outclassdefs.print("extern int bytesRecv;\n");
971 outclassdefs.print("extern int totalObjSize;\n");
972 outclassdefs.print("extern void handle();\n");
973 } else if (state.SINGLETM) {
974 outclassdefs.println("extern int nSoftAbortAbort;");
975 outclassdefs.println("extern int nSoftAbortCommit;");
976 outclassdefs.println("#ifdef STMSTATS\n");
977 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
978 outclassdefs.println("#endif\n");
980 outclassdefs.print("#endif\n");
982 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
984 outclassdefs.print("extern __thread int oid;\n");
985 outclassdefs.print("extern int numWorkers;\n");
988 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
989 cdarray=new ClassDescriptor[state.numClasses()];
991 while(it.hasNext()) {
992 ClassDescriptor cd=(ClassDescriptor)it.next();
993 cdarray[cd.getId()]=cd;
996 arraytable=new TypeDescriptor[state.numArrays()];
998 Iterator arrayit=state.getArrayIterator();
999 while(arrayit.hasNext()) {
1000 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1001 int id=state.getArrayNumber(td);
1007 /* Print out types */
1008 outclassdefs.println("/* ");
1009 for(int i=0; i<state.numClasses(); i++) {
1010 ClassDescriptor cd=cdarray[i];
1012 outclassdefs.println("NULL " + i);
1014 outclassdefs.println(cd +" "+i);
1018 for(int i=0; i<state.numArrays(); i++) {
1019 TypeDescriptor arraytd=arraytable[i];
1020 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
1023 outclassdefs.println("*/");
1026 outclassdefs.print("int classsize[]={");
1028 boolean needcomma=false;
1029 for(int i=0; i<state.numClasses(); i++) {
1031 outclassdefs.print(", ");
1033 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1035 outclassdefs.print("0");
1041 for(int i=0; i<state.numArrays(); i++) {
1043 outclassdefs.print(", ");
1044 TypeDescriptor tdelement=arraytable[i].dereference();
1045 if (tdelement.isArray()||tdelement.isClass())
1046 outclassdefs.print("sizeof(void *)");
1048 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1052 outclassdefs.println("};");
1054 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1056 outclassdefs.print("int typearray[]={");
1057 for(int i=0; i<state.numClasses(); i++) {
1058 ClassDescriptor cd=cdarray[i];
1059 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1061 outclassdefs.print(", ");
1063 outclassdefs.print("-1");
1065 outclassdefs.print(supercd.getId());
1069 for(int i=0; i<state.numArrays(); i++) {
1070 TypeDescriptor arraytd=arraytable[i];
1071 ClassDescriptor arraycd=arraytd.getClassDesc();
1072 if (arraycd==null) {
1074 outclassdefs.print(", ");
1075 outclassdefs.print(objectclass.getId());
1079 ClassDescriptor cd=arraycd.getSuperDesc();
1082 TypeDescriptor supertd=new TypeDescriptor(cd);
1083 supertd.setArrayCount(arraytd.getArrayCount());
1084 type=state.getArrayNumber(supertd);
1086 type+=state.numClasses();
1089 cd=cd.getSuperDesc();
1092 outclassdefs.print(", ");
1093 outclassdefs.print(type);
1097 outclassdefs.println("};");
1102 outclassdefs.print("int typearray2[]={");
1103 for(int i=0; i<state.numArrays(); i++) {
1104 TypeDescriptor arraytd=arraytable[i];
1105 ClassDescriptor arraycd=arraytd.getClassDesc();
1106 if (arraycd==null) {
1108 outclassdefs.print(", ");
1109 outclassdefs.print("-1");
1113 ClassDescriptor cd=arraycd.getSuperDesc();
1114 int level=arraytd.getArrayCount()-1;
1116 for(; level>0; level--) {
1117 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1118 supertd.setArrayCount(level);
1119 type=state.getArrayNumber(supertd);
1121 type+=state.numClasses();
1126 outclassdefs.print(", ");
1127 outclassdefs.print(type);
1131 outclassdefs.println("};");
1134 /** Constructs params and temp objects for each method or task.
1135 * These objects tell the compiler which temps need to be
1138 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1139 MethodDescriptor md=fm.getMethod();
1140 TaskDescriptor task=fm.getTask();
1141 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1142 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1144 paramstable.put(lb, objectparams);
1145 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1146 } else if (md!=null)
1147 paramstable.put(md, objectparams);
1149 paramstable.put(task, objectparams);
1151 for(int i=0; i<fm.numParameters(); i++) {
1152 TempDescriptor temp=fm.getParameter(i);
1153 TypeDescriptor type=temp.getType();
1154 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1155 objectparams.addPtr(temp);
1157 objectparams.addPrim(temp);
1158 if(lb!=null&&saveset.contains(temp)) {
1159 backuptable.get(lb).put(temp, temp.createNew());
1163 for(int i=0; i<fm.numTags(); i++) {
1164 TempDescriptor temp=fm.getTag(i);
1165 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1166 objectparams.addPtr(temp);
1168 objectparams.addPrim(temp);
1171 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1173 tempstable.put(lb, objecttemps);
1175 tempstable.put(md, objecttemps);
1177 tempstable.put(task, objecttemps);
1179 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1180 FlatNode fn=(FlatNode)nodeit.next();
1181 TempDescriptor[] writes=fn.writesTemps();
1182 for(int i=0; i<writes.length; i++) {
1183 TempDescriptor temp=writes[i];
1184 TypeDescriptor type=temp.getType();
1185 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1186 objecttemps.addPtr(temp);
1188 objecttemps.addPrim(temp);
1189 if(lb!=null&&saveset.contains(temp)&&
1190 !backuptable.get(lb).containsKey(temp))
1191 backuptable.get(lb).put(temp, temp.createNew());
1195 /* Create backup temps */
1197 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1198 TempDescriptor tmp=tmpit.next();
1199 TypeDescriptor type=tmp.getType();
1200 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1201 objecttemps.addPtr(tmp);
1203 objecttemps.addPrim(tmp);
1205 /* Create temp to hold revert table */
1206 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1207 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1208 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1209 objecttemps.addPtr(reverttmp);
1211 objecttemps.addPrim(reverttmp);
1212 reverttable.put(lb, reverttmp);
1217 /** This method outputs the following information about classes
1219 * (1) For classes, what are the locations of pointers.
1220 * (2) For arrays, does the array contain pointers or primitives.
1221 * (3) For classes, does the class contain flags.
1224 private void generateLayoutStructs(PrintWriter output) {
1225 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1226 while(it.hasNext()) {
1227 ClassDescriptor cn=(ClassDescriptor)it.next();
1228 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1229 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1231 while(allit.hasNext()) {
1232 FieldDescriptor fd=(FieldDescriptor)allit.next();
1233 TypeDescriptor type=fd.getType();
1234 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1239 output.print(count);
1240 allit=cn.getFieldTable().getAllDescriptorsIterator();
1241 while(allit.hasNext()) {
1242 FieldDescriptor fd=(FieldDescriptor)allit.next();
1243 TypeDescriptor type=fd.getType();
1244 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1247 output.println(",");
1248 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1251 output.println("};");
1253 output.println("unsigned INTPTR * pointerarray[]={");
1254 boolean needcomma=false;
1255 for(int i=0; i<state.numClasses(); i++) {
1256 ClassDescriptor cn=cdarray[i];
1258 output.println(",");
1261 output.print(cn.getSafeSymbol()+"_pointers");
1263 output.print("NULL");
1267 for(int i=0; i<state.numArrays(); i++) {
1269 output.println(", ");
1270 TypeDescriptor tdelement=arraytable[i].dereference();
1271 if (tdelement.isArray()||tdelement.isClass())
1272 output.print("((unsigned INTPTR *)1)");
1278 output.println("};");
1280 output.println("int hasflags[]={");
1281 for(int i=0; i<state.numClasses(); i++) {
1282 ClassDescriptor cn=cdarray[i];
1284 output.println(", ");
1286 if ((cn != null) && (cn.hasFlags()))
1291 output.println("};");
1294 /** Print out table to give us supertypes */
1295 private void generateSuperTypeTable(PrintWriter output) {
1296 output.println("int supertypes[]={");
1297 boolean needcomma=false;
1298 for(int i=0; i<state.numClasses(); i++) {
1299 ClassDescriptor cn=cdarray[i];
1301 output.println(",");
1303 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1304 ClassDescriptor cdsuper=cn.getSuperDesc();
1305 output.print(cdsuper.getId());
1309 output.println("};");
1312 /** Force consistent field ordering between inherited classes. */
1314 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1316 ClassDescriptor sp=cn.getSuperDesc();
1318 printClassStruct(sp, classdefout);
1320 if (!fieldorder.containsKey(cn)) {
1321 Vector fields=new Vector();
1322 fieldorder.put(cn,fields);
1323 Vector fieldvec=cn.getFieldVec();
1324 for(int i=0;i<fieldvec.size();i++) {
1325 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1326 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1330 Vector fields=(Vector)fieldorder.get(cn);
1332 for(int i=0; i<fields.size(); i++) {
1333 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1334 if (fd.getType().isClass()||fd.getType().isArray())
1335 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1337 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1342 /* Map flags to integers consistently between inherited
1345 protected void mapFlags(ClassDescriptor cn) {
1346 ClassDescriptor sp=cn.getSuperDesc();
1350 if (!flagorder.containsKey(cn)) {
1351 Hashtable flags=new Hashtable();
1352 flagorder.put(cn,flags);
1354 Hashtable superflags=(Hashtable)flagorder.get(sp);
1355 Iterator superflagit=superflags.keySet().iterator();
1356 while(superflagit.hasNext()) {
1357 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1358 Integer number=(Integer)superflags.get(fd);
1359 flags.put(fd, number);
1360 if ((number.intValue()+1)>max)
1361 max=number.intValue()+1;
1365 Iterator flagit=cn.getFlags();
1366 while(flagit.hasNext()) {
1367 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1368 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1369 flags.put(fd, new Integer(max++));
1375 /** This function outputs (1) structures that parameters are
1376 * passed in (when PRECISE GC is enabled) and (2) function
1377 * prototypes for the methods */
1379 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1380 /* Output class structure */
1381 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1382 classdefout.println(" int type;");
1384 classdefout.println(" int oid;");
1386 if (state.EVENTMONITOR) {
1387 classdefout.println(" int objuid;");
1390 classdefout.println(" pthread_t tid;");
1391 classdefout.println(" void * lockentry;");
1392 classdefout.println(" int lockcount;");
1396 classdefout.println(" int flag;");
1397 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1398 classdefout.println(" void * flagptr;");
1399 } else if (state.MULTICORE) {
1400 classdefout.println(" int version;");
1401 classdefout.println(" int * lock;"); // lock entry for this obj
1402 classdefout.println(" int mutex;");
1403 classdefout.println(" int lockcount;");
1404 if(state.MULTICOREGC) {
1405 classdefout.println(" int marked;");
1408 if (state.OPTIONAL) {
1409 classdefout.println(" int numfses;");
1410 classdefout.println(" int * fses;");
1413 printClassStruct(cn, classdefout);
1414 classdefout.println("};\n");
1416 if (state.DSM||state.SINGLETM) {
1417 /* Cycle through LocalityBindings */
1418 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1419 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1421 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1422 LocalityBinding lb=lbit.next();
1423 MethodDescriptor md=lb.getMethod();
1424 if (md.getModifiers().isNative()) {
1425 //make sure we only print a native method once
1426 if (nativemethods.contains(md)) {
1427 FlatMethod fm=state.getMethodFlat(md);
1428 generateTempStructs(fm, lb);
1431 nativemethods.add(md);
1433 generateMethod(cn, md, lb, headersout, output);
1436 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1437 MethodDescriptor md=(MethodDescriptor)methodit.next();
1438 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1439 //Need to build param structure for library code
1440 FlatMethod fm=state.getMethodFlat(md);
1441 generateTempStructs(fm, null);
1442 generateMethodParam(cn, md, null, output);
1447 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1448 MethodDescriptor md=(MethodDescriptor)methodit.next();
1449 generateMethod(cn, md, null, headersout, output);
1453 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1454 /* Output parameter structure */
1455 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1456 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1457 if ((state.DSM||state.SINGLETM)&&lb!=null)
1458 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1460 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1461 output.println(" int size;");
1462 output.println(" void * next;");
1463 for(int i=0; i<objectparams.numPointers(); i++) {
1464 TempDescriptor temp=objectparams.getPointer(i);
1465 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1467 output.println("};\n");
1471 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1472 FlatMethod fm=state.getMethodFlat(md);
1473 generateTempStructs(fm, lb);
1475 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1476 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1478 generateMethodParam(cn, md, lb, output);
1480 /* Output temp structure */
1481 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1482 if (state.DSM||state.SINGLETM)
1483 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1485 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1486 output.println(" int size;");
1487 output.println(" void * next;");
1488 for(int i=0; i<objecttemps.numPointers(); i++) {
1489 TempDescriptor temp=objecttemps.getPointer(i);
1490 if (temp.getType().isNull())
1491 output.println(" void * "+temp.getSafeSymbol()+";");
1493 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1495 output.println("};\n");
1498 /********* Output method declaration ***********/
1499 if (state.DSM||state.SINGLETM) {
1500 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1502 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1504 /* First the return type */
1505 if (md.getReturnType()!=null) {
1506 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1507 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1509 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1511 //catch the constructor case
1512 headersout.print("void ");
1514 /* Next the method name */
1515 if (state.DSM||state.SINGLETM) {
1516 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1518 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1520 boolean printcomma=false;
1521 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1522 if (state.DSM||state.SINGLETM) {
1523 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1525 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1529 /* Output parameter list*/
1530 for(int i=0; i<objectparams.numPrimitives(); i++) {
1531 TempDescriptor temp=objectparams.getPrimitive(i);
1533 headersout.print(", ");
1535 if (temp.getType().isClass()||temp.getType().isArray())
1536 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1538 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1540 headersout.println(");\n");
1544 /** This function outputs (1) structures that parameters are
1545 * passed in (when PRECISE GC is enabled) and (2) function
1546 * prototypes for the tasks */
1548 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1549 /* Cycle through tasks */
1550 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1552 while(taskit.hasNext()) {
1553 /* Classify parameters */
1554 TaskDescriptor task=(TaskDescriptor)taskit.next();
1555 FlatMethod fm=state.getMethodFlat(task);
1556 generateTempStructs(fm, null);
1558 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1559 TempObject objecttemps=(TempObject) tempstable.get(task);
1561 /* Output parameter structure */
1562 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1563 output.println("struct "+task.getSafeSymbol()+"_params {");
1564 output.println(" int size;");
1565 output.println(" void * next;");
1566 for(int i=0; i<objectparams.numPointers(); i++) {
1567 TempDescriptor temp=objectparams.getPointer(i);
1568 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1571 output.println("};\n");
1572 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1573 maxtaskparams=objectparams.numPointers()+fm.numTags();
1577 /* Output temp structure */
1578 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1579 output.println("struct "+task.getSafeSymbol()+"_locals {");
1580 output.println(" int size;");
1581 output.println(" void * next;");
1582 for(int i=0; i<objecttemps.numPointers(); i++) {
1583 TempDescriptor temp=objecttemps.getPointer(i);
1584 if (temp.getType().isNull())
1585 output.println(" void * "+temp.getSafeSymbol()+";");
1586 else if(temp.getType().isTag())
1587 output.println(" struct "+
1588 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1590 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1592 output.println("};\n");
1595 /* Output task declaration */
1596 headersout.print("void " + task.getSafeSymbol()+"(");
1598 boolean printcomma=false;
1599 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1600 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1602 headersout.print("void * parameterarray[]");
1603 headersout.println(");\n");
1607 /***** Generate code for FlatMethod fm. *****/
1609 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1610 static int atomicmethodcount=0;
1613 BranchAnalysis branchanalysis;
1614 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1615 if (State.PRINTFLAT)
1616 System.out.println(fm.printMethod());
1617 MethodDescriptor md=fm.getMethod();
1618 TaskDescriptor task=fm.getTask();
1619 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1620 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1622 HashSet<AtomicRecord> arset=null;
1623 branchanalysis=null;
1625 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1627 if (atomicmethodmap==null)
1628 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1630 //fix these so we get right strings for local variables
1631 localsprefixaddr=localsprefix;
1632 localsprefixderef=localsprefix+"->";
1633 arset=new HashSet<AtomicRecord>();
1635 //build branchanalysis
1636 branchanalysis=new BranchAnalysis(locality, lb, delaycomp.getNotReady(lb), delaycomp.livecode(lb), state);
1638 //Generate commit methods here
1639 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1640 FlatNode fn=fnit.next();
1641 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1642 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
1643 delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
1644 //We have an atomic enter
1645 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1646 Set<FlatNode> exitset=faen.getExits();
1648 String methodname=md.getSymbol()+(atomicmethodcount++);
1649 AtomicRecord ar=new AtomicRecord();
1653 atomicmethodmap.put(faen, ar);
1655 //build data structure declaration
1656 output.println("struct atomicprimitives_"+methodname+" {");
1658 Set<FlatNode> recordset=delaycomp.livecode(lb);
1659 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1660 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1661 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1663 ar.reallivein=new HashSet(liveinto);
1665 ar.liveoutvirtualread=liveoutvirtualread;
1668 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1669 TempDescriptor tmp=it.next();
1670 //remove the pointers
1671 if (tmp.getType().isPtr()) {
1674 //let's print it here
1675 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1678 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1679 TempDescriptor tmp=it.next();
1680 //remove the pointers
1681 if (tmp.getType().isPtr()) {
1683 } else if (!liveinto.contains(tmp)) {
1684 //let's print it here
1685 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1688 output.println("};");
1690 //print out method name
1691 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) {");
1692 //build code for commit method
1694 //first define local primitives
1695 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1696 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1697 TempDescriptor tmp=tmpit.next();
1698 if (!tmp.getType().isPtr()) {
1699 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1700 //read from live into set
1701 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1704 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1708 //turn off write barrier generation
1710 state.SINGLETM=false;
1711 generateCode(faen, fm, lb, exitset, output, false);
1712 state.SINGLETM=true;
1713 //turn on write barrier generation
1715 output.println("}\n\n");
1719 //redefine these back to normal
1721 localsprefixaddr="&"+localsprefix;
1722 localsprefixderef=localsprefix+".";
1724 generateHeader(fm, lb, md!=null ? md : task,output);
1725 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1727 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1728 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1729 AtomicRecord ar=arit.next();
1730 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1734 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1735 if (md!=null&&(state.DSM||state.SINGLETM))
1736 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1737 else if (md!=null&&!(state.DSM||state.SINGLETM))
1738 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1740 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1741 output.print(objecttemp.numPointers()+",");
1742 output.print(paramsprefix);
1743 for(int j=0; j<objecttemp.numPointers(); j++)
1744 output.print(", NULL");
1745 output.println("};");
1748 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1749 TempDescriptor td=objecttemp.getPrimitive(i);
1750 TypeDescriptor type=td.getType();
1752 output.println(" void * "+td.getSafeSymbol()+";");
1753 else if (type.isClass()||type.isArray())
1754 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1756 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1761 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1762 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1763 if( callerSESEplaceholder != mlpa.getMainSESE() ) {
1764 // declare variables for naming static SESE's
1765 output.println(" /* static SESE names */");
1766 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1767 while( pItr.hasNext() ) {
1768 SESEandAgePair pair = pItr.next();
1769 output.println(" void* "+pair+";");
1772 // declare variables for tracking dynamic sources
1773 output.println(" /* dynamic variable sources */");
1774 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1775 while( dynSrcItr.hasNext() ) {
1776 TempDescriptor dynSrcVar = dynSrcItr.next();
1777 output.println(" void* "+dynSrcVar+"_srcSESE;");
1778 output.println(" int "+dynSrcVar+"_srcOffset;");
1783 // set up related allocation sites's waiting queues
1785 ConflictGraph graph = null;
1786 graph = mlpa.getConflictGraphResults().get(fm);
1787 if (graph != null && graph.hasConflictEdge()) {
1788 output.println(" /* set up waiting queues */");
1789 output.println(" int numMemoryQueue=0;");
1790 output.println(" int memoryQueueItemID=0;");
1791 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
1793 System.out.println("#lockSet="+lockSet.hashCode());
1794 System.out.println("lockset="+lockSet);
1795 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1796 SESELock seseLock = (SESELock) iterator.next();
1797 System.out.println("id="+seseLock.getID());
1798 System.out.println("#="+seseLock);
1800 System.out.println("size="+lockSet.size());
1801 if (lockSet.size() > 0) {
1802 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1804 .println(" seseCaller->numMemoryQueue=numMemoryQueue;");
1806 .println(" seseCaller->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1813 /* Check to see if we need to do a GC if this is a
1814 * multi-threaded program...*/
1816 if (((state.MLP||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1817 || this.state.MULTICOREGC) {
1818 //Don't bother if we aren't in recursive methods...The loops case will catch it
1819 if (callgraph.getAllMethods(md).contains(md)) {
1820 if (state.DSM&&lb.isAtomic())
1821 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1822 else if (this.state.MULTICOREGC) {
1823 output.println("if(gcflag) gc("+localsprefixaddr+");");
1825 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1830 generateCode(fm.getNext(0), fm, lb, null, output, true);
1832 output.println("}\n\n");
1836 protected void initializeSESE( FlatSESEEnterNode fsen ) {
1838 FlatMethod fm = fsen.getfmEnclosing();
1839 MethodDescriptor md = fm.getMethod();
1840 ClassDescriptor cn = md.getClassDesc();
1843 // Creates bogus method descriptor to index into tables
1844 Modifiers modBogus = new Modifiers();
1845 MethodDescriptor mdBogus =
1846 new MethodDescriptor( modBogus,
1847 new TypeDescriptor( TypeDescriptor.VOID ),
1848 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1851 mdBogus.setClassDesc( fsen.getcdEnclosing() );
1852 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1853 fsen.setfmBogus( fmBogus );
1854 fsen.setmdBogus( mdBogus );
1856 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1857 inSetAndOutSet.addAll( fsen.getInVarSet() );
1858 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1860 // Build paramsobj for bogus method descriptor
1861 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
1862 paramstable.put( mdBogus, objectparams );
1864 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1865 while( itr.hasNext() ) {
1866 TempDescriptor temp = itr.next();
1867 TypeDescriptor type = temp.getType();
1868 if( type.isPtr() ) {
1869 objectparams.addPtr( temp );
1871 objectparams.addPrim( temp );
1875 // Build normal temp object for bogus method descriptor
1876 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
1877 tempstable.put( mdBogus, objecttemps );
1879 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
1880 FlatNode fn = (FlatNode)nodeit.next();
1881 TempDescriptor[] writes = fn.writesTemps();
1883 for( int i = 0; i < writes.length; i++ ) {
1884 TempDescriptor temp = writes[i];
1885 TypeDescriptor type = temp.getType();
1887 if( type.isPtr() ) {
1888 objecttemps.addPtr( temp );
1890 objecttemps.addPrim( temp );
1896 protected void generateMethodSESE(FlatSESEEnterNode fsen,
1898 PrintWriter outputStructs,
1899 PrintWriter outputMethHead,
1900 PrintWriter outputMethods
1903 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
1904 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
1906 // generate locals structure
1907 outputStructs.println("struct "+
1908 fsen.getcdEnclosing().getSafeSymbol()+
1909 fsen.getmdBogus().getSafeSymbol()+"_"+
1910 fsen.getmdBogus().getSafeMethodDescriptor()+
1912 outputStructs.println(" int size;");
1913 outputStructs.println(" void * next;");
1914 for(int i=0; i<objecttemps.numPointers(); i++) {
1915 TempDescriptor temp=objecttemps.getPointer(i);
1917 if (temp.getType().isNull())
1918 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1920 outputStructs.println(" struct "+
1921 temp.getType().getSafeSymbol()+" * "+
1922 temp.getSafeSymbol()+";");
1924 outputStructs.println("};\n");
1927 // generate the SESE record structure
1928 outputStructs.println(fsen.getSESErecordName()+" {");
1930 // data common to any SESE, and it must be placed first so
1931 // a module that doesn't know what kind of SESE record this
1932 // is can cast the pointer to a common struct
1933 outputStructs.println(" SESEcommon common;");
1935 // then garbage list stuff
1936 outputStructs.println(" int size;");
1937 outputStructs.println(" void * next;");
1939 // DYNAMIC stuff was here
1941 // invar source taking was here
1943 // space for all in and out set primitives
1944 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1945 inSetAndOutSet.addAll( fsen.getInVarSet() );
1946 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1948 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
1950 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1951 while( itr.hasNext() ) {
1952 TempDescriptor temp = itr.next();
1953 TypeDescriptor type = temp.getType();
1954 if( !type.isPtr() ) {
1955 inSetAndOutSetPrims.add( temp );
1959 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
1960 while( itrPrims.hasNext() ) {
1961 TempDescriptor temp = itrPrims.next();
1962 TypeDescriptor type = temp.getType();
1963 if(!type.isPrimitive()){
1964 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
1968 for(int i=0; i<objectparams.numPointers(); i++) {
1969 TempDescriptor temp=objectparams.getPointer(i);
1970 if (temp.getType().isNull())
1971 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1973 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1976 // DYNAMIC stuff needs a source SESE ptr and offset
1977 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
1978 while( itrDynInVars.hasNext() ) {
1979 TempDescriptor dynInVar = itrDynInVars.next();
1980 // outputStructs.println(" void* "+dynInVar+"_srcSESE;");
1981 outputStructs.println(" int "+dynInVar+"_srcOffset;");
1984 itrPrims = inSetAndOutSetPrims.iterator();
1985 while( itrPrims.hasNext() ) {
1986 TempDescriptor temp = itrPrims.next();
1987 TypeDescriptor type = temp.getType();
1988 if(type.isPrimitive()){
1989 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
1993 outputStructs.println(" int prevSESECount;");
1995 // DYNAMIC stuff needs a source SESE ptr and offset
1996 itrDynInVars = fsen.getDynamicInVarSet().iterator();
1997 while( itrDynInVars.hasNext() ) {
1998 TempDescriptor dynInVar = itrDynInVars.next();
1999 outputStructs.println(" void* "+dynInVar+"_srcSESE;");
2000 // outputStructs.println(" int "+dynInVar+"_srcOffset;");
2003 // in-set source tracking
2004 // in-vars that are READY come from parent, don't need anything
2005 // stuff STATIC needs a custom SESE pointer for each age pair
2006 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
2007 while( itrStaticInVarSrcs.hasNext() ) {
2008 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
2009 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
2012 outputStructs.println("};\n");
2015 // write method declaration to header file
2016 outputMethHead.print("void ");
2017 outputMethHead.print(fsen.getSESEmethodName()+"(");
2018 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
2019 outputMethHead.println(");\n");
2022 generateFlatMethodSESE( fsen.getfmBogus(),
2023 fsen.getcdEnclosing(),
2029 private void generateFlatMethodSESE(FlatMethod fm,
2031 FlatSESEEnterNode fsen,
2032 FlatSESEExitNode seseExit,
2036 MethodDescriptor md=fm.getMethod();
2038 output.print("void ");
2039 output.print(fsen.getSESEmethodName()+"(");
2040 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
2041 output.println("){\n");
2043 TempObject objecttemp=(TempObject) tempstable.get(md);
2045 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2046 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2047 output.print(objecttemp.numPointers()+",");
2048 output.print("&(((SESEcommon*)(___params___))[1])");
2049 for(int j=0; j<objecttemp.numPointers(); j++)
2050 output.print(", NULL");
2051 output.println("};");
2054 output.println(" /* regular local primitives */");
2055 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2056 TempDescriptor td=objecttemp.getPrimitive(i);
2057 TypeDescriptor type=td.getType();
2059 output.println(" void * "+td.getSafeSymbol()+";");
2060 else if (type.isClass()||type.isArray())
2061 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2063 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2067 // declare variables for naming static SESE's
2068 output.println(" /* static SESE names */");
2069 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
2070 while( pItr.hasNext() ) {
2071 SESEandAgePair pair = pItr.next();
2072 output.println(" void* "+pair+";");
2075 // declare variables for tracking dynamic sources
2076 output.println(" /* dynamic variable sources */");
2077 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
2078 while( dynSrcItr.hasNext() ) {
2079 TempDescriptor dynSrcVar = dynSrcItr.next();
2080 output.println(" void* "+dynSrcVar+"_srcSESE;");
2081 output.println(" int "+dynSrcVar+"_srcOffset;");
2084 // declare local temps for in-set primitives, and if it is
2085 // a ready-source variable, get the value from the record
2086 output.println(" /* local temps for in-set primitives */");
2087 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2088 while( itrInSet.hasNext() ) {
2089 TempDescriptor temp = itrInSet.next();
2090 TypeDescriptor type = temp.getType();
2091 if( !type.isPtr() ) {
2092 if( fsen.getReadyInVarSet().contains( temp ) ) {
2093 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2095 output.println(" "+type+" "+temp+";");
2100 // declare local temps for out-set primitives if its not already
2101 // in the in-set, and it's value will get written so no problem
2102 output.println(" /* local temp for out-set prim, not already in the in-set */");
2103 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2104 while( itrOutSet.hasNext() ) {
2105 TempDescriptor temp = itrOutSet.next();
2106 TypeDescriptor type = temp.getType();
2107 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2108 output.println(" "+type+" "+temp+";");
2112 // setup memory queue
2114 output.println(" // set up memory queues ");
2115 output.println(" int numMemoryQueue=0;");
2116 output.println(" int memoryQueueItemID=0;");
2117 ConflictGraph graph = null;
2118 graph = mlpa.getConflictGraphResults().get(fsen);
2119 if (graph != null && graph.hasConflictEdge()) {
2120 output.println(" {");
2122 .println(" SESEcommon* parentCommon = &(___params___->common);");
2123 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
2125 System.out.println("#lockSet="+lockSet);
2127 if (lockSet.size() > 0) {
2128 output.println(" numMemoryQueue=" + lockSet.size() + ";");
2130 .println(" parentCommon->numMemoryQueue=numMemoryQueue;");
2132 .println(" parentCommon->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2135 output.println(" }");
2139 // copy in-set into place, ready vars were already
2140 // copied when the SESE was issued
2141 Iterator<TempDescriptor> tempItr;
2143 // static vars are from a known SESE
2144 tempItr = fsen.getStaticInVarSet().iterator();
2145 while( tempItr.hasNext() ) {
2146 TempDescriptor temp = tempItr.next();
2147 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2148 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2150 // can't grab something from this source until it is done
2151 output.println(" {");
2153 If we are running, everything is done. This check is redundant.
2155 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+srcPair+";" );
2156 output.println(" pthread_mutex_lock( &(com->lock) );");
2157 output.println(" while( com->doneExecuting == FALSE ) {");
2158 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2159 output.println(" }");
2160 output.println(" pthread_mutex_unlock( &(com->lock) );");
2162 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2163 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2165 output.println(" }");
2168 // dynamic vars come from an SESE and src
2169 tempItr = fsen.getDynamicInVarSet().iterator();
2170 while( tempItr.hasNext() ) {
2171 TempDescriptor temp = tempItr.next();
2172 TypeDescriptor type = temp.getType();
2174 // go grab it from the SESE source
2175 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2177 // gotta wait until the source is done
2178 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+temp+"_srcSESE;" );
2180 If we are running, everything is done!
2181 output.println(" pthread_mutex_lock( &(com->lock) );");
2182 output.println(" while( com->doneExecuting == FALSE ) {");
2183 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2184 output.println(" }");
2185 output.println(" pthread_mutex_unlock( &(com->lock) );");
2189 if( type.isNull() ) {
2191 } else if( type.isClass() || type.isArray() ) {
2192 typeStr = "struct "+type.getSafeSymbol()+"*";
2194 typeStr = type.getSafeSymbol();
2197 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2198 " = *(("+typeStr+"*) ("+
2199 paramsprefix+"->"+temp+"_srcSESE + "+
2200 paramsprefix+"->"+temp+"_srcOffset));");
2202 // or if the source was our parent, its in the record to grab
2203 output.println(" } else {");
2204 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2205 " = "+paramsprefix+"->"+temp+";");
2206 output.println(" }");
2209 // Check to see if we need to do a GC if this is a
2210 // multi-threaded program...
2211 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2212 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2213 //Don't bother if we aren't in recursive methods...The loops case will catch it
2214 // if (callgraph.getAllMethods(md).contains(md)) {
2215 // if(this.state.MULTICOREGC) {
2216 // output.println("if(gcflag) gc("+localsprefixaddr+");");
2218 // output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2223 // initialize thread-local var to a non-zero, invalid address
2224 output.println(" seseCaller = (SESEcommon*) 0x2;");
2225 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2226 exitset.add(seseExit);
2227 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2228 output.println("}\n\n");
2233 // when a new mlp thread is created for an issued SESE, it is started
2234 // by running this method which blocks on a cond variable until
2235 // it is allowed to transition to execute. Then a case statement
2236 // allows it to invoke the method with the proper SESE body, and after
2237 // exiting the SESE method, executes proper SESE exit code before the
2238 // thread can be destroyed
2239 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2240 PrintWriter outmethod
2243 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2244 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2245 outmethod.println( " int status;");
2246 outmethod.println( " char errmsg[128];");
2248 // generate a case for each SESE class that can be invoked
2249 outmethod.println( " switch( *((int*)seseRecord) ) {");
2250 outmethod.println( " ");
2251 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
2252 FlatSESEEnterNode fsen = seseit.next();
2254 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2255 outmethod.println( " case "+fsen.getIdentifier()+":");
2256 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2258 if( fsen.equals( mlpa.getMainSESE() ) ) {
2259 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2260 outmethod.println( " exit( 0 );");
2263 outmethod.println( " break;");
2264 outmethod.println( "");
2267 // default case should never be taken, error out
2268 outmethod.println( " default:");
2269 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2270 outmethod.println( " exit(-30);");
2271 outmethod.println( " break;");
2272 outmethod.println( " }");
2273 outmethod.println( " return NULL;");
2274 outmethod.println( "}\n\n");
2278 protected void generateCode(FlatNode first,
2281 Set<FlatNode> stopset,
2282 PrintWriter output, boolean firstpass) {
2284 /* Assign labels to FlatNode's if necessary.*/
2286 Hashtable<FlatNode, Integer> nodetolabel;
2288 if (state.DELAYCOMP&&!firstpass)
2289 nodetolabel=dcassignLabels(first, stopset);
2291 nodetolabel=assignLabels(first, stopset);
2293 Set<FlatNode> storeset=null;
2294 HashSet<FlatNode> genset=null;
2295 HashSet<FlatNode> refset=null;
2296 Set<FlatNode> unionset=null;
2298 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2299 storeset=delaycomp.livecode(lb);
2300 genset=new HashSet<FlatNode>();
2301 if (state.STMARRAY&&!state.DUALVIEW) {
2302 refset=new HashSet<FlatNode>();
2303 refset.addAll(delaycomp.getDeref(lb));
2304 refset.removeAll(delaycomp.getCannotDelay(lb));
2305 refset.removeAll(delaycomp.getOther(lb));
2308 genset.addAll(delaycomp.getCannotDelay(lb));
2309 genset.addAll(delaycomp.getOther(lb));
2311 genset.addAll(delaycomp.getNotReady(lb));
2312 if (state.STMARRAY&&!state.DUALVIEW) {
2313 genset.removeAll(refset);
2316 unionset=new HashSet<FlatNode>();
2317 unionset.addAll(storeset);
2318 unionset.addAll(genset);
2319 if (state.STMARRAY&&!state.DUALVIEW)
2320 unionset.addAll(refset);
2323 /* Do the actual code generation */
2324 FlatNode current_node=null;
2325 HashSet tovisit=new HashSet();
2326 HashSet visited=new HashSet();
2328 tovisit.add(first.getNext(0));
2331 while(current_node!=null||!tovisit.isEmpty()) {
2332 if (current_node==null) {
2333 current_node=(FlatNode)tovisit.iterator().next();
2334 tovisit.remove(current_node);
2335 } else if (tovisit.contains(current_node)) {
2336 tovisit.remove(current_node);
2338 visited.add(current_node);
2339 if (nodetolabel.containsKey(current_node)) {
2340 output.println("L"+nodetolabel.get(current_node)+":");
2342 if (state.INSTRUCTIONFAILURE) {
2343 if (state.THREAD||state.DSM||state.SINGLETM) {
2344 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2346 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2348 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2350 if (!state.DELAYCOMP||firstpass) {
2351 generateFlatNode(fm, lb, current_node, output);
2353 //store primitive variables in out set
2354 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2355 Set<TempDescriptor> liveout=ar.liveout;
2356 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2357 TempDescriptor tmp=tmpit.next();
2358 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2361 if (state.MLP && stopset!=null) {
2362 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2363 assert current_node instanceof FlatSESEExitNode;
2364 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2365 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2366 assert fsen.getFlatExit().equals( fsxn );
2367 assert fsxn.getFlatEnter().equals( fsen );
2369 if (current_node.kind()!=FKind.FlatReturnNode) {
2370 output.println(" return;");
2373 } else if(current_node.numNext()==1) {
2376 current_node.kind()==FKind.FlatSESEEnterNode &&
2377 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2379 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2380 generateFlatNode(fm, lb, current_node, output);
2381 nextnode=fsen.getFlatExit().getNext(0);
2382 } else if (state.DELAYCOMP) {
2383 boolean specialprimitive=false;
2384 //skip literals...no need to add extra overhead
2385 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2386 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2387 if (!typedesc.isClass()&&!typedesc.isArray()) {
2388 specialprimitive=true;
2392 if (genset==null||genset.contains(current_node)||specialprimitive)
2393 generateFlatNode(fm, lb, current_node, output);
2394 if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2395 //need to acquire lock
2396 handleArrayDeref(fm, lb, current_node, output, firstpass);
2398 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2399 TempDescriptor wrtmp=current_node.writesTemps()[0];
2401 //need to store value written by previous node
2402 if (wrtmp.getType().isPtr()) {
2403 //only lock the objects that may actually need locking
2404 if (recorddc.getNeedTrans(lb, current_node)&&
2405 (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2406 wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2407 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2409 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2412 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2415 //need to read value read by previous node
2416 if (wrtmp.getType().isPtr()) {
2417 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2419 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");
2423 nextnode=current_node.getNext(0);
2426 generateFlatNode(fm, lb, current_node, output);
2427 nextnode=current_node.getNext(0);
2429 if (visited.contains(nextnode)) {
2430 output.println("goto L"+nodetolabel.get(nextnode)+";");
2433 current_node=nextnode;
2434 } else if (current_node.numNext()==2) {
2436 if (state.DELAYCOMP) {
2437 boolean computeside=false;
2439 //need to record which way it should go
2440 if (genset==null||genset.contains(current_node)) {
2441 if (storeset!=null&&storeset.contains(current_node)) {
2442 //need to store which way branch goes
2443 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2445 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2447 //which side to execute
2451 if (genset.contains(current_node)) {
2452 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2453 } else if (storeset.contains(current_node)) {
2455 branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2457 //which side to execute
2462 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2464 if (leftset.size()==0)
2466 if (visited.contains(current_node.getNext(branch))) {
2467 //already visited -- build jump
2468 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2471 current_node=current_node.getNext(branch);
2474 if (!visited.contains(current_node.getNext(1)))
2475 tovisit.add(current_node.getNext(1));
2476 if (visited.contains(current_node.getNext(0))) {
2477 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2480 current_node=current_node.getNext(0);
2484 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2485 if (!visited.contains(current_node.getNext(1)))
2486 tovisit.add(current_node.getNext(1));
2487 if (visited.contains(current_node.getNext(0))) {
2488 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2491 current_node=current_node.getNext(0);
2493 } else throw new Error();
2497 protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2498 if (fn.kind()==FKind.FlatSetElementNode) {
2499 FlatSetElementNode fsen=(FlatSetElementNode) fn;
2500 String dst=generateTemp(fm, fsen.getDst(), lb);
2501 String src=generateTemp(fm, fsen.getSrc(), lb);
2502 String index=generateTemp(fm, fsen.getIndex(), lb);
2503 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2505 if (elementtype.isArray()||elementtype.isClass())
2508 type=elementtype.getSafeSymbol()+" ";
2510 output.println("STOREARRAY("+dst+","+index+","+type+")");
2512 output.println("{");
2513 output.println(" struct ArrayObject *array;");
2514 output.println(" int index;");
2515 output.println(" RESTOREARRAY(array,index);");
2516 output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2517 output.println("}");
2519 } else if (fn.kind()==FKind.FlatElementNode) {
2520 FlatElementNode fen=(FlatElementNode) fn;
2521 String src=generateTemp(fm, fen.getSrc(), lb);
2522 String index=generateTemp(fm, fen.getIndex(), lb);
2523 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2524 String dst=generateTemp(fm, fen.getDst(), lb);
2526 if (elementtype.isArray()||elementtype.isClass())
2529 type=elementtype.getSafeSymbol()+" ";
2531 output.println("STOREARRAY("+src+","+index+","+type+")");
2533 output.println("{");
2534 output.println(" struct ArrayObject *array;");
2535 output.println(" int index;");
2536 output.println(" RESTOREARRAY(array,index);");
2537 output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2538 output.println("}");
2542 /** Special label assignment for delaycomputation */
2543 protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2544 HashSet tovisit=new HashSet();
2545 HashSet visited=new HashSet();
2547 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2549 //Label targets of branches
2550 Set<FlatNode> targets=branchanalysis.getTargets();
2551 for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2552 nodetolabel.put(it.next(), new Integer(labelindex++));
2557 /*Assign labels first. A node needs a label if the previous
2558 * node has two exits or this node is a join point. */
2560 while(!tovisit.isEmpty()) {
2561 FlatNode fn=(FlatNode)tovisit.iterator().next();
2566 if(lastset!=null&&lastset.contains(fn)) {
2567 // if last is not null and matches, don't go
2568 // any further for assigning labels
2572 for(int i=0; i<fn.numNext(); i++) {
2573 FlatNode nn=fn.getNext(i);
2576 //1) Edge >1 of node
2577 nodetolabel.put(nn,new Integer(labelindex++));
2579 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2583 nodetolabel.put(nn,new Integer(labelindex++));
2591 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2592 return assignLabels(first, null);
2595 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2596 HashSet tovisit=new HashSet();
2597 HashSet visited=new HashSet();
2599 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2602 /*Assign labels first. A node needs a label if the previous
2603 * node has two exits or this node is a join point. */
2605 while(!tovisit.isEmpty()) {
2606 FlatNode fn=(FlatNode)tovisit.iterator().next();
2611 if(lastset!=null&&lastset.contains(fn)) {
2612 // if last is not null and matches, don't go
2613 // any further for assigning labels
2617 for(int i=0; i<fn.numNext(); i++) {
2618 FlatNode nn=fn.getNext(i);
2621 //1) Edge >1 of node
2622 nodetolabel.put(nn,new Integer(labelindex++));
2624 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2628 nodetolabel.put(nn,new Integer(labelindex++));
2636 /** Generate text string that corresponds to the TempDescriptor td. */
2637 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2638 MethodDescriptor md=fm.getMethod();
2639 TaskDescriptor task=fm.getTask();
2640 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2642 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2643 return td.getSafeSymbol();
2646 if (objecttemps.isLocalPtr(td)) {
2647 return localsprefixderef+td.getSafeSymbol();
2650 if (objecttemps.isParamPtr(td)) {
2651 return paramsprefix+"->"+td.getSafeSymbol();
2657 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2659 // insert pre-node actions from the code plan
2662 CodePlan cp = mlpa.getCodePlan( fn );
2665 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2667 // for each sese and age pair that this parent statement
2668 // must stall on, take that child's stall semaphore, the
2669 // copying of values comes after the statement
2670 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2671 while( vstItr.hasNext() ) {
2672 VariableSourceToken vst = vstItr.next();
2674 SESEandAgePair pair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2676 output.println(" {");
2677 output.println(" SESEcommon* common = (SESEcommon*) "+pair+";");
2679 output.println(" pthread_mutex_lock( &(common->lock) );");
2680 output.println(" while( common->doneExecuting == FALSE ) {");
2681 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2682 output.println(" }");
2683 output.println(" pthread_mutex_unlock( &(common->lock) );");
2685 // copy things we might have stalled for
2686 output.println(" "+pair.getSESE().getSESErecordName()+"* child = ("+
2687 pair.getSESE().getSESErecordName()+"*) "+pair+";");
2689 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2690 while( tdItr.hasNext() ) {
2691 TempDescriptor td = tdItr.next();
2692 FlatMethod fmContext;
2693 if( currentSESE.getIsCallerSESEplaceholder() ) {
2694 fmContext = currentSESE.getfmEnclosing();
2696 fmContext = currentSESE.getfmBogus();
2698 output.println(" "+generateTemp( fmContext, td, null )+
2699 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2702 output.println(" }");
2705 // for each variable with a dynamic source, stall just for that variable
2706 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2707 while( dynItr.hasNext() ) {
2708 TempDescriptor dynVar = dynItr.next();
2710 // only stall if the dynamic source is not yourself, denoted by src==NULL
2711 // otherwise the dynamic write nodes will have the local var up-to-date
2712 output.println(" {");
2713 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2714 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2715 output.println(" psem_take( &(common->stallSem) );");
2717 FlatMethod fmContext;
2718 if( currentSESE.getIsCallerSESEplaceholder() ) {
2719 fmContext = currentSESE.getfmEnclosing();
2721 fmContext = currentSESE.getfmBogus();
2724 TypeDescriptor type=dynVar.getType();
2726 if( type.isNull() ) {
2728 } else if( type.isClass() || type.isArray() ) {
2729 typeStr = "struct "+type.getSafeSymbol()+"*";
2731 typeStr = type.getSafeSymbol();
2734 output.println(" "+generateTemp( fmContext, dynVar, null )+
2735 " = *(("+typeStr+"*) ("+
2736 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2738 output.println(" }");
2739 output.println(" }");
2742 // for each assignment of a variable to rhs that has a dynamic source,
2743 // copy the dynamic sources
2744 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2745 while( dynAssignItr.hasNext() ) {
2746 Map.Entry me = (Map.Entry) dynAssignItr.next();
2747 TempDescriptor lhs = (TempDescriptor) me.getKey();
2748 TempDescriptor rhs = (TempDescriptor) me.getValue();
2749 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
2750 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2753 // for each lhs that is dynamic from a non-dynamic source, set the
2754 // dynamic source vars to the current SESE
2755 dynItr = cp.getDynAssignCurr().iterator();
2756 while( dynItr.hasNext() ) {
2757 TempDescriptor dynVar = dynItr.next();
2758 assert currentSESE.getDynamicVarSet().contains( dynVar );
2759 output.println(" "+dynVar+"_srcSESE = NULL;");
2763 // handling stall site
2764 ParentChildConflictsMap conflictsMap = mlpa.getConflictsResults().get(fn);
2765 if (conflictsMap != null) {
2766 Set<Long> allocSet = conflictsMap.getAllocationSiteIDSetofStallSite();
2767 if (allocSet.size() > 0) {
2768 FlatNode enclosingFlatNode=null;
2769 if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
2770 enclosingFlatNode=currentSESE.getfmEnclosing();
2772 enclosingFlatNode=currentSESE;
2774 ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
2775 HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
2776 Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
2778 if(waitingElementSet.size()>0){
2779 output.println("// stall on parent's stall sites ");
2780 output.println(" {");
2781 output.println(" REntry* rentry;");
2783 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
2784 WaitingElement waitingElement = (WaitingElement) iterator.next();
2786 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
2787 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", seseCaller);");
2789 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller, (void*)&___locals___."+ waitingElement.getDynID() + ");");
2790 // output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller, ___locals___."+ waitingElement.getDynID() + "->oid);");
2792 output.println(" psem_init( &(rentry->parentStallSem) );");
2793 output.println(" rentry->queue=seseCaller->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
2795 .println(" if(ADDRENTRY(seseCaller->memoryQueueArray["+ waitingElement.getQueueID()
2796 + "],rentry)==NOTREADY){");
2797 output.println(" psem_take( &(rentry->parentStallSem) );");
2798 output.println(" } ");
2800 output.println(" }");
2809 case FKind.FlatAtomicEnterNode:
2810 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
2813 case FKind.FlatAtomicExitNode:
2814 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
2817 case FKind.FlatInstanceOfNode:
2818 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
2821 case FKind.FlatSESEEnterNode:
2822 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
2825 case FKind.FlatSESEExitNode:
2826 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
2829 case FKind.FlatWriteDynamicVarNode:
2830 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
2833 case FKind.FlatGlobalConvNode:
2834 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
2837 case FKind.FlatTagDeclaration:
2838 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
2841 case FKind.FlatCall:
2842 generateFlatCall(fm, lb, (FlatCall) fn,output);
2845 case FKind.FlatFieldNode:
2846 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
2849 case FKind.FlatElementNode:
2850 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
2853 case FKind.FlatSetElementNode:
2854 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
2857 case FKind.FlatSetFieldNode:
2858 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
2862 generateFlatNew(fm, lb, (FlatNew) fn,output);
2865 case FKind.FlatOpNode:
2866 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
2869 case FKind.FlatCastNode:
2870 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
2873 case FKind.FlatLiteralNode:
2874 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
2877 case FKind.FlatReturnNode:
2878 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
2882 output.println("/* nop */");
2885 case FKind.FlatExit:
2886 output.println("/* exit */");
2889 case FKind.FlatBackEdge:
2890 if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
2891 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
2893 if(state.DSM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
2894 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
2896 if (((state.MLP||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
2897 || (this.state.MULTICOREGC)) {
2898 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
2899 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
2900 } else if(this.state.MULTICOREGC) {
2901 output.println("if (gcflag) gc("+localsprefixaddr+");");
2903 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2906 output.println("/* nop */");
2909 case FKind.FlatCheckNode:
2910 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
2913 case FKind.FlatFlagActionNode:
2914 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
2917 case FKind.FlatPrefetchNode:
2918 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
2921 case FKind.FlatOffsetNode:
2922 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
2929 // insert post-node actions from the code-plan
2931 CodePlan cp = mlpa.getCodePlan( fn );
2938 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
2939 output.println("/* FlatOffsetNode */");
2940 FieldDescriptor fd=fofn.getField();
2941 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
2942 output.println("/* offset */");
2945 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
2946 if (state.PREFETCH) {
2947 Vector oids = new Vector();
2948 Vector fieldoffset = new Vector();
2949 Vector endoffset = new Vector();
2950 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
2951 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
2952 PrefetchPair pp = (PrefetchPair) it.next();
2953 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
2954 /* Find prefetches that can generate oid */
2955 if(statusbase == LocalityAnalysis.GLOBAL) {
2956 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
2958 } else if (statusbase == LocalityAnalysis.LOCAL) {
2959 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
2966 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
2967 output.println("{");
2968 output.println("/* prefetch */");
2969 output.println("/* prefetchid_" + fpn.siteid + " */");
2970 output.println("void * prefptr;");
2971 output.println("int tmpindex;");
2973 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
2974 /*Create C code for oid array */
2975 output.print(" unsigned int oidarray_[] = {");
2976 boolean needcomma=false;
2977 for (Iterator it = oids.iterator(); it.hasNext();) {
2980 output.print(it.next());
2983 output.println("};");
2985 /*Create C code for endoffset values */
2986 output.print(" unsigned short endoffsetarry_[] = {");
2988 for (Iterator it = endoffset.iterator(); it.hasNext();) {
2991 output.print(it.next());
2994 output.println("};");
2996 /*Create C code for Field Offset Values */
2997 output.print(" short fieldarry_[] = {");
2999 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
3002 output.print(it.next());
3005 output.println("};");
3006 /* make the prefetch call to Runtime */
3007 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
3008 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
3009 output.println(" }");
3010 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
3011 output.println(" } else {");
3012 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
3013 output.println(" }");
3014 output.println("}");
3018 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
3019 short offsetcount = 0;
3023 } else if (localbase) {
3024 for(; breakindex<pp.desc.size(); breakindex++) {
3025 Descriptor desc=pp.getDescAt(breakindex);
3026 if (desc instanceof FieldDescriptor) {
3027 FieldDescriptor fd=(FieldDescriptor)desc;
3028 if (fd.isGlobal()) {
3036 if (breakindex>pp.desc.size()) //all local
3039 TypeDescriptor lasttype=pp.base.getType();
3040 String basestr=generateTemp(fm, pp.base, lb);
3042 boolean maybenull=fm.getMethod().isStatic()||
3043 !pp.base.equals(fm.getParameter(0));
3045 for(int i=0; i<breakindex; i++) {
3046 String indexcheck="";
3048 Descriptor desc=pp.getDescAt(i);
3049 if (desc instanceof FieldDescriptor) {
3050 FieldDescriptor fd=(FieldDescriptor)desc;
3052 if (!teststr.equals(""))
3054 teststr+="((prefptr="+basestr+")!=NULL)";
3055 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3057 basestr=basestr+"->"+fd.getSafeSymbol();
3060 lasttype=fd.getType();
3062 IndexDescriptor id=(IndexDescriptor)desc;
3063 indexcheck="((tmpindex=";
3064 for(int j=0; j<id.tddesc.size(); j++) {
3065 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3067 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3069 if (!teststr.equals(""))
3071 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3072 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3074 lasttype=lasttype.dereference();
3079 if (teststr.equals("")) {
3080 oid="((unsigned int)"+basestr+")";
3082 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3086 for(int i = breakindex; i < pp.desc.size(); i++) {
3087 String newfieldoffset;
3088 Object desc = pp.getDescAt(i);
3089 if(desc instanceof FieldDescriptor) {
3090 FieldDescriptor fd=(FieldDescriptor)desc;
3091 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3092 lasttype=fd.getType();
3094 newfieldoffset = "";
3095 IndexDescriptor id=(IndexDescriptor)desc;
3096 for(int j = 0; j < id.tddesc.size(); j++) {
3097 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3099 newfieldoffset += id.offset.toString();
3100 lasttype=lasttype.dereference();
3102 fieldoffset.add(newfieldoffset);
3105 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3106 base+=pp.desc.size()-breakindex;
3107 endoffset.add(new Short((short)base));
3112 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3113 if (lb!=fgcn.getLocality())
3115 /* Have to generate flat globalconv */
3116 if (fgcn.getMakePtr()) {
3118 //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3119 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3121 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3122 //need to do translation
3123 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3124 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3125 if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3126 output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3128 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3132 /* Need to convert to OID */
3133 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3134 if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3135 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3137 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3143 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3145 if (fion.getType().isArray()) {
3146 type=state.getArrayNumber(fion.getType())+state.numClasses();
3148 type=fion.getType().getClassDesc().getId();
3151 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3152 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3154 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3157 int sandboxcounter=0;
3158 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3159 /* Check to see if we need to generate code for this atomic */
3160 if (locality==null) {
3161 if (GENERATEPRECISEGC) {
3162 output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3163 output.println("stopforgc((struct garbagelist *) &___locals___);");
3164 output.println("pthread_mutex_lock(&atomiclock);");
3165 output.println("restartaftergc();");
3166 output.println("}");
3168 output.println("pthread_mutex_lock(&atomiclock);");
3173 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3177 if (state.SANDBOX) {
3178 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3179 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3182 if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3183 AtomicRecord ar=atomicmethodmap.get(faen);
3185 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3186 TempDescriptor tmp=tmpit.next();
3187 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3190 //copy outs that depend on path
3191 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3192 TempDescriptor tmp=tmpit.next();
3193 if (!ar.livein.contains(tmp))
3194 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3198 /* Backup the temps. */
3199 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3200 TempDescriptor tmp=tmpit.next();
3201 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3204 output.println("goto transstart"+faen.getIdentifier()+";");
3206 /******* Print code to retry aborted transaction *******/
3207 output.println("transretry"+faen.getIdentifier()+":");
3210 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3211 TempDescriptor tmp=tmpit.next();
3212 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3216 /********* Need to revert local object store ********/
3217 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3219 output.println("while ("+revertptr+") {");
3220 output.println("struct ___Object___ * tmpptr;");
3221 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3222 output.println("REVERT_OBJ("+revertptr+");");
3223 output.println(revertptr+"=tmpptr;");
3224 output.println("}");
3226 /******* Tell the runtime to start the transaction *******/
3228 output.println("transstart"+faen.getIdentifier()+":");
3229 if (state.SANDBOX) {
3230 output.println("transaction_check_counter=*counter_reset_pointer;");
3233 output.println("transStart();");
3235 if (state.ABORTREADERS||state.SANDBOX) {
3237 output.println("abortenabled=1;");
3238 output.println("if (_setjmp(aborttrans)) {");
3239 output.println(" goto transretry"+faen.getIdentifier()+"; }");
3243 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3244 /* Check to see if we need to generate code for this atomic */
3245 if (locality==null) {
3246 output.println("pthread_mutex_unlock(&atomiclock);");
3249 if (locality.getAtomic(lb).get(faen).intValue()>0)
3251 //store the revert list before we lose the transaction object
3254 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3255 output.println(revertptr+"=revertlist;");
3256 output.println("if (transCommit()) {");
3257 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3258 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3259 output.println("} else {");
3260 /* Need to commit local object store */
3261 output.println("while ("+revertptr+") {");
3262 output.println("struct ___Object___ * tmpptr;");
3263 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3264 output.println("COMMIT_OBJ("+revertptr+");");
3265 output.println(revertptr+"=tmpptr;");
3266 output.println("}");
3267 output.println("}");
3271 if (!state.DELAYCOMP) {
3273 output.println("if (transCommit()) {");
3274 /* Transaction aborts if it returns true */
3275 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3276 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3277 output.println("}");
3279 if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
3280 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3281 output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3283 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3284 TempDescriptor tmp=tmpit.next();
3285 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3287 } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3288 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3290 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3291 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3292 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3293 output.println("}");
3295 output.println("else {");
3296 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3297 TempDescriptor tmp=tmpit.next();
3298 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3300 output.println("}");
3302 output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3303 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3304 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3305 output.println("}");
3310 public void generateFlatSESEEnterNode( FlatMethod fm,
3312 FlatSESEEnterNode fsen,
3316 // if MLP flag is off, okay that SESE nodes are in IR graph,
3317 // just skip over them and code generates exactly the same
3322 // there may be an SESE in an unreachable method, skip over
3323 if( !mlpa.getAllSESEs().contains( fsen ) ) {
3327 // also, if we have encountered a placeholder, just skip it
3328 if( fsen.getIsCallerSESEplaceholder() ) {
3332 output.println(" {");
3334 // set up the parent
3335 if( fsen == mlpa.getMainSESE() ) {
3336 output.println(" SESEcommon* parentCommon = NULL;");
3338 if( fsen.getParent() == null ) {
3339 System.out.println( "in "+fm+", "+fsen+" has null parent" );
3341 assert fsen.getParent() != null;
3342 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3343 output.println(" SESEcommon* parentCommon = &("+paramsprefix+"->common);");
3345 //output.println(" SESEcommon* parentCommon = (SESEcommon*) peekItem( seseCallStack );");
3346 output.println(" SESEcommon* parentCommon = seseCaller;");
3350 // before doing anything, lock your own record and increment the running children
3351 if( fsen != mlpa.getMainSESE() ) {
3352 output.println(" atomic_inc(&parentCommon->numRunningChildren);");
3355 // just allocate the space for this record
3356 output.println(" "+fsen.getSESErecordName()+"* seseToIssue = ("+
3357 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3358 fsen.getSESErecordName()+" ) );");
3359 //eomgc need to set next, size
3360 // output.println(" struct garbagelist * gl= (struct garbagelist *)&(((SESEcommon*)(seseToIssue))[1]);");
3361 output.println(" struct garbagelist * gl= (struct garbagelist *)&(((SESEcommon*)(seseToIssue))[1]);");
3362 // sizeof(int)*2 + sizeof(void*)*calculateSizeOfSESEParamList(fsen)
3363 //output.println(" // sizeof(int)*2+sizeof(void*)*"+calculateSizeOfSESEParamList(fsen));
3364 //output.println(" // blah="+calculateSizeOfSESEParamSize(fsen));
3365 output.println(" (seseToIssue->common).offsetsize=sizeof(int)+sizeof(void*)+sizeof(void*)*"+calculateSizeOfSESEParamList(fsen)+calculateSizeOfSESEParamSize(fsen)+";");
3366 output.println(" gl->size="+calculateSizeOfSESEParamList(fsen)+";");
3367 // output.println(" gl->next = (struct garbagelist *)&___locals___;");
3368 output.println(" seseToIssue->prevSESECount="+calculatePrevSESECount(fsen)+";");
3369 // output.println(" seseToIssue->prevSESECount=50;");
3370 output.println(" gl->next = NULL;");
3371 // output.println(" seseToIssue->size = "+calculateSizeOfSESEParamList(fsen)+";");
3372 // output.println(" seseToIssue->next = &___locals___;");
3375 // and keep the thread-local sese stack up to date
3376 //output.println(" addNewItem( seseCallStack, (void*) seseToIssue);");
3378 // fill in common data
3379 output.println(" int localCount=0;");
3380 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3381 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
3383 output.println(" seseToIssue->common.forwardList = createQueue();");
3384 output.println(" seseToIssue->common.unresolvedDependencies = 10000;");
3385 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3386 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3387 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3388 output.println(" seseToIssue->common.numRunningChildren = 0;");
3389 output.println(" seseToIssue->common.parent = parentCommon;");
3391 // all READY in-vars should be copied now and be done with it
3392 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3393 while( tempItr.hasNext() ) {
3394 TempDescriptor temp = tempItr.next();
3396 // when we are issuing the main SESE or an SESE with placeholder
3397 // caller SESE as parent, generate temp child child's eclosing method,
3398 // otherwise use the parent's enclosing method as the context
3399 boolean useParentContext = false;
3401 if( fsen != mlpa.getMainSESE() ) {
3402 assert fsen.getParent() != null;
3403 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3404 useParentContext = true;
3408 if( useParentContext ) {
3409 output.println(" seseToIssue->"+temp+" = "+
3410 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3412 output.println(" seseToIssue->"+temp+" = "+
3413 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3417 // before potentially adding this SESE to other forwarding lists,
3418 // create it's lock and take it immediately
3419 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3420 // output.println(" pthread_mutex_lock( &(seseToIssue->common.lock) );");
3422 if( fsen != mlpa.getMainSESE() ) {
3423 // count up outstanding dependencies, static first, then dynamic
3424 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3425 while( staticSrcsItr.hasNext() ) {
3426 SESEandAgePair srcPair = staticSrcsItr.next();
3427 output.println(" {");
3428 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3430 if(GENERATEPRECISEGC){
3431 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3433 output.println(" pthread_mutex_lock( &(src->lock) );");
3434 if(GENERATEPRECISEGC){
3435 output.println(" restartaftergc();");
3437 output.println(" if( !isEmpty( src->forwardList ) &&");
3438 output.println(" seseToIssue == peekItem( src->forwardList ) ) {");
3439 output.println(" printf( \"This shouldnt already be here\\n\");");
3440 output.println(" exit( -1 );");
3441 output.println(" }");
3442 output.println(" if( !src->doneExecuting ) {");
3443 output.println(" addNewItem( src->forwardList, seseToIssue );");
3444 // output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3445 output.println(" ++(localCount);");
3446 output.println(" }");
3447 output.println(" pthread_mutex_unlock( &(src->lock) );");
3448 output.println(" }");
3450 // whether or not it is an outstanding dependency, make sure
3451 // to pass the static name to the child's record
3452 output.println(" seseToIssue->"+srcPair+" = "+srcPair+";");
3455 // dynamic sources might already be accounted for in the static list,
3456 // so only add them to forwarding lists if they're not already there
3457 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3458 while( dynVarsItr.hasNext() ) {
3459 TempDescriptor dynInVar = dynVarsItr.next();
3460 output.println(" {");
3461 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3463 // the dynamic source is NULL if it comes from your own space--you can't pass
3464 // the address off to the new child, because you're not done executing and
3465 // might change the variable, so copy it right now
3466 output.println(" if( src != NULL ) {");
3468 if(GENERATEPRECISEGC){
3469 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3471 output.println(" pthread_mutex_lock( &(src->lock) );");
3472 if(GENERATEPRECISEGC){
3473 output.println(" restartaftergc();");
3475 output.println(" if( isEmpty( src->forwardList ) ||");
3476 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3477 output.println(" if( !src->doneExecuting ) {");
3478 output.println(" addNewItem( src->forwardList, seseToIssue );");
3479 // output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3480 output.println(" ++(localCount);");
3481 output.println(" }");
3482 output.println(" }");
3483 output.println(" pthread_mutex_unlock( &(src->lock) );");
3484 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3485 output.println(" } else {");
3487 boolean useParentContext = false;
3488 if( fsen != mlpa.getMainSESE() ) {
3489 assert fsen.getParent() != null;
3490 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3491 useParentContext = true;
3494 if( useParentContext ) {
3495 output.println(" seseToIssue->"+dynInVar+" = "+
3496 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3498 output.println(" seseToIssue->"+dynInVar+" = "+
3499 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3502 output.println(" }");
3503 output.println(" }");
3505 // even if the value is already copied, make sure your NULL source
3506 // gets passed so child knows it already has the dynamic value
3507 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3510 // maintain pointers for finding dynamic SESE
3511 // instances from static names
3512 SESEandAgePair pair = new SESEandAgePair( fsen, 0 );
3513 if( fsen.getParent() != null &&
3514 //!fsen.getParent().getIsCallerSESEplaceholder() &&
3515 fsen.getParent().getNeededStaticNames().contains( pair )
3518 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3519 SESEandAgePair pair1 = new SESEandAgePair( fsen, i );
3520 SESEandAgePair pair2 = new SESEandAgePair( fsen, i-1 );
3521 output.println(" "+pair1+" = "+pair2+";");
3523 output.println(" "+pair+" = seseToIssue;");
3527 // count up memory conflict dependencies,
3529 ConflictGraph graph = null;
3530 FlatSESEEnterNode parent = fsen.getParent();
3531 if (parent != null) {
3532 if (parent.isCallerSESEplaceholder) {
3533 graph = mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
3535 graph = mlpa.getConflictGraphResults().get(parent);
3538 if (graph != null && graph.hasConflictEdge()) {
3539 HashSet<SESELock> seseLockSet = mlpa.getConflictGraphLockMap()
3542 output.println(" //add memory queue element");
3543 Set<WaitingElement> waitingQueueSet = graph
3544 .getWaitingElementSetBySESEID(fsen.getIdentifier(),
3546 if (waitingQueueSet.size() > 0) {
3547 output.println(" {");
3548 output.println(" REntry* rentry=NULL;");
3549 output.println(" INTPTR* pointer=NULL;");
3550 output.println(" seseToIssue->common.rentryIdx=0;");
3551 for (Iterator iterator = waitingQueueSet.iterator(); iterator
3553 WaitingElement waitingElement = (WaitingElement) iterator
3556 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
3557 output.println(" rentry=mlpCreateREntry("
3558 + waitingElement.getStatus()
3559 + ", seseToIssue);");
3561 TempDescriptor td = waitingElement.getTempDesc();
3562 // decide whether waiting element is dynamic or
3564 if(fsen.getDynamicInVarSet().contains(td)){
3565 // dynamic in-var case
3566 output.println(" pointer=seseToIssue->"+ waitingElement.getDynID()+"_srcSESE+seseToIssue->"+ waitingElement.getDynID()+"_srcOffset;");
3567 output.println(" rentry=mlpCreateFineREntry("
3568 + waitingElement.getStatus()
3569 + ", seseToIssue, pointer );");
3570 // output.println(" rentry=mlpCreateFineREntry("
3571 // + waitingElement.getStatus()
3572 // + ", seseToIssue, seseToIssue->"
3573 // + waitingElement.getDynID() + "->oid);");
3574 }else if(fsen.getStaticInVarSet().contains(td)){
3575 // static in-var case
3576 VariableSourceToken vst = fsen.getStaticInVarSrc(td);
3579 String srcId = "SESE_"
3581 .getPrettyIdentifier()
3582 + vst.getSESE().getIdentifier()
3583 + "_" + vst.getAge();
3585 .println(" pointer=(void*)&seseToIssue->"
3588 + waitingElement.getDynID()
3590 output.println(" rentry=mlpCreateFineREntry("
3591 + waitingElement.getStatus()
3592 + ", seseToIssue, pointer );");
3594 // output.println(" rentry=mlpCreateFineREntry("
3595 // + waitingElement.getStatus()
3596 // + ", seseToIssue, seseToIssue->"
3597 // + waitingElement.getDynID() + "->oid);");
3600 output.println(" rentry=mlpCreateFineREntry("
3601 + waitingElement.getStatus()
3602 + ", seseToIssue, (void*)&seseToIssue->"
3603 + waitingElement.getDynID() + ");");
3604 // output.println(" rentry=mlpCreateFineREntry("
3605 // + waitingElement.getStatus()
3606 // + ", seseToIssue, seseToIssue->"
3607 // + waitingElement.getDynID() + "->oid);");
3611 .println(" rentry->queue=parentCommon->memoryQueueArray["
3612 + waitingElement.getQueueID() + "];");
3614 .println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
3616 .println(" if(ADDRENTRY(parentCommon->memoryQueueArray["
3617 + waitingElement.getQueueID()
3618 + "],rentry)==NOTREADY){");
3619 output.println(" ++(localCount);");
3620 output.println(" } ");
3623 output.println(" }");
3633 // release this SESE for siblings to update its dependencies or,
3634 // eventually, for it to mark itself finished
3635 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3637 // if there were no outstanding dependencies, issue here
3638 output.println(" if( atomic_sub_and_test(10000-localCount,&(seseToIssue->common.unresolvedDependencies) ) ) {");
3639 output.println(" workScheduleSubmit( (void*)seseToIssue );");
3640 output.println(" }");
3642 output.println(" if( seseToIssue->common.unresolvedDependencies == 0 ) {");
3643 output.println(" workScheduleSubmit( (void*)seseToIssue );");
3644 output.println(" }");
3646 // release this SESE for siblings to update its dependencies or,
3647 // eventually, for it to mark itself finished
3648 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3649 output.println(" }");
3653 public void generateFlatSESEExitNode( FlatMethod fm,
3655 FlatSESEExitNode fsexn,
3659 // if MLP flag is off, okay that SESE nodes are in IR graph,
3660 // just skip over them and code generates exactly the same
3665 // get the enter node for this exit that has meta data embedded
3666 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
3668 // there may be an SESE in an unreachable method, skip over
3669 if( !mlpa.getAllSESEs().contains( fsen ) ) {
3673 // also, if we have encountered a placeholder, just jump it
3674 if( fsen.getIsCallerSESEplaceholder() ) {
3678 output.println(" /* SESE exiting */");
3680 String com = paramsprefix+"->common";
3682 // this SESE cannot be done until all of its children are done
3683 // so grab your own lock with the condition variable for watching
3684 // that the number of your running children is greater than zero
3685 if (GENERATEPRECISEGC){
3686 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3688 output.println(" pthread_mutex_lock( &("+com+".lock) );");
3689 if (GENERATEPRECISEGC){
3690 output.println(" restartaftergc();");
3692 output.println(" while( "+com+".numRunningChildren > 0 ) {");
3693 if (GENERATEPRECISEGC){
3694 // output.println(" stopforgc((struct garbagelist *)&(((SESEcommon*)(___params___))[1]));");
3695 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3697 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
3698 if (GENERATEPRECISEGC){
3699 output.println(" restartaftergc();");
3701 output.println(" }");
3704 // copy out-set from local temps into the sese record
3705 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
3706 while( itr.hasNext() ) {
3707 TempDescriptor temp = itr.next();
3709 // only have to do this for primitives non-arrays
3711 temp.getType().isPrimitive() && !temp.getType().isArray()
3717 // have to determine the context enclosing this sese
3718 boolean useParentContext = false;
3720 if( fsen != mlpa.getMainSESE() ) {
3721 assert fsen.getParent() != null;
3722 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3723 useParentContext = true;
3728 if( useParentContext ) {
3729 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
3731 from = generateTemp( fsen.getfmEnclosing(), temp, null );
3734 output.println(" "+paramsprefix+
3735 "->"+temp.getSafeSymbol()+
3739 // mark yourself done, your SESE data is now read-only
3740 output.println(" "+com+".doneExecuting = TRUE;");
3741 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
3742 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
3744 // decrement dependency count for all SESE's on your forwarding list
3745 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
3746 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
3749 output.println(" if(consumer->rentryIdx>0){");
3750 output.println(" // resolved null pointer");
3751 output.println(" int idx;");
3752 output.println(" for(idx=0;idx<consumer->rentryIdx;idx++){");
3753 output.println(" resolvePointer(consumer->rentryArray[idx]);");
3754 output.println(" }");
3755 output.println(" }");
3758 // output.println(" pthread_mutex_lock( &(consumer->lock) );");
3759 // output.println(" --(consumer->unresolvedDependencies);");
3760 // output.println(" if( consumer->unresolvedDependencies == 0 ) {");
3761 output.println(" if( atomic_sub_and_test(1, &(consumer->unresolvedDependencies)) ){");
3762 output.println(" workScheduleSubmit( (void*)consumer );");
3763 output.println(" }");
3764 // output.println(" pthread_mutex_unlock( &(consumer->lock) );");
3765 output.println(" }");
3769 // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
3770 if( fsen != mlpa.getMainSESE() ) {
3773 output.println(" /* check memory dependency*/");
3774 output.println(" {");
3775 output.println(" int idx;");
3776 output.println(" for(idx=0;idx<___params___->common.rentryIdx;idx++){");
3777 output.println(" REntry* re=___params___->common.rentryArray[idx];");
3778 output.println(" RETIRERENTRY(re->queue,re);");
3779 output.println(" }");
3780 output.println(" }");
3784 // if parent is stalling on you, let them know you're done
3785 if( fsexn.getFlatEnter() != mlpa.getMainSESE() ) {
3786 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
3789 // last of all, decrement your parent's number of running children
3790 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
3791 output.println(" if (atomic_sub_and_test(1, &"+paramsprefix+"->common.parent->numRunningChildren)) {");
3792 if (GENERATEPRECISEGC){
3793 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3795 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
3796 if (GENERATEPRECISEGC){
3797 output.println(" restartaftergc();");
3799 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
3800 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
3801 output.println(" }");
3802 output.println(" }");
3804 // this is a thread-only variable that can be handled when critical sese-to-sese
3805 // data has been taken care of--set sese pointer to remember self over method
3806 // calls to a non-zero, invalid address
3807 output.println(" seseCaller = (SESEcommon*) 0x1;");
3811 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
3813 FlatWriteDynamicVarNode fwdvn,
3817 // should node should not be in an IR graph if the
3818 // MLP flag is not set
3819 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
3822 Hashtable<TempDescriptor, VSTWrapper> writeDynamic = fwdvn.getVar2src();
3824 assert writeDynamic != null;
3826 Iterator wdItr = writeDynamic.entrySet().iterator();
3827 while( wdItr.hasNext() ) {
3828 Map.Entry me = (Map.Entry) wdItr.next();
3829 TempDescriptor refVar = (TempDescriptor) me.getKey();
3830 VSTWrapper vstW = (VSTWrapper) me.getValue();
3831 VariableSourceToken vst = vstW.vst;
3834 // only do this if the variable in question should be tracked,
3835 // meaning that it was explicitly added to the dynamic var set
3836 if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
3842 // if there is no given source, this variable is ready so
3843 // mark src pointer NULL to signify that the var is up-to-date
3844 output.println(" "+refVar+"_srcSESE = NULL;");
3848 // otherwise we track where it will come from
3849 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
3850 output.println(" "+refVar+"_srcSESE = "+instance+";");
3851 output.println(" "+refVar+"_srcOffset = (int) &((("+
3852 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
3857 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
3858 if (state.CONSCHECK) {
3859 String specname=fcn.getSpec();
3860 String varname="repairstate___";
3861 output.println("{");
3862 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
3864 TempDescriptor[] temps=fcn.getTemps();
3865 String[] vars=fcn.getVars();
3866 for(int i=0; i<temps.length; i++) {
3867 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
3870 output.println("if (doanalysis"+specname+"("+varname+")) {");
3871 output.println("free"+specname+"_state("+varname+");");
3872 output.println("} else {");
3873 output.println("/* Bad invariant */");
3874 output.println("free"+specname+"_state("+varname+");");
3875 output.println("abort_task();");
3876 output.println("}");
3877 output.println("}");
3881 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
3883 if( state.MLP && !nonSESEpass ) {
3884 output.println(" seseCaller = (SESEcommon*)"+paramsprefix+";");
3887 MethodDescriptor md=fc.getMethod();
3888 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
3889 ClassDescriptor cn=md.getClassDesc();
3890 output.println("{");
3891 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3893 LocalityBinding fclb=locality.getBinding(lb, fc);
3894 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3896 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3897 output.print(objectparams.numPointers());
3898 output.print(", "+localsprefixaddr);
3899 if (md.getThis()!=null) {
3901 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
3903 if (fc.getThis()!=null&&md.getThis()==null) {
3904 System.out.println("WARNING!!!!!!!!!!!!");
3905 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
3909 for(int i=0; i<fc.numArgs(); i++) {
3910 Descriptor var=md.getParameter(i);
3911 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3912 if (objectparams.isParamPtr(paramtemp)) {
3913 TempDescriptor targ=fc.getArg(i);
3915 TypeDescriptor td=md.getParamType(i);
3917 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3919 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3922 output.println("};");
3927 if (fc.getReturnTemp()!=null)
3928 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
3930 /* Do we need to do virtual dispatch? */
3931 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
3934 LocalityBinding fclb=locality.getBinding(lb, fc);
3935 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3937 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3942 if (md.getReturnType().isClass()||md.getReturnType().isArray())
3943 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3945 output.print(md.getReturnType().getSafeSymbol()+" ");
3946 output.print("(*)(");
3948 boolean printcomma=false;
3949 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3951 LocalityBinding fclb=locality.getBinding(lb, fc);
3952 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3954 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3958 for(int i=0; i<objectparams.numPrimitives(); i++) {
3959 TempDescriptor temp=objectparams.getPrimitive(i);
3963 if (temp.getType().isClass()||temp.getType().isArray())
3964 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
3966 output.print(temp.getType().getSafeSymbol());
3971 LocalityBinding fclb=locality.getBinding(lb, fc);
3972 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
3974 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
3978 boolean needcomma=false;
3979 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3980 output.print("&__parameterlist__");
3984 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
3985 if (fc.getThis()!=null) {
3986 TypeDescriptor ptd=md.getThis().getType();
3989 if (ptd.isClass()&&!ptd.isArray())
3990 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3991 output.print(generateTemp(fm,fc.getThis(),lb));
3996 for(int i=0; i<fc.numArgs(); i++) {
3997 Descriptor var=md.getParameter(i);
3998 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3999 if (objectparams.isParamPrim(paramtemp)) {
4000 TempDescriptor targ=fc.getArg(i);
4004 TypeDescriptor ptd=md.getParamType(i);
4005 if (ptd.isClass()&&!ptd.isArray())
4006 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4007 output.print(generateTemp(fm, targ,lb));
4011 output.println(");");
4012 output.println(" }");
4015 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
4016 Set subclasses=typeutil.getSubClasses(thiscd);
4017 if (subclasses==null)
4019 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
4020 ClassDescriptor cd=(ClassDescriptor)classit.next();
4021 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
4022 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
4023 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
4024 if (md.matches(matchmd))
4031 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
4032 if (state.SINGLETM) {
4033 //single machine transactional memory case
4034 String field=ffn.getField().getSafeSymbol();
4035 String src=generateTemp(fm, ffn.getSrc(),lb);
4036 String dst=generateTemp(fm, ffn.getDst(),lb);
4038 output.println(dst+"="+ src +"->"+field+ ";");
4039 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
4040 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
4041 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
4042 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
4043 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
4044 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
4045 if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
4046 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4048 output.println("TRANSREADRD("+dst+", "+dst+");");
4051 } else if (state.DSM) {
4052 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
4053 if (status==LocalityAnalysis.GLOBAL) {
4054 String field=ffn.getField().getSafeSymbol();
4055 String src=generateTemp(fm, ffn.getSrc(),lb);
4056 String dst=generateTemp(fm, ffn.getDst(),lb);
4058 if (ffn.getField().getType().isPtr()) {
4060 //TODO: Uncomment this when we have runtime support
4061 //if (ffn.getSrc()==ffn.getDst()) {
4062 //output.println("{");
4063 //output.println("void * temp="+src+";");
4064 //output.println("if (temp&0x1) {");
4065 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
4066 //output.println(src+"->"+field+"="+temp+";");
4067 //output.println("}");
4068 //output.println(dst+"=temp;");
4069 //output.println("}");
4071 output.println(dst+"="+ src +"->"+field+ ";");
4072 //output.println("if ("+dst+"&0x1) {");
4073 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4074 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4075 //output.println(src+"->"+field+"="+src+"->"+field+";");
4076 //output.println("}");
4079 output.println(dst+"="+ src+"->"+field+";");
4081 } else if (status==LocalityAnalysis.LOCAL) {
4082 if (ffn.getField().getType().isPtr()&&
4083 ffn.getField().isGlobal()) {
4084 String field=ffn.getField().getSafeSymbol();
4085 String src=generateTemp(fm, ffn.getSrc(),lb);
4086 String dst=generateTemp(fm, ffn.getDst(),lb);
4087 output.println(dst+"="+ src +"->"+field+ ";");
4088 if (locality.getAtomic(lb).get(ffn).intValue()>0)
4089 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4090 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4092 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4093 } else if (status==LocalityAnalysis.EITHER) {
4094 //Code is reading from a null pointer
4095 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
4096 output.println("#ifndef RAW");
4097 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4098 output.println("#endif");
4099 //This should throw a suitable null pointer error
4100 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4102 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4104 // DEBUG if(!ffn.getDst().getType().isPrimitive()){
4105 // DEBUG output.println("within((void*)"+generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+");");
4107 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4112 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
4113 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
4114 throw new Error("Can't set array length");
4115 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4116 //Single Machine Transaction Case
4117 boolean srcptr=fsfn.getSrc().getType().isPtr();
4118 String src=generateTemp(fm,fsfn.getSrc(),lb);
4119 String dst=generateTemp(fm,fsfn.getDst(),lb);
4120 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
4121 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
4122 output.println("{");
4123 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
4124 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
4125 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4127 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4130 if (wb.needBarrier(fsfn)&&
4131 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
4132 if (state.EVENTMONITOR) {
4133 output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
4135 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
4137 if (srcptr&!fsfn.getSrc().getType().isNull()) {
4138 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4139 output.println("}");
4141 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4143 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4144 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
4145 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
4146 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4148 String src=generateTemp(fm,fsfn.getSrc(),lb);
4149 String dst=generateTemp(fm,fsfn.getDst(),lb);
4151 output.println("{");
4152 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4154 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
4157 if (wb.needBarrier(fsfn))
4158 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
4160 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4162 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4163 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
4164 /** Check if we need to copy */
4165 output.println("if(!"+dst+"->"+localcopystr+") {");
4166 /* Link object into list */
4167 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4168 output.println(revertptr+"=revertlist;");
4169 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4170 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4172 output.println("COPY_OBJ("+dst+");");
4173 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4174 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4175 output.println("}");
4177 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4179 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4180 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
4181 //writing to a null...bad
4182 output.println("if ("+dst+") {");
4183 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
4185 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4187 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4190 output.println("}");
4193 if (state.FASTCHECK) {
4194 String dst=generateTemp(fm, fsfn.getDst(),lb);
4195 output.println("if(!"+dst+"->"+localcopystr+") {");
4196 /* Link object into list */
4197 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4198 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4200 output.println("COPY_OBJ("+dst+");");
4201 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4202 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4203 output.println("}");
4206 // DEBUG if(!fsfn.getField().getType().isPrimitive()){
4207 // DEBUG output.println("within((void*)"+generateTemp(fm,fsfn.getSrc(),lb)+");");
4209 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4213 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
4214 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
4217 if (elementtype.isArray()||elementtype.isClass())
4220 type=elementtype.getSafeSymbol()+" ";
4222 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
4223 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
4224 output.println("failedboundschk();");
4226 if (state.SINGLETM) {
4227 //Single machine transaction case
4228 String dst=generateTemp(fm, fen.getDst(),lb);
4229 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))) {
4230 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4232 output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
4235 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
4236 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
4237 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
4238 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
4239 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
4240 if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
4241 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4243 output.println("TRANSREADRD("+dst+", "+dst+");");
4246 } else if (state.DSM) {
4247 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
4248 if (status==LocalityAnalysis.GLOBAL) {
4249 String dst=generateTemp(fm, fen.getDst(),lb);
4250 if (elementtype.isPtr()) {
4251 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4252 //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
4253 output.println("TRANSREAD("+dst+", "+dst+");");
4255 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4257 } else if (status==LocalityAnalysis.LOCAL) {
4258 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4259 } else if (status==LocalityAnalysis.EITHER) {
4260 //Code is reading from a null pointer
4261 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
4262 output.println("#ifndef RAW");
4263 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4264 output.println("#endif");
4265 //This should throw a suitable null pointer error
4266 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4268 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4270 // DEBUG output.println("within((void*)"+generateTemp(fm,fen.getSrc(),lb)+");");
4271 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4275 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
4276 //TODO: need dynamic check to make sure this assignment is actually legal
4277 //Because Object[] could actually be something more specific...ie. Integer[]
4279 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
4282 if (elementtype.isArray()||elementtype.isClass())
4285 type=elementtype.getSafeSymbol()+" ";
4287 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
4288 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
4289 output.println("failedboundschk();");
4292 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4293 //Transaction set element case
4294 if (wb.needBarrier(fsen)&&
4295 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
4296 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
4298 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
4299 output.println("{");
4300 String src=generateTemp(fm, fsen.getSrc(), lb);
4301 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
4302 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
4303 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4305 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4307 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4308 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
4310 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4312 output.println("}");
4314 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4315 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
4317 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4320 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4321 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
4322 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
4323 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4324 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
4325 boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
4328 if (wb.needBarrier(fsen))
4329 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
4330 } else if (dstlocal) {
4331 /** Check if we need to copy */
4332 String dst=generateTemp(fm, fsen.getDst(),lb);
4333 output.println("if(!"+dst+"->"+localcopystr+") {");
4334 /* Link object into list */
4335 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4336 output.println(revertptr+"=revertlist;");
4337 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
4338 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4340 output.println("COPY_OBJ("+dst+");");
4341 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4342 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4343 output.println("}");
4345 System.out.println("Node: "+fsen);
4346 System.out.println(lb);
4347 System.out.println("statusdst="+statusdst);
4348 System.out.println(fm.printMethod());
4349 throw new Error("Unknown array type");
4352 output.println("{");
4353 String src=generateTemp(fm, fsen.getSrc(), lb);
4354 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4355 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4356 output.println("}");
4358 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4361 if (state.FASTCHECK) {
4362 String dst=generateTemp(fm, fsen.getDst(),lb);
4363 output.println("if(!"+dst+"->"+localcopystr+") {");
4364 /* Link object into list */
4365 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4366 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4368 output.println("COPY_OBJ("+dst+");");
4369 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4370 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4371 output.println("}");
4373 // DEBUG output.println("within((void*)"+generateTemp(fm,fsen.getDst(),lb)+");");
4374 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4378 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
4379 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4380 //Stash pointer in case of GC
4381 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4382 output.println(revertptr+"=revertlist;");
4384 if (state.SINGLETM) {
4385 if (fn.getType().isArray()) {
4386 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4387 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4388 //inside transaction
4389 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4391 //outside transaction
4392 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4395 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4396 //inside transaction
4397 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4399 //outside transaction
4400 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4403 } else if (fn.getType().isArray()) {
4404 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4405 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4406 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4407 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4409 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray_oid("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+", oid);");
4410 output.println(" oid += numWorkers;");
4412 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4415 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4418 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4419 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
4420 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4421 if (this.state.MLP){
4422 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new_oid("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+", oid);");
4423 output.println(" oid += numWorkers;");
4425 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4428 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
4431 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4432 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4433 String dst=generateTemp(fm,fn.getDst(),lb);
4434 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4435 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4436 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4438 if (state.FASTCHECK) {
4439 String dst=generateTemp(fm,fn.getDst(),lb);
4440 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4441 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4442 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4446 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
4447 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4448 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
4450 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
4454 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
4455 if (fon.getRight()!=null) {
4456 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
4457 if (fon.getLeft().getType().isLong())
4458 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4460 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4462 } else if (dc!=null) {
4463 output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
4464 if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4465 output.print("(void *)");
4466 if (dc.getNeedLeftSrcTrans(lb, fon))
4467 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
4469 output.print(generateTemp(fm, fon.getLeft(),lb));
4470 output.print(")"+fon.getOp().toString()+"(");
4471 if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4472 output.print("(void *)");
4473 if (dc.getNeedRightSrcTrans(lb, fon))
4474 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
4476 output.println(generateTemp(fm,fon.getRight(),lb)+");");
4478 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
4479 } else if (fon.getOp().getOp()==Operation.ASSIGN)
4480 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4481 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
4482 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4483 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
4484 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
4485 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
4486 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
4487 else if (fon.getOp().getOp()==Operation.COMP)
4488 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
4489 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
4490 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
4492 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
4495 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
4496 /* TODO: Do type check here */
4497 if (fcn.getType().isArray()) {
4498 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4499 } else if (fcn.getType().isClass())
4500 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4502 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
4505 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
4506 if (fln.getValue()==null)
4507 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4508 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
4509 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4510 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4511 //Stash pointer in case of GC
4512 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4513 output.println(revertptr+"=revertlist;");
4515 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4516 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4517 //Stash pointer in case of GC
4518 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4519 output.println("revertlist="+revertptr+";");
4522 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4524 } else if (fln.getType().isBoolean()) {
4525 if (((Boolean)fln.getValue()).booleanValue())
4526 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
4528 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4529 } else if (fln.getType().isChar()) {
4530 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
4531 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
4532 } else if (fln.getType().isLong()) {
4533 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
4535 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
4538 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
4539 if (frn.getReturnTemp()!=null) {
4540 if (frn.getReturnTemp().getType().isPtr())
4541 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4543 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4545 output.println("return;");
4549 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4552 //only record if this group has more than one exit
4553 if (branchanalysis.numJumps(fcb)>1) {
4554 left=branchanalysis.jumpValue(fcb, 0);
4555 right=branchanalysis.jumpValue(fcb, 1);
4557 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
4559 output.println("STOREBRANCH("+right+");");
4560 output.println("goto "+label+";");
4561 output.println("}");
4563 output.println("STOREBRANCH("+left+");");
4566 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4567 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
4570 /** This method generates header information for the method or
4571 * task referenced by the Descriptor des. */
4572 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
4573 generateHeader(fm, lb, des, output, false);
4576 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
4578 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
4579 MethodDescriptor md=null;
4580 TaskDescriptor task=null;
4581 if (des instanceof MethodDescriptor)
4582 md=(MethodDescriptor) des;
4584 task=(TaskDescriptor) des;
4586 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
4588 if (md!=null&&md.getReturnType()!=null) {
4589 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4590 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4592 output.print(md.getReturnType().getSafeSymbol()+" ");
4594 //catch the constructor case
4595 output.print("void ");
4597 if (state.DSM||state.SINGLETM) {
4598 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4600 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4602 output.print(task.getSafeSymbol()+"(");
4604 boolean printcomma=false;
4605 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4607 if (state.DSM||state.SINGLETM) {
4608 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4610 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4612 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
4618 for(int i=0; i<objectparams.numPrimitives(); i++) {
4619 TempDescriptor temp=objectparams.getPrimitive(i);
4623 if (temp.getType().isClass()||temp.getType().isArray())
4624 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
4626 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
4628 output.println(") {");
4629 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4630 /* Imprecise Task */
4631 output.println("void * parameterarray[]) {");
4632 /* Unpack variables */
4633 for(int i=0; i<objectparams.numPrimitives(); i++) {
4634 TempDescriptor temp=objectparams.getPrimitive(i);
4635 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
4637 for(int i=0; i<fm.numTags(); i++) {
4638 TempDescriptor temp=fm.getTag(i);
4639 int offset=i+objectparams.numPrimitives();
4640 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
4643 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
4644 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
4645 } else output.println(") {");
4648 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
4649 output.println("/* FlatFlagActionNode */");
4652 /* Process tag changes */
4653 Relation tagsettable=new Relation();
4654 Relation tagcleartable=new Relation();
4656 Iterator tagsit=ffan.getTempTagPairs();
4657 while (tagsit.hasNext()) {
4658 TempTagPair ttp=(TempTagPair) tagsit.next();
4659 TempDescriptor objtmp=ttp.getTemp();
4660 TagDescriptor tag=ttp.getTag();
4661 TempDescriptor tagtmp=ttp.getTagTemp();
4662 boolean tagstatus=ffan.getTagChange(ttp);
4664 tagsettable.put(objtmp, tagtmp);
4666 tagcleartable.put(objtmp, tagtmp);
4671 Hashtable flagandtable=new Hashtable();
4672 Hashtable flagortable=new Hashtable();
4674 /* Process flag changes */
4675 Iterator flagsit=ffan.getTempFlagPairs();
4676 while(flagsit.hasNext()) {
4677 TempFlagPair tfp=(TempFlagPair)flagsit.next();
4678 TempDescriptor temp=tfp.getTemp();
4679 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
4680 FlagDescriptor flag=tfp.getFlag();
4682 //Newly allocate objects that don't set any flags case
4683 if (flagortable.containsKey(temp)) {
4687 flagortable.put(temp,new Integer(mask));
4689 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
4690 boolean flagstatus=ffan.getFlagChange(tfp);
4693 if (flagortable.containsKey(temp)) {
4694 mask=((Integer)flagortable.get(temp)).intValue();
4697 flagortable.put(temp,new Integer(mask));
4699 int mask=0xFFFFFFFF;
4700 if (flagandtable.containsKey(temp)) {
4701 mask=((Integer)flagandtable.get(temp)).intValue();
4703 mask&=(0xFFFFFFFF^flagid);
4704 flagandtable.put(temp,new Integer(mask));
4710 HashSet flagtagset=new HashSet();
4711 flagtagset.addAll(flagortable.keySet());
4712 flagtagset.addAll(flagandtable.keySet());
4713 flagtagset.addAll(tagsettable.keySet());
4714 flagtagset.addAll(tagcleartable.keySet());
4716 Iterator ftit=flagtagset.iterator();
4717 while(ftit.hasNext()) {
4718 TempDescriptor temp=(TempDescriptor)ftit.next();
4721 Set tagtmps=tagcleartable.get(temp);
4722 if (tagtmps!=null) {
4723 Iterator tagit=tagtmps.iterator();
4724 while(tagit.hasNext()) {
4725 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4726 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4727 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4729 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4733 tagtmps=tagsettable.get(temp);
4734 if (tagtmps!=null) {
4735 Iterator tagit=tagtmps.iterator();
4736 while(tagit.hasNext()) {
4737 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4738 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4739 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4741 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
4746 int andmask=0xFFFFFFF;
4748 if (flagortable.containsKey(temp))
4749 ormask=((Integer)flagortable.get(temp)).intValue();
4750 if (flagandtable.containsKey(temp))
4751 andmask=((Integer)flagandtable.get(temp)).intValue();
4752 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
4753 generateObjectDistribute(ffan, fm, lb, temp, output);
4757 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
4758 PrintWriter output, int ormask, int andmask) {
4759 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
4760 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4762 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4766 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
4767 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
4770 void generateOptionalHeader(PrintWriter headers) {
4773 headers.println("#include \"task.h\"\n\n");
4774 headers.println("#ifndef _OPTIONAL_STRUCT_");
4775 headers.println("#define _OPTIONAL_STRUCT_");
4777 //STRUCT PREDICATEMEMBER
4778 headers.println("struct predicatemember{");
4779 headers.println("int type;");
4780 headers.println("int numdnfterms;");
4781 headers.println("int * flags;");
4782 headers.println("int numtags;");
4783 headers.println("int * tags;\n};\n\n");
4785 //STRUCT OPTIONALTASKDESCRIPTOR
4786 headers.println("struct optionaltaskdescriptor{");
4787 headers.println("struct taskdescriptor * task;");
4788 headers.println("int index;");
4789 headers.println("int numenterflags;");
4790 headers.println("int * enterflags;");
4791 headers.println("int numpredicatemembers;");
4792 headers.println("struct predicatemember ** predicatememberarray;");
4793 headers.println("};\n\n");
4795 //STRUCT TASKFAILURE
4796 headers.println("struct taskfailure {");
4797 headers.println("struct taskdescriptor * task;");
4798 headers.println("int index;");
4799 headers.println("int numoptionaltaskdescriptors;");
4800 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4802 //STRUCT FSANALYSISWRAPPER
4803 headers.println("struct fsanalysiswrapper{");
4804 headers.println("int flags;");
4805 headers.println("int numtags;");
4806 headers.println("int * tags;");
4807 headers.println("int numtaskfailures;");
4808 headers.println("struct taskfailure ** taskfailurearray;");
4809 headers.println("int numoptionaltaskdescriptors;");
4810 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4812 //STRUCT CLASSANALYSISWRAPPER
4813 headers.println("struct classanalysiswrapper{");
4814 headers.println("int type;");
4815 headers.println("int numotd;");
4816 headers.println("struct optionaltaskdescriptor ** otdarray;");
4817 headers.println("int numfsanalysiswrappers;");
4818 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
4820 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
4822 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
4823 while(taskit.hasNext()) {
4824 TaskDescriptor td=(TaskDescriptor)taskit.next();
4825 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
4830 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
4831 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
4832 int predicateindex = 0;
4833 //iterate through the classes concerned by the predicate
4834 Set c_vard = predicate.vardescriptors;
4835 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
4838 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
4839 VarDescriptor vard = (VarDescriptor)vard_it.next();
4840 TypeDescriptor typed = vard.getType();
4842 //generate for flags
4843 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
4844 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4846 if (fen_hashset!=null) {
4847 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
4848 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
4850 DNFFlag dflag=fen.getDNF();
4851 numberterms+=dflag.size();
4853 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
4855 for(int j=0; j<dflag.size(); j++) {
4857 output.println(",");
4858 Vector term=dflag.get(j);
4861 for(int k=0; k<term.size(); k++) {
4862 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
4863 FlagDescriptor fd=dfa.getFlag();
4864 boolean negated=dfa.getNegated();
4865 int flagid=1<<((Integer)flags.get(fd)).intValue();
4870 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
4875 output.println("};\n");
4878 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
4879 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4882 for(int j=0; j<tagel.numTags(); j++) {
4884 output.println(",");
4885 TempDescriptor tmp=tagel.getTemp(j);
4886 if (!slotnumber.containsKey(tmp)) {
4887 Integer slotint=new Integer(current_slot++);
4888 slotnumber.put(tmp,slotint);
4890 int slot=slotnumber.get(tmp).intValue();
4891 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
4893 numtags = tagel.numTags();
4895 output.println("};");
4897 //store the result into a predicatemember struct
4898 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4899 output.println("/*type*/"+typed.getClassDesc().getId()+",");
4900 output.println("/* number of dnf terms */"+numberterms+",");
4901 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4902 output.println("/* number of tag */"+numtags+",");
4903 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4904 output.println("};\n");
4909 //generate an array that stores the entire predicate
4910 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4911 for( int j = 0; j<predicateindex; j++) {
4912 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4913 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4915 output.println("};\n");
4916 return predicateindex;
4920 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
4921 generateOptionalHeader(headers);
4923 output.println("#include \"optionalstruct.h\"\n\n");
4924 output.println("#include \"stdlib.h\"\n");
4926 HashSet processedcd = new HashSet();
4928 Enumeration e = safeexecution.keys();
4929 while (e.hasMoreElements()) {
4932 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
4933 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
4935 //Generate the struct of optionals
4936 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4937 numotd = c_otd.size();
4938 if(maxotd<numotd) maxotd = numotd;
4939 if( !c_otd.isEmpty() ) {
4940 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4941 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4943 //generate the int arrays for the predicate
4944 Predicate predicate = otd.predicate;
4945 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
4946 TreeSet<Integer> fsset=new TreeSet<Integer>();
4947 //iterate through possible FSes corresponding to
4948 //the state when entering
4950 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
4951 FlagState fs = (FlagState)fses.next();
4953 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4954 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4955 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4958 fsset.add(new Integer(flagid));
4959 //tag information not needed because tag
4960 //changes are not tolerated.
4963 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4964 boolean needcomma=false;
4965 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
4968 output.println(it.next());
4971 output.println("};\n");
4974 //generate optionaltaskdescriptor that actually
4975 //includes exit fses, predicate and the task
4977 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4978 output.println("&task_"+otd.td.getSafeSymbol()+",");
4979 output.println("/*index*/"+otd.getIndex()+",");
4980 output.println("/*number of enter flags*/"+fsset.size()+",");
4981 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4982 output.println("/*number of members */"+predicateindex+",");
4983 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4984 output.println("};\n");
4988 // if there are no optionals, there is no need to build the rest of the struct
4990 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
4991 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4992 if( !c_otd.isEmpty() ) {
4993 boolean needcomma=false;
4994 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4995 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4997 output.println(",");
4999 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5002 output.println("};\n");
5004 //get all the possible flagstates reachable by an object
5005 Hashtable hashtbtemp = safeexecution.get(cdtemp);
5007 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
5008 fsts.addAll(hashtbtemp.keySet());
5009 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
5010 FlagState fs = (FlagState)fsit.next();
5013 //get the set of OptionalTaskDescriptors corresponding
5014 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
5015 //iterate through the OptionalTaskDescriptors and
5016 //store the pointers to the optionals struct (see on
5017 //top) into an array
5019 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
5020 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
5021 OptionalTaskDescriptor mm = mos.next();
5023 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
5025 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5028 output.println("};\n");
5030 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
5033 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5034 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5035 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5039 //process tag information
5042 boolean first = true;
5043 Enumeration tag_enum = fs.getTags();
5044 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5045 while(tag_enum.hasMoreElements()) {
5047 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
5051 output.println(", ");
5052 output.println("/*tagid*/"+state.getTagId(tagd));
5054 output.println("};");
5056 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
5057 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5058 TaskIndex ti=itti.next();
5062 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
5064 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
5065 boolean needcomma=false;
5066 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
5067 OptionalTaskDescriptor otd=otdit.next();
5071 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5073 output.println("};");
5075 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
5076 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
5077 output.print(ti.getIndex()+", ");
5078 output.print(otdset.size()+", ");
5079 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
5080 output.println("};");
5083 tiset=sa.getTaskIndex(fs);
5084 boolean needcomma=false;
5086 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5087 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5088 TaskIndex ti=itti.next();
5089 if (ti.isRuntime()) {
5096 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
5098 output.println("};\n");
5100 //Store the result in fsanalysiswrapper
5102 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
5103 output.println("/*flag*/"+flagid+",");
5104 output.println("/* number of tags*/"+tagcounter+",");
5105 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5106 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
5107 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5108 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
5109 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
5110 output.println("};\n");
5114 //Build the array of fsanalysiswrappers
5115 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
5116 boolean needcomma=false;
5117 for(int i = 0; i<fscounter; i++) {
5118 if (needcomma) output.print(",");
5119 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
5122 output.println("};");
5124 //Build the classanalysiswrapper referring to the previous array
5125 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
5126 output.println("/*type*/"+cdtemp.getId()+",");
5127 output.println("/*numotd*/"+numotd+",");
5128 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
5129 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
5130 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
5131 processedcd.add(cdtemp);
5134 //build an array containing every classes for which code has been build
5135 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
5136 for(int i=0; i<state.numClasses(); i++) {
5137 ClassDescriptor cn=cdarray[i];
5140 if ((cn != null) && (processedcd.contains(cn)))
5141 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
5143 output.print("NULL");
5145 output.println("};");
5147 output.println("#define MAXOTD "+maxotd);
5148 headers.println("#endif");
5151 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
5152 Relation r=new Relation();
5153 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
5154 OptionalTaskDescriptor otd=otdit.next();
5155 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
5159 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
5160 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
5161 Set s=r.get(it.next());
5162 for(Iterator it2=s.iterator(); it2.hasNext();) {
5163 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
5171 protected void outputTransCode(PrintWriter output) {
5174 private int calculateSizeOfSESEParamList(FlatSESEEnterNode fsen){
5176 Set<TempDescriptor> tdSet=new HashSet<TempDescriptor>();
5178 for (Iterator iterator = fsen.getInVarSet().iterator(); iterator.hasNext();) {
5179 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5180 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5181 tdSet.add(tempDescriptor);
5185 for (Iterator iterator = fsen.getOutVarSet().iterator(); iterator.hasNext();) {
5186 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5187 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5188 tdSet.add(tempDescriptor);
5192 return tdSet.size();
5195 private String calculateSizeOfSESEParamSize(FlatSESEEnterNode fsen){
5196 HashMap <String,Integer> map=new HashMap();
5197 HashSet <TempDescriptor> processed=new HashSet<TempDescriptor>();
5200 // space for all in and out set primitives
5201 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
5202 inSetAndOutSet.addAll( fsen.getInVarSet() );
5203 inSetAndOutSet.addAll( fsen.getOutVarSet() );
5205 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
5207 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
5208 while( itr.hasNext() ) {
5209 TempDescriptor temp = itr.next();
5210 TypeDescriptor type = temp.getType();
5211 if( !type.isPtr() ) {
5212 inSetAndOutSetPrims.add( temp );
5216 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
5217 while( itrPrims.hasNext() ) {
5218 TempDescriptor temp = itrPrims.next();
5219 TypeDescriptor type = temp.getType();
5220 if(type.isPrimitive()){
5221 Integer count=map.get(type.getSymbol());
5223 count=new Integer(1);
5224 map.put(type.getSymbol(), count);
5226 map.put(type.getSymbol(), new Integer(count.intValue()+1));
5231 Set<String> keySet=map.keySet();
5232 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
5233 String key = (String) iterator.next();
5234 rtr+="+sizeof("+key+")*"+map.get(key);
5239 private int calculatePrevSESECount(FlatSESEEnterNode fsen){
5243 Iterator<TempDescriptor>itrDynInVars = fsen.getDynamicInVarSet().iterator();
5244 while( itrDynInVars.hasNext() ) {
5245 TempDescriptor dynInVar = itrDynInVars.next();
5249 // in-set source tracking
5250 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
5251 while( itrStaticInVarSrcs.hasNext() ) {
5252 SESEandAgePair srcPair = itrStaticInVarSrcs.next();