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.SESEWaitingQueue;
36 import Analysis.MLP.VariableSourceToken;
37 import Analysis.MLP.VSTWrapper;
38 import Analysis.MLP.CodePlan;
39 import Analysis.MLP.SESEandAgePair;
40 import Analysis.MLP.WaitingElement;
42 public class BuildCode {
45 Hashtable paramstable;
50 String localsprefix="___locals___";
51 String localsprefixaddr="&"+localsprefix;
52 String localsprefixderef=localsprefix+".";
53 String fcrevert="___fcrevert___";
54 String paramsprefix="___params___";
55 String oidstr="___nextobject___";
56 String nextobjstr="___nextobject___";
57 String localcopystr="___localcopy___";
58 public static boolean GENERATEPRECISEGC=false;
59 public static String PREFIX="";
60 public static String arraytype="ArrayObject";
61 public static int flagcount = 0;
64 protected int maxtaskparams=0;
65 private int maxcount=0;
66 ClassDescriptor[] cdarray;
67 TypeDescriptor[] arraytable;
68 LocalityAnalysis locality;
69 Hashtable<LocalityBinding, TempDescriptor> reverttable;
70 Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>> backuptable;
74 String mlperrstr = "if(status != 0) { "+
75 "sprintf(errmsg, \"MLP error at %s:%d\", __FILE__, __LINE__); "+
76 "perror(errmsg); exit(-1); }";
77 boolean nonSESEpass=true;
80 DiscoverConflicts recorddc;
85 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa) {
86 this(st, temptovar, typeutil, null, sa, pa, null);
89 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa) {
90 this(st, temptovar, typeutil, null, sa, pa, mlpa);
93 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, PrefetchAnalysis pa, MLPAnalysis mlpa) {
94 this(st, temptovar, typeutil, locality, null, pa, mlpa);
97 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa) {
102 callgraph=new CallGraph(state);
104 oidstr="___objlocation___";
105 this.temptovar=temptovar;
106 paramstable=new Hashtable();
107 tempstable=new Hashtable();
108 fieldorder=new Hashtable();
109 flagorder=new Hashtable();
110 this.typeutil=typeutil;
111 virtualcalls=new Virtual(state,locality);
112 if (locality!=null) {
113 this.locality=locality;
114 this.reverttable=new Hashtable<LocalityBinding, TempDescriptor>();
115 this.backuptable=new Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>>();
116 this.wb=new WriteBarrier(locality, st);
118 if (state.SINGLETM&&state.DCOPTS) {
119 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
120 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
121 this.dc=new DiscoverConflicts(locality, st, typeanalysis, gft);
124 if (state.DELAYCOMP) {
125 //TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
126 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
127 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
128 delaycomp=new DCWrapper(locality, st, typeanalysis, gft);
129 dc=delaycomp.getConflicts();
130 recorddc=new DiscoverConflicts(locality, st, typeanalysis, delaycomp.getCannotDelayMap(), true, true, null);
131 recorddc.doAnalysis();
135 /** The buildCode method outputs C code for all the methods. The Flat
136 * versions of the methods must already be generated and stored in
137 * the State object. */
138 PrintWriter outsandbox=null;
140 public void buildCode() {
141 /* Create output streams to write to */
142 PrintWriter outclassdefs=null;
143 PrintWriter outstructs=null;
144 PrintWriter outrepairstructs=null;
145 PrintWriter outmethodheader=null;
146 PrintWriter outmethod=null;
147 PrintWriter outvirtual=null;
148 PrintWriter outtask=null;
149 PrintWriter outtaskdefs=null;
150 PrintWriter outoptionalarrays=null;
151 PrintWriter optionalheaders=null;
155 outsandbox=new PrintWriter(new FileOutputStream(PREFIX+"sandboxdefs.c"), true);
157 outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
158 outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
159 outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
160 outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
161 outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
163 outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
164 outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
165 if (state.OPTIONAL) {
166 outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
167 optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
170 if (state.structfile!=null) {
171 outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
173 } catch (Exception e) {
178 /* Build the virtual dispatch tables */
179 buildVirtualTables(outvirtual);
181 /* Output includes */
182 outmethodheader.println("#ifndef METHODHEADERS_H");
183 outmethodheader.println("#define METHODHEADERS_H");
184 outmethodheader.println("#include \"structdefs.h\"");
186 outmethodheader.println("#include \"dstm.h\"");
188 outmethodheader.println("#include \"sandbox.h\"");
190 if (state.EVENTMONITOR) {
191 outmethodheader.println("#include \"monitor.h\"");
193 if (state.SINGLETM) {
194 outmethodheader.println("#include \"tm.h\"");
195 outmethodheader.println("#include \"delaycomp.h\"");
196 outmethodheader.println("#include \"inlinestm.h\"");
198 if (state.ABORTREADERS) {
199 outmethodheader.println("#include \"abortreaders.h\"");
200 outmethodheader.println("#include <setjmp.h>");
203 outmethodheader.println("#include <stdlib.h>");
204 outmethodheader.println("#include <stdio.h>");
205 outmethodheader.println("#include <string.h>");
206 outmethodheader.println("#include \"mlp_runtime.h\"");
207 outmethodheader.println("#include \"psemaphore.h\"");
210 /* Output Structures */
211 outputStructs(outstructs);
213 // Output the C class declarations
214 // These could mutually reference each other
215 outputClassDeclarations(outclassdefs);
217 // Output function prototypes and structures for parameters
218 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
219 while(it.hasNext()) {
220 ClassDescriptor cn=(ClassDescriptor)it.next();
221 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader);
223 outclassdefs.close();
226 /* Map flags to integers */
227 /* The runtime keeps track of flags using these integers */
228 it=state.getClassSymbolTable().getDescriptorsIterator();
229 while(it.hasNext()) {
230 ClassDescriptor cn=(ClassDescriptor)it.next();
234 generateTaskStructs(outstructs, outmethodheader);
236 /* Outputs generic task structures if this is a task
238 outputTaskTypes(outtask);
242 // have to initialize some SESE compiler data before
243 // analyzing normal methods, which must happen before
244 // generating SESE internal code
245 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
246 FlatSESEEnterNode fsen = seseit.next();
247 initializeSESE( fsen );
251 /* Build the actual methods */
252 outputMethods(outmethod);
254 // Output function prototypes and structures for SESE's and code
257 // used to differentiate, during code generation, whether we are
258 // passing over SESE body code, or non-SESE code
261 // first generate code for each sese's internals
262 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
263 FlatSESEEnterNode fsen = seseit.next();
264 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
267 // then write the invokeSESE switch to decouple scheduler
268 // from having to do unique details of sese invocation
269 generateSESEinvocationMethod(outmethodheader, outmethod);
273 /* Output code for tasks */
274 outputTaskCode(outtaskdefs, outmethod);
276 /* Record maximum number of task parameters */
277 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
278 } else if (state.main!=null) {
279 /* Generate main method */
280 outputMainMethod(outmethod);
283 /* Generate information for task with optional parameters */
284 if (state.TASK&&state.OPTIONAL) {
285 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
286 outoptionalarrays.close();
289 /* Output structure definitions for repair tool */
290 if (state.structfile!=null) {
291 buildRepairStructs(outrepairstructs);
292 outrepairstructs.close();
296 outmethodheader.println("#endif");
297 outmethodheader.close();
299 outstructs.println("#endif");
304 /* This code just generates the main C method for java programs.
305 * The main C method packs up the arguments into a string array
306 * and passes it to the java main method. */
308 private void outputMainMethod(PrintWriter outmethod) {
309 outmethod.println("int main(int argc, const char *argv[]) {");
310 outmethod.println(" int i;");
313 //outmethod.println(" pthread_once( &mlpOnceObj, mlpInitOncePerThread );");
314 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
318 if (state.DSMRECOVERYSTATS) {
319 outmethod.println("#ifdef RECOVERYSTATS \n");
320 outmethod.println("handle();\n");
321 outmethod.println("#endif\n");
323 outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
324 outmethod.println("handle();\n");
325 outmethod.println("#endif\n");
329 if (state.THREAD||state.DSM||state.SINGLETM) {
330 outmethod.println("initializethreads();");
333 outmethod.println("if (dstmStartup(argv[1])) {");
334 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
335 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
337 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
340 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
341 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
343 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
347 outmethod.println(" for(i=2;i<argc;i++) {");
349 outmethod.println(" for(i=1;i<argc;i++) {");
350 outmethod.println(" int length=strlen(argv[i]);");
351 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
352 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
354 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
357 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
359 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
360 outmethod.println(" }");
362 MethodDescriptor md=typeutil.getMain();
363 ClassDescriptor cd=typeutil.getMainClass();
365 outmethod.println(" {");
366 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
367 if (state.DSM||state.SINGLETM) {
368 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
370 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
371 outmethod.println("1, NULL,"+"stringarray};");
372 if (state.DSM||state.SINGLETM)
373 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
375 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
377 if (state.DSM||state.SINGLETM)
378 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
380 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
382 outmethod.println(" }");
385 outmethod.println("}");
388 if (state.THREAD||state.DSM||state.SINGLETM) {
389 outmethod.println("pthread_mutex_lock(&gclistlock);");
390 outmethod.println("threadcount--;");
391 outmethod.println("pthread_cond_signal(&gccond);");
392 outmethod.println("pthread_mutex_unlock(&gclistlock);");
395 if (state.DSM||state.SINGLETM) {
396 //outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
397 outmethod.println("#if defined(TRANSSTATS) \n");
398 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
399 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
400 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
401 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
403 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
404 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
405 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
406 outmethod.println("printf(\"ndirtyCacheObj= %d\\n\", ndirtyCacheObj);");
407 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
408 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
409 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
410 outmethod.println("printf(\"totalObjSize= %d\\n\", totalObjSize);");
411 outmethod.println("printf(\"sendRemoteReq= %d\\n\", sendRemoteReq);");
412 outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
413 } else if (state.SINGLETM) {
414 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
415 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
416 outmethod.println("#ifdef STMSTATS\n");
417 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
418 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
419 outmethod.println("}\n");
420 outmethod.println("#endif\n");
421 outmethod.println("fflush(stdout);");
423 outmethod.println("#endif\n");
426 if (state.EVENTMONITOR) {
427 outmethod.println("dumpdata();");
430 if (state.THREAD||state.SINGLETM)
431 outmethod.println("pthread_exit(NULL);");
434 outmethod.println(" workScheduleBegin();");
437 outmethod.println("}");
440 /* This method outputs code for each task. */
442 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
443 /* Compile task based program */
444 outtaskdefs.println("#include \"task.h\"");
445 outtaskdefs.println("#include \"methodheaders.h\"");
446 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
447 while(taskit.hasNext()) {
448 TaskDescriptor td=(TaskDescriptor)taskit.next();
449 FlatMethod fm=state.getMethodFlat(td);
450 generateFlatMethod(fm, null, outmethod);
451 generateTaskDescriptor(outtaskdefs, fm, td);
454 //Output task descriptors
455 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
456 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
458 while(taskit.hasNext()) {
459 TaskDescriptor td=(TaskDescriptor)taskit.next();
463 outtaskdefs.println(",");
464 outtaskdefs.print("&task_"+td.getSafeSymbol());
466 outtaskdefs.println("};");
468 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
471 /* This method outputs most of the methods.c file. This includes
472 * some standard includes and then an array with the sizes of
473 * objets and array that stores supertype and then the code for
474 * the Java methods.. */
476 protected void outputMethods(PrintWriter outmethod) {
477 outmethod.println("#include \"methodheaders.h\"");
478 outmethod.println("#include \"virtualtable.h\"");
479 outmethod.println("#include \"runtime.h\"");
481 outmethod.println("#include \"sandboxdefs.c\"");
484 outmethod.println("#include \"addPrefetchEnhance.h\"");
485 outmethod.println("#include \"localobjects.h\"");
487 if (state.FASTCHECK) {
488 outmethod.println("#include \"localobjects.h\"");
490 if(state.MULTICORE) {
491 outmethod.println("#include \"task.h\"");
492 outmethod.println("#include \"multicoreruntime.h\"");
493 outmethod.println("#include \"runtime_arch.h\"");
495 if (state.THREAD||state.DSM||state.SINGLETM)
496 outmethod.println("#include <thread.h>");
497 if (state.main!=null) {
498 outmethod.println("#include <string.h>");
500 if (state.CONSCHECK) {
501 outmethod.println("#include \"checkers.h\"");
504 outmethod.println("#include <stdlib.h>");
505 outmethod.println("#include <stdio.h>");
506 outmethod.println("#include \"mlp_runtime.h\"");
507 outmethod.println("#include \"psemaphore.h\"");
511 //Store the sizes of classes & array elements
512 generateSizeArray(outmethod);
514 //Store table of supertypes
515 generateSuperTypeTable(outmethod);
517 //Store the layout of classes
518 generateLayoutStructs(outmethod);
520 /* Generate code for methods */
521 if (state.DSM||state.SINGLETM) {
522 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
523 LocalityBinding lb=lbit.next();
524 MethodDescriptor md=lb.getMethod();
525 FlatMethod fm=state.getMethodFlat(md);
527 if (!md.getModifiers().isNative()) {
528 generateFlatMethod(fm, lb, outmethod);
529 //System.out.println("fm= " + fm + " md= " + md);
533 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
534 while(classit.hasNext()) {
535 ClassDescriptor cn=(ClassDescriptor)classit.next();
536 Iterator methodit=cn.getMethods();
537 while(methodit.hasNext()) {
538 /* Classify parameters */
539 MethodDescriptor md=(MethodDescriptor)methodit.next();
540 FlatMethod fm=state.getMethodFlat(md);
541 if (!md.getModifiers().isNative()) {
542 generateFlatMethod(fm, null, outmethod);
549 protected void outputStructs(PrintWriter outstructs) {
550 outstructs.println("#ifndef STRUCTDEFS_H");
551 outstructs.println("#define STRUCTDEFS_H");
552 outstructs.println("#include \"classdefs.h\"");
553 outstructs.println("#ifndef INTPTR");
554 outstructs.println("#ifdef BIT64");
555 outstructs.println("#define INTPTR long");
556 outstructs.println("#else");
557 outstructs.println("#define INTPTR int");
558 outstructs.println("#endif");
559 outstructs.println("#endif");
561 outstructs.println("#include \"mlp_runtime.h\"");
562 outstructs.println("#include \"psemaphore.h\"");
565 /* Output #defines that the runtime uses to determine type
566 * numbers for various objects it needs */
567 outstructs.println("#define MAXCOUNT "+maxcount);
568 if (state.DSM||state.SINGLETM) {
569 LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
571 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
573 else if (state.SINGLETM) {
574 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
576 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
580 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
582 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
583 else if( state.SINGLETM)
584 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
585 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
588 outstructs.println("#define STRINGARRAYTYPE "+
589 (state.getArrayNumber(
590 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
592 outstructs.println("#define OBJECTARRAYTYPE "+
593 (state.getArrayNumber(
594 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
597 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
598 outstructs.println("#define CHARARRAYTYPE "+
599 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
601 outstructs.println("#define BYTEARRAYTYPE "+
602 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
604 outstructs.println("#define BYTEARRAYARRAYTYPE "+
605 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
607 outstructs.println("#define NUMCLASSES "+state.numClasses());
608 int totalClassSize = state.numClasses() + state.numArrays();
609 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
611 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
612 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
613 outstructs.println("#define TAGARRAYTYPE "+
614 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
618 protected void outputClassDeclarations(PrintWriter outclassdefs) {
619 if (state.THREAD||state.DSM||state.SINGLETM)
620 outclassdefs.println("#include <pthread.h>");
621 outclassdefs.println("#ifndef INTPTR");
622 outclassdefs.println("#ifdef BIT64");
623 outclassdefs.println("#define INTPTR long");
624 outclassdefs.println("#else");
625 outclassdefs.println("#define INTPTR int");
626 outclassdefs.println("#endif");
627 outclassdefs.println("#endif");
629 outclassdefs.println("#include \"optionalstruct.h\"");
630 outclassdefs.println("struct "+arraytype+";");
631 /* Start by declaring all structs */
632 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
633 while(it.hasNext()) {
634 ClassDescriptor cn=(ClassDescriptor)it.next();
635 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
637 outclassdefs.println("");
638 //Print out definition for array type
639 outclassdefs.println("struct "+arraytype+" {");
640 outclassdefs.println(" int type;");
642 outclassdefs.println(" int oid;");
644 if (state.EVENTMONITOR) {
645 outclassdefs.println(" int objuid;");
648 outclassdefs.println(" pthread_t tid;");
649 outclassdefs.println(" void * lockentry;");
650 outclassdefs.println(" int lockcount;");
653 outclassdefs.println(" int flag;");
654 if(!state.MULTICORE) {
655 outclassdefs.println(" void * flagptr;");
657 outclassdefs.println(" int version;");
658 outclassdefs.println(" int * lock;"); // lock entry for this obj
659 outclassdefs.println(" int mutex;");
660 outclassdefs.println(" int lockcount;");
661 if(state.MULTICOREGC) {
662 outclassdefs.println(" int marked;");
666 outclassdefs.println(" int numfses;");
667 outclassdefs.println(" int * fses;");
670 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
672 if (state.STMARRAY) {
673 outclassdefs.println(" int lowindex;");
674 outclassdefs.println(" int highindex;");
677 outclassdefs.println(" int paddingforarray;");
678 if (state.DUALVIEW) {
679 outclassdefs.println(" int arrayversion;");
682 outclassdefs.println(" int ___length___;");
683 outclassdefs.println("};\n");
684 outclassdefs.println("extern int classsize[];");
685 outclassdefs.println("extern int hasflags[];");
686 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
687 outclassdefs.println("extern int supertypes[];");
690 /** Prints out definitions for generic task structures */
692 private void outputTaskTypes(PrintWriter outtask) {
693 outtask.println("#ifndef _TASK_H");
694 outtask.println("#define _TASK_H");
695 outtask.println("struct parameterdescriptor {");
696 outtask.println("int type;");
697 outtask.println("int numberterms;");
698 outtask.println("int *intarray;");
699 outtask.println("void * queue;");
700 outtask.println("int numbertags;");
701 outtask.println("int *tagarray;");
702 outtask.println("};");
704 outtask.println("struct taskdescriptor {");
705 outtask.println("void * taskptr;");
706 outtask.println("int numParameters;");
707 outtask.println(" int numTotal;");
708 outtask.println("struct parameterdescriptor **descriptorarray;");
709 outtask.println("char * name;");
710 outtask.println("};");
711 outtask.println("extern struct taskdescriptor * taskarray[];");
712 outtask.println("extern numtasks;");
713 outtask.println("#endif");
717 private void buildRepairStructs(PrintWriter outrepairstructs) {
718 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
719 while(classit.hasNext()) {
720 ClassDescriptor cn=(ClassDescriptor)classit.next();
721 outrepairstructs.println("structure "+cn.getSymbol()+" {");
722 outrepairstructs.println(" int __type__;");
724 outrepairstructs.println(" int __flag__;");
725 if(!state.MULTICORE) {
726 outrepairstructs.println(" int __flagptr__;");
729 printRepairStruct(cn, outrepairstructs);
730 outrepairstructs.println("}\n");
733 for(int i=0; i<state.numArrays(); i++) {
734 TypeDescriptor tdarray=arraytable[i];
735 TypeDescriptor tdelement=tdarray.dereference();
736 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
737 outrepairstructs.println(" int __type__;");
738 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
739 outrepairstructs.println(" int length;");
741 // Need to add support to repair tool for this
742 if (tdelement.isClass()||tdelement.isArray())
743 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
745 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
747 outrepairstructs.println("}\n");
751 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
752 ClassDescriptor sp=cn.getSuperDesc();
754 printRepairStruct(sp, output);
756 Vector fields=(Vector)fieldorder.get(cn);
758 for(int i=0; i<fields.size(); i++) {
759 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
760 if (fd.getType().isArray()) {
761 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
762 } else if (fd.getType().isClass())
763 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
764 else if (fd.getType().isFloat())
765 output.println(" int "+fd.getSymbol()+"; /* really float */");
767 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
771 /** This method outputs TaskDescriptor information */
772 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
773 for (int i=0; i<task.numParameters(); i++) {
774 VarDescriptor param_var=task.getParameter(i);
775 TypeDescriptor param_type=task.getParamType(i);
776 FlagExpressionNode param_flag=task.getFlag(param_var);
777 TagExpressionList param_tag=task.getTag(param_var);
780 if (param_flag==null) {
781 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
782 output.println("0x0, 0x0 };");
785 DNFFlag dflag=param_flag.getDNF();
786 dnfterms=dflag.size();
788 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
789 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
790 for(int j=0; j<dflag.size(); j++) {
793 Vector term=dflag.get(j);
796 for(int k=0; k<term.size(); k++) {
797 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
798 FlagDescriptor fd=dfa.getFlag();
799 boolean negated=dfa.getNegated();
800 int flagid=1<<((Integer)flags.get(fd)).intValue();
805 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
807 output.println("};");
810 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
811 //BUG...added next line to fix, test with any task program
813 for(int j=0; j<param_tag.numTags(); j++) {
816 /* for each tag we need */
817 /* which slot it is */
818 /* what type it is */
819 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
820 TempDescriptor tmp=param_tag.getTemp(j);
821 int slot=fm.getTagInt(tmp);
822 output.println(slot+", "+state.getTagId(tvd.getTag()));
824 output.println("};");
826 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
827 output.println("/* type */"+param_type.getClassDesc().getId()+",");
828 output.println("/* number of DNF terms */"+dnfterms+",");
829 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
830 output.println("0,");
831 //BUG, added next line to fix and else statement...test
832 //with any task program
834 output.println("/* number of tags */"+param_tag.numTags()+",");
836 output.println("/* number of tags */ 0,");
837 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
838 output.println("};");
842 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
843 for (int i=0; i<task.numParameters(); i++) {
846 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
848 output.println("};");
850 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
851 output.println("&"+task.getSafeSymbol()+",");
852 output.println("/* number of parameters */" +task.numParameters() + ",");
853 int numtotal=task.numParameters()+fm.numTags();
854 output.println("/* number total parameters */" +numtotal + ",");
855 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
856 output.println("\""+task.getSymbol()+"\"");
857 output.println("};");
861 /** The buildVirtualTables method outputs the virtual dispatch
862 * tables for methods. */
864 protected void buildVirtualTables(PrintWriter outvirtual) {
865 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
866 while(classit.hasNext()) {
867 ClassDescriptor cd=(ClassDescriptor)classit.next();
868 if (virtualcalls.getMethodCount(cd)>maxcount)
869 maxcount=virtualcalls.getMethodCount(cd);
871 MethodDescriptor[][] virtualtable=null;
872 LocalityBinding[][] lbvirtualtable=null;
873 if (state.DSM||state.SINGLETM)
874 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
876 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
878 /* Fill in virtual table */
879 classit=state.getClassSymbolTable().getDescriptorsIterator();
880 while(classit.hasNext()) {
881 ClassDescriptor cd=(ClassDescriptor)classit.next();
882 if (state.DSM||state.SINGLETM)
883 fillinRow(cd, lbvirtualtable, cd.getId());
885 fillinRow(cd, virtualtable, cd.getId());
888 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
889 Iterator arrayit=state.getArrayIterator();
890 while(arrayit.hasNext()) {
891 TypeDescriptor td=(TypeDescriptor)arrayit.next();
892 int id=state.getArrayNumber(td);
893 if (state.DSM||state.SINGLETM)
894 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
896 fillinRow(objectcd, virtualtable, id+state.numClasses());
899 outvirtual.print("void * virtualtable[]={");
900 boolean needcomma=false;
901 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
902 for(int j=0; j<maxcount; j++) {
904 outvirtual.print(", ");
905 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
906 LocalityBinding lb=lbvirtualtable[i][j];
907 MethodDescriptor md=lb.getMethod();
908 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
909 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
910 MethodDescriptor md=virtualtable[i][j];
911 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
913 outvirtual.print("0");
917 outvirtual.println("");
919 outvirtual.println("};");
923 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
924 /* Get inherited methods */
925 if (cd.getSuperDesc()!=null)
926 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
927 /* Override them with our methods */
928 for(Iterator it=cd.getMethods(); it.hasNext();) {
929 MethodDescriptor md=(MethodDescriptor)it.next();
930 if (md.isStatic()||md.getReturnType()==null)
932 int methodnum=virtualcalls.getMethodNumber(md);
933 virtualtable[rownum][methodnum]=md;
937 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
938 /* Get inherited methods */
939 if (cd.getSuperDesc()!=null)
940 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
941 /* Override them with our methods */
942 if (locality.getClassBindings(cd)!=null)
943 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
944 LocalityBinding lb=lbit.next();
945 MethodDescriptor md=lb.getMethod();
946 //Is the method static or a constructor
947 if (md.isStatic()||md.getReturnType()==null)
949 int methodnum=virtualcalls.getLocalityNumber(lb);
950 virtualtable[rownum][methodnum]=lb;
954 /** Generate array that contains the sizes of class objects. The
955 * object allocation functions in the runtime use this
958 private void generateSizeArray(PrintWriter outclassdefs) {
959 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
960 outclassdefs.print("#ifdef TRANSSTATS \n");
961 outclassdefs.print("extern int numTransAbort;\n");
962 outclassdefs.print("extern int numTransCommit;\n");
963 outclassdefs.print("extern int nSoftAbort;\n");
965 outclassdefs.print("extern int nchashSearch;\n");
966 outclassdefs.print("extern int nmhashSearch;\n");
967 outclassdefs.print("extern int nprehashSearch;\n");
968 outclassdefs.print("extern int ndirtyCacheObj;\n");
969 outclassdefs.print("extern int nRemoteSend;\n");
970 outclassdefs.print("extern int sendRemoteReq;\n");
971 outclassdefs.print("extern int getResponse;\n");
972 outclassdefs.print("extern int bytesSent;\n");
973 outclassdefs.print("extern int bytesRecv;\n");
974 outclassdefs.print("extern int totalObjSize;\n");
975 outclassdefs.print("extern void handle();\n");
976 } else if (state.SINGLETM) {
977 outclassdefs.println("extern int nSoftAbortAbort;");
978 outclassdefs.println("extern int nSoftAbortCommit;");
979 outclassdefs.println("#ifdef STMSTATS\n");
980 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
981 outclassdefs.println("#endif\n");
983 outclassdefs.print("#endif\n");
985 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
987 outclassdefs.print("extern __thread int oid;\n");
988 outclassdefs.print("extern int numWorkers;\n");
991 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
992 cdarray=new ClassDescriptor[state.numClasses()];
994 while(it.hasNext()) {
995 ClassDescriptor cd=(ClassDescriptor)it.next();
996 cdarray[cd.getId()]=cd;
999 arraytable=new TypeDescriptor[state.numArrays()];
1001 Iterator arrayit=state.getArrayIterator();
1002 while(arrayit.hasNext()) {
1003 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1004 int id=state.getArrayNumber(td);
1010 /* Print out types */
1011 outclassdefs.println("/* ");
1012 for(int i=0; i<state.numClasses(); i++) {
1013 ClassDescriptor cd=cdarray[i];
1015 outclassdefs.println("NULL " + i);
1017 outclassdefs.println(cd +" "+i);
1021 for(int i=0; i<state.numArrays(); i++) {
1022 TypeDescriptor arraytd=arraytable[i];
1023 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
1026 outclassdefs.println("*/");
1029 outclassdefs.print("int classsize[]={");
1031 boolean needcomma=false;
1032 for(int i=0; i<state.numClasses(); i++) {
1034 outclassdefs.print(", ");
1036 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1038 outclassdefs.print("0");
1044 for(int i=0; i<state.numArrays(); i++) {
1046 outclassdefs.print(", ");
1047 TypeDescriptor tdelement=arraytable[i].dereference();
1048 if (tdelement.isArray()||tdelement.isClass())
1049 outclassdefs.print("sizeof(void *)");
1051 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1055 outclassdefs.println("};");
1057 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1059 outclassdefs.print("int typearray[]={");
1060 for(int i=0; i<state.numClasses(); i++) {
1061 ClassDescriptor cd=cdarray[i];
1062 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1064 outclassdefs.print(", ");
1066 outclassdefs.print("-1");
1068 outclassdefs.print(supercd.getId());
1072 for(int i=0; i<state.numArrays(); i++) {
1073 TypeDescriptor arraytd=arraytable[i];
1074 ClassDescriptor arraycd=arraytd.getClassDesc();
1075 if (arraycd==null) {
1077 outclassdefs.print(", ");
1078 outclassdefs.print(objectclass.getId());
1082 ClassDescriptor cd=arraycd.getSuperDesc();
1085 TypeDescriptor supertd=new TypeDescriptor(cd);
1086 supertd.setArrayCount(arraytd.getArrayCount());
1087 type=state.getArrayNumber(supertd);
1089 type+=state.numClasses();
1092 cd=cd.getSuperDesc();
1095 outclassdefs.print(", ");
1096 outclassdefs.print(type);
1100 outclassdefs.println("};");
1105 outclassdefs.print("int typearray2[]={");
1106 for(int i=0; i<state.numArrays(); i++) {
1107 TypeDescriptor arraytd=arraytable[i];
1108 ClassDescriptor arraycd=arraytd.getClassDesc();
1109 if (arraycd==null) {
1111 outclassdefs.print(", ");
1112 outclassdefs.print("-1");
1116 ClassDescriptor cd=arraycd.getSuperDesc();
1117 int level=arraytd.getArrayCount()-1;
1119 for(; level>0; level--) {
1120 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1121 supertd.setArrayCount(level);
1122 type=state.getArrayNumber(supertd);
1124 type+=state.numClasses();
1129 outclassdefs.print(", ");
1130 outclassdefs.print(type);
1134 outclassdefs.println("};");
1137 /** Constructs params and temp objects for each method or task.
1138 * These objects tell the compiler which temps need to be
1141 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1142 MethodDescriptor md=fm.getMethod();
1143 TaskDescriptor task=fm.getTask();
1144 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1145 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1147 paramstable.put(lb, objectparams);
1148 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1149 } else if (md!=null)
1150 paramstable.put(md, objectparams);
1152 paramstable.put(task, objectparams);
1154 for(int i=0; i<fm.numParameters(); i++) {
1155 TempDescriptor temp=fm.getParameter(i);
1156 TypeDescriptor type=temp.getType();
1157 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1158 objectparams.addPtr(temp);
1160 objectparams.addPrim(temp);
1161 if(lb!=null&&saveset.contains(temp)) {
1162 backuptable.get(lb).put(temp, temp.createNew());
1166 for(int i=0; i<fm.numTags(); i++) {
1167 TempDescriptor temp=fm.getTag(i);
1168 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1169 objectparams.addPtr(temp);
1171 objectparams.addPrim(temp);
1174 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1176 tempstable.put(lb, objecttemps);
1178 tempstable.put(md, objecttemps);
1180 tempstable.put(task, objecttemps);
1182 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1183 FlatNode fn=(FlatNode)nodeit.next();
1184 TempDescriptor[] writes=fn.writesTemps();
1185 for(int i=0; i<writes.length; i++) {
1186 TempDescriptor temp=writes[i];
1187 TypeDescriptor type=temp.getType();
1188 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1189 objecttemps.addPtr(temp);
1191 objecttemps.addPrim(temp);
1192 if(lb!=null&&saveset.contains(temp)&&
1193 !backuptable.get(lb).containsKey(temp))
1194 backuptable.get(lb).put(temp, temp.createNew());
1198 /* Create backup temps */
1200 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1201 TempDescriptor tmp=tmpit.next();
1202 TypeDescriptor type=tmp.getType();
1203 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1204 objecttemps.addPtr(tmp);
1206 objecttemps.addPrim(tmp);
1208 /* Create temp to hold revert table */
1209 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1210 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1211 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1212 objecttemps.addPtr(reverttmp);
1214 objecttemps.addPrim(reverttmp);
1215 reverttable.put(lb, reverttmp);
1220 /** This method outputs the following information about classes
1222 * (1) For classes, what are the locations of pointers.
1223 * (2) For arrays, does the array contain pointers or primitives.
1224 * (3) For classes, does the class contain flags.
1227 private void generateLayoutStructs(PrintWriter output) {
1228 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1229 while(it.hasNext()) {
1230 ClassDescriptor cn=(ClassDescriptor)it.next();
1231 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1232 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1234 while(allit.hasNext()) {
1235 FieldDescriptor fd=(FieldDescriptor)allit.next();
1236 TypeDescriptor type=fd.getType();
1237 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1242 output.print(count);
1243 allit=cn.getFieldTable().getAllDescriptorsIterator();
1244 while(allit.hasNext()) {
1245 FieldDescriptor fd=(FieldDescriptor)allit.next();
1246 TypeDescriptor type=fd.getType();
1247 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1250 output.println(",");
1251 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1254 output.println("};");
1256 output.println("unsigned INTPTR * pointerarray[]={");
1257 boolean needcomma=false;
1258 for(int i=0; i<state.numClasses(); i++) {
1259 ClassDescriptor cn=cdarray[i];
1261 output.println(",");
1264 output.print(cn.getSafeSymbol()+"_pointers");
1266 output.print("NULL");
1270 for(int i=0; i<state.numArrays(); i++) {
1272 output.println(", ");
1273 TypeDescriptor tdelement=arraytable[i].dereference();
1274 if (tdelement.isArray()||tdelement.isClass())
1275 output.print("((unsigned INTPTR *)1)");
1281 output.println("};");
1283 output.println("int hasflags[]={");
1284 for(int i=0; i<state.numClasses(); i++) {
1285 ClassDescriptor cn=cdarray[i];
1287 output.println(", ");
1289 if ((cn != null) && (cn.hasFlags()))
1294 output.println("};");
1297 /** Print out table to give us supertypes */
1298 private void generateSuperTypeTable(PrintWriter output) {
1299 output.println("int supertypes[]={");
1300 boolean needcomma=false;
1301 for(int i=0; i<state.numClasses(); i++) {
1302 ClassDescriptor cn=cdarray[i];
1304 output.println(",");
1306 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1307 ClassDescriptor cdsuper=cn.getSuperDesc();
1308 output.print(cdsuper.getId());
1312 output.println("};");
1315 /** Force consistent field ordering between inherited classes. */
1317 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1319 ClassDescriptor sp=cn.getSuperDesc();
1321 printClassStruct(sp, classdefout);
1323 if (!fieldorder.containsKey(cn)) {
1324 Vector fields=new Vector();
1325 fieldorder.put(cn,fields);
1326 Vector fieldvec=cn.getFieldVec();
1327 for(int i=0;i<fieldvec.size();i++) {
1328 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1329 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1333 Vector fields=(Vector)fieldorder.get(cn);
1335 for(int i=0; i<fields.size(); i++) {
1336 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1337 if (fd.getType().isClass()||fd.getType().isArray())
1338 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1340 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1345 /* Map flags to integers consistently between inherited
1348 protected void mapFlags(ClassDescriptor cn) {
1349 ClassDescriptor sp=cn.getSuperDesc();
1353 if (!flagorder.containsKey(cn)) {
1354 Hashtable flags=new Hashtable();
1355 flagorder.put(cn,flags);
1357 Hashtable superflags=(Hashtable)flagorder.get(sp);
1358 Iterator superflagit=superflags.keySet().iterator();
1359 while(superflagit.hasNext()) {
1360 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1361 Integer number=(Integer)superflags.get(fd);
1362 flags.put(fd, number);
1363 if ((number.intValue()+1)>max)
1364 max=number.intValue()+1;
1368 Iterator flagit=cn.getFlags();
1369 while(flagit.hasNext()) {
1370 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1371 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1372 flags.put(fd, new Integer(max++));
1378 /** This function outputs (1) structures that parameters are
1379 * passed in (when PRECISE GC is enabled) and (2) function
1380 * prototypes for the methods */
1382 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1383 /* Output class structure */
1384 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1385 classdefout.println(" int type;");
1387 classdefout.println(" int oid;");
1389 if (state.EVENTMONITOR) {
1390 classdefout.println(" int objuid;");
1393 classdefout.println(" pthread_t tid;");
1394 classdefout.println(" void * lockentry;");
1395 classdefout.println(" int lockcount;");
1399 classdefout.println(" int flag;");
1400 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1401 classdefout.println(" void * flagptr;");
1402 } else if (state.MULTICORE) {
1403 classdefout.println(" int version;");
1404 classdefout.println(" int * lock;"); // lock entry for this obj
1405 classdefout.println(" int mutex;");
1406 classdefout.println(" int lockcount;");
1407 if(state.MULTICOREGC) {
1408 classdefout.println(" int marked;");
1411 if (state.OPTIONAL) {
1412 classdefout.println(" int numfses;");
1413 classdefout.println(" int * fses;");
1416 printClassStruct(cn, classdefout);
1417 classdefout.println("};\n");
1419 if (state.DSM||state.SINGLETM) {
1420 /* Cycle through LocalityBindings */
1421 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1422 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1424 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1425 LocalityBinding lb=lbit.next();
1426 MethodDescriptor md=lb.getMethod();
1427 if (md.getModifiers().isNative()) {
1428 //make sure we only print a native method once
1429 if (nativemethods.contains(md)) {
1430 FlatMethod fm=state.getMethodFlat(md);
1431 generateTempStructs(fm, lb);
1434 nativemethods.add(md);
1436 generateMethod(cn, md, lb, headersout, output);
1439 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1440 MethodDescriptor md=(MethodDescriptor)methodit.next();
1441 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1442 //Need to build param structure for library code
1443 FlatMethod fm=state.getMethodFlat(md);
1444 generateTempStructs(fm, null);
1445 generateMethodParam(cn, md, null, output);
1450 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1451 MethodDescriptor md=(MethodDescriptor)methodit.next();
1452 generateMethod(cn, md, null, headersout, output);
1456 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1457 /* Output parameter structure */
1458 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1459 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1460 if ((state.DSM||state.SINGLETM)&&lb!=null)
1461 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1463 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1464 output.println(" int size;");
1465 output.println(" void * next;");
1466 for(int i=0; i<objectparams.numPointers(); i++) {
1467 TempDescriptor temp=objectparams.getPointer(i);
1468 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1470 output.println("};\n");
1474 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1475 FlatMethod fm=state.getMethodFlat(md);
1476 generateTempStructs(fm, lb);
1478 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1479 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1481 generateMethodParam(cn, md, lb, output);
1483 /* Output temp structure */
1484 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1485 if (state.DSM||state.SINGLETM)
1486 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1488 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1489 output.println(" int size;");
1490 output.println(" void * next;");
1491 for(int i=0; i<objecttemps.numPointers(); i++) {
1492 TempDescriptor temp=objecttemps.getPointer(i);
1493 if (temp.getType().isNull())
1494 output.println(" void * "+temp.getSafeSymbol()+";");
1496 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1498 output.println("};\n");
1501 /********* Output method declaration ***********/
1502 if (state.DSM||state.SINGLETM) {
1503 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1505 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1507 /* First the return type */
1508 if (md.getReturnType()!=null) {
1509 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1510 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1512 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1514 //catch the constructor case
1515 headersout.print("void ");
1517 /* Next the method name */
1518 if (state.DSM||state.SINGLETM) {
1519 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1521 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1523 boolean printcomma=false;
1524 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1525 if (state.DSM||state.SINGLETM) {
1526 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1528 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1532 /* Output parameter list*/
1533 for(int i=0; i<objectparams.numPrimitives(); i++) {
1534 TempDescriptor temp=objectparams.getPrimitive(i);
1536 headersout.print(", ");
1538 if (temp.getType().isClass()||temp.getType().isArray())
1539 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1541 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1543 headersout.println(");\n");
1547 /** This function outputs (1) structures that parameters are
1548 * passed in (when PRECISE GC is enabled) and (2) function
1549 * prototypes for the tasks */
1551 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1552 /* Cycle through tasks */
1553 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1555 while(taskit.hasNext()) {
1556 /* Classify parameters */
1557 TaskDescriptor task=(TaskDescriptor)taskit.next();
1558 FlatMethod fm=state.getMethodFlat(task);
1559 generateTempStructs(fm, null);
1561 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1562 TempObject objecttemps=(TempObject) tempstable.get(task);
1564 /* Output parameter structure */
1565 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1566 output.println("struct "+task.getSafeSymbol()+"_params {");
1567 output.println(" int size;");
1568 output.println(" void * next;");
1569 for(int i=0; i<objectparams.numPointers(); i++) {
1570 TempDescriptor temp=objectparams.getPointer(i);
1571 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1574 output.println("};\n");
1575 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1576 maxtaskparams=objectparams.numPointers()+fm.numTags();
1580 /* Output temp structure */
1581 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1582 output.println("struct "+task.getSafeSymbol()+"_locals {");
1583 output.println(" int size;");
1584 output.println(" void * next;");
1585 for(int i=0; i<objecttemps.numPointers(); i++) {
1586 TempDescriptor temp=objecttemps.getPointer(i);
1587 if (temp.getType().isNull())
1588 output.println(" void * "+temp.getSafeSymbol()+";");
1589 else if(temp.getType().isTag())
1590 output.println(" struct "+
1591 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1593 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1595 output.println("};\n");
1598 /* Output task declaration */
1599 headersout.print("void " + task.getSafeSymbol()+"(");
1601 boolean printcomma=false;
1602 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1603 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1605 headersout.print("void * parameterarray[]");
1606 headersout.println(");\n");
1610 /***** Generate code for FlatMethod fm. *****/
1612 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1613 static int atomicmethodcount=0;
1616 BranchAnalysis branchanalysis;
1617 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1618 if (State.PRINTFLAT)
1619 System.out.println(fm.printMethod());
1620 MethodDescriptor md=fm.getMethod();
1621 TaskDescriptor task=fm.getTask();
1622 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1623 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1625 HashSet<AtomicRecord> arset=null;
1626 branchanalysis=null;
1628 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1630 if (atomicmethodmap==null)
1631 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1633 //fix these so we get right strings for local variables
1634 localsprefixaddr=localsprefix;
1635 localsprefixderef=localsprefix+"->";
1636 arset=new HashSet<AtomicRecord>();
1638 //build branchanalysis
1639 branchanalysis=new BranchAnalysis(locality, lb, delaycomp.getNotReady(lb), delaycomp.livecode(lb), state);
1641 //Generate commit methods here
1642 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1643 FlatNode fn=fnit.next();
1644 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1645 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
1646 delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
1647 //We have an atomic enter
1648 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1649 Set<FlatNode> exitset=faen.getExits();
1651 String methodname=md.getSymbol()+(atomicmethodcount++);
1652 AtomicRecord ar=new AtomicRecord();
1656 atomicmethodmap.put(faen, ar);
1658 //build data structure declaration
1659 output.println("struct atomicprimitives_"+methodname+" {");
1661 Set<FlatNode> recordset=delaycomp.livecode(lb);
1662 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1663 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1664 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1666 ar.reallivein=new HashSet(liveinto);
1668 ar.liveoutvirtualread=liveoutvirtualread;
1671 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1672 TempDescriptor tmp=it.next();
1673 //remove the pointers
1674 if (tmp.getType().isPtr()) {
1677 //let's print it here
1678 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1681 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1682 TempDescriptor tmp=it.next();
1683 //remove the pointers
1684 if (tmp.getType().isPtr()) {
1686 } else if (!liveinto.contains(tmp)) {
1687 //let's print it here
1688 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1691 output.println("};");
1693 //print out method name
1694 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) {");
1695 //build code for commit method
1697 //first define local primitives
1698 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1699 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1700 TempDescriptor tmp=tmpit.next();
1701 if (!tmp.getType().isPtr()) {
1702 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1703 //read from live into set
1704 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1707 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1711 //turn off write barrier generation
1713 state.SINGLETM=false;
1714 generateCode(faen, fm, lb, exitset, output, false);
1715 state.SINGLETM=true;
1716 //turn on write barrier generation
1718 output.println("}\n\n");
1722 //redefine these back to normal
1724 localsprefixaddr="&"+localsprefix;
1725 localsprefixderef=localsprefix+".";
1727 generateHeader(fm, lb, md!=null ? md : task,output);
1728 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1730 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1731 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1732 AtomicRecord ar=arit.next();
1733 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1737 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1738 if (md!=null&&(state.DSM||state.SINGLETM))
1739 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1740 else if (md!=null&&!(state.DSM||state.SINGLETM))
1741 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1743 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1744 output.print(objecttemp.numPointers()+",");
1745 output.print(paramsprefix);
1746 for(int j=0; j<objecttemp.numPointers(); j++)
1747 output.print(", NULL");
1748 output.println("};");
1751 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1752 TempDescriptor td=objecttemp.getPrimitive(i);
1753 TypeDescriptor type=td.getType();
1755 output.println(" void * "+td.getSafeSymbol()+";");
1756 else if (type.isClass()||type.isArray())
1757 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1759 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1764 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1765 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1766 if( callerSESEplaceholder != mlpa.getMainSESE() ) {
1767 // declare variables for naming static SESE's
1768 output.println(" /* static SESE names */");
1769 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1770 while( pItr.hasNext() ) {
1771 SESEandAgePair pair = pItr.next();
1772 output.println(" void* "+pair+";");
1775 // declare variables for tracking dynamic sources
1776 output.println(" /* dynamic variable sources */");
1777 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1778 while( dynSrcItr.hasNext() ) {
1779 TempDescriptor dynSrcVar = dynSrcItr.next();
1780 output.println(" void* "+dynSrcVar+"_srcSESE;");
1781 output.println(" int "+dynSrcVar+"_srcOffset;");
1786 // set up related allocation sites's waiting queues
1788 ConflictGraph graph = null;
1789 graph = mlpa.getConflictGraphResults().get(fm);
1790 if (graph != null && graph.hasConflictEdge()) {
1791 output.println(" /* set up waiting queues */");
1792 output.println(" int numMemoryQueue=0;");
1793 output.println(" int memoryQueueItemID=0;");
1794 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
1796 System.out.println("#lockSet="+lockSet.hashCode());
1797 System.out.println("lockset="+lockSet);
1798 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1799 SESELock seseLock = (SESELock) iterator.next();
1800 System.out.println("id="+seseLock.getID());
1801 System.out.println("#="+seseLock);
1803 System.out.println("size="+lockSet.size());
1804 if (lockSet.size() > 0) {
1805 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1807 .println(" seseCaller->numMemoryQueue=numMemoryQueue;");
1809 .println(" seseCaller->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1816 /* Check to see if we need to do a GC if this is a
1817 * multi-threaded program...*/
1819 if (((state.MLP||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1820 || this.state.MULTICOREGC) {
1821 //Don't bother if we aren't in recursive methods...The loops case will catch it
1822 if (callgraph.getAllMethods(md).contains(md)) {
1823 if (state.DSM&&lb.isAtomic())
1824 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1825 else if (this.state.MULTICOREGC) {
1826 output.println("if(gcflag) gc("+localsprefixaddr+");");
1828 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1833 generateCode(fm.getNext(0), fm, lb, null, output, true);
1835 output.println("}\n\n");
1839 protected void initializeSESE( FlatSESEEnterNode fsen ) {
1841 FlatMethod fm = fsen.getfmEnclosing();
1842 MethodDescriptor md = fm.getMethod();
1843 ClassDescriptor cn = md.getClassDesc();
1846 // Creates bogus method descriptor to index into tables
1847 Modifiers modBogus = new Modifiers();
1848 MethodDescriptor mdBogus =
1849 new MethodDescriptor( modBogus,
1850 new TypeDescriptor( TypeDescriptor.VOID ),
1851 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1854 mdBogus.setClassDesc( fsen.getcdEnclosing() );
1855 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1856 fsen.setfmBogus( fmBogus );
1857 fsen.setmdBogus( mdBogus );
1859 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1860 inSetAndOutSet.addAll( fsen.getInVarSet() );
1861 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1863 // Build paramsobj for bogus method descriptor
1864 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
1865 paramstable.put( mdBogus, objectparams );
1867 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1868 while( itr.hasNext() ) {
1869 TempDescriptor temp = itr.next();
1870 TypeDescriptor type = temp.getType();
1871 if( type.isPtr() ) {
1872 objectparams.addPtr( temp );
1874 objectparams.addPrim( temp );
1878 // Build normal temp object for bogus method descriptor
1879 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
1880 tempstable.put( mdBogus, objecttemps );
1882 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
1883 FlatNode fn = (FlatNode)nodeit.next();
1884 TempDescriptor[] writes = fn.writesTemps();
1886 for( int i = 0; i < writes.length; i++ ) {
1887 TempDescriptor temp = writes[i];
1888 TypeDescriptor type = temp.getType();
1890 if( type.isPtr() ) {
1891 objecttemps.addPtr( temp );
1893 objecttemps.addPrim( temp );
1899 protected void generateMethodSESE(FlatSESEEnterNode fsen,
1901 PrintWriter outputStructs,
1902 PrintWriter outputMethHead,
1903 PrintWriter outputMethods
1906 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
1907 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
1909 // generate locals structure
1910 outputStructs.println("struct "+
1911 fsen.getcdEnclosing().getSafeSymbol()+
1912 fsen.getmdBogus().getSafeSymbol()+"_"+
1913 fsen.getmdBogus().getSafeMethodDescriptor()+
1915 outputStructs.println(" int size;");
1916 outputStructs.println(" void * next;");
1917 for(int i=0; i<objecttemps.numPointers(); i++) {
1918 TempDescriptor temp=objecttemps.getPointer(i);
1920 if (temp.getType().isNull())
1921 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1923 outputStructs.println(" struct "+
1924 temp.getType().getSafeSymbol()+" * "+
1925 temp.getSafeSymbol()+";");
1927 outputStructs.println("};\n");
1930 // generate the SESE record structure
1931 outputStructs.println(fsen.getSESErecordName()+" {");
1933 // data common to any SESE, and it must be placed first so
1934 // a module that doesn't know what kind of SESE record this
1935 // is can cast the pointer to a common struct
1936 outputStructs.println(" SESEcommon common;");
1938 // then garbage list stuff
1939 outputStructs.println(" int size;");
1940 outputStructs.println(" void * next;");
1942 // DYNAMIC stuff was here
1944 // invar source taking was here
1946 // space for all in and out set primitives
1947 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1948 inSetAndOutSet.addAll( fsen.getInVarSet() );
1949 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1951 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
1953 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1954 while( itr.hasNext() ) {
1955 TempDescriptor temp = itr.next();
1956 TypeDescriptor type = temp.getType();
1957 if( !type.isPtr() ) {
1958 inSetAndOutSetPrims.add( temp );
1962 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
1963 while( itrPrims.hasNext() ) {
1964 TempDescriptor temp = itrPrims.next();
1965 TypeDescriptor type = temp.getType();
1966 if(!type.isPrimitive()){
1967 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
1971 for(int i=0; i<objectparams.numPointers(); i++) {
1972 TempDescriptor temp=objectparams.getPointer(i);
1973 if (temp.getType().isNull())
1974 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1976 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1979 // DYNAMIC stuff needs a source SESE ptr and offset
1980 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
1981 while( itrDynInVars.hasNext() ) {
1982 TempDescriptor dynInVar = itrDynInVars.next();
1983 // outputStructs.println(" void* "+dynInVar+"_srcSESE;");
1984 outputStructs.println(" int "+dynInVar+"_srcOffset;");
1987 itrPrims = inSetAndOutSetPrims.iterator();
1988 while( itrPrims.hasNext() ) {
1989 TempDescriptor temp = itrPrims.next();
1990 TypeDescriptor type = temp.getType();
1991 if(type.isPrimitive()){
1992 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
1996 outputStructs.println(" int prevSESECount;");
1998 // DYNAMIC stuff needs a source SESE ptr and offset
1999 itrDynInVars = fsen.getDynamicInVarSet().iterator();
2000 while( itrDynInVars.hasNext() ) {
2001 TempDescriptor dynInVar = itrDynInVars.next();
2002 outputStructs.println(" void* "+dynInVar+"_srcSESE;");
2003 // outputStructs.println(" int "+dynInVar+"_srcOffset;");
2006 // in-set source tracking
2007 // in-vars that are READY come from parent, don't need anything
2008 // stuff STATIC needs a custom SESE pointer for each age pair
2009 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
2010 while( itrStaticInVarSrcs.hasNext() ) {
2011 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
2012 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
2015 outputStructs.println("};\n");
2018 // write method declaration to header file
2019 outputMethHead.print("void ");
2020 outputMethHead.print(fsen.getSESEmethodName()+"(");
2021 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
2022 outputMethHead.println(");\n");
2025 generateFlatMethodSESE( fsen.getfmBogus(),
2026 fsen.getcdEnclosing(),
2032 private void generateFlatMethodSESE(FlatMethod fm,
2034 FlatSESEEnterNode fsen,
2035 FlatSESEExitNode seseExit,
2039 MethodDescriptor md=fm.getMethod();
2041 output.print("void ");
2042 output.print(fsen.getSESEmethodName()+"(");
2043 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
2044 output.println("){\n");
2046 TempObject objecttemp=(TempObject) tempstable.get(md);
2048 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2049 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2050 output.print(objecttemp.numPointers()+",");
2051 output.print("&(((SESEcommon*)(___params___))[1])");
2052 for(int j=0; j<objecttemp.numPointers(); j++)
2053 output.print(", NULL");
2054 output.println("};");
2057 output.println(" /* regular local primitives */");
2058 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2059 TempDescriptor td=objecttemp.getPrimitive(i);
2060 TypeDescriptor type=td.getType();
2062 output.println(" void * "+td.getSafeSymbol()+";");
2063 else if (type.isClass()||type.isArray())
2064 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2066 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2070 // declare variables for naming static SESE's
2071 output.println(" /* static SESE names */");
2072 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
2073 while( pItr.hasNext() ) {
2074 SESEandAgePair pair = pItr.next();
2075 output.println(" void* "+pair+";");
2078 // declare variables for tracking dynamic sources
2079 output.println(" /* dynamic variable sources */");
2080 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
2081 while( dynSrcItr.hasNext() ) {
2082 TempDescriptor dynSrcVar = dynSrcItr.next();
2083 output.println(" void* "+dynSrcVar+"_srcSESE;");
2084 output.println(" int "+dynSrcVar+"_srcOffset;");
2087 // declare local temps for in-set primitives, and if it is
2088 // a ready-source variable, get the value from the record
2089 output.println(" /* local temps for in-set primitives */");
2090 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2091 while( itrInSet.hasNext() ) {
2092 TempDescriptor temp = itrInSet.next();
2093 TypeDescriptor type = temp.getType();
2094 if( !type.isPtr() ) {
2095 if( fsen.getReadyInVarSet().contains( temp ) ) {
2096 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2098 output.println(" "+type+" "+temp+";");
2103 // declare local temps for out-set primitives if its not already
2104 // in the in-set, and it's value will get written so no problem
2105 output.println(" /* local temp for out-set prim, not already in the in-set */");
2106 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2107 while( itrOutSet.hasNext() ) {
2108 TempDescriptor temp = itrOutSet.next();
2109 TypeDescriptor type = temp.getType();
2110 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2111 output.println(" "+type+" "+temp+";");
2115 // setup memory queue
2117 output.println(" // set up memory queues ");
2118 output.println(" int numMemoryQueue=0;");
2119 output.println(" int memoryQueueItemID=0;");
2120 ConflictGraph graph = null;
2121 graph = mlpa.getConflictGraphResults().get(fsen);
2122 if (graph != null && graph.hasConflictEdge()) {
2123 output.println(" {");
2125 .println(" SESEcommon* parentCommon = &(___params___->common);");
2126 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
2128 System.out.println("#lockSet="+lockSet);
2130 if (lockSet.size() > 0) {
2131 output.println(" numMemoryQueue=" + lockSet.size() + ";");
2133 .println(" parentCommon->numMemoryQueue=numMemoryQueue;");
2135 .println(" parentCommon->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2138 output.println(" }");
2142 // copy in-set into place, ready vars were already
2143 // copied when the SESE was issued
2144 Iterator<TempDescriptor> tempItr;
2146 // static vars are from a known SESE
2147 tempItr = fsen.getStaticInVarSet().iterator();
2148 while( tempItr.hasNext() ) {
2149 TempDescriptor temp = tempItr.next();
2150 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2151 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2153 // can't grab something from this source until it is done
2154 output.println(" {");
2156 If we are running, everything is done. This check is redundant.
2158 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+srcPair+";" );
2159 output.println(" pthread_mutex_lock( &(com->lock) );");
2160 output.println(" while( com->doneExecuting == FALSE ) {");
2161 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2162 output.println(" }");
2163 output.println(" pthread_mutex_unlock( &(com->lock) );");
2165 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2166 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2168 output.println(" }");
2171 // dynamic vars come from an SESE and src
2172 tempItr = fsen.getDynamicInVarSet().iterator();
2173 while( tempItr.hasNext() ) {
2174 TempDescriptor temp = tempItr.next();
2175 TypeDescriptor type = temp.getType();
2177 // go grab it from the SESE source
2178 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2180 // gotta wait until the source is done
2181 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+temp+"_srcSESE;" );
2183 If we are running, everything is done!
2184 output.println(" pthread_mutex_lock( &(com->lock) );");
2185 output.println(" while( com->doneExecuting == FALSE ) {");
2186 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2187 output.println(" }");
2188 output.println(" pthread_mutex_unlock( &(com->lock) );");
2192 if( type.isNull() ) {
2194 } else if( type.isClass() || type.isArray() ) {
2195 typeStr = "struct "+type.getSafeSymbol()+"*";
2197 typeStr = type.getSafeSymbol();
2200 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2201 " = *(("+typeStr+"*) ("+
2202 paramsprefix+"->"+temp+"_srcSESE + "+
2203 paramsprefix+"->"+temp+"_srcOffset));");
2205 // or if the source was our parent, its in the record to grab
2206 output.println(" } else {");
2207 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2208 " = "+paramsprefix+"->"+temp+";");
2209 output.println(" }");
2212 // Check to see if we need to do a GC if this is a
2213 // multi-threaded program...
2214 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2215 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2216 //Don't bother if we aren't in recursive methods...The loops case will catch it
2217 // if (callgraph.getAllMethods(md).contains(md)) {
2218 // if(this.state.MULTICOREGC) {
2219 // output.println("if(gcflag) gc("+localsprefixaddr+");");
2221 // output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2226 // initialize thread-local var to a non-zero, invalid address
2227 output.println(" seseCaller = (SESEcommon*) 0x2;");
2228 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2229 exitset.add(seseExit);
2230 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2231 output.println("}\n\n");
2236 // when a new mlp thread is created for an issued SESE, it is started
2237 // by running this method which blocks on a cond variable until
2238 // it is allowed to transition to execute. Then a case statement
2239 // allows it to invoke the method with the proper SESE body, and after
2240 // exiting the SESE method, executes proper SESE exit code before the
2241 // thread can be destroyed
2242 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2243 PrintWriter outmethod
2246 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2247 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2248 outmethod.println( " int status;");
2249 outmethod.println( " char errmsg[128];");
2251 // generate a case for each SESE class that can be invoked
2252 outmethod.println( " switch( *((int*)seseRecord) ) {");
2253 outmethod.println( " ");
2254 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
2255 FlatSESEEnterNode fsen = seseit.next();
2257 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2258 outmethod.println( " case "+fsen.getIdentifier()+":");
2259 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2261 if( fsen.equals( mlpa.getMainSESE() ) ) {
2262 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2263 outmethod.println( " exit( 0 );");
2266 outmethod.println( " break;");
2267 outmethod.println( "");
2270 // default case should never be taken, error out
2271 outmethod.println( " default:");
2272 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2273 outmethod.println( " exit(-30);");
2274 outmethod.println( " break;");
2275 outmethod.println( " }");
2276 outmethod.println( " return NULL;");
2277 outmethod.println( "}\n\n");
2281 protected void generateCode(FlatNode first,
2284 Set<FlatNode> stopset,
2285 PrintWriter output, boolean firstpass) {
2287 /* Assign labels to FlatNode's if necessary.*/
2289 Hashtable<FlatNode, Integer> nodetolabel;
2291 if (state.DELAYCOMP&&!firstpass)
2292 nodetolabel=dcassignLabels(first, stopset);
2294 nodetolabel=assignLabels(first, stopset);
2296 Set<FlatNode> storeset=null;
2297 HashSet<FlatNode> genset=null;
2298 HashSet<FlatNode> refset=null;
2299 Set<FlatNode> unionset=null;
2301 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2302 storeset=delaycomp.livecode(lb);
2303 genset=new HashSet<FlatNode>();
2304 if (state.STMARRAY&&!state.DUALVIEW) {
2305 refset=new HashSet<FlatNode>();
2306 refset.addAll(delaycomp.getDeref(lb));
2307 refset.removeAll(delaycomp.getCannotDelay(lb));
2308 refset.removeAll(delaycomp.getOther(lb));
2311 genset.addAll(delaycomp.getCannotDelay(lb));
2312 genset.addAll(delaycomp.getOther(lb));
2314 genset.addAll(delaycomp.getNotReady(lb));
2315 if (state.STMARRAY&&!state.DUALVIEW) {
2316 genset.removeAll(refset);
2319 unionset=new HashSet<FlatNode>();
2320 unionset.addAll(storeset);
2321 unionset.addAll(genset);
2322 if (state.STMARRAY&&!state.DUALVIEW)
2323 unionset.addAll(refset);
2326 /* Do the actual code generation */
2327 FlatNode current_node=null;
2328 HashSet tovisit=new HashSet();
2329 HashSet visited=new HashSet();
2331 tovisit.add(first.getNext(0));
2334 while(current_node!=null||!tovisit.isEmpty()) {
2335 if (current_node==null) {
2336 current_node=(FlatNode)tovisit.iterator().next();
2337 tovisit.remove(current_node);
2338 } else if (tovisit.contains(current_node)) {
2339 tovisit.remove(current_node);
2341 visited.add(current_node);
2342 if (nodetolabel.containsKey(current_node)) {
2343 output.println("L"+nodetolabel.get(current_node)+":");
2345 if (state.INSTRUCTIONFAILURE) {
2346 if (state.THREAD||state.DSM||state.SINGLETM) {
2347 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2349 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2351 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2353 if (!state.DELAYCOMP||firstpass) {
2354 generateFlatNode(fm, lb, current_node, output);
2356 //store primitive variables in out set
2357 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2358 Set<TempDescriptor> liveout=ar.liveout;
2359 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2360 TempDescriptor tmp=tmpit.next();
2361 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2364 if (state.MLP && stopset!=null) {
2365 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2366 assert current_node instanceof FlatSESEExitNode;
2367 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2368 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2369 assert fsen.getFlatExit().equals( fsxn );
2370 assert fsxn.getFlatEnter().equals( fsen );
2372 if (current_node.kind()!=FKind.FlatReturnNode) {
2373 output.println(" return;");
2376 } else if(current_node.numNext()==1) {
2379 current_node.kind()==FKind.FlatSESEEnterNode &&
2380 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2382 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2383 generateFlatNode(fm, lb, current_node, output);
2384 nextnode=fsen.getFlatExit().getNext(0);
2385 } else if (state.DELAYCOMP) {
2386 boolean specialprimitive=false;
2387 //skip literals...no need to add extra overhead
2388 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2389 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2390 if (!typedesc.isClass()&&!typedesc.isArray()) {
2391 specialprimitive=true;
2395 if (genset==null||genset.contains(current_node)||specialprimitive)
2396 generateFlatNode(fm, lb, current_node, output);
2397 if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2398 //need to acquire lock
2399 handleArrayDeref(fm, lb, current_node, output, firstpass);
2401 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2402 TempDescriptor wrtmp=current_node.writesTemps()[0];
2404 //need to store value written by previous node
2405 if (wrtmp.getType().isPtr()) {
2406 //only lock the objects that may actually need locking
2407 if (recorddc.getNeedTrans(lb, current_node)&&
2408 (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2409 wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2410 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2412 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2415 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2418 //need to read value read by previous node
2419 if (wrtmp.getType().isPtr()) {
2420 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2422 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");
2426 nextnode=current_node.getNext(0);
2429 generateFlatNode(fm, lb, current_node, output);
2430 nextnode=current_node.getNext(0);
2432 if (visited.contains(nextnode)) {
2433 output.println("goto L"+nodetolabel.get(nextnode)+";");
2436 current_node=nextnode;
2437 } else if (current_node.numNext()==2) {
2439 if (state.DELAYCOMP) {
2440 boolean computeside=false;
2442 //need to record which way it should go
2443 if (genset==null||genset.contains(current_node)) {
2444 if (storeset!=null&&storeset.contains(current_node)) {
2445 //need to store which way branch goes
2446 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2448 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2450 //which side to execute
2454 if (genset.contains(current_node)) {
2455 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2456 } else if (storeset.contains(current_node)) {
2458 branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2460 //which side to execute
2465 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2467 if (leftset.size()==0)
2469 if (visited.contains(current_node.getNext(branch))) {
2470 //already visited -- build jump
2471 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2474 current_node=current_node.getNext(branch);
2477 if (!visited.contains(current_node.getNext(1)))
2478 tovisit.add(current_node.getNext(1));
2479 if (visited.contains(current_node.getNext(0))) {
2480 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2483 current_node=current_node.getNext(0);
2487 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2488 if (!visited.contains(current_node.getNext(1)))
2489 tovisit.add(current_node.getNext(1));
2490 if (visited.contains(current_node.getNext(0))) {
2491 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2494 current_node=current_node.getNext(0);
2496 } else throw new Error();
2500 protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2501 if (fn.kind()==FKind.FlatSetElementNode) {
2502 FlatSetElementNode fsen=(FlatSetElementNode) fn;
2503 String dst=generateTemp(fm, fsen.getDst(), lb);
2504 String src=generateTemp(fm, fsen.getSrc(), lb);
2505 String index=generateTemp(fm, fsen.getIndex(), lb);
2506 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2508 if (elementtype.isArray()||elementtype.isClass())
2511 type=elementtype.getSafeSymbol()+" ";
2513 output.println("STOREARRAY("+dst+","+index+","+type+")");
2515 output.println("{");
2516 output.println(" struct ArrayObject *array;");
2517 output.println(" int index;");
2518 output.println(" RESTOREARRAY(array,index);");
2519 output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2520 output.println("}");
2522 } else if (fn.kind()==FKind.FlatElementNode) {
2523 FlatElementNode fen=(FlatElementNode) fn;
2524 String src=generateTemp(fm, fen.getSrc(), lb);
2525 String index=generateTemp(fm, fen.getIndex(), lb);
2526 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2527 String dst=generateTemp(fm, fen.getDst(), lb);
2529 if (elementtype.isArray()||elementtype.isClass())
2532 type=elementtype.getSafeSymbol()+" ";
2534 output.println("STOREARRAY("+src+","+index+","+type+")");
2536 output.println("{");
2537 output.println(" struct ArrayObject *array;");
2538 output.println(" int index;");
2539 output.println(" RESTOREARRAY(array,index);");
2540 output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2541 output.println("}");
2545 /** Special label assignment for delaycomputation */
2546 protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2547 HashSet tovisit=new HashSet();
2548 HashSet visited=new HashSet();
2550 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2552 //Label targets of branches
2553 Set<FlatNode> targets=branchanalysis.getTargets();
2554 for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2555 nodetolabel.put(it.next(), new Integer(labelindex++));
2560 /*Assign labels first. A node needs a label if the previous
2561 * node has two exits or this node is a join point. */
2563 while(!tovisit.isEmpty()) {
2564 FlatNode fn=(FlatNode)tovisit.iterator().next();
2569 if(lastset!=null&&lastset.contains(fn)) {
2570 // if last is not null and matches, don't go
2571 // any further for assigning labels
2575 for(int i=0; i<fn.numNext(); i++) {
2576 FlatNode nn=fn.getNext(i);
2579 //1) Edge >1 of node
2580 nodetolabel.put(nn,new Integer(labelindex++));
2582 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2586 nodetolabel.put(nn,new Integer(labelindex++));
2594 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2595 return assignLabels(first, null);
2598 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2599 HashSet tovisit=new HashSet();
2600 HashSet visited=new HashSet();
2602 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2605 /*Assign labels first. A node needs a label if the previous
2606 * node has two exits or this node is a join point. */
2608 while(!tovisit.isEmpty()) {
2609 FlatNode fn=(FlatNode)tovisit.iterator().next();
2614 if(lastset!=null&&lastset.contains(fn)) {
2615 // if last is not null and matches, don't go
2616 // any further for assigning labels
2620 for(int i=0; i<fn.numNext(); i++) {
2621 FlatNode nn=fn.getNext(i);
2624 //1) Edge >1 of node
2625 nodetolabel.put(nn,new Integer(labelindex++));
2627 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2631 nodetolabel.put(nn,new Integer(labelindex++));
2639 /** Generate text string that corresponds to the TempDescriptor td. */
2640 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2641 MethodDescriptor md=fm.getMethod();
2642 TaskDescriptor task=fm.getTask();
2643 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2645 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2646 return td.getSafeSymbol();
2649 if (objecttemps.isLocalPtr(td)) {
2650 return localsprefixderef+td.getSafeSymbol();
2653 if (objecttemps.isParamPtr(td)) {
2654 return paramsprefix+"->"+td.getSafeSymbol();
2660 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2662 // insert pre-node actions from the code plan
2665 CodePlan cp = mlpa.getCodePlan( fn );
2668 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2670 // for each sese and age pair that this parent statement
2671 // must stall on, take that child's stall semaphore, the
2672 // copying of values comes after the statement
2673 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2674 while( vstItr.hasNext() ) {
2675 VariableSourceToken vst = vstItr.next();
2677 SESEandAgePair pair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2679 output.println(" {");
2680 output.println(" SESEcommon* common = (SESEcommon*) "+pair+";");
2682 output.println(" pthread_mutex_lock( &(common->lock) );");
2683 output.println(" while( common->doneExecuting == FALSE ) {");
2684 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2685 output.println(" }");
2686 output.println(" pthread_mutex_unlock( &(common->lock) );");
2688 // copy things we might have stalled for
2689 output.println(" "+pair.getSESE().getSESErecordName()+"* child = ("+
2690 pair.getSESE().getSESErecordName()+"*) "+pair+";");
2692 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2693 while( tdItr.hasNext() ) {
2694 TempDescriptor td = tdItr.next();
2695 FlatMethod fmContext;
2696 if( currentSESE.getIsCallerSESEplaceholder() ) {
2697 fmContext = currentSESE.getfmEnclosing();
2699 fmContext = currentSESE.getfmBogus();
2701 output.println(" "+generateTemp( fmContext, td, null )+
2702 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2705 output.println(" }");
2708 // for each variable with a dynamic source, stall just for that variable
2709 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2710 while( dynItr.hasNext() ) {
2711 TempDescriptor dynVar = dynItr.next();
2713 // only stall if the dynamic source is not yourself, denoted by src==NULL
2714 // otherwise the dynamic write nodes will have the local var up-to-date
2715 output.println(" {");
2716 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2717 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2718 output.println(" psem_take( &(common->stallSem) );");
2720 FlatMethod fmContext;
2721 if( currentSESE.getIsCallerSESEplaceholder() ) {
2722 fmContext = currentSESE.getfmEnclosing();
2724 fmContext = currentSESE.getfmBogus();
2727 TypeDescriptor type=dynVar.getType();
2729 if( type.isNull() ) {
2731 } else if( type.isClass() || type.isArray() ) {
2732 typeStr = "struct "+type.getSafeSymbol()+"*";
2734 typeStr = type.getSafeSymbol();
2737 output.println(" "+generateTemp( fmContext, dynVar, null )+
2738 " = *(("+typeStr+"*) ("+
2739 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2741 output.println(" }");
2742 output.println(" }");
2745 // for each assignment of a variable to rhs that has a dynamic source,
2746 // copy the dynamic sources
2747 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2748 while( dynAssignItr.hasNext() ) {
2749 Map.Entry me = (Map.Entry) dynAssignItr.next();
2750 TempDescriptor lhs = (TempDescriptor) me.getKey();
2751 TempDescriptor rhs = (TempDescriptor) me.getValue();
2752 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
2753 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2756 // for each lhs that is dynamic from a non-dynamic source, set the
2757 // dynamic source vars to the current SESE
2758 dynItr = cp.getDynAssignCurr().iterator();
2759 while( dynItr.hasNext() ) {
2760 TempDescriptor dynVar = dynItr.next();
2761 assert currentSESE.getDynamicVarSet().contains( dynVar );
2762 output.println(" "+dynVar+"_srcSESE = NULL;");
2766 // handling stall site
2767 ParentChildConflictsMap conflictsMap = mlpa.getConflictsResults().get(fn);
2768 if (conflictsMap != null) {
2769 Set<Long> allocSet = conflictsMap.getAllocationSiteIDSetofStallSite();
2770 if (allocSet.size() > 0) {
2771 FlatNode enclosingFlatNode=null;
2772 if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
2773 enclosingFlatNode=currentSESE.getfmEnclosing();
2775 enclosingFlatNode=currentSESE;
2777 ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
2778 HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
2779 Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
2781 if(waitingElementSet.size()>0){
2782 output.println("// stall on parent's stall sites ");
2783 output.println(" {");
2784 output.println(" REntry* rentry;");
2786 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
2787 WaitingElement waitingElement = (WaitingElement) iterator.next();
2789 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
2790 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", seseCaller);");
2792 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller, (void*)&___locals___."+ waitingElement.getDynID() + ");");
2793 // output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller, ___locals___."+ waitingElement.getDynID() + "->oid);");
2795 output.println(" psem_init( &(rentry->parentStallSem) );");
2796 output.println(" rentry->queue=seseCaller->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
2798 .println(" if(ADDRENTRY(seseCaller->memoryQueueArray["+ waitingElement.getQueueID()
2799 + "],rentry)==NOTREADY){");
2800 output.println(" psem_take( &(rentry->parentStallSem) );");
2801 output.println(" } ");
2803 output.println(" }");
2812 case FKind.FlatAtomicEnterNode:
2813 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
2816 case FKind.FlatAtomicExitNode:
2817 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
2820 case FKind.FlatInstanceOfNode:
2821 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
2824 case FKind.FlatSESEEnterNode:
2825 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
2828 case FKind.FlatSESEExitNode:
2829 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
2832 case FKind.FlatWriteDynamicVarNode:
2833 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
2836 case FKind.FlatGlobalConvNode:
2837 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
2840 case FKind.FlatTagDeclaration:
2841 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
2844 case FKind.FlatCall:
2845 generateFlatCall(fm, lb, (FlatCall) fn,output);
2848 case FKind.FlatFieldNode:
2849 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
2852 case FKind.FlatElementNode:
2853 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
2856 case FKind.FlatSetElementNode:
2857 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
2860 case FKind.FlatSetFieldNode:
2861 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
2865 generateFlatNew(fm, lb, (FlatNew) fn,output);
2868 case FKind.FlatOpNode:
2869 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
2872 case FKind.FlatCastNode:
2873 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
2876 case FKind.FlatLiteralNode:
2877 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
2880 case FKind.FlatReturnNode:
2881 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
2885 output.println("/* nop */");
2888 case FKind.FlatExit:
2889 output.println("/* exit */");
2892 case FKind.FlatBackEdge:
2893 if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
2894 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
2896 if(state.DSM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
2897 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
2899 if (((state.MLP||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
2900 || (this.state.MULTICOREGC)) {
2901 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
2902 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
2903 } else if(this.state.MULTICOREGC) {
2904 output.println("if (gcflag) gc("+localsprefixaddr+");");
2906 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2909 output.println("/* nop */");
2912 case FKind.FlatCheckNode:
2913 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
2916 case FKind.FlatFlagActionNode:
2917 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
2920 case FKind.FlatPrefetchNode:
2921 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
2924 case FKind.FlatOffsetNode:
2925 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
2932 // insert post-node actions from the code-plan
2934 CodePlan cp = mlpa.getCodePlan( fn );
2941 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
2942 output.println("/* FlatOffsetNode */");
2943 FieldDescriptor fd=fofn.getField();
2944 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
2945 output.println("/* offset */");
2948 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
2949 if (state.PREFETCH) {
2950 Vector oids = new Vector();
2951 Vector fieldoffset = new Vector();
2952 Vector endoffset = new Vector();
2953 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
2954 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
2955 PrefetchPair pp = (PrefetchPair) it.next();
2956 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
2957 /* Find prefetches that can generate oid */
2958 if(statusbase == LocalityAnalysis.GLOBAL) {
2959 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
2961 } else if (statusbase == LocalityAnalysis.LOCAL) {
2962 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
2969 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
2970 output.println("{");
2971 output.println("/* prefetch */");
2972 output.println("/* prefetchid_" + fpn.siteid + " */");
2973 output.println("void * prefptr;");
2974 output.println("int tmpindex;");
2976 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
2977 /*Create C code for oid array */
2978 output.print(" unsigned int oidarray_[] = {");
2979 boolean needcomma=false;
2980 for (Iterator it = oids.iterator(); it.hasNext();) {
2983 output.print(it.next());
2986 output.println("};");
2988 /*Create C code for endoffset values */
2989 output.print(" unsigned short endoffsetarry_[] = {");
2991 for (Iterator it = endoffset.iterator(); it.hasNext();) {
2994 output.print(it.next());
2997 output.println("};");
2999 /*Create C code for Field Offset Values */
3000 output.print(" short fieldarry_[] = {");
3002 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
3005 output.print(it.next());
3008 output.println("};");
3009 /* make the prefetch call to Runtime */
3010 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
3011 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
3012 output.println(" }");
3013 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
3014 output.println(" } else {");
3015 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
3016 output.println(" }");
3017 output.println("}");
3021 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
3022 short offsetcount = 0;
3026 } else if (localbase) {
3027 for(; breakindex<pp.desc.size(); breakindex++) {
3028 Descriptor desc=pp.getDescAt(breakindex);
3029 if (desc instanceof FieldDescriptor) {
3030 FieldDescriptor fd=(FieldDescriptor)desc;
3031 if (fd.isGlobal()) {
3039 if (breakindex>pp.desc.size()) //all local
3042 TypeDescriptor lasttype=pp.base.getType();
3043 String basestr=generateTemp(fm, pp.base, lb);
3045 boolean maybenull=fm.getMethod().isStatic()||
3046 !pp.base.equals(fm.getParameter(0));
3048 for(int i=0; i<breakindex; i++) {
3049 String indexcheck="";
3051 Descriptor desc=pp.getDescAt(i);
3052 if (desc instanceof FieldDescriptor) {
3053 FieldDescriptor fd=(FieldDescriptor)desc;
3055 if (!teststr.equals(""))
3057 teststr+="((prefptr="+basestr+")!=NULL)";
3058 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3060 basestr=basestr+"->"+fd.getSafeSymbol();
3063 lasttype=fd.getType();
3065 IndexDescriptor id=(IndexDescriptor)desc;
3066 indexcheck="((tmpindex=";
3067 for(int j=0; j<id.tddesc.size(); j++) {
3068 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3070 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3072 if (!teststr.equals(""))
3074 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3075 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3077 lasttype=lasttype.dereference();
3082 if (teststr.equals("")) {
3083 oid="((unsigned int)"+basestr+")";
3085 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3089 for(int i = breakindex; i < pp.desc.size(); i++) {
3090 String newfieldoffset;
3091 Object desc = pp.getDescAt(i);
3092 if(desc instanceof FieldDescriptor) {
3093 FieldDescriptor fd=(FieldDescriptor)desc;
3094 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3095 lasttype=fd.getType();
3097 newfieldoffset = "";
3098 IndexDescriptor id=(IndexDescriptor)desc;
3099 for(int j = 0; j < id.tddesc.size(); j++) {
3100 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3102 newfieldoffset += id.offset.toString();
3103 lasttype=lasttype.dereference();
3105 fieldoffset.add(newfieldoffset);
3108 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3109 base+=pp.desc.size()-breakindex;
3110 endoffset.add(new Short((short)base));
3115 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3116 if (lb!=fgcn.getLocality())
3118 /* Have to generate flat globalconv */
3119 if (fgcn.getMakePtr()) {
3121 //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3122 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3124 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3125 //need to do translation
3126 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3127 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3128 if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3129 output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3131 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3135 /* Need to convert to OID */
3136 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3137 if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3138 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3140 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3146 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3148 if (fion.getType().isArray()) {
3149 type=state.getArrayNumber(fion.getType())+state.numClasses();
3151 type=fion.getType().getClassDesc().getId();
3154 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3155 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3157 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3160 int sandboxcounter=0;
3161 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3162 /* Check to see if we need to generate code for this atomic */
3163 if (locality==null) {
3164 if (GENERATEPRECISEGC) {
3165 output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3166 output.println("stopforgc((struct garbagelist *) &___locals___);");
3167 output.println("pthread_mutex_lock(&atomiclock);");
3168 output.println("restartaftergc();");
3169 output.println("}");
3171 output.println("pthread_mutex_lock(&atomiclock);");
3176 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3180 if (state.SANDBOX) {
3181 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3182 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3185 if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3186 AtomicRecord ar=atomicmethodmap.get(faen);
3188 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3189 TempDescriptor tmp=tmpit.next();
3190 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3193 //copy outs that depend on path
3194 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3195 TempDescriptor tmp=tmpit.next();
3196 if (!ar.livein.contains(tmp))
3197 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3201 /* Backup the temps. */
3202 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3203 TempDescriptor tmp=tmpit.next();
3204 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3207 output.println("goto transstart"+faen.getIdentifier()+";");
3209 /******* Print code to retry aborted transaction *******/
3210 output.println("transretry"+faen.getIdentifier()+":");
3213 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3214 TempDescriptor tmp=tmpit.next();
3215 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3219 /********* Need to revert local object store ********/
3220 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3222 output.println("while ("+revertptr+") {");
3223 output.println("struct ___Object___ * tmpptr;");
3224 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3225 output.println("REVERT_OBJ("+revertptr+");");
3226 output.println(revertptr+"=tmpptr;");
3227 output.println("}");
3229 /******* Tell the runtime to start the transaction *******/
3231 output.println("transstart"+faen.getIdentifier()+":");
3232 if (state.SANDBOX) {
3233 output.println("transaction_check_counter=*counter_reset_pointer;");
3236 output.println("transStart();");
3238 if (state.ABORTREADERS||state.SANDBOX) {
3240 output.println("abortenabled=1;");
3241 output.println("if (_setjmp(aborttrans)) {");
3242 output.println(" goto transretry"+faen.getIdentifier()+"; }");
3246 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3247 /* Check to see if we need to generate code for this atomic */
3248 if (locality==null) {
3249 output.println("pthread_mutex_unlock(&atomiclock);");
3252 if (locality.getAtomic(lb).get(faen).intValue()>0)
3254 //store the revert list before we lose the transaction object
3257 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3258 output.println(revertptr+"=revertlist;");
3259 output.println("if (transCommit()) {");
3260 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3261 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3262 output.println("} else {");
3263 /* Need to commit local object store */
3264 output.println("while ("+revertptr+") {");
3265 output.println("struct ___Object___ * tmpptr;");
3266 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3267 output.println("COMMIT_OBJ("+revertptr+");");
3268 output.println(revertptr+"=tmpptr;");
3269 output.println("}");
3270 output.println("}");
3274 if (!state.DELAYCOMP) {
3276 output.println("if (transCommit()) {");
3277 /* Transaction aborts if it returns true */
3278 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3279 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3280 output.println("}");
3282 if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
3283 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3284 output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3286 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3287 TempDescriptor tmp=tmpit.next();
3288 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3290 } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3291 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3293 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3294 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3295 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3296 output.println("}");
3298 output.println("else {");
3299 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3300 TempDescriptor tmp=tmpit.next();
3301 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3303 output.println("}");
3305 output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3306 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3307 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3308 output.println("}");
3313 public void generateFlatSESEEnterNode( FlatMethod fm,
3315 FlatSESEEnterNode fsen,
3319 // if MLP flag is off, okay that SESE nodes are in IR graph,
3320 // just skip over them and code generates exactly the same
3325 // there may be an SESE in an unreachable method, skip over
3326 if( !mlpa.getAllSESEs().contains( fsen ) ) {
3330 // also, if we have encountered a placeholder, just skip it
3331 if( fsen.getIsCallerSESEplaceholder() ) {
3335 output.println(" {");
3337 // set up the parent
3338 if( fsen == mlpa.getMainSESE() ) {
3339 output.println(" SESEcommon* parentCommon = NULL;");
3341 if( fsen.getParent() == null ) {
3342 System.out.println( "in "+fm+", "+fsen+" has null parent" );
3344 assert fsen.getParent() != null;
3345 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3346 output.println(" SESEcommon* parentCommon = &("+paramsprefix+"->common);");
3348 //output.println(" SESEcommon* parentCommon = (SESEcommon*) peekItem( seseCallStack );");
3349 output.println(" SESEcommon* parentCommon = seseCaller;");
3353 // before doing anything, lock your own record and increment the running children
3354 if( fsen != mlpa.getMainSESE() ) {
3355 output.println(" atomic_inc(&parentCommon->numRunningChildren);");
3358 // just allocate the space for this record
3359 output.println(" "+fsen.getSESErecordName()+"* seseToIssue = ("+
3360 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3361 fsen.getSESErecordName()+" ) );");
3362 //eomgc need to set next, size
3363 // output.println(" struct garbagelist * gl= (struct garbagelist *)&(((SESEcommon*)(seseToIssue))[1]);");
3364 output.println(" struct garbagelist * gl= (struct garbagelist *)&(((SESEcommon*)(seseToIssue))[1]);");
3365 // sizeof(int)*2 + sizeof(void*)*calculateSizeOfSESEParamList(fsen)
3366 //output.println(" // sizeof(int)*2+sizeof(void*)*"+calculateSizeOfSESEParamList(fsen));
3367 //output.println(" // blah="+calculateSizeOfSESEParamSize(fsen));
3368 output.println(" (seseToIssue->common).offsetsize=sizeof(int)+sizeof(void*)+sizeof(void*)*"+calculateSizeOfSESEParamList(fsen)+calculateSizeOfSESEParamSize(fsen)+";");
3369 output.println(" gl->size="+calculateSizeOfSESEParamList(fsen)+";");
3370 // output.println(" gl->next = (struct garbagelist *)&___locals___;");
3371 output.println(" seseToIssue->prevSESECount="+calculatePrevSESECount(fsen)+";");
3372 // output.println(" seseToIssue->prevSESECount=50;");
3373 output.println(" gl->next = NULL;");
3374 // output.println(" seseToIssue->size = "+calculateSizeOfSESEParamList(fsen)+";");
3375 // output.println(" seseToIssue->next = &___locals___;");
3378 // and keep the thread-local sese stack up to date
3379 //output.println(" addNewItem( seseCallStack, (void*) seseToIssue);");
3381 // fill in common data
3382 output.println(" int localCount=0;");
3383 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3384 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
3386 output.println(" seseToIssue->common.forwardList = createQueue();");
3387 output.println(" seseToIssue->common.unresolvedDependencies = 10000;");
3388 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3389 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3390 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3391 output.println(" seseToIssue->common.numRunningChildren = 0;");
3392 output.println(" seseToIssue->common.parent = parentCommon;");
3394 // all READY in-vars should be copied now and be done with it
3395 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3396 while( tempItr.hasNext() ) {
3397 TempDescriptor temp = tempItr.next();
3399 // when we are issuing the main SESE or an SESE with placeholder
3400 // caller SESE as parent, generate temp child child's eclosing method,
3401 // otherwise use the parent's enclosing method as the context
3402 boolean useParentContext = false;
3404 if( fsen != mlpa.getMainSESE() ) {
3405 assert fsen.getParent() != null;
3406 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3407 useParentContext = true;
3411 if( useParentContext ) {
3412 output.println(" seseToIssue->"+temp+" = "+
3413 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3415 output.println(" seseToIssue->"+temp+" = "+
3416 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3420 // before potentially adding this SESE to other forwarding lists,
3421 // create it's lock and take it immediately
3422 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3423 // output.println(" pthread_mutex_lock( &(seseToIssue->common.lock) );");
3425 if( fsen != mlpa.getMainSESE() ) {
3426 // count up outstanding dependencies, static first, then dynamic
3427 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3428 while( staticSrcsItr.hasNext() ) {
3429 SESEandAgePair srcPair = staticSrcsItr.next();
3430 output.println(" {");
3431 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3433 if(GENERATEPRECISEGC){
3434 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3436 output.println(" pthread_mutex_lock( &(src->lock) );");
3437 if(GENERATEPRECISEGC){
3438 output.println(" restartaftergc();");
3440 output.println(" if( !isEmpty( src->forwardList ) &&");
3441 output.println(" seseToIssue == peekItem( src->forwardList ) ) {");
3442 output.println(" printf( \"This shouldnt already be here\\n\");");
3443 output.println(" exit( -1 );");
3444 output.println(" }");
3445 output.println(" if( !src->doneExecuting ) {");
3446 output.println(" addNewItem( src->forwardList, seseToIssue );");
3447 // output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3448 output.println(" ++(localCount);");
3449 output.println(" }");
3450 output.println(" pthread_mutex_unlock( &(src->lock) );");
3451 output.println(" }");
3453 // whether or not it is an outstanding dependency, make sure
3454 // to pass the static name to the child's record
3455 output.println(" seseToIssue->"+srcPair+" = "+srcPair+";");
3458 // dynamic sources might already be accounted for in the static list,
3459 // so only add them to forwarding lists if they're not already there
3460 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3461 while( dynVarsItr.hasNext() ) {
3462 TempDescriptor dynInVar = dynVarsItr.next();
3463 output.println(" {");
3464 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3466 // the dynamic source is NULL if it comes from your own space--you can't pass
3467 // the address off to the new child, because you're not done executing and
3468 // might change the variable, so copy it right now
3469 output.println(" if( src != NULL ) {");
3471 if(GENERATEPRECISEGC){
3472 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3474 output.println(" pthread_mutex_lock( &(src->lock) );");
3475 if(GENERATEPRECISEGC){
3476 output.println(" restartaftergc();");
3478 output.println(" if( isEmpty( src->forwardList ) ||");
3479 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3480 output.println(" if( !src->doneExecuting ) {");
3481 output.println(" addNewItem( src->forwardList, seseToIssue );");
3482 // output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3483 output.println(" ++(localCount);");
3484 output.println(" }");
3485 output.println(" }");
3486 output.println(" pthread_mutex_unlock( &(src->lock) );");
3487 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3488 output.println(" } else {");
3490 boolean useParentContext = false;
3491 if( fsen != mlpa.getMainSESE() ) {
3492 assert fsen.getParent() != null;
3493 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3494 useParentContext = true;
3497 if( useParentContext ) {
3498 output.println(" seseToIssue->"+dynInVar+" = "+
3499 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3501 output.println(" seseToIssue->"+dynInVar+" = "+
3502 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3505 output.println(" }");
3506 output.println(" }");
3508 // even if the value is already copied, make sure your NULL source
3509 // gets passed so child knows it already has the dynamic value
3510 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3513 // maintain pointers for finding dynamic SESE
3514 // instances from static names
3515 SESEandAgePair pair = new SESEandAgePair( fsen, 0 );
3516 if( fsen.getParent() != null &&
3517 //!fsen.getParent().getIsCallerSESEplaceholder() &&
3518 fsen.getParent().getNeededStaticNames().contains( pair )
3521 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3522 SESEandAgePair pair1 = new SESEandAgePair( fsen, i );
3523 SESEandAgePair pair2 = new SESEandAgePair( fsen, i-1 );
3524 output.println(" "+pair1+" = "+pair2+";");
3526 output.println(" "+pair+" = seseToIssue;");
3530 // count up memory conflict dependencies,
3532 ConflictGraph graph = null;
3533 FlatSESEEnterNode parent = fsen.getParent();
3534 if (parent != null) {
3535 if (parent.isCallerSESEplaceholder) {
3536 graph = mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
3538 graph = mlpa.getConflictGraphResults().get(parent);
3541 if (graph != null && graph.hasConflictEdge()) {
3542 HashSet<SESELock> seseLockSet = mlpa.getConflictGraphLockMap()
3545 output.println(" //add memory queue element");
3546 SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(fsen.getIdentifier(),
3548 if(seseWaitingQueue.getWaitingElementSize()>0){
3549 output.println(" {");
3550 output.println(" REntry* rentry=NULL;");
3551 output.println(" INTPTR* pointer=NULL;");
3552 output.println(" seseToIssue->common.rentryIdx=0;");
3554 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
3555 for (Iterator iterator = queueIDSet.iterator(); iterator
3557 Integer key = (Integer) iterator.next();
3558 int queueID=key.intValue();
3559 Set<WaitingElement> waitingQueueSet = seseWaitingQueue.getWaitingElementSet(queueID);
3560 int enqueueType=seseWaitingQueue.getType(queueID);
3561 if(enqueueType==SESEWaitingQueue.EXCEPTION){
3562 output.println(" INITIALIZEBUF(parentCommon->memoryQueueArray["
3565 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2
3567 WaitingElement waitingElement = (WaitingElement) iterator2
3569 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
3570 output.println(" rentry=mlpCreateREntry("
3571 + waitingElement.getStatus()
3572 + ", seseToIssue);");
3574 TempDescriptor td = waitingElement
3576 // decide whether waiting element is dynamic or
3578 if (fsen.getDynamicInVarSet().contains(td)) {
3579 // dynamic in-var case
3580 output.println(" pointer=seseToIssue->"
3581 + waitingElement.getDynID()
3582 + "_srcSESE+seseToIssue->"
3583 + waitingElement.getDynID()
3586 .println(" rentry=mlpCreateFineREntry("
3589 + ", seseToIssue, pointer );");
3590 } else if (fsen.getStaticInVarSet()
3592 // static in-var case
3593 VariableSourceToken vst = fsen
3594 .getStaticInVarSrc(td);
3597 String srcId = "SESE_"
3599 .getPrettyIdentifier()
3600 + vst.getSESE().getIdentifier()
3601 + "_" + vst.getAge();
3603 .println(" pointer=(void*)&seseToIssue->"
3610 .println(" rentry=mlpCreateFineREntry("
3613 + ", seseToIssue, pointer );");
3618 .println(" rentry=mlpCreateFineREntry("
3621 + ", seseToIssue, (void*)&seseToIssue->"
3622 + waitingElement.getDynID()
3627 .println(" rentry->queue=parentCommon->memoryQueueArray["
3628 + waitingElement.getQueueID()
3631 if(enqueueType==SESEWaitingQueue.NORMAL){
3633 .println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
3635 .println(" if(ADDRENTRY(parentCommon->memoryQueueArray["
3636 + waitingElement.getQueueID()
3637 + "],rentry)==NOTREADY){");
3638 output.println(" ++(localCount);");
3639 output.println(" } ");
3642 .println(" ADDRENTRYTOBUF(parentCommon->memoryQueueArray["
3643 + waitingElement.getQueueID()
3647 if(enqueueType!=SESEWaitingQueue.NORMAL){
3648 output.println(" localCount+=RESOLVEBUF(parentCommon->memoryQueueArray["
3649 + queueID+ "],&seseToIssue->common);");
3652 output.println(" }");
3659 // release this SESE for siblings to update its dependencies or,
3660 // eventually, for it to mark itself finished
3661 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3663 // if there were no outstanding dependencies, issue here
3664 output.println(" if( atomic_sub_and_test(10000-localCount,&(seseToIssue->common.unresolvedDependencies) ) ) {");
3665 output.println(" workScheduleSubmit( (void*)seseToIssue );");
3666 output.println(" }");
3668 output.println(" if( seseToIssue->common.unresolvedDependencies == 0 ) {");
3669 output.println(" workScheduleSubmit( (void*)seseToIssue );");
3670 output.println(" }");
3672 // release this SESE for siblings to update its dependencies or,
3673 // eventually, for it to mark itself finished
3674 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3675 output.println(" }");
3679 public void generateFlatSESEExitNode( FlatMethod fm,
3681 FlatSESEExitNode fsexn,
3685 // if MLP flag is off, okay that SESE nodes are in IR graph,
3686 // just skip over them and code generates exactly the same
3691 // get the enter node for this exit that has meta data embedded
3692 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
3694 // there may be an SESE in an unreachable method, skip over
3695 if( !mlpa.getAllSESEs().contains( fsen ) ) {
3699 // also, if we have encountered a placeholder, just jump it
3700 if( fsen.getIsCallerSESEplaceholder() ) {
3704 output.println(" /* SESE exiting */");
3706 String com = paramsprefix+"->common";
3708 // this SESE cannot be done until all of its children are done
3709 // so grab your own lock with the condition variable for watching
3710 // that the number of your running children is greater than zero
3711 if (GENERATEPRECISEGC){
3712 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3714 output.println(" pthread_mutex_lock( &("+com+".lock) );");
3715 if (GENERATEPRECISEGC){
3716 output.println(" restartaftergc();");
3718 output.println(" while( "+com+".numRunningChildren > 0 ) {");
3719 if (GENERATEPRECISEGC){
3720 // output.println(" stopforgc((struct garbagelist *)&(((SESEcommon*)(___params___))[1]));");
3721 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3723 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
3724 if (GENERATEPRECISEGC){
3725 output.println(" restartaftergc();");
3727 output.println(" }");
3730 // copy out-set from local temps into the sese record
3731 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
3732 while( itr.hasNext() ) {
3733 TempDescriptor temp = itr.next();
3735 // only have to do this for primitives non-arrays
3737 temp.getType().isPrimitive() && !temp.getType().isArray()
3743 // have to determine the context enclosing this sese
3744 boolean useParentContext = false;
3746 if( fsen != mlpa.getMainSESE() ) {
3747 assert fsen.getParent() != null;
3748 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3749 useParentContext = true;
3754 if( useParentContext ) {
3755 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
3757 from = generateTemp( fsen.getfmEnclosing(), temp, null );
3760 output.println(" "+paramsprefix+
3761 "->"+temp.getSafeSymbol()+
3765 // mark yourself done, your SESE data is now read-only
3766 output.println(" "+com+".doneExecuting = TRUE;");
3767 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
3768 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
3770 // decrement dependency count for all SESE's on your forwarding list
3771 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
3772 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
3775 output.println(" if(consumer->rentryIdx>0){");
3776 output.println(" // resolved null pointer");
3777 output.println(" int idx;");
3778 output.println(" for(idx=0;idx<consumer->rentryIdx;idx++){");
3779 output.println(" resolvePointer(consumer->rentryArray[idx]);");
3780 output.println(" }");
3781 output.println(" }");
3784 // output.println(" pthread_mutex_lock( &(consumer->lock) );");
3785 // output.println(" --(consumer->unresolvedDependencies);");
3786 // output.println(" if( consumer->unresolvedDependencies == 0 ) {");
3787 output.println(" if( atomic_sub_and_test(1, &(consumer->unresolvedDependencies)) ){");
3788 output.println(" workScheduleSubmit( (void*)consumer );");
3789 output.println(" }");
3790 // output.println(" pthread_mutex_unlock( &(consumer->lock) );");
3791 output.println(" }");
3795 // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
3796 if( fsen != mlpa.getMainSESE() ) {
3799 output.println(" /* check memory dependency*/");
3800 output.println(" {");
3801 output.println(" int idx;");
3802 output.println(" for(idx=0;idx<___params___->common.rentryIdx;idx++){");
3803 output.println(" REntry* re=___params___->common.rentryArray[idx];");
3804 output.println(" RETIRERENTRY(re->queue,re);");
3805 output.println(" }");
3806 output.println(" }");
3810 // if parent is stalling on you, let them know you're done
3811 if( fsexn.getFlatEnter() != mlpa.getMainSESE() ) {
3812 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
3815 // last of all, decrement your parent's number of running children
3816 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
3817 output.println(" if (atomic_sub_and_test(1, &"+paramsprefix+"->common.parent->numRunningChildren)) {");
3818 if (GENERATEPRECISEGC){
3819 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3821 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
3822 if (GENERATEPRECISEGC){
3823 output.println(" restartaftergc();");
3825 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
3826 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
3827 output.println(" }");
3828 output.println(" }");
3830 // this is a thread-only variable that can be handled when critical sese-to-sese
3831 // data has been taken care of--set sese pointer to remember self over method
3832 // calls to a non-zero, invalid address
3833 output.println(" seseCaller = (SESEcommon*) 0x1;");
3837 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
3839 FlatWriteDynamicVarNode fwdvn,
3843 // should node should not be in an IR graph if the
3844 // MLP flag is not set
3845 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
3848 Hashtable<TempDescriptor, VSTWrapper> writeDynamic = fwdvn.getVar2src();
3850 assert writeDynamic != null;
3852 Iterator wdItr = writeDynamic.entrySet().iterator();
3853 while( wdItr.hasNext() ) {
3854 Map.Entry me = (Map.Entry) wdItr.next();
3855 TempDescriptor refVar = (TempDescriptor) me.getKey();
3856 VSTWrapper vstW = (VSTWrapper) me.getValue();
3857 VariableSourceToken vst = vstW.vst;
3860 // only do this if the variable in question should be tracked,
3861 // meaning that it was explicitly added to the dynamic var set
3862 if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
3868 // if there is no given source, this variable is ready so
3869 // mark src pointer NULL to signify that the var is up-to-date
3870 output.println(" "+refVar+"_srcSESE = NULL;");
3874 // otherwise we track where it will come from
3875 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
3876 output.println(" "+refVar+"_srcSESE = "+instance+";");
3877 output.println(" "+refVar+"_srcOffset = (int) &((("+
3878 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
3883 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
3884 if (state.CONSCHECK) {
3885 String specname=fcn.getSpec();
3886 String varname="repairstate___";
3887 output.println("{");
3888 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
3890 TempDescriptor[] temps=fcn.getTemps();
3891 String[] vars=fcn.getVars();
3892 for(int i=0; i<temps.length; i++) {
3893 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
3896 output.println("if (doanalysis"+specname+"("+varname+")) {");
3897 output.println("free"+specname+"_state("+varname+");");
3898 output.println("} else {");
3899 output.println("/* Bad invariant */");
3900 output.println("free"+specname+"_state("+varname+");");
3901 output.println("abort_task();");
3902 output.println("}");
3903 output.println("}");
3907 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
3909 if( state.MLP && !nonSESEpass ) {
3910 output.println(" seseCaller = (SESEcommon*)"+paramsprefix+";");
3913 MethodDescriptor md=fc.getMethod();
3914 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
3915 ClassDescriptor cn=md.getClassDesc();
3916 output.println("{");
3917 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3919 LocalityBinding fclb=locality.getBinding(lb, fc);
3920 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3922 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3923 output.print(objectparams.numPointers());
3924 output.print(", "+localsprefixaddr);
3925 if (md.getThis()!=null) {
3927 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
3929 if (fc.getThis()!=null&&md.getThis()==null) {
3930 System.out.println("WARNING!!!!!!!!!!!!");
3931 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
3935 for(int i=0; i<fc.numArgs(); i++) {
3936 Descriptor var=md.getParameter(i);
3937 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3938 if (objectparams.isParamPtr(paramtemp)) {
3939 TempDescriptor targ=fc.getArg(i);
3941 TypeDescriptor td=md.getParamType(i);
3943 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3945 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3948 output.println("};");
3953 if (fc.getReturnTemp()!=null)
3954 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
3956 /* Do we need to do virtual dispatch? */
3957 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
3960 LocalityBinding fclb=locality.getBinding(lb, fc);
3961 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3963 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3968 if (md.getReturnType().isClass()||md.getReturnType().isArray())
3969 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3971 output.print(md.getReturnType().getSafeSymbol()+" ");
3972 output.print("(*)(");
3974 boolean printcomma=false;
3975 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3977 LocalityBinding fclb=locality.getBinding(lb, fc);
3978 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3980 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3984 for(int i=0; i<objectparams.numPrimitives(); i++) {
3985 TempDescriptor temp=objectparams.getPrimitive(i);
3989 if (temp.getType().isClass()||temp.getType().isArray())
3990 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
3992 output.print(temp.getType().getSafeSymbol());
3997 LocalityBinding fclb=locality.getBinding(lb, fc);
3998 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
4000 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
4004 boolean needcomma=false;
4005 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4006 output.print("&__parameterlist__");
4010 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4011 if (fc.getThis()!=null) {
4012 TypeDescriptor ptd=md.getThis().getType();
4015 if (ptd.isClass()&&!ptd.isArray())
4016 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4017 output.print(generateTemp(fm,fc.getThis(),lb));
4022 for(int i=0; i<fc.numArgs(); i++) {
4023 Descriptor var=md.getParameter(i);
4024 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4025 if (objectparams.isParamPrim(paramtemp)) {
4026 TempDescriptor targ=fc.getArg(i);
4030 TypeDescriptor ptd=md.getParamType(i);
4031 if (ptd.isClass()&&!ptd.isArray())
4032 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4033 output.print(generateTemp(fm, targ,lb));
4037 output.println(");");
4038 output.println(" }");
4041 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
4042 Set subclasses=typeutil.getSubClasses(thiscd);
4043 if (subclasses==null)
4045 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
4046 ClassDescriptor cd=(ClassDescriptor)classit.next();
4047 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
4048 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
4049 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
4050 if (md.matches(matchmd))
4057 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
4058 if (state.SINGLETM) {
4059 //single machine transactional memory case
4060 String field=ffn.getField().getSafeSymbol();
4061 String src=generateTemp(fm, ffn.getSrc(),lb);
4062 String dst=generateTemp(fm, ffn.getDst(),lb);
4064 output.println(dst+"="+ src +"->"+field+ ";");
4065 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
4066 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
4067 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
4068 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
4069 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
4070 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
4071 if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
4072 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4074 output.println("TRANSREADRD("+dst+", "+dst+");");
4077 } else if (state.DSM) {
4078 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
4079 if (status==LocalityAnalysis.GLOBAL) {
4080 String field=ffn.getField().getSafeSymbol();
4081 String src=generateTemp(fm, ffn.getSrc(),lb);
4082 String dst=generateTemp(fm, ffn.getDst(),lb);
4084 if (ffn.getField().getType().isPtr()) {
4086 //TODO: Uncomment this when we have runtime support
4087 //if (ffn.getSrc()==ffn.getDst()) {
4088 //output.println("{");
4089 //output.println("void * temp="+src+";");
4090 //output.println("if (temp&0x1) {");
4091 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
4092 //output.println(src+"->"+field+"="+temp+";");
4093 //output.println("}");
4094 //output.println(dst+"=temp;");
4095 //output.println("}");
4097 output.println(dst+"="+ src +"->"+field+ ";");
4098 //output.println("if ("+dst+"&0x1) {");
4099 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4100 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4101 //output.println(src+"->"+field+"="+src+"->"+field+";");
4102 //output.println("}");
4105 output.println(dst+"="+ src+"->"+field+";");
4107 } else if (status==LocalityAnalysis.LOCAL) {
4108 if (ffn.getField().getType().isPtr()&&
4109 ffn.getField().isGlobal()) {
4110 String field=ffn.getField().getSafeSymbol();
4111 String src=generateTemp(fm, ffn.getSrc(),lb);
4112 String dst=generateTemp(fm, ffn.getDst(),lb);
4113 output.println(dst+"="+ src +"->"+field+ ";");
4114 if (locality.getAtomic(lb).get(ffn).intValue()>0)
4115 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4116 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4118 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4119 } else if (status==LocalityAnalysis.EITHER) {
4120 //Code is reading from a null pointer
4121 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
4122 output.println("#ifndef RAW");
4123 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4124 output.println("#endif");
4125 //This should throw a suitable null pointer error
4126 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4128 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4130 // DEBUG if(!ffn.getDst().getType().isPrimitive()){
4131 // DEBUG output.println("within((void*)"+generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+");");
4133 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4138 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
4139 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
4140 throw new Error("Can't set array length");
4141 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4142 //Single Machine Transaction Case
4143 boolean srcptr=fsfn.getSrc().getType().isPtr();
4144 String src=generateTemp(fm,fsfn.getSrc(),lb);
4145 String dst=generateTemp(fm,fsfn.getDst(),lb);
4146 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
4147 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
4148 output.println("{");
4149 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
4150 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
4151 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4153 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4156 if (wb.needBarrier(fsfn)&&
4157 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
4158 if (state.EVENTMONITOR) {
4159 output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
4161 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
4163 if (srcptr&!fsfn.getSrc().getType().isNull()) {
4164 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4165 output.println("}");
4167 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4169 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4170 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
4171 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
4172 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4174 String src=generateTemp(fm,fsfn.getSrc(),lb);
4175 String dst=generateTemp(fm,fsfn.getDst(),lb);
4177 output.println("{");
4178 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4180 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
4183 if (wb.needBarrier(fsfn))
4184 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
4186 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4188 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4189 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
4190 /** Check if we need to copy */
4191 output.println("if(!"+dst+"->"+localcopystr+") {");
4192 /* Link object into list */
4193 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4194 output.println(revertptr+"=revertlist;");
4195 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4196 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4198 output.println("COPY_OBJ("+dst+");");
4199 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4200 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4201 output.println("}");
4203 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4205 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4206 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
4207 //writing to a null...bad
4208 output.println("if ("+dst+") {");
4209 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
4211 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4213 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4216 output.println("}");
4219 if (state.FASTCHECK) {
4220 String dst=generateTemp(fm, fsfn.getDst(),lb);
4221 output.println("if(!"+dst+"->"+localcopystr+") {");
4222 /* Link object into list */
4223 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4224 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4226 output.println("COPY_OBJ("+dst+");");
4227 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4228 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4229 output.println("}");
4232 // DEBUG if(!fsfn.getField().getType().isPrimitive()){
4233 // DEBUG output.println("within((void*)"+generateTemp(fm,fsfn.getSrc(),lb)+");");
4235 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4239 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
4240 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
4243 if (elementtype.isArray()||elementtype.isClass())
4246 type=elementtype.getSafeSymbol()+" ";
4248 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
4249 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
4250 output.println("failedboundschk();");
4252 if (state.SINGLETM) {
4253 //Single machine transaction case
4254 String dst=generateTemp(fm, fen.getDst(),lb);
4255 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))) {
4256 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4258 output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
4261 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
4262 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
4263 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
4264 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
4265 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
4266 if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
4267 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4269 output.println("TRANSREADRD("+dst+", "+dst+");");
4272 } else if (state.DSM) {
4273 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
4274 if (status==LocalityAnalysis.GLOBAL) {
4275 String dst=generateTemp(fm, fen.getDst(),lb);
4276 if (elementtype.isPtr()) {
4277 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4278 //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
4279 output.println("TRANSREAD("+dst+", "+dst+");");
4281 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4283 } else if (status==LocalityAnalysis.LOCAL) {
4284 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4285 } else if (status==LocalityAnalysis.EITHER) {
4286 //Code is reading from a null pointer
4287 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
4288 output.println("#ifndef RAW");
4289 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4290 output.println("#endif");
4291 //This should throw a suitable null pointer error
4292 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4294 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4296 // DEBUG output.println("within((void*)"+generateTemp(fm,fen.getSrc(),lb)+");");
4297 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4301 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
4302 //TODO: need dynamic check to make sure this assignment is actually legal
4303 //Because Object[] could actually be something more specific...ie. Integer[]
4305 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
4308 if (elementtype.isArray()||elementtype.isClass())
4311 type=elementtype.getSafeSymbol()+" ";
4313 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
4314 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
4315 output.println("failedboundschk();");
4318 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4319 //Transaction set element case
4320 if (wb.needBarrier(fsen)&&
4321 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
4322 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
4324 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
4325 output.println("{");
4326 String src=generateTemp(fm, fsen.getSrc(), lb);
4327 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
4328 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
4329 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4331 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4333 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4334 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
4336 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4338 output.println("}");
4340 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4341 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
4343 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4346 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4347 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
4348 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
4349 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4350 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
4351 boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
4354 if (wb.needBarrier(fsen))
4355 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
4356 } else if (dstlocal) {
4357 /** Check if we need to copy */
4358 String dst=generateTemp(fm, fsen.getDst(),lb);
4359 output.println("if(!"+dst+"->"+localcopystr+") {");
4360 /* Link object into list */
4361 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4362 output.println(revertptr+"=revertlist;");
4363 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
4364 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4366 output.println("COPY_OBJ("+dst+");");
4367 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4368 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4369 output.println("}");
4371 System.out.println("Node: "+fsen);
4372 System.out.println(lb);
4373 System.out.println("statusdst="+statusdst);
4374 System.out.println(fm.printMethod());
4375 throw new Error("Unknown array type");
4378 output.println("{");
4379 String src=generateTemp(fm, fsen.getSrc(), lb);
4380 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4381 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4382 output.println("}");
4384 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4387 if (state.FASTCHECK) {
4388 String dst=generateTemp(fm, fsen.getDst(),lb);
4389 output.println("if(!"+dst+"->"+localcopystr+") {");
4390 /* Link object into list */
4391 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4392 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4394 output.println("COPY_OBJ("+dst+");");
4395 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4396 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4397 output.println("}");
4399 // DEBUG output.println("within((void*)"+generateTemp(fm,fsen.getDst(),lb)+");");
4400 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4404 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
4405 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4406 //Stash pointer in case of GC
4407 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4408 output.println(revertptr+"=revertlist;");
4410 if (state.SINGLETM) {
4411 if (fn.getType().isArray()) {
4412 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4413 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4414 //inside transaction
4415 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4417 //outside transaction
4418 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4421 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4422 //inside transaction
4423 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4425 //outside transaction
4426 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4429 } else if (fn.getType().isArray()) {
4430 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4431 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4432 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4433 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4435 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray_oid("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+", oid);");
4436 output.println(" oid += numWorkers;");
4438 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4441 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4444 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4445 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
4446 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4447 if (this.state.MLP){
4448 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new_oid("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+", oid);");
4449 output.println(" oid += numWorkers;");
4451 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4454 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
4457 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4458 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4459 String dst=generateTemp(fm,fn.getDst(),lb);
4460 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4461 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4462 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4464 if (state.FASTCHECK) {
4465 String dst=generateTemp(fm,fn.getDst(),lb);
4466 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4467 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4468 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4472 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
4473 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4474 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
4476 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
4480 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
4481 if (fon.getRight()!=null) {
4482 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
4483 if (fon.getLeft().getType().isLong())
4484 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4486 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4488 } else if (dc!=null) {
4489 output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
4490 if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4491 output.print("(void *)");
4492 if (dc.getNeedLeftSrcTrans(lb, fon))
4493 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
4495 output.print(generateTemp(fm, fon.getLeft(),lb));
4496 output.print(")"+fon.getOp().toString()+"(");
4497 if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4498 output.print("(void *)");
4499 if (dc.getNeedRightSrcTrans(lb, fon))
4500 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
4502 output.println(generateTemp(fm,fon.getRight(),lb)+");");
4504 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
4505 } else if (fon.getOp().getOp()==Operation.ASSIGN)
4506 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4507 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
4508 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4509 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
4510 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
4511 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
4512 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
4513 else if (fon.getOp().getOp()==Operation.COMP)
4514 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
4515 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
4516 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
4518 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
4521 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
4522 /* TODO: Do type check here */
4523 if (fcn.getType().isArray()) {
4524 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4525 } else if (fcn.getType().isClass())
4526 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4528 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
4531 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
4532 if (fln.getValue()==null)
4533 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4534 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
4535 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4536 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4537 //Stash pointer in case of GC
4538 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4539 output.println(revertptr+"=revertlist;");
4541 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4542 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4543 //Stash pointer in case of GC
4544 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4545 output.println("revertlist="+revertptr+";");
4548 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4550 } else if (fln.getType().isBoolean()) {
4551 if (((Boolean)fln.getValue()).booleanValue())
4552 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
4554 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4555 } else if (fln.getType().isChar()) {
4556 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
4557 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
4558 } else if (fln.getType().isLong()) {
4559 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
4561 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
4564 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
4565 if (frn.getReturnTemp()!=null) {
4566 if (frn.getReturnTemp().getType().isPtr())
4567 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4569 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4571 output.println("return;");
4575 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4578 //only record if this group has more than one exit
4579 if (branchanalysis.numJumps(fcb)>1) {
4580 left=branchanalysis.jumpValue(fcb, 0);
4581 right=branchanalysis.jumpValue(fcb, 1);
4583 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
4585 output.println("STOREBRANCH("+right+");");
4586 output.println("goto "+label+";");
4587 output.println("}");
4589 output.println("STOREBRANCH("+left+");");
4592 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4593 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
4596 /** This method generates header information for the method or
4597 * task referenced by the Descriptor des. */
4598 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
4599 generateHeader(fm, lb, des, output, false);
4602 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
4604 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
4605 MethodDescriptor md=null;
4606 TaskDescriptor task=null;
4607 if (des instanceof MethodDescriptor)
4608 md=(MethodDescriptor) des;
4610 task=(TaskDescriptor) des;
4612 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
4614 if (md!=null&&md.getReturnType()!=null) {
4615 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4616 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4618 output.print(md.getReturnType().getSafeSymbol()+" ");
4620 //catch the constructor case
4621 output.print("void ");
4623 if (state.DSM||state.SINGLETM) {
4624 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4626 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4628 output.print(task.getSafeSymbol()+"(");
4630 boolean printcomma=false;
4631 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4633 if (state.DSM||state.SINGLETM) {
4634 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4636 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4638 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
4644 for(int i=0; i<objectparams.numPrimitives(); i++) {
4645 TempDescriptor temp=objectparams.getPrimitive(i);
4649 if (temp.getType().isClass()||temp.getType().isArray())
4650 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
4652 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
4654 output.println(") {");
4655 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4656 /* Imprecise Task */
4657 output.println("void * parameterarray[]) {");
4658 /* Unpack variables */
4659 for(int i=0; i<objectparams.numPrimitives(); i++) {
4660 TempDescriptor temp=objectparams.getPrimitive(i);
4661 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
4663 for(int i=0; i<fm.numTags(); i++) {
4664 TempDescriptor temp=fm.getTag(i);
4665 int offset=i+objectparams.numPrimitives();
4666 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
4669 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
4670 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
4671 } else output.println(") {");
4674 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
4675 output.println("/* FlatFlagActionNode */");
4678 /* Process tag changes */
4679 Relation tagsettable=new Relation();
4680 Relation tagcleartable=new Relation();
4682 Iterator tagsit=ffan.getTempTagPairs();
4683 while (tagsit.hasNext()) {
4684 TempTagPair ttp=(TempTagPair) tagsit.next();
4685 TempDescriptor objtmp=ttp.getTemp();
4686 TagDescriptor tag=ttp.getTag();
4687 TempDescriptor tagtmp=ttp.getTagTemp();
4688 boolean tagstatus=ffan.getTagChange(ttp);
4690 tagsettable.put(objtmp, tagtmp);
4692 tagcleartable.put(objtmp, tagtmp);
4697 Hashtable flagandtable=new Hashtable();
4698 Hashtable flagortable=new Hashtable();
4700 /* Process flag changes */
4701 Iterator flagsit=ffan.getTempFlagPairs();
4702 while(flagsit.hasNext()) {
4703 TempFlagPair tfp=(TempFlagPair)flagsit.next();
4704 TempDescriptor temp=tfp.getTemp();
4705 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
4706 FlagDescriptor flag=tfp.getFlag();
4708 //Newly allocate objects that don't set any flags case
4709 if (flagortable.containsKey(temp)) {
4713 flagortable.put(temp,new Integer(mask));
4715 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
4716 boolean flagstatus=ffan.getFlagChange(tfp);
4719 if (flagortable.containsKey(temp)) {
4720 mask=((Integer)flagortable.get(temp)).intValue();
4723 flagortable.put(temp,new Integer(mask));
4725 int mask=0xFFFFFFFF;
4726 if (flagandtable.containsKey(temp)) {
4727 mask=((Integer)flagandtable.get(temp)).intValue();
4729 mask&=(0xFFFFFFFF^flagid);
4730 flagandtable.put(temp,new Integer(mask));
4736 HashSet flagtagset=new HashSet();
4737 flagtagset.addAll(flagortable.keySet());
4738 flagtagset.addAll(flagandtable.keySet());
4739 flagtagset.addAll(tagsettable.keySet());
4740 flagtagset.addAll(tagcleartable.keySet());
4742 Iterator ftit=flagtagset.iterator();
4743 while(ftit.hasNext()) {
4744 TempDescriptor temp=(TempDescriptor)ftit.next();
4747 Set tagtmps=tagcleartable.get(temp);
4748 if (tagtmps!=null) {
4749 Iterator tagit=tagtmps.iterator();
4750 while(tagit.hasNext()) {
4751 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4752 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4753 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4755 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4759 tagtmps=tagsettable.get(temp);
4760 if (tagtmps!=null) {
4761 Iterator tagit=tagtmps.iterator();
4762 while(tagit.hasNext()) {
4763 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4764 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4765 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4767 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
4772 int andmask=0xFFFFFFF;
4774 if (flagortable.containsKey(temp))
4775 ormask=((Integer)flagortable.get(temp)).intValue();
4776 if (flagandtable.containsKey(temp))
4777 andmask=((Integer)flagandtable.get(temp)).intValue();
4778 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
4779 generateObjectDistribute(ffan, fm, lb, temp, output);
4783 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
4784 PrintWriter output, int ormask, int andmask) {
4785 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
4786 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4788 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4792 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
4793 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
4796 void generateOptionalHeader(PrintWriter headers) {
4799 headers.println("#include \"task.h\"\n\n");
4800 headers.println("#ifndef _OPTIONAL_STRUCT_");
4801 headers.println("#define _OPTIONAL_STRUCT_");
4803 //STRUCT PREDICATEMEMBER
4804 headers.println("struct predicatemember{");
4805 headers.println("int type;");
4806 headers.println("int numdnfterms;");
4807 headers.println("int * flags;");
4808 headers.println("int numtags;");
4809 headers.println("int * tags;\n};\n\n");
4811 //STRUCT OPTIONALTASKDESCRIPTOR
4812 headers.println("struct optionaltaskdescriptor{");
4813 headers.println("struct taskdescriptor * task;");
4814 headers.println("int index;");
4815 headers.println("int numenterflags;");
4816 headers.println("int * enterflags;");
4817 headers.println("int numpredicatemembers;");
4818 headers.println("struct predicatemember ** predicatememberarray;");
4819 headers.println("};\n\n");
4821 //STRUCT TASKFAILURE
4822 headers.println("struct taskfailure {");
4823 headers.println("struct taskdescriptor * task;");
4824 headers.println("int index;");
4825 headers.println("int numoptionaltaskdescriptors;");
4826 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4828 //STRUCT FSANALYSISWRAPPER
4829 headers.println("struct fsanalysiswrapper{");
4830 headers.println("int flags;");
4831 headers.println("int numtags;");
4832 headers.println("int * tags;");
4833 headers.println("int numtaskfailures;");
4834 headers.println("struct taskfailure ** taskfailurearray;");
4835 headers.println("int numoptionaltaskdescriptors;");
4836 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4838 //STRUCT CLASSANALYSISWRAPPER
4839 headers.println("struct classanalysiswrapper{");
4840 headers.println("int type;");
4841 headers.println("int numotd;");
4842 headers.println("struct optionaltaskdescriptor ** otdarray;");
4843 headers.println("int numfsanalysiswrappers;");
4844 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
4846 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
4848 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
4849 while(taskit.hasNext()) {
4850 TaskDescriptor td=(TaskDescriptor)taskit.next();
4851 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
4856 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
4857 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
4858 int predicateindex = 0;
4859 //iterate through the classes concerned by the predicate
4860 Set c_vard = predicate.vardescriptors;
4861 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
4864 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
4865 VarDescriptor vard = (VarDescriptor)vard_it.next();
4866 TypeDescriptor typed = vard.getType();
4868 //generate for flags
4869 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
4870 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4872 if (fen_hashset!=null) {
4873 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
4874 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
4876 DNFFlag dflag=fen.getDNF();
4877 numberterms+=dflag.size();
4879 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
4881 for(int j=0; j<dflag.size(); j++) {
4883 output.println(",");
4884 Vector term=dflag.get(j);
4887 for(int k=0; k<term.size(); k++) {
4888 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
4889 FlagDescriptor fd=dfa.getFlag();
4890 boolean negated=dfa.getNegated();
4891 int flagid=1<<((Integer)flags.get(fd)).intValue();
4896 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
4901 output.println("};\n");
4904 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
4905 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4908 for(int j=0; j<tagel.numTags(); j++) {
4910 output.println(",");
4911 TempDescriptor tmp=tagel.getTemp(j);
4912 if (!slotnumber.containsKey(tmp)) {
4913 Integer slotint=new Integer(current_slot++);
4914 slotnumber.put(tmp,slotint);
4916 int slot=slotnumber.get(tmp).intValue();
4917 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
4919 numtags = tagel.numTags();
4921 output.println("};");
4923 //store the result into a predicatemember struct
4924 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4925 output.println("/*type*/"+typed.getClassDesc().getId()+",");
4926 output.println("/* number of dnf terms */"+numberterms+",");
4927 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4928 output.println("/* number of tag */"+numtags+",");
4929 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4930 output.println("};\n");
4935 //generate an array that stores the entire predicate
4936 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4937 for( int j = 0; j<predicateindex; j++) {
4938 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4939 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4941 output.println("};\n");
4942 return predicateindex;
4946 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
4947 generateOptionalHeader(headers);
4949 output.println("#include \"optionalstruct.h\"\n\n");
4950 output.println("#include \"stdlib.h\"\n");
4952 HashSet processedcd = new HashSet();
4954 Enumeration e = safeexecution.keys();
4955 while (e.hasMoreElements()) {
4958 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
4959 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
4961 //Generate the struct of optionals
4962 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4963 numotd = c_otd.size();
4964 if(maxotd<numotd) maxotd = numotd;
4965 if( !c_otd.isEmpty() ) {
4966 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4967 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4969 //generate the int arrays for the predicate
4970 Predicate predicate = otd.predicate;
4971 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
4972 TreeSet<Integer> fsset=new TreeSet<Integer>();
4973 //iterate through possible FSes corresponding to
4974 //the state when entering
4976 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
4977 FlagState fs = (FlagState)fses.next();
4979 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4980 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4981 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4984 fsset.add(new Integer(flagid));
4985 //tag information not needed because tag
4986 //changes are not tolerated.
4989 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4990 boolean needcomma=false;
4991 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
4994 output.println(it.next());
4997 output.println("};\n");
5000 //generate optionaltaskdescriptor that actually
5001 //includes exit fses, predicate and the task
5003 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5004 output.println("&task_"+otd.td.getSafeSymbol()+",");
5005 output.println("/*index*/"+otd.getIndex()+",");
5006 output.println("/*number of enter flags*/"+fsset.size()+",");
5007 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5008 output.println("/*number of members */"+predicateindex+",");
5009 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5010 output.println("};\n");
5014 // if there are no optionals, there is no need to build the rest of the struct
5016 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
5017 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5018 if( !c_otd.isEmpty() ) {
5019 boolean needcomma=false;
5020 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5021 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5023 output.println(",");
5025 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5028 output.println("};\n");
5030 //get all the possible flagstates reachable by an object
5031 Hashtable hashtbtemp = safeexecution.get(cdtemp);
5033 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
5034 fsts.addAll(hashtbtemp.keySet());
5035 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
5036 FlagState fs = (FlagState)fsit.next();
5039 //get the set of OptionalTaskDescriptors corresponding
5040 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
5041 //iterate through the OptionalTaskDescriptors and
5042 //store the pointers to the optionals struct (see on
5043 //top) into an array
5045 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
5046 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
5047 OptionalTaskDescriptor mm = mos.next();
5049 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
5051 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5054 output.println("};\n");
5056 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
5059 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5060 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5061 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5065 //process tag information
5068 boolean first = true;
5069 Enumeration tag_enum = fs.getTags();
5070 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5071 while(tag_enum.hasMoreElements()) {
5073 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
5077 output.println(", ");
5078 output.println("/*tagid*/"+state.getTagId(tagd));
5080 output.println("};");
5082 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
5083 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5084 TaskIndex ti=itti.next();
5088 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
5090 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
5091 boolean needcomma=false;
5092 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
5093 OptionalTaskDescriptor otd=otdit.next();
5097 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5099 output.println("};");
5101 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
5102 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
5103 output.print(ti.getIndex()+", ");
5104 output.print(otdset.size()+", ");
5105 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
5106 output.println("};");
5109 tiset=sa.getTaskIndex(fs);
5110 boolean needcomma=false;
5112 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5113 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5114 TaskIndex ti=itti.next();
5115 if (ti.isRuntime()) {
5122 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
5124 output.println("};\n");
5126 //Store the result in fsanalysiswrapper
5128 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
5129 output.println("/*flag*/"+flagid+",");
5130 output.println("/* number of tags*/"+tagcounter+",");
5131 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5132 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
5133 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5134 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
5135 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
5136 output.println("};\n");
5140 //Build the array of fsanalysiswrappers
5141 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
5142 boolean needcomma=false;
5143 for(int i = 0; i<fscounter; i++) {
5144 if (needcomma) output.print(",");
5145 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
5148 output.println("};");
5150 //Build the classanalysiswrapper referring to the previous array
5151 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
5152 output.println("/*type*/"+cdtemp.getId()+",");
5153 output.println("/*numotd*/"+numotd+",");
5154 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
5155 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
5156 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
5157 processedcd.add(cdtemp);
5160 //build an array containing every classes for which code has been build
5161 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
5162 for(int i=0; i<state.numClasses(); i++) {
5163 ClassDescriptor cn=cdarray[i];
5166 if ((cn != null) && (processedcd.contains(cn)))
5167 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
5169 output.print("NULL");
5171 output.println("};");
5173 output.println("#define MAXOTD "+maxotd);
5174 headers.println("#endif");
5177 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
5178 Relation r=new Relation();
5179 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
5180 OptionalTaskDescriptor otd=otdit.next();
5181 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
5185 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
5186 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
5187 Set s=r.get(it.next());
5188 for(Iterator it2=s.iterator(); it2.hasNext();) {
5189 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
5197 protected void outputTransCode(PrintWriter output) {
5200 private int calculateSizeOfSESEParamList(FlatSESEEnterNode fsen){
5202 Set<TempDescriptor> tdSet=new HashSet<TempDescriptor>();
5204 for (Iterator iterator = fsen.getInVarSet().iterator(); iterator.hasNext();) {
5205 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5206 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5207 tdSet.add(tempDescriptor);
5211 for (Iterator iterator = fsen.getOutVarSet().iterator(); iterator.hasNext();) {
5212 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5213 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5214 tdSet.add(tempDescriptor);
5218 return tdSet.size();
5221 private String calculateSizeOfSESEParamSize(FlatSESEEnterNode fsen){
5222 HashMap <String,Integer> map=new HashMap();
5223 HashSet <TempDescriptor> processed=new HashSet<TempDescriptor>();
5226 // space for all in and out set primitives
5227 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
5228 inSetAndOutSet.addAll( fsen.getInVarSet() );
5229 inSetAndOutSet.addAll( fsen.getOutVarSet() );
5231 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
5233 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
5234 while( itr.hasNext() ) {
5235 TempDescriptor temp = itr.next();
5236 TypeDescriptor type = temp.getType();
5237 if( !type.isPtr() ) {
5238 inSetAndOutSetPrims.add( temp );
5242 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
5243 while( itrPrims.hasNext() ) {
5244 TempDescriptor temp = itrPrims.next();
5245 TypeDescriptor type = temp.getType();
5246 if(type.isPrimitive()){
5247 Integer count=map.get(type.getSymbol());
5249 count=new Integer(1);
5250 map.put(type.getSymbol(), count);
5252 map.put(type.getSymbol(), new Integer(count.intValue()+1));
5257 Set<String> keySet=map.keySet();
5258 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
5259 String key = (String) iterator.next();
5260 rtr+="+sizeof("+key+")*"+map.get(key);
5265 private int calculatePrevSESECount(FlatSESEEnterNode fsen){
5269 Iterator<TempDescriptor>itrDynInVars = fsen.getDynamicInVarSet().iterator();
5270 while( itrDynInVars.hasNext() ) {
5271 TempDescriptor dynInVar = itrDynInVars.next();
5275 // in-set source tracking
5276 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
5277 while( itrStaticInVarSrcs.hasNext() ) {
5278 SESEandAgePair srcPair = itrStaticInVarSrcs.next();