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.MLPAnalysis;
32 import Analysis.MLP.ParentChildConflictsMap;
33 import Analysis.MLP.SESELock;
34 import Analysis.MLP.VariableSourceToken;
35 import Analysis.MLP.CodePlan;
36 import Analysis.MLP.SESEandAgePair;
37 import Analysis.MLP.WaitingElement;
39 public class BuildCode {
42 Hashtable paramstable;
47 String localsprefix="___locals___";
48 String localsprefixaddr="&"+localsprefix;
49 String localsprefixderef=localsprefix+".";
50 String fcrevert="___fcrevert___";
51 String paramsprefix="___params___";
52 String oidstr="___nextobject___";
53 String nextobjstr="___nextobject___";
54 String localcopystr="___localcopy___";
55 public static boolean GENERATEPRECISEGC=false;
56 public static String PREFIX="";
57 public static String arraytype="ArrayObject";
58 public static int flagcount = 0;
61 protected int maxtaskparams=0;
62 private int maxcount=0;
63 ClassDescriptor[] cdarray;
64 TypeDescriptor[] arraytable;
65 LocalityAnalysis locality;
66 Hashtable<LocalityBinding, TempDescriptor> reverttable;
67 Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>> backuptable;
71 String mlperrstr = "if(status != 0) { "+
72 "sprintf(errmsg, \"MLP error at %s:%d\", __FILE__, __LINE__); "+
73 "perror(errmsg); exit(-1); }";
74 boolean nonSESEpass=true;
77 DiscoverConflicts recorddc;
82 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa) {
83 this(st, temptovar, typeutil, null, sa, pa, null);
86 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa) {
87 this(st, temptovar, typeutil, null, sa, pa, mlpa);
90 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, PrefetchAnalysis pa, MLPAnalysis mlpa) {
91 this(st, temptovar, typeutil, locality, null, pa, mlpa);
94 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa) {
99 callgraph=new CallGraph(state);
101 oidstr="___objlocation___";
102 this.temptovar=temptovar;
103 paramstable=new Hashtable();
104 tempstable=new Hashtable();
105 fieldorder=new Hashtable();
106 flagorder=new Hashtable();
107 this.typeutil=typeutil;
108 virtualcalls=new Virtual(state,locality);
109 if (locality!=null) {
110 this.locality=locality;
111 this.reverttable=new Hashtable<LocalityBinding, TempDescriptor>();
112 this.backuptable=new Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>>();
113 this.wb=new WriteBarrier(locality, st);
115 if (state.SINGLETM&&state.DCOPTS) {
116 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
117 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
118 this.dc=new DiscoverConflicts(locality, st, typeanalysis, gft);
121 if (state.DELAYCOMP) {
122 //TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
123 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
124 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
125 delaycomp=new DCWrapper(locality, st, typeanalysis, gft);
126 dc=delaycomp.getConflicts();
127 recorddc=new DiscoverConflicts(locality, st, typeanalysis, delaycomp.getCannotDelayMap(), true, true, null);
128 recorddc.doAnalysis();
132 /** The buildCode method outputs C code for all the methods. The Flat
133 * versions of the methods must already be generated and stored in
134 * the State object. */
135 PrintWriter outsandbox=null;
137 public void buildCode() {
138 /* Create output streams to write to */
139 PrintWriter outclassdefs=null;
140 PrintWriter outstructs=null;
141 PrintWriter outrepairstructs=null;
142 PrintWriter outmethodheader=null;
143 PrintWriter outmethod=null;
144 PrintWriter outvirtual=null;
145 PrintWriter outtask=null;
146 PrintWriter outtaskdefs=null;
147 PrintWriter outoptionalarrays=null;
148 PrintWriter optionalheaders=null;
152 outsandbox=new PrintWriter(new FileOutputStream(PREFIX+"sandboxdefs.c"), true);
154 outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
155 outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
156 outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
157 outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
158 outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
160 outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
161 outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
162 if (state.OPTIONAL) {
163 outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
164 optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
167 if (state.structfile!=null) {
168 outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
170 } catch (Exception e) {
175 /* Build the virtual dispatch tables */
176 buildVirtualTables(outvirtual);
178 /* Output includes */
179 outmethodheader.println("#ifndef METHODHEADERS_H");
180 outmethodheader.println("#define METHODHEADERS_H");
181 outmethodheader.println("#include \"structdefs.h\"");
183 outmethodheader.println("#include \"dstm.h\"");
185 outmethodheader.println("#include \"sandbox.h\"");
187 if (state.EVENTMONITOR) {
188 outmethodheader.println("#include \"monitor.h\"");
190 if (state.SINGLETM) {
191 outmethodheader.println("#include \"tm.h\"");
192 outmethodheader.println("#include \"delaycomp.h\"");
193 outmethodheader.println("#include \"inlinestm.h\"");
195 if (state.ABORTREADERS) {
196 outmethodheader.println("#include \"abortreaders.h\"");
197 outmethodheader.println("#include <setjmp.h>");
200 outmethodheader.println("#include <stdlib.h>");
201 outmethodheader.println("#include <stdio.h>");
202 outmethodheader.println("#include <string.h>");
203 outmethodheader.println("#include \"mlp_runtime.h\"");
204 outmethodheader.println("#include \"psemaphore.h\"");
207 /* Output Structures */
208 outputStructs(outstructs);
210 // Output the C class declarations
211 // These could mutually reference each other
212 outputClassDeclarations(outclassdefs);
214 // Output function prototypes and structures for parameters
215 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
216 while(it.hasNext()) {
217 ClassDescriptor cn=(ClassDescriptor)it.next();
218 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader);
220 outclassdefs.close();
223 /* Map flags to integers */
224 /* The runtime keeps track of flags using these integers */
225 it=state.getClassSymbolTable().getDescriptorsIterator();
226 while(it.hasNext()) {
227 ClassDescriptor cn=(ClassDescriptor)it.next();
231 generateTaskStructs(outstructs, outmethodheader);
233 /* Outputs generic task structures if this is a task
235 outputTaskTypes(outtask);
239 // have to initialize some SESE compiler data before
240 // analyzing normal methods, which must happen before
241 // generating SESE internal code
242 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
243 FlatSESEEnterNode fsen = seseit.next();
244 initializeSESE( fsen );
248 /* Build the actual methods */
249 outputMethods(outmethod);
251 // Output function prototypes and structures for SESE's and code
254 // used to differentiate, during code generation, whether we are
255 // passing over SESE body code, or non-SESE code
258 // first generate code for each sese's internals
259 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
260 FlatSESEEnterNode fsen = seseit.next();
261 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
264 // then write the invokeSESE switch to decouple scheduler
265 // from having to do unique details of sese invocation
266 generateSESEinvocationMethod(outmethodheader, outmethod);
270 /* Output code for tasks */
271 outputTaskCode(outtaskdefs, outmethod);
273 /* Record maximum number of task parameters */
274 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
275 } else if (state.main!=null) {
276 /* Generate main method */
277 outputMainMethod(outmethod);
280 /* Generate information for task with optional parameters */
281 if (state.TASK&&state.OPTIONAL) {
282 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
283 outoptionalarrays.close();
286 /* Output structure definitions for repair tool */
287 if (state.structfile!=null) {
288 buildRepairStructs(outrepairstructs);
289 outrepairstructs.close();
293 outmethodheader.println("#endif");
294 outmethodheader.close();
296 outstructs.println("#endif");
301 /* This code just generates the main C method for java programs.
302 * The main C method packs up the arguments into a string array
303 * and passes it to the java main method. */
305 private void outputMainMethod(PrintWriter outmethod) {
306 outmethod.println("int main(int argc, const char *argv[]) {");
307 outmethod.println(" int i;");
310 //outmethod.println(" pthread_once( &mlpOnceObj, mlpInitOncePerThread );");
311 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
315 outmethod.println("#ifdef TRANSSTATS \n");
316 outmethod.println("handle();\n");
317 outmethod.println("#endif\n");
319 if (state.THREAD||state.DSM||state.SINGLETM) {
320 outmethod.println("initializethreads();");
323 outmethod.println("if (dstmStartup(argv[1])) {");
324 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
325 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
327 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
330 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
331 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
333 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
337 outmethod.println(" for(i=2;i<argc;i++) {");
339 outmethod.println(" for(i=1;i<argc;i++) {");
340 outmethod.println(" int length=strlen(argv[i]);");
341 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
342 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
344 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
347 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
349 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
350 outmethod.println(" }");
352 MethodDescriptor md=typeutil.getMain();
353 ClassDescriptor cd=typeutil.getMainClass();
355 outmethod.println(" {");
356 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
357 if (state.DSM||state.SINGLETM) {
358 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
360 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
361 outmethod.println("1, NULL,"+"stringarray};");
362 if (state.DSM||state.SINGLETM)
363 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
365 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
367 if (state.DSM||state.SINGLETM)
368 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
370 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
372 outmethod.println(" }");
375 outmethod.println("}");
378 if (state.THREAD||state.DSM||state.SINGLETM) {
379 outmethod.println("pthread_mutex_lock(&gclistlock);");
380 outmethod.println("threadcount--;");
381 outmethod.println("pthread_cond_signal(&gccond);");
382 outmethod.println("pthread_mutex_unlock(&gclistlock);");
385 if (state.DSM||state.SINGLETM) {
386 outmethod.println("#ifdef TRANSSTATS \n");
387 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
388 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
389 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
390 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
392 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
393 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
394 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
395 outmethod.println("printf(\"ndirtyCacheObj= %d\\n\", ndirtyCacheObj);");
396 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
397 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
398 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
399 outmethod.println("printf(\"totalObjSize= %d\\n\", totalObjSize);");
400 outmethod.println("printf(\"sendRemoteReq= %d\\n\", sendRemoteReq);");
401 outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
402 } else if (state.SINGLETM) {
403 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
404 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
405 outmethod.println("#ifdef STMSTATS\n");
406 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
407 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
408 outmethod.println("}\n");
409 outmethod.println("#endif\n");
410 outmethod.println("fflush(stdout);");
412 outmethod.println("#endif\n");
415 if(state.DSMRECOVERYSTATS) {
416 outmethod.println("#ifdef RECOVERYSTATS\n");
417 outmethod.println("printf(\"***** Recovery Stats *****\\n\");");
418 outmethod.println("printf(\"numRecovery = %d\\n\",numRecovery);");
419 outmethod.println("int nRecovery=0;");
420 outmethod.println("for(nRecovery=0;nRecovery<numRecovery;nRecovery++) {");
421 outmethod.println(" printf(\"Dead Machine = %s\\n\",midtoIPString(deadMachine[nRecovery]));");
422 outmethod.println(" printf(\"Recovery Time = %.2f\\n\",elapsedTime[nRecovery]);");
423 outmethod.println("}\n");
424 outmethod.println("printf(\"**************************\\n\\n\");");
425 outmethod.println("#endif\n");
428 if (state.EVENTMONITOR) {
429 outmethod.println("dumpdata();");
432 if (state.THREAD||state.SINGLETM)
433 outmethod.println("pthread_exit(NULL);");
436 outmethod.println(" workScheduleBegin();");
439 outmethod.println("}");
442 /* This method outputs code for each task. */
444 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
445 /* Compile task based program */
446 outtaskdefs.println("#include \"task.h\"");
447 outtaskdefs.println("#include \"methodheaders.h\"");
448 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
449 while(taskit.hasNext()) {
450 TaskDescriptor td=(TaskDescriptor)taskit.next();
451 FlatMethod fm=state.getMethodFlat(td);
452 generateFlatMethod(fm, null, outmethod);
453 generateTaskDescriptor(outtaskdefs, fm, td);
456 //Output task descriptors
457 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
458 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
460 while(taskit.hasNext()) {
461 TaskDescriptor td=(TaskDescriptor)taskit.next();
465 outtaskdefs.println(",");
466 outtaskdefs.print("&task_"+td.getSafeSymbol());
468 outtaskdefs.println("};");
470 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
473 /* This method outputs most of the methods.c file. This includes
474 * some standard includes and then an array with the sizes of
475 * objets and array that stores supertype and then the code for
476 * the Java methods.. */
478 protected void outputMethods(PrintWriter outmethod) {
479 outmethod.println("#include \"methodheaders.h\"");
480 outmethod.println("#include \"virtualtable.h\"");
481 outmethod.println("#include \"runtime.h\"");
483 outmethod.println("#include \"sandboxdefs.c\"");
486 outmethod.println("#include \"addPrefetchEnhance.h\"");
487 outmethod.println("#include \"localobjects.h\"");
489 if (state.FASTCHECK) {
490 outmethod.println("#include \"localobjects.h\"");
492 if(state.MULTICORE) {
493 outmethod.println("#include \"task.h\"");
494 outmethod.println("#include \"multicoreruntime.h\"");
495 outmethod.println("#include \"runtime_arch.h\"");
497 if (state.THREAD||state.DSM||state.SINGLETM)
498 outmethod.println("#include <thread.h>");
499 if (state.main!=null) {
500 outmethod.println("#include <string.h>");
502 if (state.CONSCHECK) {
503 outmethod.println("#include \"checkers.h\"");
506 outmethod.println("#include <stdlib.h>");
507 outmethod.println("#include <stdio.h>");
508 outmethod.println("#include \"mlp_runtime.h\"");
509 outmethod.println("#include \"psemaphore.h\"");
513 //Store the sizes of classes & array elements
514 generateSizeArray(outmethod);
516 //Store table of supertypes
517 generateSuperTypeTable(outmethod);
519 //Store the layout of classes
520 generateLayoutStructs(outmethod);
522 /* Generate code for methods */
523 if (state.DSM||state.SINGLETM) {
524 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
525 LocalityBinding lb=lbit.next();
526 MethodDescriptor md=lb.getMethod();
527 FlatMethod fm=state.getMethodFlat(md);
529 if (!md.getModifiers().isNative()) {
530 generateFlatMethod(fm, lb, outmethod);
531 //System.out.println("fm= " + fm + " md= " + md);
535 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
536 while(classit.hasNext()) {
537 ClassDescriptor cn=(ClassDescriptor)classit.next();
538 Iterator methodit=cn.getMethods();
539 while(methodit.hasNext()) {
540 /* Classify parameters */
541 MethodDescriptor md=(MethodDescriptor)methodit.next();
542 FlatMethod fm=state.getMethodFlat(md);
543 if (!md.getModifiers().isNative()) {
544 generateFlatMethod(fm, null, outmethod);
551 protected void outputStructs(PrintWriter outstructs) {
552 outstructs.println("#ifndef STRUCTDEFS_H");
553 outstructs.println("#define STRUCTDEFS_H");
554 outstructs.println("#include \"classdefs.h\"");
555 outstructs.println("#ifndef INTPTR");
556 outstructs.println("#ifdef BIT64");
557 outstructs.println("#define INTPTR long");
558 outstructs.println("#else");
559 outstructs.println("#define INTPTR int");
560 outstructs.println("#endif");
561 outstructs.println("#endif");
563 outstructs.println("#include \"mlp_runtime.h\"");
564 outstructs.println("#include \"psemaphore.h\"");
567 /* Output #defines that the runtime uses to determine type
568 * numbers for various objects it needs */
569 outstructs.println("#define MAXCOUNT "+maxcount);
570 if (state.DSM||state.SINGLETM) {
571 LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
573 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
575 else if (state.SINGLETM) {
576 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
578 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
582 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
584 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
585 else if( state.SINGLETM)
586 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
587 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
590 outstructs.println("#define STRINGARRAYTYPE "+
591 (state.getArrayNumber(
592 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
594 outstructs.println("#define OBJECTARRAYTYPE "+
595 (state.getArrayNumber(
596 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
599 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
600 outstructs.println("#define CHARARRAYTYPE "+
601 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
603 outstructs.println("#define BYTEARRAYTYPE "+
604 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
606 outstructs.println("#define BYTEARRAYARRAYTYPE "+
607 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
609 outstructs.println("#define NUMCLASSES "+state.numClasses());
610 int totalClassSize = state.numClasses() + state.numArrays();
611 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
613 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
614 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
615 outstructs.println("#define TAGARRAYTYPE "+
616 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
620 protected void outputClassDeclarations(PrintWriter outclassdefs) {
621 if (state.THREAD||state.DSM||state.SINGLETM)
622 outclassdefs.println("#include <pthread.h>");
623 outclassdefs.println("#ifndef INTPTR");
624 outclassdefs.println("#ifdef BIT64");
625 outclassdefs.println("#define INTPTR long");
626 outclassdefs.println("#else");
627 outclassdefs.println("#define INTPTR int");
628 outclassdefs.println("#endif");
629 outclassdefs.println("#endif");
631 outclassdefs.println("#include \"optionalstruct.h\"");
632 outclassdefs.println("struct "+arraytype+";");
633 /* Start by declaring all structs */
634 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
635 while(it.hasNext()) {
636 ClassDescriptor cn=(ClassDescriptor)it.next();
637 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
639 outclassdefs.println("");
640 //Print out definition for array type
641 outclassdefs.println("struct "+arraytype+" {");
642 outclassdefs.println(" int type;");
643 if (state.EVENTMONITOR) {
644 outclassdefs.println(" int objuid;");
647 outclassdefs.println(" pthread_t tid;");
648 outclassdefs.println(" void * lockentry;");
649 outclassdefs.println(" int lockcount;");
652 outclassdefs.println(" int flag;");
653 if(!state.MULTICORE) {
654 outclassdefs.println(" void * flagptr;");
656 outclassdefs.println(" int version;");
657 outclassdefs.println(" int * lock;"); // lock entry for this obj
658 outclassdefs.println(" int mutex;");
659 outclassdefs.println(" int lockcount;");
660 if(state.MULTICOREGC) {
661 outclassdefs.println(" int marked;");
665 outclassdefs.println(" int numfses;");
666 outclassdefs.println(" int * fses;");
669 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
671 if (state.STMARRAY) {
672 outclassdefs.println(" int lowindex;");
673 outclassdefs.println(" int highindex;");
676 outclassdefs.println(" int paddingforarray;");
677 if (state.DUALVIEW) {
678 outclassdefs.println(" int arrayversion;");
681 outclassdefs.println(" int ___length___;");
682 outclassdefs.println("};\n");
683 outclassdefs.println("extern int classsize[];");
684 outclassdefs.println("extern int hasflags[];");
685 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
686 outclassdefs.println("extern int supertypes[];");
689 /** Prints out definitions for generic task structures */
691 private void outputTaskTypes(PrintWriter outtask) {
692 outtask.println("#ifndef _TASK_H");
693 outtask.println("#define _TASK_H");
694 outtask.println("struct parameterdescriptor {");
695 outtask.println("int type;");
696 outtask.println("int numberterms;");
697 outtask.println("int *intarray;");
698 outtask.println("void * queue;");
699 outtask.println("int numbertags;");
700 outtask.println("int *tagarray;");
701 outtask.println("};");
703 outtask.println("struct taskdescriptor {");
704 outtask.println("void * taskptr;");
705 outtask.println("int numParameters;");
706 outtask.println(" int numTotal;");
707 outtask.println("struct parameterdescriptor **descriptorarray;");
708 outtask.println("char * name;");
709 outtask.println("};");
710 outtask.println("extern struct taskdescriptor * taskarray[];");
711 outtask.println("extern numtasks;");
712 outtask.println("#endif");
716 private void buildRepairStructs(PrintWriter outrepairstructs) {
717 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
718 while(classit.hasNext()) {
719 ClassDescriptor cn=(ClassDescriptor)classit.next();
720 outrepairstructs.println("structure "+cn.getSymbol()+" {");
721 outrepairstructs.println(" int __type__;");
723 outrepairstructs.println(" int __flag__;");
724 if(!state.MULTICORE) {
725 outrepairstructs.println(" int __flagptr__;");
728 printRepairStruct(cn, outrepairstructs);
729 outrepairstructs.println("}\n");
732 for(int i=0; i<state.numArrays(); i++) {
733 TypeDescriptor tdarray=arraytable[i];
734 TypeDescriptor tdelement=tdarray.dereference();
735 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
736 outrepairstructs.println(" int __type__;");
737 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
738 outrepairstructs.println(" int length;");
740 // Need to add support to repair tool for this
741 if (tdelement.isClass()||tdelement.isArray())
742 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
744 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
746 outrepairstructs.println("}\n");
750 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
751 ClassDescriptor sp=cn.getSuperDesc();
753 printRepairStruct(sp, output);
755 Vector fields=(Vector)fieldorder.get(cn);
757 for(int i=0; i<fields.size(); i++) {
758 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
759 if (fd.getType().isArray()) {
760 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
761 } else if (fd.getType().isClass())
762 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
763 else if (fd.getType().isFloat())
764 output.println(" int "+fd.getSymbol()+"; /* really float */");
766 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
770 /** This method outputs TaskDescriptor information */
771 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
772 for (int i=0; i<task.numParameters(); i++) {
773 VarDescriptor param_var=task.getParameter(i);
774 TypeDescriptor param_type=task.getParamType(i);
775 FlagExpressionNode param_flag=task.getFlag(param_var);
776 TagExpressionList param_tag=task.getTag(param_var);
779 if (param_flag==null) {
780 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
781 output.println("0x0, 0x0 };");
784 DNFFlag dflag=param_flag.getDNF();
785 dnfterms=dflag.size();
787 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
788 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
789 for(int j=0; j<dflag.size(); j++) {
792 Vector term=dflag.get(j);
795 for(int k=0; k<term.size(); k++) {
796 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
797 FlagDescriptor fd=dfa.getFlag();
798 boolean negated=dfa.getNegated();
799 int flagid=1<<((Integer)flags.get(fd)).intValue();
804 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
806 output.println("};");
809 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
810 //BUG...added next line to fix, test with any task program
812 for(int j=0; j<param_tag.numTags(); j++) {
815 /* for each tag we need */
816 /* which slot it is */
817 /* what type it is */
818 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
819 TempDescriptor tmp=param_tag.getTemp(j);
820 int slot=fm.getTagInt(tmp);
821 output.println(slot+", "+state.getTagId(tvd.getTag()));
823 output.println("};");
825 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
826 output.println("/* type */"+param_type.getClassDesc().getId()+",");
827 output.println("/* number of DNF terms */"+dnfterms+",");
828 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
829 output.println("0,");
830 //BUG, added next line to fix and else statement...test
831 //with any task program
833 output.println("/* number of tags */"+param_tag.numTags()+",");
835 output.println("/* number of tags */ 0,");
836 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
837 output.println("};");
841 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
842 for (int i=0; i<task.numParameters(); i++) {
845 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
847 output.println("};");
849 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
850 output.println("&"+task.getSafeSymbol()+",");
851 output.println("/* number of parameters */" +task.numParameters() + ",");
852 int numtotal=task.numParameters()+fm.numTags();
853 output.println("/* number total parameters */" +numtotal + ",");
854 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
855 output.println("\""+task.getSymbol()+"\"");
856 output.println("};");
860 /** The buildVirtualTables method outputs the virtual dispatch
861 * tables for methods. */
863 protected void buildVirtualTables(PrintWriter outvirtual) {
864 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
865 while(classit.hasNext()) {
866 ClassDescriptor cd=(ClassDescriptor)classit.next();
867 if (virtualcalls.getMethodCount(cd)>maxcount)
868 maxcount=virtualcalls.getMethodCount(cd);
870 MethodDescriptor[][] virtualtable=null;
871 LocalityBinding[][] lbvirtualtable=null;
872 if (state.DSM||state.SINGLETM)
873 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
875 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
877 /* Fill in virtual table */
878 classit=state.getClassSymbolTable().getDescriptorsIterator();
879 while(classit.hasNext()) {
880 ClassDescriptor cd=(ClassDescriptor)classit.next();
881 if (state.DSM||state.SINGLETM)
882 fillinRow(cd, lbvirtualtable, cd.getId());
884 fillinRow(cd, virtualtable, cd.getId());
887 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
888 Iterator arrayit=state.getArrayIterator();
889 while(arrayit.hasNext()) {
890 TypeDescriptor td=(TypeDescriptor)arrayit.next();
891 int id=state.getArrayNumber(td);
892 if (state.DSM||state.SINGLETM)
893 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
895 fillinRow(objectcd, virtualtable, id+state.numClasses());
898 outvirtual.print("void * virtualtable[]={");
899 boolean needcomma=false;
900 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
901 for(int j=0; j<maxcount; j++) {
903 outvirtual.print(", ");
904 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
905 LocalityBinding lb=lbvirtualtable[i][j];
906 MethodDescriptor md=lb.getMethod();
907 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
908 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
909 MethodDescriptor md=virtualtable[i][j];
910 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
912 outvirtual.print("0");
916 outvirtual.println("");
918 outvirtual.println("};");
922 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
923 /* Get inherited methods */
924 if (cd.getSuperDesc()!=null)
925 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
926 /* Override them with our methods */
927 for(Iterator it=cd.getMethods(); it.hasNext();) {
928 MethodDescriptor md=(MethodDescriptor)it.next();
929 if (md.isStatic()||md.getReturnType()==null)
931 int methodnum=virtualcalls.getMethodNumber(md);
932 virtualtable[rownum][methodnum]=md;
936 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
937 /* Get inherited methods */
938 if (cd.getSuperDesc()!=null)
939 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
940 /* Override them with our methods */
941 if (locality.getClassBindings(cd)!=null)
942 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
943 LocalityBinding lb=lbit.next();
944 MethodDescriptor md=lb.getMethod();
945 //Is the method static or a constructor
946 if (md.isStatic()||md.getReturnType()==null)
948 int methodnum=virtualcalls.getLocalityNumber(lb);
949 virtualtable[rownum][methodnum]=lb;
953 /** Generate array that contains the sizes of class objects. The
954 * object allocation functions in the runtime use this
957 private void generateSizeArray(PrintWriter outclassdefs) {
958 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
959 outclassdefs.print("#ifdef TRANSSTATS \n");
960 outclassdefs.print("extern int numTransAbort;\n");
961 outclassdefs.print("extern int numTransCommit;\n");
962 outclassdefs.print("extern int nSoftAbort;\n");
964 outclassdefs.print("extern int nchashSearch;\n");
965 outclassdefs.print("extern int nmhashSearch;\n");
966 outclassdefs.print("extern int nprehashSearch;\n");
967 outclassdefs.print("extern int ndirtyCacheObj;\n");
968 outclassdefs.print("extern int nRemoteSend;\n");
969 outclassdefs.print("extern int sendRemoteReq;\n");
970 outclassdefs.print("extern int getResponse;\n");
971 outclassdefs.print("extern int bytesSent;\n");
972 outclassdefs.print("extern int bytesRecv;\n");
973 outclassdefs.print("extern int totalObjSize;\n");
974 outclassdefs.print("extern void handle();\n");
975 } else if (state.SINGLETM) {
976 outclassdefs.println("extern int nSoftAbortAbort;");
977 outclassdefs.println("extern int nSoftAbortCommit;");
978 outclassdefs.println("#ifdef STMSTATS\n");
979 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
980 outclassdefs.println("#endif\n");
982 outclassdefs.print("#endif\n");
984 if(state.DSMRECOVERYSTATS) {
985 outclassdefs.print("#ifdef RECOVERYSTATS\n");
986 outclassdefs.print("extern int numRecovery;\n");
987 outclassdefs.print("extern unsigned int deadMachine[8];\n");
988 outclassdefs.print("extern double elapsedTime[8];\n");
989 outclassdefs.print("#endif\n");
991 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
993 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
994 cdarray=new ClassDescriptor[state.numClasses()];
996 while(it.hasNext()) {
997 ClassDescriptor cd=(ClassDescriptor)it.next();
998 cdarray[cd.getId()]=cd;
1001 arraytable=new TypeDescriptor[state.numArrays()];
1003 Iterator arrayit=state.getArrayIterator();
1004 while(arrayit.hasNext()) {
1005 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1006 int id=state.getArrayNumber(td);
1012 /* Print out types */
1013 outclassdefs.println("/* ");
1014 for(int i=0; i<state.numClasses(); i++) {
1015 ClassDescriptor cd=cdarray[i];
1017 outclassdefs.println("NULL " + i);
1019 outclassdefs.println(cd +" "+i);
1023 for(int i=0; i<state.numArrays(); i++) {
1024 TypeDescriptor arraytd=arraytable[i];
1025 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
1028 outclassdefs.println("*/");
1031 outclassdefs.print("int classsize[]={");
1033 boolean needcomma=false;
1034 for(int i=0; i<state.numClasses(); i++) {
1036 outclassdefs.print(", ");
1038 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1040 outclassdefs.print("0");
1046 for(int i=0; i<state.numArrays(); i++) {
1048 outclassdefs.print(", ");
1049 TypeDescriptor tdelement=arraytable[i].dereference();
1050 if (tdelement.isArray()||tdelement.isClass())
1051 outclassdefs.print("sizeof(void *)");
1053 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1057 outclassdefs.println("};");
1059 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1061 outclassdefs.print("int typearray[]={");
1062 for(int i=0; i<state.numClasses(); i++) {
1063 ClassDescriptor cd=cdarray[i];
1064 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1066 outclassdefs.print(", ");
1068 outclassdefs.print("-1");
1070 outclassdefs.print(supercd.getId());
1074 for(int i=0; i<state.numArrays(); i++) {
1075 TypeDescriptor arraytd=arraytable[i];
1076 ClassDescriptor arraycd=arraytd.getClassDesc();
1077 if (arraycd==null) {
1079 outclassdefs.print(", ");
1080 outclassdefs.print(objectclass.getId());
1084 ClassDescriptor cd=arraycd.getSuperDesc();
1087 TypeDescriptor supertd=new TypeDescriptor(cd);
1088 supertd.setArrayCount(arraytd.getArrayCount());
1089 type=state.getArrayNumber(supertd);
1091 type+=state.numClasses();
1094 cd=cd.getSuperDesc();
1097 outclassdefs.print(", ");
1098 outclassdefs.print(type);
1102 outclassdefs.println("};");
1107 outclassdefs.print("int typearray2[]={");
1108 for(int i=0; i<state.numArrays(); i++) {
1109 TypeDescriptor arraytd=arraytable[i];
1110 ClassDescriptor arraycd=arraytd.getClassDesc();
1111 if (arraycd==null) {
1113 outclassdefs.print(", ");
1114 outclassdefs.print("-1");
1118 ClassDescriptor cd=arraycd.getSuperDesc();
1119 int level=arraytd.getArrayCount()-1;
1121 for(; level>0; level--) {
1122 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1123 supertd.setArrayCount(level);
1124 type=state.getArrayNumber(supertd);
1126 type+=state.numClasses();
1131 outclassdefs.print(", ");
1132 outclassdefs.print(type);
1136 outclassdefs.println("};");
1139 /** Constructs params and temp objects for each method or task.
1140 * These objects tell the compiler which temps need to be
1143 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1144 MethodDescriptor md=fm.getMethod();
1145 TaskDescriptor task=fm.getTask();
1146 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1147 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1149 paramstable.put(lb, objectparams);
1150 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1151 } else if (md!=null)
1152 paramstable.put(md, objectparams);
1154 paramstable.put(task, objectparams);
1156 for(int i=0; i<fm.numParameters(); i++) {
1157 TempDescriptor temp=fm.getParameter(i);
1158 TypeDescriptor type=temp.getType();
1159 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1160 objectparams.addPtr(temp);
1162 objectparams.addPrim(temp);
1163 if(lb!=null&&saveset.contains(temp)) {
1164 backuptable.get(lb).put(temp, temp.createNew());
1168 for(int i=0; i<fm.numTags(); i++) {
1169 TempDescriptor temp=fm.getTag(i);
1170 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1171 objectparams.addPtr(temp);
1173 objectparams.addPrim(temp);
1176 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1178 tempstable.put(lb, objecttemps);
1180 tempstable.put(md, objecttemps);
1182 tempstable.put(task, objecttemps);
1184 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1185 FlatNode fn=(FlatNode)nodeit.next();
1186 TempDescriptor[] writes=fn.writesTemps();
1187 for(int i=0; i<writes.length; i++) {
1188 TempDescriptor temp=writes[i];
1189 TypeDescriptor type=temp.getType();
1190 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1191 objecttemps.addPtr(temp);
1193 objecttemps.addPrim(temp);
1194 if(lb!=null&&saveset.contains(temp)&&
1195 !backuptable.get(lb).containsKey(temp))
1196 backuptable.get(lb).put(temp, temp.createNew());
1200 /* Create backup temps */
1202 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1203 TempDescriptor tmp=tmpit.next();
1204 TypeDescriptor type=tmp.getType();
1205 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1206 objecttemps.addPtr(tmp);
1208 objecttemps.addPrim(tmp);
1210 /* Create temp to hold revert table */
1211 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1212 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1213 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1214 objecttemps.addPtr(reverttmp);
1216 objecttemps.addPrim(reverttmp);
1217 reverttable.put(lb, reverttmp);
1222 /** This method outputs the following information about classes
1224 * (1) For classes, what are the locations of pointers.
1225 * (2) For arrays, does the array contain pointers or primitives.
1226 * (3) For classes, does the class contain flags.
1229 private void generateLayoutStructs(PrintWriter output) {
1230 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1231 while(it.hasNext()) {
1232 ClassDescriptor cn=(ClassDescriptor)it.next();
1233 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1234 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1236 while(allit.hasNext()) {
1237 FieldDescriptor fd=(FieldDescriptor)allit.next();
1238 TypeDescriptor type=fd.getType();
1239 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1244 output.print(count);
1245 allit=cn.getFieldTable().getAllDescriptorsIterator();
1246 while(allit.hasNext()) {
1247 FieldDescriptor fd=(FieldDescriptor)allit.next();
1248 TypeDescriptor type=fd.getType();
1249 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1252 output.println(",");
1253 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1256 output.println("};");
1258 output.println("unsigned INTPTR * pointerarray[]={");
1259 boolean needcomma=false;
1260 for(int i=0; i<state.numClasses(); i++) {
1261 ClassDescriptor cn=cdarray[i];
1263 output.println(",");
1266 output.print(cn.getSafeSymbol()+"_pointers");
1268 output.print("NULL");
1272 for(int i=0; i<state.numArrays(); i++) {
1274 output.println(", ");
1275 TypeDescriptor tdelement=arraytable[i].dereference();
1276 if (tdelement.isArray()||tdelement.isClass())
1277 output.print("((unsigned INTPTR *)1)");
1283 output.println("};");
1285 output.println("int hasflags[]={");
1286 for(int i=0; i<state.numClasses(); i++) {
1287 ClassDescriptor cn=cdarray[i];
1289 output.println(", ");
1291 if ((cn != null) && (cn.hasFlags()))
1296 output.println("};");
1299 /** Print out table to give us supertypes */
1300 private void generateSuperTypeTable(PrintWriter output) {
1301 output.println("int supertypes[]={");
1302 boolean needcomma=false;
1303 for(int i=0; i<state.numClasses(); i++) {
1304 ClassDescriptor cn=cdarray[i];
1306 output.println(",");
1308 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1309 ClassDescriptor cdsuper=cn.getSuperDesc();
1310 output.print(cdsuper.getId());
1314 output.println("};");
1317 /** Force consistent field ordering between inherited classes. */
1319 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1321 ClassDescriptor sp=cn.getSuperDesc();
1323 printClassStruct(sp, classdefout);
1325 if (!fieldorder.containsKey(cn)) {
1326 Vector fields=new Vector();
1327 fieldorder.put(cn,fields);
1328 Vector fieldvec=cn.getFieldVec();
1329 for(int i=0;i<fieldvec.size();i++) {
1330 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1331 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1335 Vector fields=(Vector)fieldorder.get(cn);
1337 for(int i=0; i<fields.size(); i++) {
1338 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1339 if (fd.getType().isClass()||fd.getType().isArray())
1340 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1342 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1347 /* Map flags to integers consistently between inherited
1350 protected void mapFlags(ClassDescriptor cn) {
1351 ClassDescriptor sp=cn.getSuperDesc();
1355 if (!flagorder.containsKey(cn)) {
1356 Hashtable flags=new Hashtable();
1357 flagorder.put(cn,flags);
1359 Hashtable superflags=(Hashtable)flagorder.get(sp);
1360 Iterator superflagit=superflags.keySet().iterator();
1361 while(superflagit.hasNext()) {
1362 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1363 Integer number=(Integer)superflags.get(fd);
1364 flags.put(fd, number);
1365 if ((number.intValue()+1)>max)
1366 max=number.intValue()+1;
1370 Iterator flagit=cn.getFlags();
1371 while(flagit.hasNext()) {
1372 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1373 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1374 flags.put(fd, new Integer(max++));
1380 /** This function outputs (1) structures that parameters are
1381 * passed in (when PRECISE GC is enabled) and (2) function
1382 * prototypes for the methods */
1384 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1385 /* Output class structure */
1386 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1387 classdefout.println(" int type;");
1388 if (state.EVENTMONITOR) {
1389 classdefout.println(" int objuid;");
1392 classdefout.println(" pthread_t tid;");
1393 classdefout.println(" void * lockentry;");
1394 classdefout.println(" int lockcount;");
1398 classdefout.println(" int flag;");
1399 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1400 classdefout.println(" void * flagptr;");
1401 } else if (state.MULTICORE) {
1402 classdefout.println(" int version;");
1403 classdefout.println(" int * lock;"); // lock entry for this obj
1404 classdefout.println(" int mutex;");
1405 classdefout.println(" int lockcount;");
1406 if(state.MULTICOREGC) {
1407 classdefout.println(" int marked;");
1410 if (state.OPTIONAL) {
1411 classdefout.println(" int numfses;");
1412 classdefout.println(" int * fses;");
1415 printClassStruct(cn, classdefout);
1416 classdefout.println("};\n");
1418 if (state.DSM||state.SINGLETM) {
1419 /* Cycle through LocalityBindings */
1420 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1421 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1423 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1424 LocalityBinding lb=lbit.next();
1425 MethodDescriptor md=lb.getMethod();
1426 if (md.getModifiers().isNative()) {
1427 //make sure we only print a native method once
1428 if (nativemethods.contains(md)) {
1429 FlatMethod fm=state.getMethodFlat(md);
1430 generateTempStructs(fm, lb);
1433 nativemethods.add(md);
1435 generateMethod(cn, md, lb, headersout, output);
1438 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1439 MethodDescriptor md=(MethodDescriptor)methodit.next();
1440 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1441 //Need to build param structure for library code
1442 FlatMethod fm=state.getMethodFlat(md);
1443 generateTempStructs(fm, null);
1444 generateMethodParam(cn, md, null, output);
1449 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1450 MethodDescriptor md=(MethodDescriptor)methodit.next();
1451 generateMethod(cn, md, null, headersout, output);
1455 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1456 /* Output parameter structure */
1457 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1458 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1459 if ((state.DSM||state.SINGLETM)&&lb!=null)
1460 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1462 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1463 output.println(" INTPTR size;");
1464 output.println(" void * next;");
1465 for(int i=0; i<objectparams.numPointers(); i++) {
1466 TempDescriptor temp=objectparams.getPointer(i);
1467 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1469 output.println("};\n");
1473 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1474 FlatMethod fm=state.getMethodFlat(md);
1475 generateTempStructs(fm, lb);
1477 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1478 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1480 generateMethodParam(cn, md, lb, output);
1482 /* Output temp structure */
1483 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1484 if (state.DSM||state.SINGLETM)
1485 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1487 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1488 output.println(" INTPTR size;");
1489 output.println(" void * next;");
1490 for(int i=0; i<objecttemps.numPointers(); i++) {
1491 TempDescriptor temp=objecttemps.getPointer(i);
1492 if (temp.getType().isNull())
1493 output.println(" void * "+temp.getSafeSymbol()+";");
1495 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1497 output.println("};\n");
1500 /********* Output method declaration ***********/
1501 if (state.DSM||state.SINGLETM) {
1502 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1504 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1506 /* First the return type */
1507 if (md.getReturnType()!=null) {
1508 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1509 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1511 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1513 //catch the constructor case
1514 headersout.print("void ");
1516 /* Next the method name */
1517 if (state.DSM||state.SINGLETM) {
1518 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1520 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1522 boolean printcomma=false;
1523 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1524 if (state.DSM||state.SINGLETM) {
1525 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1527 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1531 /* Output parameter list*/
1532 for(int i=0; i<objectparams.numPrimitives(); i++) {
1533 TempDescriptor temp=objectparams.getPrimitive(i);
1535 headersout.print(", ");
1537 if (temp.getType().isClass()||temp.getType().isArray())
1538 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1540 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1542 headersout.println(");\n");
1546 /** This function outputs (1) structures that parameters are
1547 * passed in (when PRECISE GC is enabled) and (2) function
1548 * prototypes for the tasks */
1550 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1551 /* Cycle through tasks */
1552 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1554 while(taskit.hasNext()) {
1555 /* Classify parameters */
1556 TaskDescriptor task=(TaskDescriptor)taskit.next();
1557 FlatMethod fm=state.getMethodFlat(task);
1558 generateTempStructs(fm, null);
1560 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1561 TempObject objecttemps=(TempObject) tempstable.get(task);
1563 /* Output parameter structure */
1564 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1565 output.println("struct "+task.getSafeSymbol()+"_params {");
1567 output.println(" INTPTR 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(" INTPTR 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+"={");
1745 output.print(objecttemp.numPointers()+",");
1746 output.print(paramsprefix);
1747 for(int j=0; j<objecttemp.numPointers(); j++)
1748 output.print(", NULL");
1749 output.println("};");
1752 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1753 TempDescriptor td=objecttemp.getPrimitive(i);
1754 TypeDescriptor type=td.getType();
1756 output.println(" void * "+td.getSafeSymbol()+";");
1757 else if (type.isClass()||type.isArray())
1758 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1760 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1765 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1766 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1767 if( callerSESEplaceholder != mlpa.getMainSESE() ) {
1768 // declare variables for naming static SESE's
1769 output.println(" /* static SESE names */");
1770 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1771 while( pItr.hasNext() ) {
1772 SESEandAgePair p = pItr.next();
1773 output.println(" void* "+p+";");
1776 // declare variables for tracking dynamic sources
1777 output.println(" /* dynamic variable sources */");
1778 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1779 while( dynSrcItr.hasNext() ) {
1780 TempDescriptor dynSrcVar = dynSrcItr.next();
1781 output.println(" void* "+dynSrcVar+"_srcSESE;");
1782 output.println(" int "+dynSrcVar+"_srcOffset;");
1787 // set up related allocation sites's waiting queues
1789 output.println(" /* set up waiting queues */");
1790 output.println(" int numRelatedWaitingQueue=0;");
1791 output.println(" int waitingQueueItemID=0;");
1792 ConflictGraph graph=null;
1793 graph=mlpa.getConflictGraphResults().get(fm);
1795 HashSet<SESELock> lockSet=mlpa.getConflictGraphLockMap().get(graph);
1797 if(lockSet.size()>0){
1798 output.println(" numRelatedWaitingQueue="+lockSet.size()+";");
1799 output.println(" seseCaller->numRelatedWaitingQueue=numRelatedWaitingQueue;");
1800 output.println(" seseCaller->allocSiteArray=mlpCreateAllocSiteArray(numRelatedWaitingQueue);");
1802 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1803 SESELock seseLock = (SESELock) iterator.next();
1804 output.println(" seseCaller->allocSiteArray["+idx+"].id="+seseLock.getID()+";");
1814 /* Check to see if we need to do a GC if this is a
1815 * multi-threaded program...*/
1817 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1818 || this.state.MULTICOREGC) {
1819 //Don't bother if we aren't in recursive methods...The loops case will catch it
1820 if (callgraph.getAllMethods(md).contains(md)) {
1821 if (state.DSM&&lb.isAtomic())
1822 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1823 else if (this.state.MULTICOREGC) {
1824 output.println("if(gcflag) gc("+localsprefixaddr+");");
1826 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1831 generateCode(fm.getNext(0), fm, lb, null, output, true);
1833 output.println("}\n\n");
1837 protected void initializeSESE( FlatSESEEnterNode fsen ) {
1839 FlatMethod fm = fsen.getfmEnclosing();
1840 MethodDescriptor md = fm.getMethod();
1841 ClassDescriptor cn = md.getClassDesc();
1844 // Creates bogus method descriptor to index into tables
1845 Modifiers modBogus = new Modifiers();
1846 MethodDescriptor mdBogus =
1847 new MethodDescriptor( modBogus,
1848 new TypeDescriptor( TypeDescriptor.VOID ),
1849 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1852 mdBogus.setClassDesc( fsen.getcdEnclosing() );
1853 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1854 fsen.setfmBogus( fmBogus );
1855 fsen.setmdBogus( mdBogus );
1857 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1858 inSetAndOutSet.addAll( fsen.getInVarSet() );
1859 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1861 // Build paramsobj for bogus method descriptor
1862 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
1863 paramstable.put( mdBogus, objectparams );
1865 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1866 while( itr.hasNext() ) {
1867 TempDescriptor temp = itr.next();
1868 TypeDescriptor type = temp.getType();
1869 if( type.isPtr() ) {
1870 objectparams.addPtr( temp );
1872 objectparams.addPrim( temp );
1876 // Build normal temp object for bogus method descriptor
1877 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
1878 tempstable.put( mdBogus, objecttemps );
1880 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
1881 FlatNode fn = (FlatNode)nodeit.next();
1882 TempDescriptor[] writes = fn.writesTemps();
1884 for( int i = 0; i < writes.length; i++ ) {
1885 TempDescriptor temp = writes[i];
1886 TypeDescriptor type = temp.getType();
1888 if( type.isPtr() ) {
1889 objecttemps.addPtr( temp );
1891 objecttemps.addPrim( temp );
1897 protected void generateMethodSESE(FlatSESEEnterNode fsen,
1899 PrintWriter outputStructs,
1900 PrintWriter outputMethHead,
1901 PrintWriter outputMethods
1904 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
1905 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
1907 // generate locals structure
1908 outputStructs.println("struct "+
1909 fsen.getcdEnclosing().getSafeSymbol()+
1910 fsen.getmdBogus().getSafeSymbol()+"_"+
1911 fsen.getmdBogus().getSafeMethodDescriptor()+
1913 outputStructs.println(" INTPTR size;");
1914 outputStructs.println(" void * next;");
1915 for(int i=0; i<objecttemps.numPointers(); i++) {
1916 TempDescriptor temp=objecttemps.getPointer(i);
1918 if( fsen.getPrettyIdentifier().equals( "calc" ) ) {
1919 System.out.println( " got a pointer "+temp );
1922 if (temp.getType().isNull())
1923 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1925 outputStructs.println(" struct "+
1926 temp.getType().getSafeSymbol()+" * "+
1927 temp.getSafeSymbol()+";");
1929 outputStructs.println("};\n");
1932 // generate the SESE record structure
1933 outputStructs.println(fsen.getSESErecordName()+" {");
1935 // data common to any SESE, and it must be placed first so
1936 // a module that doesn't know what kind of SESE record this
1937 // is can cast the pointer to a common struct
1938 outputStructs.println(" SESEcommon common;");
1940 // then garbage list stuff
1941 outputStructs.println(" INTPTR size;");
1942 outputStructs.println(" void * next;");
1944 // in-set source tracking
1945 // in-vars that are READY come from parent, don't need anything
1946 // stuff STATIC needs a custom SESE pointer for each age pair
1947 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
1948 while( itrStaticInVarSrcs.hasNext() ) {
1949 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
1950 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
1953 // DYNAMIC stuff needs a source SESE ptr and offset
1954 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
1955 while( itrDynInVars.hasNext() ) {
1956 TempDescriptor dynInVar = itrDynInVars.next();
1957 outputStructs.println(" void* "+dynInVar+"_srcSESE;");
1958 outputStructs.println(" int "+dynInVar+"_srcOffset;");
1961 // space for all in and out set primitives
1962 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1963 inSetAndOutSet.addAll( fsen.getInVarSet() );
1964 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1966 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
1968 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1969 while( itr.hasNext() ) {
1970 TempDescriptor temp = itr.next();
1971 TypeDescriptor type = temp.getType();
1972 if( !type.isPtr() ) {
1973 inSetAndOutSetPrims.add( temp );
1977 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
1978 while( itrPrims.hasNext() ) {
1979 TempDescriptor temp = itrPrims.next();
1980 TypeDescriptor type = temp.getType();
1981 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
1984 for(int i=0; i<objectparams.numPointers(); i++) {
1985 TempDescriptor temp=objectparams.getPointer(i);
1986 if (temp.getType().isNull())
1987 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1989 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1992 outputStructs.println("};\n");
1995 // write method declaration to header file
1996 outputMethHead.print("void ");
1997 outputMethHead.print(fsen.getSESEmethodName()+"(");
1998 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
1999 outputMethHead.println(");\n");
2002 generateFlatMethodSESE( fsen.getfmBogus(),
2003 fsen.getcdEnclosing(),
2009 private void generateFlatMethodSESE(FlatMethod fm,
2011 FlatSESEEnterNode fsen,
2012 FlatSESEExitNode seseExit,
2016 MethodDescriptor md=fm.getMethod();
2018 output.print("void ");
2019 output.print(fsen.getSESEmethodName()+"(");
2020 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
2021 output.println("){\n");
2023 TempObject objecttemp=(TempObject) tempstable.get(md);
2025 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2026 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2027 output.print(objecttemp.numPointers()+",");
2028 output.print("(void*) &("+paramsprefix+"->size)");
2029 for(int j=0; j<objecttemp.numPointers(); j++)
2030 output.print(", NULL");
2031 output.println("};");
2034 output.println(" /* regular local primitives */");
2035 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2036 TempDescriptor td=objecttemp.getPrimitive(i);
2037 TypeDescriptor type=td.getType();
2039 output.println(" void * "+td.getSafeSymbol()+";");
2040 else if (type.isClass()||type.isArray())
2041 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2043 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2047 // declare variables for naming static SESE's
2048 output.println(" /* static SESE names */");
2049 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
2050 while( pItr.hasNext() ) {
2051 SESEandAgePair p = pItr.next();
2052 output.println(" void* "+p+";");
2055 // declare variables for tracking dynamic sources
2056 output.println(" /* dynamic variable sources */");
2057 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
2058 while( dynSrcItr.hasNext() ) {
2059 TempDescriptor dynSrcVar = dynSrcItr.next();
2060 output.println(" void* "+dynSrcVar+"_srcSESE;");
2061 output.println(" int "+dynSrcVar+"_srcOffset;");
2064 // declare local temps for in-set primitives, and if it is
2065 // a ready-source variable, get the value from the record
2066 output.println(" /* local temps for in-set primitives */");
2067 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2068 while( itrInSet.hasNext() ) {
2069 TempDescriptor temp = itrInSet.next();
2070 TypeDescriptor type = temp.getType();
2071 if( !type.isPtr() ) {
2072 if( fsen.getReadyInVarSet().contains( temp ) ) {
2073 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2075 output.println(" "+type+" "+temp+";");
2080 // declare local temps for out-set primitives if its not already
2081 // in the in-set, and it's value will get written so no problem
2082 output.println(" /* local temp for out-set prim, not already in the in-set */");
2083 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2084 while( itrOutSet.hasNext() ) {
2085 TempDescriptor temp = itrOutSet.next();
2086 TypeDescriptor type = temp.getType();
2087 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2088 output.println(" "+type+" "+temp+";");
2092 // set up related allocation sites's waiting queues
2094 output.println(" /* set up waiting queues */");
2095 output.println(" int numRelatedWaitingQueue=0;");
2096 output.println(" int waitingQueueItemID=0;");
2097 ConflictGraph graph=null;
2098 graph=mlpa.getConflictGraphResults().get(fsen);
2099 if (graph != null) {
2100 output.println(" {");
2101 output.println(" SESEcommon* parentCommon = &(___params___->common);");
2102 HashSet<SESELock> lockSet=mlpa.getConflictGraphLockMap().get(graph);
2104 if (lockSet.size() > 0) {
2105 output.println(" numRelatedWaitingQueue=" + lockSet.size()
2108 .println(" parentCommon->numRelatedWaitingQueue=numRelatedWaitingQueue;");
2110 .println(" parentCommon->allocSiteArray=mlpCreateAllocSiteArray(numRelatedWaitingQueue);");
2112 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
2113 SESELock seseLock = (SESELock) iterator.next();
2114 output.println(" parentCommon->allocSiteArray[" + idx
2115 + "].id=" + seseLock.getID() + ";");
2120 output.println(" }");
2123 // copy in-set into place, ready vars were already
2124 // copied when the SESE was issued
2125 Iterator<TempDescriptor> tempItr;
2127 // static vars are from a known SESE
2128 tempItr = fsen.getStaticInVarSet().iterator();
2129 while( tempItr.hasNext() ) {
2130 TempDescriptor temp = tempItr.next();
2131 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2132 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2134 // can't grab something from this source until it is done
2135 output.println(" {");
2136 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+srcPair+";" );
2137 output.println(" pthread_mutex_lock( &(com->lock) );");
2138 output.println(" while( com->doneExecuting == FALSE ) {");
2139 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2140 output.println(" }");
2141 output.println(" pthread_mutex_unlock( &(com->lock) );");
2143 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2144 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2146 output.println(" }");
2149 // dynamic vars come from an SESE and src
2150 tempItr = fsen.getDynamicInVarSet().iterator();
2151 while( tempItr.hasNext() ) {
2152 TempDescriptor temp = tempItr.next();
2153 TypeDescriptor type = temp.getType();
2155 // go grab it from the SESE source
2156 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2158 // gotta wait until the source is done
2159 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+temp+"_srcSESE;" );
2160 output.println(" pthread_mutex_lock( &(com->lock) );");
2161 output.println(" while( com->doneExecuting == FALSE ) {");
2162 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2163 output.println(" }");
2164 output.println(" pthread_mutex_unlock( &(com->lock) );");
2167 if( type.isNull() ) {
2169 } else if( type.isClass() || type.isArray() ) {
2170 typeStr = "struct "+type.getSafeSymbol()+"*";
2172 typeStr = type.getSafeSymbol();
2175 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2176 " = *(("+typeStr+"*) ("+
2177 paramsprefix+"->"+temp+"_srcSESE + "+
2178 paramsprefix+"->"+temp+"_srcOffset));");
2180 // or if the source was our parent, its in the record to grab
2181 output.println(" } else {");
2182 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2183 " = "+paramsprefix+"->"+temp+";");
2184 output.println(" }");
2187 // Check to see if we need to do a GC if this is a
2188 // multi-threaded program...
2189 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2190 //Don't bother if we aren't in recursive methods...The loops case will catch it
2191 if (callgraph.getAllMethods(md).contains(md)) {
2192 if(this.state.MULTICOREGC) {
2193 output.println("if(gcflag) gc("+localsprefixaddr+");");
2195 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2200 // initialize thread-local var to a non-zero, invalid address
2201 output.println(" seseCaller = (SESEcommon*) 0x2;");
2202 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2203 exitset.add(seseExit);
2204 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2205 output.println("}\n\n");
2210 // when a new mlp thread is created for an issued SESE, it is started
2211 // by running this method which blocks on a cond variable until
2212 // it is allowed to transition to execute. Then a case statement
2213 // allows it to invoke the method with the proper SESE body, and after
2214 // exiting the SESE method, executes proper SESE exit code before the
2215 // thread can be destroyed
2216 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2217 PrintWriter outmethod
2220 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2221 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2222 outmethod.println( " int status;");
2223 outmethod.println( " char errmsg[128];");
2225 // generate a case for each SESE class that can be invoked
2226 outmethod.println( " switch( *((int*)seseRecord) ) {");
2227 outmethod.println( " ");
2228 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
2229 FlatSESEEnterNode fsen = seseit.next();
2231 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2232 outmethod.println( " case "+fsen.getIdentifier()+":");
2233 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2235 if( fsen.equals( mlpa.getMainSESE() ) ) {
2236 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2237 outmethod.println( " exit( 0 );");
2240 outmethod.println( " break;");
2241 outmethod.println( "");
2244 // default case should never be taken, error out
2245 outmethod.println( " default:");
2246 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2247 outmethod.println( " exit(-30);");
2248 outmethod.println( " break;");
2249 outmethod.println( " }");
2250 outmethod.println( " return NULL;");
2251 outmethod.println( "}\n\n");
2255 protected void generateCode(FlatNode first,
2258 Set<FlatNode> stopset,
2259 PrintWriter output, boolean firstpass) {
2261 /* Assign labels to FlatNode's if necessary.*/
2263 Hashtable<FlatNode, Integer> nodetolabel;
2265 if (state.DELAYCOMP&&!firstpass)
2266 nodetolabel=dcassignLabels(first, stopset);
2268 nodetolabel=assignLabels(first, stopset);
2270 Set<FlatNode> storeset=null;
2271 HashSet<FlatNode> genset=null;
2272 HashSet<FlatNode> refset=null;
2273 Set<FlatNode> unionset=null;
2275 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2276 storeset=delaycomp.livecode(lb);
2277 genset=new HashSet<FlatNode>();
2278 if (state.STMARRAY&&!state.DUALVIEW) {
2279 refset=new HashSet<FlatNode>();
2280 refset.addAll(delaycomp.getDeref(lb));
2281 refset.removeAll(delaycomp.getCannotDelay(lb));
2282 refset.removeAll(delaycomp.getOther(lb));
2285 genset.addAll(delaycomp.getCannotDelay(lb));
2286 genset.addAll(delaycomp.getOther(lb));
2288 genset.addAll(delaycomp.getNotReady(lb));
2289 if (state.STMARRAY&&!state.DUALVIEW) {
2290 genset.removeAll(refset);
2293 unionset=new HashSet<FlatNode>();
2294 unionset.addAll(storeset);
2295 unionset.addAll(genset);
2296 if (state.STMARRAY&&!state.DUALVIEW)
2297 unionset.addAll(refset);
2300 /* Do the actual code generation */
2301 FlatNode current_node=null;
2302 HashSet tovisit=new HashSet();
2303 HashSet visited=new HashSet();
2305 tovisit.add(first.getNext(0));
2308 while(current_node!=null||!tovisit.isEmpty()) {
2309 if (current_node==null) {
2310 current_node=(FlatNode)tovisit.iterator().next();
2311 tovisit.remove(current_node);
2312 } else if (tovisit.contains(current_node)) {
2313 tovisit.remove(current_node);
2315 visited.add(current_node);
2316 if (nodetolabel.containsKey(current_node)) {
2317 output.println("L"+nodetolabel.get(current_node)+":");
2319 if (state.INSTRUCTIONFAILURE) {
2320 if (state.THREAD||state.DSM||state.SINGLETM) {
2321 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2323 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2325 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2327 if (!state.DELAYCOMP||firstpass) {
2328 generateFlatNode(fm, lb, current_node, output);
2330 //store primitive variables in out set
2331 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2332 Set<TempDescriptor> liveout=ar.liveout;
2333 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2334 TempDescriptor tmp=tmpit.next();
2335 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2338 if (state.MLP && stopset!=null) {
2339 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2340 assert current_node instanceof FlatSESEExitNode;
2341 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2342 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2343 assert fsen.getFlatExit().equals( fsxn );
2344 assert fsxn.getFlatEnter().equals( fsen );
2346 if (current_node.kind()!=FKind.FlatReturnNode) {
2347 output.println(" return;");
2350 } else if(current_node.numNext()==1) {
2353 current_node.kind()==FKind.FlatSESEEnterNode &&
2354 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2356 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2357 generateFlatNode(fm, lb, current_node, output);
2358 nextnode=fsen.getFlatExit().getNext(0);
2359 } else if (state.DELAYCOMP) {
2360 boolean specialprimitive=false;
2361 //skip literals...no need to add extra overhead
2362 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2363 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2364 if (!typedesc.isClass()&&!typedesc.isArray()) {
2365 specialprimitive=true;
2369 if (genset==null||genset.contains(current_node)||specialprimitive)
2370 generateFlatNode(fm, lb, current_node, output);
2371 if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2372 //need to acquire lock
2373 handleArrayDeref(fm, lb, current_node, output, firstpass);
2375 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2376 TempDescriptor wrtmp=current_node.writesTemps()[0];
2378 //need to store value written by previous node
2379 if (wrtmp.getType().isPtr()) {
2380 //only lock the objects that may actually need locking
2381 if (recorddc.getNeedTrans(lb, current_node)&&
2382 (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2383 wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2384 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2386 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2389 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2392 //need to read value read by previous node
2393 if (wrtmp.getType().isPtr()) {
2394 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2396 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");
2400 nextnode=current_node.getNext(0);
2403 generateFlatNode(fm, lb, current_node, output);
2404 nextnode=current_node.getNext(0);
2406 if (visited.contains(nextnode)) {
2407 output.println("goto L"+nodetolabel.get(nextnode)+";");
2410 current_node=nextnode;
2411 } else if (current_node.numNext()==2) {
2413 if (state.DELAYCOMP) {
2414 boolean computeside=false;
2416 //need to record which way it should go
2417 if (genset==null||genset.contains(current_node)) {
2418 if (storeset!=null&&storeset.contains(current_node)) {
2419 //need to store which way branch goes
2420 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2422 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2424 //which side to execute
2428 if (genset.contains(current_node)) {
2429 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2430 } else if (storeset.contains(current_node)) {
2432 branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2434 //which side to execute
2439 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2441 if (leftset.size()==0)
2443 if (visited.contains(current_node.getNext(branch))) {
2444 //already visited -- build jump
2445 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2448 current_node=current_node.getNext(branch);
2451 if (!visited.contains(current_node.getNext(1)))
2452 tovisit.add(current_node.getNext(1));
2453 if (visited.contains(current_node.getNext(0))) {
2454 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2457 current_node=current_node.getNext(0);
2461 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2462 if (!visited.contains(current_node.getNext(1)))
2463 tovisit.add(current_node.getNext(1));
2464 if (visited.contains(current_node.getNext(0))) {
2465 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2468 current_node=current_node.getNext(0);
2470 } else throw new Error();
2474 protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2475 if (fn.kind()==FKind.FlatSetElementNode) {
2476 FlatSetElementNode fsen=(FlatSetElementNode) fn;
2477 String dst=generateTemp(fm, fsen.getDst(), lb);
2478 String src=generateTemp(fm, fsen.getSrc(), lb);
2479 String index=generateTemp(fm, fsen.getIndex(), lb);
2480 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2482 if (elementtype.isArray()||elementtype.isClass())
2485 type=elementtype.getSafeSymbol()+" ";
2487 output.println("STOREARRAY("+dst+","+index+","+type+")");
2489 output.println("{");
2490 output.println(" struct ArrayObject *array;");
2491 output.println(" int index;");
2492 output.println(" RESTOREARRAY(array,index);");
2493 output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2494 output.println("}");
2496 } else if (fn.kind()==FKind.FlatElementNode) {
2497 FlatElementNode fen=(FlatElementNode) fn;
2498 String src=generateTemp(fm, fen.getSrc(), lb);
2499 String index=generateTemp(fm, fen.getIndex(), lb);
2500 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2501 String dst=generateTemp(fm, fen.getDst(), lb);
2503 if (elementtype.isArray()||elementtype.isClass())
2506 type=elementtype.getSafeSymbol()+" ";
2508 output.println("STOREARRAY("+src+","+index+","+type+")");
2510 output.println("{");
2511 output.println(" struct ArrayObject *array;");
2512 output.println(" int index;");
2513 output.println(" RESTOREARRAY(array,index);");
2514 output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2515 output.println("}");
2519 /** Special label assignment for delaycomputation */
2520 protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2521 HashSet tovisit=new HashSet();
2522 HashSet visited=new HashSet();
2524 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2526 //Label targets of branches
2527 Set<FlatNode> targets=branchanalysis.getTargets();
2528 for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2529 nodetolabel.put(it.next(), new Integer(labelindex++));
2534 /*Assign labels first. A node needs a label if the previous
2535 * node has two exits or this node is a join point. */
2537 while(!tovisit.isEmpty()) {
2538 FlatNode fn=(FlatNode)tovisit.iterator().next();
2543 if(lastset!=null&&lastset.contains(fn)) {
2544 // if last is not null and matches, don't go
2545 // any further for assigning labels
2549 for(int i=0; i<fn.numNext(); i++) {
2550 FlatNode nn=fn.getNext(i);
2553 //1) Edge >1 of node
2554 nodetolabel.put(nn,new Integer(labelindex++));
2556 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2560 nodetolabel.put(nn,new Integer(labelindex++));
2568 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2569 return assignLabels(first, null);
2572 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2573 HashSet tovisit=new HashSet();
2574 HashSet visited=new HashSet();
2576 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2579 /*Assign labels first. A node needs a label if the previous
2580 * node has two exits or this node is a join point. */
2582 while(!tovisit.isEmpty()) {
2583 FlatNode fn=(FlatNode)tovisit.iterator().next();
2588 if(lastset!=null&&lastset.contains(fn)) {
2589 // if last is not null and matches, don't go
2590 // any further for assigning labels
2594 for(int i=0; i<fn.numNext(); i++) {
2595 FlatNode nn=fn.getNext(i);
2598 //1) Edge >1 of node
2599 nodetolabel.put(nn,new Integer(labelindex++));
2601 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2605 nodetolabel.put(nn,new Integer(labelindex++));
2613 /** Generate text string that corresponds to the TempDescriptor td. */
2614 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2615 MethodDescriptor md=fm.getMethod();
2616 TaskDescriptor task=fm.getTask();
2617 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2619 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2620 //System.out.println("generateTemp returns " + td.getSafeSymbol());
2621 return td.getSafeSymbol();
2624 if (objecttemps.isLocalPtr(td)) {
2625 return localsprefixderef+td.getSafeSymbol();
2628 if (objecttemps.isParamPtr(td)) {
2629 return paramsprefix+"->"+td.getSafeSymbol();
2635 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2637 // insert pre-node actions from the code plan
2640 CodePlan cp = mlpa.getCodePlan( fn );
2643 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2645 // for each sese and age pair that this parent statement
2646 // must stall on, take that child's stall semaphore, the
2647 // copying of values comes after the statement
2648 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2649 while( vstItr.hasNext() ) {
2650 VariableSourceToken vst = vstItr.next();
2652 SESEandAgePair p = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2654 output.println(" {");
2655 output.println(" SESEcommon* common = (SESEcommon*) "+p+";");
2657 output.println(" pthread_mutex_lock( &(common->lock) );");
2658 output.println(" while( common->doneExecuting == FALSE ) {");
2659 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2660 output.println(" }");
2661 output.println(" pthread_mutex_unlock( &(common->lock) );");
2663 //output.println(" psem_take( &(common->stallSem) );");
2665 // copy things we might have stalled for
2666 output.println(" "+p.getSESE().getSESErecordName()+"* child = ("+
2667 p.getSESE().getSESErecordName()+"*) "+p+";");
2669 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2670 while( tdItr.hasNext() ) {
2671 TempDescriptor td = tdItr.next();
2672 FlatMethod fmContext;
2673 if( currentSESE.getIsCallerSESEplaceholder() ) {
2674 fmContext = currentSESE.getfmEnclosing();
2676 fmContext = currentSESE.getfmBogus();
2678 output.println(" "+generateTemp( fmContext, td, null )+
2679 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2682 output.println(" }");
2685 // for each variable with a dynamic source, stall just for that variable
2686 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2687 while( dynItr.hasNext() ) {
2688 TempDescriptor dynVar = dynItr.next();
2690 // only stall if the dynamic source is not yourself, denoted by src==NULL
2691 // otherwise the dynamic write nodes will have the local var up-to-date
2692 output.println(" {");
2693 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2694 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2695 output.println(" psem_take( &(common->stallSem) );");
2697 FlatMethod fmContext;
2698 if( currentSESE.getIsCallerSESEplaceholder() ) {
2699 fmContext = currentSESE.getfmEnclosing();
2701 fmContext = currentSESE.getfmBogus();
2703 output.println(" "+generateTemp( fmContext, dynVar, null )+
2704 " = *(("+dynVar.getType()+"*) ("+
2705 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2707 output.println(" }");
2708 output.println(" }");
2711 // for each assignment of a variable to rhs that has a dynamic source,
2712 // copy the dynamic sources
2713 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2714 while( dynAssignItr.hasNext() ) {
2715 Map.Entry me = (Map.Entry) dynAssignItr.next();
2716 TempDescriptor lhs = (TempDescriptor) me.getKey();
2717 TempDescriptor rhs = (TempDescriptor) me.getValue();
2718 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
2719 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2722 // for each lhs that is dynamic from a non-dynamic source, set the
2723 // dynamic source vars to the current SESE
2724 dynItr = cp.getDynAssignCurr().iterator();
2725 while( dynItr.hasNext() ) {
2726 TempDescriptor dynVar = dynItr.next();
2727 output.println(" "+dynVar+"_srcSESE = NULL;");
2731 // handling stall site
2733 ParentChildConflictsMap conflictsMap=mlpa.getConflictsResults().get(fn);
2735 if (conflictsMap != null) {
2737 Set<Long> allocSet = conflictsMap
2738 .getAllocationSiteIDSetofStallSite();
2740 if (allocSet.size() > 0) {
2742 FlatNode enclosingFlatNode=null;
2743 if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
2744 enclosingFlatNode=currentSESE.getfmEnclosing();
2746 enclosingFlatNode=currentSESE;
2749 ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
2750 HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
2751 Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
2753 if(waitingElementSet.size()>0){
2754 output.println(" /* stall on parent's stall sites */");
2755 output.println(" {");
2756 output.println(" pthread_mutex_lock( &(seseCaller->lock) );");
2757 output.println(" ConflictNode* node;");
2758 output.println(" struct Queue* list=NULL;");
2759 output.println(" WaitingElement* newElement=NULL;");
2760 output.println(" struct QueueItem* newQItem=NULL;");
2761 output.println(" waitingQueueItemID++;");
2762 output.println(" psem_init( &(seseCaller->memoryStallSiteSem) );");
2763 output.println(" int qIdx;");
2764 output.println(" int takeCount=0;");
2765 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
2766 WaitingElement waitingElement = (WaitingElement) iterator.next();
2768 output.println(" qIdx=getQueueIdx(seseCaller->allocSiteArray,numRelatedWaitingQueue,"
2769 + waitingElement.getWaitingID() + ");");
2770 output.println(" if(qIdx!=-1 && !isEmpty(seseCaller->allocSiteArray[qIdx].waitingQueue)){");
2771 output.println(" list=createQueue();");
2772 for (Iterator iterator2 = waitingElement.getAllocList().iterator(); iterator2.hasNext();) {
2773 Integer allocID = (Integer) iterator2 .next();
2774 output.println(" node=mlpCreateConflictNode( "+ allocID + " );");
2775 output.println(" addNewItem(list,node);");
2777 output.println(" newElement=mlpCreateWaitingElement( "+ waitingElement.getStatus()
2778 + ", seseCaller, list, waitingQueueItemID );");
2779 output.println(" addNewItemBack(seseCaller->allocSiteArray[qIdx].waitingQueue,newElement);");
2780 output.println(" takeCount++;");
2781 output.println(" }");
2785 output.println(" pthread_mutex_unlock( &(seseCaller->lock) );");
2786 output.println(" if( takeCount>0 ){");
2787 output.println(" psem_take( &(seseCaller->memoryStallSiteSem) );");
2788 output.println(" }");
2789 output.println(" }");
2793 } // end of if (conflictsMap != null) {
2798 case FKind.FlatAtomicEnterNode:
2799 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
2802 case FKind.FlatAtomicExitNode:
2803 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
2806 case FKind.FlatInstanceOfNode:
2807 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
2810 case FKind.FlatSESEEnterNode:
2811 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
2814 case FKind.FlatSESEExitNode:
2815 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
2818 case FKind.FlatWriteDynamicVarNode:
2819 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
2822 case FKind.FlatGlobalConvNode:
2823 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
2826 case FKind.FlatTagDeclaration:
2827 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
2830 case FKind.FlatCall:
2831 generateFlatCall(fm, lb, (FlatCall) fn,output);
2834 case FKind.FlatFieldNode:
2835 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
2838 case FKind.FlatElementNode:
2839 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
2842 case FKind.FlatSetElementNode:
2843 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
2846 case FKind.FlatSetFieldNode:
2847 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
2851 generateFlatNew(fm, lb, (FlatNew) fn,output);
2854 case FKind.FlatOpNode:
2855 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
2858 case FKind.FlatCastNode:
2859 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
2862 case FKind.FlatLiteralNode:
2863 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
2866 case FKind.FlatReturnNode:
2867 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
2871 output.println("/* nop */");
2874 case FKind.FlatExit:
2875 output.println("/* exit */");
2878 case FKind.FlatBackEdge:
2879 if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
2880 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
2882 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
2883 || (this.state.MULTICOREGC)) {
2884 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
2885 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
2886 } else if(this.state.MULTICOREGC) {
2887 output.println("if (gcflag) gc("+localsprefixaddr+");");
2889 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2892 output.println("/* nop */");
2895 case FKind.FlatCheckNode:
2896 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
2899 case FKind.FlatFlagActionNode:
2900 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
2903 case FKind.FlatPrefetchNode:
2904 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
2907 case FKind.FlatOffsetNode:
2908 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
2915 // insert post-node actions from the code-plan
2917 CodePlan cp = mlpa.getCodePlan( fn );
2924 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
2925 output.println("/* FlatOffsetNode */");
2926 FieldDescriptor fd=fofn.getField();
2927 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
2928 output.println("/* offset */");
2931 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
2932 if (state.PREFETCH) {
2933 Vector oids = new Vector();
2934 Vector fieldoffset = new Vector();
2935 Vector endoffset = new Vector();
2936 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
2937 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
2938 PrefetchPair pp = (PrefetchPair) it.next();
2939 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
2940 /* Find prefetches that can generate oid */
2941 if(statusbase == LocalityAnalysis.GLOBAL) {
2942 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
2944 } else if (statusbase == LocalityAnalysis.LOCAL) {
2945 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
2952 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
2953 output.println("{");
2954 output.println("/* prefetch */");
2955 output.println("/* prefetchid_" + fpn.siteid + " */");
2956 output.println("void * prefptr;");
2957 output.println("int tmpindex;");
2959 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
2960 /*Create C code for oid array */
2961 output.print(" unsigned int oidarray_[] = {");
2962 boolean needcomma=false;
2963 for (Iterator it = oids.iterator(); it.hasNext();) {
2966 output.print(it.next());
2969 output.println("};");
2971 /*Create C code for endoffset values */
2972 output.print(" unsigned short endoffsetarry_[] = {");
2974 for (Iterator it = endoffset.iterator(); it.hasNext();) {
2977 output.print(it.next());
2980 output.println("};");
2982 /*Create C code for Field Offset Values */
2983 output.print(" short fieldarry_[] = {");
2985 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
2988 output.print(it.next());
2991 output.println("};");
2992 /* make the prefetch call to Runtime */
2993 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
2994 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
2995 output.println(" }");
2996 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
2997 output.println(" } else {");
2998 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
2999 output.println(" }");
3000 output.println("}");
3004 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
3005 short offsetcount = 0;
3009 } else if (localbase) {
3010 for(; breakindex<pp.desc.size(); breakindex++) {
3011 Descriptor desc=pp.getDescAt(breakindex);
3012 if (desc instanceof FieldDescriptor) {
3013 FieldDescriptor fd=(FieldDescriptor)desc;
3014 if (fd.isGlobal()) {
3022 if (breakindex>pp.desc.size()) //all local
3025 TypeDescriptor lasttype=pp.base.getType();
3026 String basestr=generateTemp(fm, pp.base, lb);
3028 boolean maybenull=fm.getMethod().isStatic()||
3029 !pp.base.equals(fm.getParameter(0));
3031 for(int i=0; i<breakindex; i++) {
3032 String indexcheck="";
3034 Descriptor desc=pp.getDescAt(i);
3035 if (desc instanceof FieldDescriptor) {
3036 FieldDescriptor fd=(FieldDescriptor)desc;
3038 if (!teststr.equals(""))
3040 teststr+="((prefptr="+basestr+")!=NULL)";
3041 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3043 basestr=basestr+"->"+fd.getSafeSymbol();
3046 lasttype=fd.getType();
3048 IndexDescriptor id=(IndexDescriptor)desc;
3049 indexcheck="((tmpindex=";
3050 for(int j=0; j<id.tddesc.size(); j++) {
3051 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3053 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3055 if (!teststr.equals(""))
3057 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3058 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3060 lasttype=lasttype.dereference();
3065 if (teststr.equals("")) {
3066 oid="((unsigned int)"+basestr+")";
3068 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3072 for(int i = breakindex; i < pp.desc.size(); i++) {
3073 String newfieldoffset;
3074 Object desc = pp.getDescAt(i);
3075 if(desc instanceof FieldDescriptor) {
3076 FieldDescriptor fd=(FieldDescriptor)desc;
3077 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3078 lasttype=fd.getType();
3080 newfieldoffset = "";
3081 IndexDescriptor id=(IndexDescriptor)desc;
3082 for(int j = 0; j < id.tddesc.size(); j++) {
3083 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3085 newfieldoffset += id.offset.toString();
3086 lasttype=lasttype.dereference();
3088 fieldoffset.add(newfieldoffset);
3091 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3092 base+=pp.desc.size()-breakindex;
3093 endoffset.add(new Short((short)base));
3098 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3099 if (lb!=fgcn.getLocality())
3101 /* Have to generate flat globalconv */
3102 if (fgcn.getMakePtr()) {
3104 //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3105 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3107 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3108 //need to do translation
3109 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3110 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3111 if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3112 output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3114 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3118 /* Need to convert to OID */
3119 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3120 if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3121 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3123 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3129 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3131 if (fion.getType().isArray()) {
3132 type=state.getArrayNumber(fion.getType())+state.numClasses();
3134 type=fion.getType().getClassDesc().getId();
3137 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3138 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3140 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3143 int sandboxcounter=0;
3144 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3145 /* Check to see if we need to generate code for this atomic */
3146 if (locality==null) {
3147 if (GENERATEPRECISEGC) {
3148 output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3149 output.println("stopforgc((struct garbagelist *) &___locals___);");
3150 output.println("pthread_mutex_lock(&atomiclock);");
3151 output.println("restartaftergc();");
3152 output.println("}");
3154 output.println("pthread_mutex_lock(&atomiclock);");
3159 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3163 if (state.SANDBOX) {
3164 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3165 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3168 if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3169 AtomicRecord ar=atomicmethodmap.get(faen);
3171 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3172 TempDescriptor tmp=tmpit.next();
3173 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3176 //copy outs that depend on path
3177 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3178 TempDescriptor tmp=tmpit.next();
3179 if (!ar.livein.contains(tmp))
3180 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3184 /* Backup the temps. */
3185 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3186 TempDescriptor tmp=tmpit.next();
3187 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3190 output.println("goto transstart"+faen.getIdentifier()+";");
3192 /******* Print code to retry aborted transaction *******/
3193 output.println("transretry"+faen.getIdentifier()+":");
3196 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3197 TempDescriptor tmp=tmpit.next();
3198 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3202 /********* Need to revert local object store ********/
3203 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3205 output.println("while ("+revertptr+") {");
3206 output.println("struct ___Object___ * tmpptr;");
3207 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3208 output.println("REVERT_OBJ("+revertptr+");");
3209 output.println(revertptr+"=tmpptr;");
3210 output.println("}");
3212 /******* Tell the runtime to start the transaction *******/
3214 output.println("transstart"+faen.getIdentifier()+":");
3215 if (state.SANDBOX) {
3216 output.println("transaction_check_counter=*counter_reset_pointer;");
3219 output.println("transStart();");
3221 if (state.ABORTREADERS||state.SANDBOX) {
3223 output.println("abortenabled=1;");
3224 output.println("if (_setjmp(aborttrans)) {");
3225 output.println(" goto transretry"+faen.getIdentifier()+"; }");
3229 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3230 /* Check to see if we need to generate code for this atomic */
3231 if (locality==null) {
3232 output.println("pthread_mutex_unlock(&atomiclock);");
3235 if (locality.getAtomic(lb).get(faen).intValue()>0)
3237 //store the revert list before we lose the transaction object
3240 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3241 output.println(revertptr+"=revertlist;");
3242 output.println("if (transCommit()) {");
3243 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3244 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3245 output.println("} else {");
3246 /* Need to commit local object store */
3247 output.println("while ("+revertptr+") {");
3248 output.println("struct ___Object___ * tmpptr;");
3249 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3250 output.println("COMMIT_OBJ("+revertptr+");");
3251 output.println(revertptr+"=tmpptr;");
3252 output.println("}");
3253 output.println("}");
3257 if (!state.DELAYCOMP) {
3259 output.println("if (transCommit()) {");
3260 /* Transaction aborts if it returns true */
3261 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3262 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3263 output.println("}");
3265 if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
3266 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3267 output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3269 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3270 TempDescriptor tmp=tmpit.next();
3271 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3273 } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3274 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3276 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3277 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3278 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3279 output.println("}");
3281 output.println("else {");
3282 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3283 TempDescriptor tmp=tmpit.next();
3284 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3286 output.println("}");
3288 output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3289 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3290 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3291 output.println("}");
3296 public void generateFlatSESEEnterNode( FlatMethod fm,
3298 FlatSESEEnterNode fsen,
3302 // if MLP flag is off, okay that SESE nodes are in IR graph,
3303 // just skip over them and code generates exactly the same
3308 // there may be an SESE in an unreachable method, skip over
3309 if( !mlpa.getAllSESEs().contains( fsen ) ) {
3313 // also, if we have encountered a placeholder, just skip it
3314 if( fsen.getIsCallerSESEplaceholder() ) {
3318 output.println(" {");
3320 // set up the parent
3321 if( fsen == mlpa.getMainSESE() ) {
3322 output.println(" SESEcommon* parentCommon = NULL;");
3324 if( fsen.getParent() == null ) {
3325 System.out.println( "in "+fm+", "+fsen+" has null parent" );
3327 assert fsen.getParent() != null;
3328 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3329 output.println(" SESEcommon* parentCommon = &("+paramsprefix+"->common);");
3331 //output.println(" SESEcommon* parentCommon = (SESEcommon*) peekItem( seseCallStack );");
3332 output.println(" SESEcommon* parentCommon = seseCaller;");
3336 // before doing anything, lock your own record and increment the running children
3337 if( fsen != mlpa.getMainSESE() ) {
3338 output.println(" pthread_mutex_lock( &(parentCommon->lock) );");
3339 output.println(" ++(parentCommon->numRunningChildren);");
3340 output.println(" pthread_mutex_unlock( &(parentCommon->lock) );");
3343 // just allocate the space for this record
3344 output.println(" "+fsen.getSESErecordName()+"* seseToIssue = ("+
3345 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3346 fsen.getSESErecordName()+" ) );");
3348 // and keep the thread-local sese stack up to date
3349 //output.println(" addNewItem( seseCallStack, (void*) seseToIssue);");
3351 // fill in common data
3352 output.println(" int localCount=0;");
3353 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3354 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
3356 output.println(" seseToIssue->common.forwardList = createQueue();");
3357 output.println(" seseToIssue->common.unresolvedDependencies = 10000;");
3358 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3359 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3360 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3361 output.println(" seseToIssue->common.numRunningChildren = 0;");
3362 output.println(" seseToIssue->common.parent = parentCommon;");
3364 // all READY in-vars should be copied now and be done with it
3365 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3366 while( tempItr.hasNext() ) {
3367 TempDescriptor temp = tempItr.next();
3369 // when we are issuing the main SESE or an SESE with placeholder
3370 // caller SESE as parent, generate temp child child's eclosing method,
3371 // otherwise use the parent's enclosing method as the context
3372 boolean useParentContext = false;
3374 if( fsen != mlpa.getMainSESE() ) {
3375 assert fsen.getParent() != null;
3376 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3377 useParentContext = true;
3381 if( useParentContext ) {
3382 output.println(" seseToIssue->"+temp+" = "+
3383 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3385 output.println(" seseToIssue->"+temp+" = "+
3386 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3390 // before potentially adding this SESE to other forwarding lists,
3391 // create it's lock and take it immediately
3392 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3393 output.println(" pthread_mutex_lock( &(seseToIssue->common.lock) );");
3395 // count up memory conflict dependencies,
3397 ConflictGraph graph=null;
3398 FlatSESEEnterNode parent=fsen.getParent();
3400 if(parent.isCallerSESEplaceholder){
3401 graph=mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
3403 graph=mlpa.getConflictGraphResults().get(parent);
3406 if (graph != null) {
3408 HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
3411 output.println(" /*add waiting queue element*/");
3412 output.println(" pthread_mutex_lock( &(parentCommon->lock) );");
3413 output.println(" struct Queue* newWaitingItemQueue=createQueue();");
3415 Set<WaitingElement> waitingQueueSet=graph.getWaitingElementSetBySESEID(fsen
3416 .getIdentifier(),seseLockSet);
3417 if (waitingQueueSet.size() > 0) {
3418 output.println(" {");
3419 output.println(" waitingQueueItemID++;");
3420 output.println(" ConflictNode* node;");
3421 output.println(" WaitingElement* newElement=NULL;");
3422 output.println(" struct Queue* list=NULL;");
3423 output.println(" struct QueueItem* newQItem=NULL;");
3424 // output.println(" pthread_mutex_lock( &(parentCommon->lock) );");
3425 for (Iterator iterator = waitingQueueSet.iterator(); iterator
3427 WaitingElement waitingElement = (WaitingElement) iterator.next();
3428 output.println(" list=createQueue();");
3429 for (Iterator iterator2 = waitingElement.getAllocList().iterator(); iterator2
3431 Integer allocID = (Integer) iterator2
3433 output.println(" node=mlpCreateConflictNode( "+allocID+" );");
3434 output.println(" addNewItem(list,node);");
3436 output.println(" seseToIssue->common.waitingQueueItemID=waitingQueueItemID;");
3437 output.println(" newElement=mlpCreateWaitingElement( "+waitingElement.getStatus()+", seseToIssue, list, waitingQueueItemID );");
3440 .println(" newQItem=addWaitingQueueElement(parentCommon->allocSiteArray,numRelatedWaitingQueue,"
3441 + waitingElement.getWaitingID() + ",newElement);");
3443 .println(" addNewItem(newWaitingItemQueue,newQItem);");
3444 // output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3445 output.println(" ++(localCount);");
3449 // output.println(" pthread_mutex_unlock( &(parentCommon->lock) );");
3450 output.println(" }");
3453 output.println(" /*decide whether it is runnable or not in regarding to memory conflicts*/");
3454 output.println(" {");
3455 output.println(" if( !isEmpty(newWaitingItemQueue) ){");
3456 // output.println(" pthread_mutex_lock( &(parentCommon->lock) );");
3457 output.println(" int idx;");
3458 output.println(" for(idx = 0 ; idx < numRelatedWaitingQueue ; idx++){");
3459 output.println(" struct Queue *allocQueue=parentCommon->allocSiteArray[idx].waitingQueue;");
3460 output.println(" if( !isEmpty(allocQueue) ){");
3461 output.println(" struct QueueItem* nextQItem=getHead(allocQueue);");
3462 output.println(" while( nextQItem != NULL ){");
3463 output.println(" if(contains(newWaitingItemQueue,nextQItem) && isRunnable(allocQueue,nextQItem)){");
3464 // output.println(" if(seseToIssue->common.unresolvedDependencies>0)");
3465 // output.println(" --(seseToIssue->common.unresolvedDependencies);");
3466 output.println(" --(localCount);");
3467 output.println(" }");
3468 output.println(" nextQItem=getNextQueueItem(nextQItem);");
3469 output.println(" }");
3470 output.println(" }");
3471 output.println(" }");
3473 output.println(" }");
3474 output.println(" }");
3475 output.println(" pthread_mutex_unlock( &(parentCommon->lock) );");
3481 // output.println(" pthread_mutex_init( &(seseToIssue->common.waitingQueueLock), NULL );");
3484 if( fsen != mlpa.getMainSESE() ) {
3485 // count up outstanding dependencies, static first, then dynamic
3486 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3487 while( staticSrcsItr.hasNext() ) {
3488 SESEandAgePair srcPair = staticSrcsItr.next();
3489 output.println(" {");
3490 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3491 output.println(" pthread_mutex_lock( &(src->lock) );");
3492 output.println(" if( !isEmpty( src->forwardList ) &&");
3493 output.println(" seseToIssue == peekItem( src->forwardList ) ) {");
3494 output.println(" printf( \"This shouldnt already be here\\n\");");
3495 output.println(" exit( -1 );");
3496 output.println(" }");
3497 output.println(" if( !src->doneExecuting ) {");
3498 output.println(" addNewItem( src->forwardList, seseToIssue );");
3499 // output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3500 output.println(" ++(localCount);");
3501 output.println(" }");
3502 output.println(" pthread_mutex_unlock( &(src->lock) );");
3503 output.println(" }");
3505 // whether or not it is an outstanding dependency, make sure
3506 // to pass the static name to the child's record
3507 output.println(" seseToIssue->"+srcPair+" = "+srcPair+";");
3510 // dynamic sources might already be accounted for in the static list,
3511 // so only add them to forwarding lists if they're not already there
3512 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3513 while( dynVarsItr.hasNext() ) {
3514 TempDescriptor dynInVar = dynVarsItr.next();
3515 output.println(" {");
3516 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3518 // the dynamic source is NULL if it comes from your own space--you can't pass
3519 // the address off to the new child, because you're not done executing and
3520 // might change the variable, so copy it right now
3521 output.println(" if( src != NULL ) {");
3522 output.println(" pthread_mutex_lock( &(src->lock) );");
3523 output.println(" if( isEmpty( src->forwardList ) ||");
3524 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3525 output.println(" if( !src->doneExecuting ) {");
3526 output.println(" addNewItem( src->forwardList, seseToIssue );");
3527 // output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3528 output.println(" ++(localCount);");
3529 output.println(" }");
3530 output.println(" }");
3531 output.println(" pthread_mutex_unlock( &(src->lock) );");
3532 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3533 output.println(" } else {");
3535 boolean useParentContext = false;
3536 if( fsen != mlpa.getMainSESE() ) {
3537 assert fsen.getParent() != null;
3538 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3539 useParentContext = true;
3542 if( useParentContext ) {
3543 output.println(" seseToIssue->"+dynInVar+" = "+
3544 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3546 output.println(" seseToIssue->"+dynInVar+" = "+
3547 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3550 output.println(" }");
3551 output.println(" }");
3553 // even if the value is already copied, make sure your NULL source
3554 // gets passed so child knows it already has the dynamic value
3555 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3558 // maintain pointers for for finding dynamic SESE
3559 // instances from static names
3560 SESEandAgePair p = new SESEandAgePair( fsen, 0 );
3561 if( fsen.getParent() != null &&
3562 //!fsen.getParent().getIsCallerSESEplaceholder() &&
3563 fsen.getParent().getNeededStaticNames().contains( p )
3566 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3567 SESEandAgePair p1 = new SESEandAgePair( fsen, i );
3568 SESEandAgePair p2 = new SESEandAgePair( fsen, i-1 );
3569 output.println(" "+p1+" = "+p2+";");
3571 output.println(" "+p+" = seseToIssue;");
3576 // release this SESE for siblings to update its dependencies or,
3577 // eventually, for it to mark itself finished
3578 output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3580 // if there were no outstanding dependencies, issue here
3581 output.println(" if( atomic_sub_and_test(10000-localCount,&(seseToIssue->common.unresolvedDependencies) ) ) {");
3582 output.println(" workScheduleSubmit( (void*)seseToIssue );");
3583 output.println(" }");
3585 output.println(" if( seseToIssue->common.unresolvedDependencies == 0 ) {");
3586 output.println(" workScheduleSubmit( (void*)seseToIssue );");
3587 output.println(" }");
3589 // release this SESE for siblings to update its dependencies or,
3590 // eventually, for it to mark itself finished
3591 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3592 output.println(" }");
3596 public void generateFlatSESEExitNode( FlatMethod fm,
3598 FlatSESEExitNode fsexn,
3602 // if MLP flag is off, okay that SESE nodes are in IR graph,
3603 // just skip over them and code generates exactly the same
3608 // get the enter node for this exit that has meta data embedded
3609 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
3611 // there may be an SESE in an unreachable method, skip over
3612 if( !mlpa.getAllSESEs().contains( fsen ) ) {
3616 // also, if we have encountered a placeholder, just jump it
3617 if( fsen.getIsCallerSESEplaceholder() ) {
3621 output.println(" /* SESE exiting */");
3623 String com = paramsprefix+"->common";
3625 // this SESE cannot be done until all of its children are done
3626 // so grab your own lock with the condition variable for watching
3627 // that the number of your running children is greater than zero
3628 output.println(" pthread_mutex_lock( &("+com+".lock) );");
3629 output.println(" while( "+com+".numRunningChildren > 0 ) {");
3630 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
3631 output.println(" }");
3633 // copy out-set from local temps into the sese record
3634 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
3635 while( itr.hasNext() ) {
3636 TempDescriptor temp = itr.next();
3638 // only have to do this for primitives non-arrays
3640 temp.getType().isPrimitive() && !temp.getType().isArray()
3646 // have to determine the context enclosing this sese
3647 boolean useParentContext = false;
3649 if( fsen != mlpa.getMainSESE() ) {
3650 assert fsen.getParent() != null;
3651 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3652 useParentContext = true;
3657 if( useParentContext ) {
3658 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
3660 from = generateTemp( fsen.getfmEnclosing(), temp, null );
3663 output.println(" "+paramsprefix+
3664 "->"+temp.getSafeSymbol()+
3668 // mark yourself done, your SESE data is now read-only
3669 output.println(" "+com+".doneExecuting = TRUE;");
3670 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
3671 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
3673 // decrement dependency count for all SESE's on your forwarding list
3674 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
3675 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
3676 // output.println(" pthread_mutex_lock( &(consumer->lock) );");
3677 // output.println(" --(consumer->unresolvedDependencies);");
3678 // output.println(" if( consumer->unresolvedDependencies == 0 ) {");
3679 output.println(" if( atomic_sub_and_test(1, &(consumer->unresolvedDependencies)) ){");
3680 output.println(" workScheduleSubmit( (void*)consumer );");
3681 output.println(" }");
3682 // output.println(" pthread_mutex_unlock( &(consumer->lock) );");
3683 output.println(" }");
3687 // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
3688 if( fsen != mlpa.getMainSESE() ) {
3691 output.println(" /* check memory dependency*/");
3692 output.println(" {");
3693 output.println(" pthread_mutex_lock( &(___params___->common.parent->lock) );");
3694 // output.println(" pthread_mutex_lock( &(___params___->common.parent->waitingQueueLock) );");
3695 output.println(" int idx;");
3696 output.println(" int giveCount=0;");
3697 output.println(" struct Queue* launchQueue=createQueue();");
3698 output.println(" struct QueueItem* nextQueueItem;");
3699 output.println(" for(idx = 0 ; idx < ___params___->common.parent->numRelatedWaitingQueue ; idx++){");
3700 output.println(" if(!isEmpty(___params___->common.parent->allocSiteArray[idx].waitingQueue)){");
3701 output.println(" struct QueueItem* qItem=getHead(___params___->common.parent->allocSiteArray[idx].waitingQueue);");
3702 output.println(" int removed=0;");
3703 output.println(" while(qItem!=NULL){");
3704 output.println(" WaitingElement* item=qItem->objectptr;");
3705 output.println(" SESEcommon* seseItem=(SESEcommon*)item->seseRec;");
3706 output.println(" if(seseItem->classID==___params___->common.classID && item->id==___params___->common.waitingQueueItemID){");
3707 output.println(" struct QueueItem* nItem=getNextQueueItem(qItem);");
3708 output.println(" removeItem(___params___->common.parent->allocSiteArray[idx].waitingQueue,qItem);");
3709 output.println(" removed=1;");
3710 output.println(" qItem=nItem;");
3711 output.println(" }else if(removed){");
3712 output.println(" qItem=NULL;");
3713 output.println(" }else{");
3714 output.println(" qItem=getNextQueueItem(qItem);");
3715 output.println(" }");
3716 output.println(" }");
3717 output.println(" if( !isEmpty(___params___->common.parent->allocSiteArray[idx].waitingQueue) ){");
3719 output.println(" struct QueueItem* nextQItem=getHead(___params___->common.parent->allocSiteArray[idx].waitingQueue);");
3720 output.println(" while(nextQItem!=NULL){");
3721 output.println(" WaitingElement* nextItem=nextQItem->objectptr;");
3722 output.println(" SESEcommon* seseNextItem=(SESEcommon*)nextItem->seseRec;");
3723 // output.println(" int isResolved=resolveWaitingQueue(___params___->common.parent->allocSiteArray[idx].waitingQueue,nextQItem);");
3724 output.println(" int isResolved=isRunnable(___params___->common.parent->allocSiteArray[idx].waitingQueue,nextQItem);");
3725 output.println(" if(seseNextItem->classID==___params___->common.parent->classID){"); // stall site
3726 output.println(" if(isResolved){");
3727 output.println(" struct QueueItem* stallItem=findItem(___params___->common.parent->allocSiteArray[idx].waitingQueue,nextItem);");
3728 output.println(" removeItem(___params___->common.parent->allocSiteArray[idx].waitingQueue,stallItem);");
3729 output.println(" giveCount++;");
3730 output.println(" }");
3731 output.println(" if(!isEmpty(___params___->common.parent->allocSiteArray[idx].waitingQueue)){");
3732 // output.println(" nextQItem=getHead(___params___->common.parent->allocSiteArray[idx].waitingQueue);");
3733 output.println(" nextQItem=getNextQueueItem(nextQItem);");
3734 output.println(" }else{");
3735 output.println(" nextQItem=NULL;");
3736 output.println(" }");
3737 output.println(" }else{");
3738 output.println(" if(isResolved){");
3739 // output.println(" pthread_mutex_lock( &(seseNextItem->lock) );");
3740 // output.println(" if(seseNextItem->unresolvedDependencies > 0){");
3741 // output.println(" --(seseNextItem->unresolvedDependencies);");
3742 // output.println(" if( seseNextItem->unresolvedDependencies == 0){");
3743 //output.println(" workScheduleSubmit( (void*)nextItem);");
3744 output.println(" if( atomic_sub_and_test(1, &(seseNextItem->unresolvedDependencies)) ){");
3745 output.println(" addNewItem(launchQueue,(void*)seseNextItem);");
3746 output.println(" }");
3747 // output.println(" }");
3748 // output.println(" pthread_mutex_unlock( &(seseNextItem->lock) );");
3749 output.println(" }");
3750 output.println(" nextQItem=getNextQueueItem(nextQItem);");
3751 output.println(" }");
3752 output.println(" } "); // end of while(nextQItem!=NULL)
3753 output.println(" }");
3754 output.println(" }");
3755 // output.println(" }");
3756 output.println(" }");
3757 output.println(" pthread_mutex_unlock( &(___params___->common.parent->lock) );");
3758 // output.println(" pthread_mutex_unlock( &(___params___->common.parent->waitingQueueLock) );");
3759 output.println(" if(!isEmpty(launchQueue)){");
3760 output.println(" struct QueueItem* qItem=getHead(launchQueue);");
3761 output.println(" while(qItem!=NULL){");
3762 output.println(" workScheduleSubmit(qItem->objectptr);");
3763 output.println(" qItem=getNextQueueItem(qItem);");
3764 output.println(" }");
3765 output.println(" }");
3766 output.println(" if(giveCount>0){");
3767 output.println(" psem_give(&(___params___->common.parent->memoryStallSiteSem));");
3768 output.println(" }");
3769 output.println(" }");
3773 // if parent is stalling on you, let them know you're done
3774 if( fsexn.getFlatEnter() != mlpa.getMainSESE() ) {
3775 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
3778 // last of all, decrement your parent's number of running children
3779 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
3780 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
3781 output.println(" --("+paramsprefix+"->common.parent->numRunningChildren);");
3782 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
3783 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
3784 output.println(" }");
3786 // this is a thread-only variable that can be handled when critical sese-to-sese
3787 // data has been taken care of--set sese pointer to remember self over method
3788 // calls to a non-zero, invalid address
3789 output.println(" seseCaller = (SESEcommon*) 0x1;");
3793 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
3795 FlatWriteDynamicVarNode fwdvn,
3799 // should node should not be in an IR graph if the
3800 // MLP flag is not set
3801 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
3804 Hashtable<TempDescriptor, VariableSourceToken> writeDynamic =
3807 assert writeDynamic != null;
3809 Iterator wdItr = writeDynamic.entrySet().iterator();
3810 while( wdItr.hasNext() ) {
3811 Map.Entry me = (Map.Entry) wdItr.next();
3812 TempDescriptor refVar = (TempDescriptor) me.getKey();
3813 VariableSourceToken vst = (VariableSourceToken) me.getValue();
3815 FlatSESEEnterNode current = fwdvn.getEnclosingSESE();
3817 // only do this if the variable in question should be tracked,
3818 // meaning that it was explicitly added to the dynamic var set
3819 if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
3823 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
3825 output.println(" {");
3827 if( current.equals( vst.getSESE() ) ) {
3828 // if the src comes from this SESE, it's a method local variable,
3829 // mark src pointer NULL to signify that the var is up-to-date
3830 output.println(" "+vst.getAddrVar()+"_srcSESE = NULL;");
3833 // otherwise we track where it will come from
3834 output.println(" "+vst.getAddrVar()+"_srcSESE = "+instance+";");
3835 output.println(" "+vst.getAddrVar()+"_srcOffset = (int) &((("+
3836 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
3839 output.println(" }");
3844 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
3845 if (state.CONSCHECK) {
3846 String specname=fcn.getSpec();
3847 String varname="repairstate___";
3848 output.println("{");
3849 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
3851 TempDescriptor[] temps=fcn.getTemps();
3852 String[] vars=fcn.getVars();
3853 for(int i=0; i<temps.length; i++) {
3854 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
3857 output.println("if (doanalysis"+specname+"("+varname+")) {");
3858 output.println("free"+specname+"_state("+varname+");");
3859 output.println("} else {");
3860 output.println("/* Bad invariant */");
3861 output.println("free"+specname+"_state("+varname+");");
3862 output.println("abort_task();");
3863 output.println("}");
3864 output.println("}");
3868 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
3870 if( state.MLP && !nonSESEpass ) {
3871 output.println(" seseCaller = (SESEcommon*)"+paramsprefix+";");
3874 MethodDescriptor md=fc.getMethod();
3875 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
3876 ClassDescriptor cn=md.getClassDesc();
3877 output.println("{");
3878 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3880 LocalityBinding fclb=locality.getBinding(lb, fc);
3881 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3883 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3885 output.print(objectparams.numPointers());
3886 output.print(", "+localsprefixaddr);
3887 if (md.getThis()!=null) {
3889 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
3891 if (fc.getThis()!=null&&md.getThis()==null) {
3892 System.out.println("WARNING!!!!!!!!!!!!");
3893 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
3897 for(int i=0; i<fc.numArgs(); i++) {
3898 Descriptor var=md.getParameter(i);
3899 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3900 if (objectparams.isParamPtr(paramtemp)) {
3901 TempDescriptor targ=fc.getArg(i);
3903 TypeDescriptor td=md.getParamType(i);
3905 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3907 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3910 output.println("};");
3915 if (fc.getReturnTemp()!=null)
3916 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
3918 /* Do we need to do virtual dispatch? */
3919 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
3922 LocalityBinding fclb=locality.getBinding(lb, fc);
3923 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3925 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3930 if (md.getReturnType().isClass()||md.getReturnType().isArray())
3931 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3933 output.print(md.getReturnType().getSafeSymbol()+" ");
3934 output.print("(*)(");
3936 boolean printcomma=false;
3937 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3939 LocalityBinding fclb=locality.getBinding(lb, fc);
3940 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3942 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3946 for(int i=0; i<objectparams.numPrimitives(); i++) {
3947 TempDescriptor temp=objectparams.getPrimitive(i);
3951 if (temp.getType().isClass()||temp.getType().isArray())
3952 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
3954 output.print(temp.getType().getSafeSymbol());
3959 LocalityBinding fclb=locality.getBinding(lb, fc);
3960 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
3962 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
3966 boolean needcomma=false;
3967 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3968 output.print("&__parameterlist__");
3972 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
3973 if (fc.getThis()!=null) {
3974 TypeDescriptor ptd=md.getThis().getType();
3977 if (ptd.isClass()&&!ptd.isArray())
3978 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3979 output.print(generateTemp(fm,fc.getThis(),lb));
3984 for(int i=0; i<fc.numArgs(); i++) {
3985 Descriptor var=md.getParameter(i);
3986 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3987 if (objectparams.isParamPrim(paramtemp)) {
3988 TempDescriptor targ=fc.getArg(i);
3992 TypeDescriptor ptd=md.getParamType(i);
3993 if (ptd.isClass()&&!ptd.isArray())
3994 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3995 output.print(generateTemp(fm, targ,lb));
3999 output.println(");");
4000 output.println(" }");
4003 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
4004 Set subclasses=typeutil.getSubClasses(thiscd);
4005 if (subclasses==null)
4007 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
4008 ClassDescriptor cd=(ClassDescriptor)classit.next();
4009 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
4010 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
4011 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
4012 if (md.matches(matchmd))
4019 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
4020 if (state.SINGLETM) {
4021 //single machine transactional memory case
4022 String field=ffn.getField().getSafeSymbol();
4023 String src=generateTemp(fm, ffn.getSrc(),lb);
4024 String dst=generateTemp(fm, ffn.getDst(),lb);
4026 output.println(dst+"="+ src +"->"+field+ ";");
4027 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
4028 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
4029 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
4030 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
4031 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
4032 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
4033 if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
4034 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4036 output.println("TRANSREADRD("+dst+", "+dst+");");
4039 } else if (state.DSM) {
4040 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
4041 if (status==LocalityAnalysis.GLOBAL) {
4042 String field=ffn.getField().getSafeSymbol();
4043 String src=generateTemp(fm, ffn.getSrc(),lb);
4044 String dst=generateTemp(fm, ffn.getDst(),lb);
4046 if (ffn.getField().getType().isPtr()) {
4048 //TODO: Uncomment this when we have runtime support
4049 //if (ffn.getSrc()==ffn.getDst()) {
4050 //output.println("{");
4051 //output.println("void * temp="+src+";");
4052 //output.println("if (temp&0x1) {");
4053 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
4054 //output.println(src+"->"+field+"="+temp+";");
4055 //output.println("}");
4056 //output.println(dst+"=temp;");
4057 //output.println("}");
4059 output.println(dst+"="+ src +"->"+field+ ";");
4060 //output.println("if ("+dst+"&0x1) {");
4061 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4062 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4063 //output.println(src+"->"+field+"="+src+"->"+field+";");
4064 //output.println("}");
4067 output.println(dst+"="+ src+"->"+field+";");
4069 } else if (status==LocalityAnalysis.LOCAL) {
4070 if (ffn.getField().getType().isPtr()&&
4071 ffn.getField().isGlobal()) {
4072 String field=ffn.getField().getSafeSymbol();
4073 String src=generateTemp(fm, ffn.getSrc(),lb);
4074 String dst=generateTemp(fm, ffn.getDst(),lb);
4075 output.println(dst+"="+ src +"->"+field+ ";");
4076 if (locality.getAtomic(lb).get(ffn).intValue()>0)
4077 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4078 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4080 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4081 } else if (status==LocalityAnalysis.EITHER) {
4082 //Code is reading from a null pointer
4083 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
4084 output.println("#ifndef RAW");
4085 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4086 output.println("#endif");
4087 //This should throw a suitable null pointer error
4088 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4090 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4092 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4096 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
4097 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
4098 throw new Error("Can't set array length");
4099 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4100 //Single Machine Transaction Case
4101 boolean srcptr=fsfn.getSrc().getType().isPtr();
4102 String src=generateTemp(fm,fsfn.getSrc(),lb);
4103 String dst=generateTemp(fm,fsfn.getDst(),lb);
4104 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
4105 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
4106 output.println("{");
4107 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
4108 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
4109 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4111 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4114 if (wb.needBarrier(fsfn)&&
4115 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
4116 if (state.EVENTMONITOR) {
4117 output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
4119 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
4121 if (srcptr&!fsfn.getSrc().getType().isNull()) {
4122 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4123 output.println("}");
4125 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4127 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4128 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
4129 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
4130 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4132 String src=generateTemp(fm,fsfn.getSrc(),lb);
4133 String dst=generateTemp(fm,fsfn.getDst(),lb);
4135 output.println("{");
4136 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4138 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
4141 if (wb.needBarrier(fsfn))
4142 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
4144 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4146 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4147 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
4148 /** Check if we need to copy */
4149 output.println("if(!"+dst+"->"+localcopystr+") {");
4150 /* Link object into list */
4151 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4152 output.println(revertptr+"=revertlist;");
4153 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4154 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4156 output.println("COPY_OBJ("+dst+");");
4157 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4158 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4159 output.println("}");
4161 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4163 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4164 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
4165 //writing to a null...bad
4166 output.println("if ("+dst+") {");
4167 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
4169 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4171 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4174 output.println("}");
4177 if (state.FASTCHECK) {
4178 String dst=generateTemp(fm, fsfn.getDst(),lb);
4179 output.println("if(!"+dst+"->"+localcopystr+") {");
4180 /* Link object into list */
4181 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4182 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4184 output.println("COPY_OBJ("+dst+");");
4185 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4186 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4187 output.println("}");
4189 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4193 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
4194 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
4197 if (elementtype.isArray()||elementtype.isClass())
4200 type=elementtype.getSafeSymbol()+" ";
4202 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
4203 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
4204 output.println("failedboundschk();");
4206 if (state.SINGLETM) {
4207 //Single machine transaction case
4208 String dst=generateTemp(fm, fen.getDst(),lb);
4209 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))) {
4210 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4212 output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
4215 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
4216 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
4217 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
4218 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
4219 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
4220 if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
4221 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4223 output.println("TRANSREADRD("+dst+", "+dst+");");
4226 } else if (state.DSM) {
4227 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
4228 if (status==LocalityAnalysis.GLOBAL) {
4229 String dst=generateTemp(fm, fen.getDst(),lb);
4230 if (elementtype.isPtr()) {
4231 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4232 //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
4233 output.println("TRANSREAD("+dst+", "+dst+");");
4235 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4237 } else if (status==LocalityAnalysis.LOCAL) {
4238 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4239 } else if (status==LocalityAnalysis.EITHER) {
4240 //Code is reading from a null pointer
4241 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
4242 output.println("#ifndef RAW");
4243 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4244 output.println("#endif");
4245 //This should throw a suitable null pointer error
4246 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4248 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4250 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4254 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
4255 //TODO: need dynamic check to make sure this assignment is actually legal
4256 //Because Object[] could actually be something more specific...ie. Integer[]
4258 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
4261 if (elementtype.isArray()||elementtype.isClass())
4264 type=elementtype.getSafeSymbol()+" ";
4266 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
4267 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
4268 output.println("failedboundschk();");
4271 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4272 //Transaction set element case
4273 if (wb.needBarrier(fsen)&&
4274 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
4275 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
4277 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
4278 output.println("{");
4279 String src=generateTemp(fm, fsen.getSrc(), lb);
4280 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
4281 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
4282 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4284 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4286 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4287 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
4289 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4291 output.println("}");
4293 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4294 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
4296 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4299 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4300 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
4301 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
4302 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4303 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
4304 boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
4307 if (wb.needBarrier(fsen))
4308 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
4309 } else if (dstlocal) {
4310 /** Check if we need to copy */
4311 String dst=generateTemp(fm, fsen.getDst(),lb);
4312 output.println("if(!"+dst+"->"+localcopystr+") {");
4313 /* Link object into list */
4314 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4315 output.println(revertptr+"=revertlist;");
4316 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
4317 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4319 output.println("COPY_OBJ("+dst+");");
4320 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4321 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4322 output.println("}");
4324 System.out.println("Node: "+fsen);
4325 System.out.println(lb);
4326 System.out.println("statusdst="+statusdst);
4327 System.out.println(fm.printMethod());
4328 throw new Error("Unknown array type");
4331 output.println("{");
4332 String src=generateTemp(fm, fsen.getSrc(), lb);
4333 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4334 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4335 output.println("}");
4337 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4340 if (state.FASTCHECK) {
4341 String dst=generateTemp(fm, fsen.getDst(),lb);
4342 output.println("if(!"+dst+"->"+localcopystr+") {");
4343 /* Link object into list */
4344 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4345 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4347 output.println("COPY_OBJ("+dst+");");
4348 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4349 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4350 output.println("}");
4352 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4356 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
4357 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4358 //Stash pointer in case of GC
4359 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4360 output.println(revertptr+"=revertlist;");
4362 if (state.SINGLETM) {
4363 if (fn.getType().isArray()) {
4364 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4365 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4366 //inside transaction
4367 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4369 //outside transaction
4370 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4373 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4374 //inside transaction
4375 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4377 //outside transaction
4378 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4381 } else if (fn.getType().isArray()) {
4382 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4383 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4384 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4385 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4386 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4388 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4391 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4392 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
4393 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4394 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4396 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
4399 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4400 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4401 String dst=generateTemp(fm,fn.getDst(),lb);
4402 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4403 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4404 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4406 if (state.FASTCHECK) {
4407 String dst=generateTemp(fm,fn.getDst(),lb);
4408 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4409 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4410 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4414 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
4415 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4416 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
4418 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
4422 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
4423 if (fon.getRight()!=null) {
4424 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
4425 if (fon.getLeft().getType().isLong())
4426 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4428 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4430 } else if (dc!=null) {
4431 output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
4432 if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4433 output.print("(void *)");
4434 if (dc.getNeedLeftSrcTrans(lb, fon))
4435 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
4437 output.print(generateTemp(fm, fon.getLeft(),lb));
4438 output.print(")"+fon.getOp().toString()+"(");
4439 if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4440 output.print("(void *)");
4441 if (dc.getNeedRightSrcTrans(lb, fon))
4442 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
4444 output.println(generateTemp(fm,fon.getRight(),lb)+");");
4446 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
4447 } else if (fon.getOp().getOp()==Operation.ASSIGN)
4448 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4449 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
4450 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4451 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
4452 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
4453 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
4454 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
4455 else if (fon.getOp().getOp()==Operation.COMP)
4456 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
4457 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
4458 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
4460 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
4463 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
4464 /* TODO: Do type check here */
4465 if (fcn.getType().isArray()) {
4466 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4467 } else if (fcn.getType().isClass())
4468 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4470 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
4473 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
4474 if (fln.getValue()==null)
4475 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4476 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
4477 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4478 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4479 //Stash pointer in case of GC
4480 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4481 output.println(revertptr+"=revertlist;");
4483 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4484 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4485 //Stash pointer in case of GC
4486 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4487 output.println("revertlist="+revertptr+";");
4490 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4492 } else if (fln.getType().isBoolean()) {
4493 if (((Boolean)fln.getValue()).booleanValue())
4494 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
4496 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4497 } else if (fln.getType().isChar()) {
4498 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
4499 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
4500 } else if (fln.getType().isLong()) {
4501 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
4503 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
4506 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
4507 if (frn.getReturnTemp()!=null) {
4508 if (frn.getReturnTemp().getType().isPtr())
4509 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4511 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4513 output.println("return;");
4517 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4520 //only record if this group has more than one exit
4521 if (branchanalysis.numJumps(fcb)>1) {
4522 left=branchanalysis.jumpValue(fcb, 0);
4523 right=branchanalysis.jumpValue(fcb, 1);
4525 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
4527 output.println("STOREBRANCH("+right+");");
4528 output.println("goto "+label+";");
4529 output.println("}");
4531 output.println("STOREBRANCH("+left+");");
4534 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4535 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
4538 /** This method generates header information for the method or
4539 * task referenced by the Descriptor des. */
4540 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
4541 generateHeader(fm, lb, des, output, false);
4544 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
4546 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
4547 MethodDescriptor md=null;
4548 TaskDescriptor task=null;
4549 if (des instanceof MethodDescriptor)
4550 md=(MethodDescriptor) des;
4552 task=(TaskDescriptor) des;
4554 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
4556 if (md!=null&&md.getReturnType()!=null) {
4557 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4558 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4560 output.print(md.getReturnType().getSafeSymbol()+" ");
4562 //catch the constructor case
4563 output.print("void ");
4565 if (state.DSM||state.SINGLETM) {
4566 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4568 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4570 output.print(task.getSafeSymbol()+"(");
4572 boolean printcomma=false;
4573 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4575 if (state.DSM||state.SINGLETM) {
4576 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4578 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4580 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
4586 for(int i=0; i<objectparams.numPrimitives(); i++) {
4587 TempDescriptor temp=objectparams.getPrimitive(i);
4591 if (temp.getType().isClass()||temp.getType().isArray())
4592 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
4594 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
4596 output.println(") {");
4597 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4598 /* Imprecise Task */
4599 output.println("void * parameterarray[]) {");
4600 /* Unpack variables */
4601 for(int i=0; i<objectparams.numPrimitives(); i++) {
4602 TempDescriptor temp=objectparams.getPrimitive(i);
4603 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
4605 for(int i=0; i<fm.numTags(); i++) {
4606 TempDescriptor temp=fm.getTag(i);
4607 int offset=i+objectparams.numPrimitives();
4608 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
4611 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
4612 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
4613 } else output.println(") {");
4616 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
4617 output.println("/* FlatFlagActionNode */");
4620 /* Process tag changes */
4621 Relation tagsettable=new Relation();
4622 Relation tagcleartable=new Relation();
4624 Iterator tagsit=ffan.getTempTagPairs();
4625 while (tagsit.hasNext()) {
4626 TempTagPair ttp=(TempTagPair) tagsit.next();
4627 TempDescriptor objtmp=ttp.getTemp();
4628 TagDescriptor tag=ttp.getTag();
4629 TempDescriptor tagtmp=ttp.getTagTemp();
4630 boolean tagstatus=ffan.getTagChange(ttp);
4632 tagsettable.put(objtmp, tagtmp);
4634 tagcleartable.put(objtmp, tagtmp);
4639 Hashtable flagandtable=new Hashtable();
4640 Hashtable flagortable=new Hashtable();
4642 /* Process flag changes */
4643 Iterator flagsit=ffan.getTempFlagPairs();
4644 while(flagsit.hasNext()) {
4645 TempFlagPair tfp=(TempFlagPair)flagsit.next();
4646 TempDescriptor temp=tfp.getTemp();
4647 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
4648 FlagDescriptor flag=tfp.getFlag();
4650 //Newly allocate objects that don't set any flags case
4651 if (flagortable.containsKey(temp)) {
4655 flagortable.put(temp,new Integer(mask));
4657 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
4658 boolean flagstatus=ffan.getFlagChange(tfp);
4661 if (flagortable.containsKey(temp)) {
4662 mask=((Integer)flagortable.get(temp)).intValue();
4665 flagortable.put(temp,new Integer(mask));
4667 int mask=0xFFFFFFFF;
4668 if (flagandtable.containsKey(temp)) {
4669 mask=((Integer)flagandtable.get(temp)).intValue();
4671 mask&=(0xFFFFFFFF^flagid);
4672 flagandtable.put(temp,new Integer(mask));
4678 HashSet flagtagset=new HashSet();
4679 flagtagset.addAll(flagortable.keySet());
4680 flagtagset.addAll(flagandtable.keySet());
4681 flagtagset.addAll(tagsettable.keySet());
4682 flagtagset.addAll(tagcleartable.keySet());
4684 Iterator ftit=flagtagset.iterator();
4685 while(ftit.hasNext()) {
4686 TempDescriptor temp=(TempDescriptor)ftit.next();
4689 Set tagtmps=tagcleartable.get(temp);
4690 if (tagtmps!=null) {
4691 Iterator tagit=tagtmps.iterator();
4692 while(tagit.hasNext()) {
4693 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4694 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4695 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4697 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4701 tagtmps=tagsettable.get(temp);
4702 if (tagtmps!=null) {
4703 Iterator tagit=tagtmps.iterator();
4704 while(tagit.hasNext()) {
4705 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4706 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4707 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4709 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
4714 int andmask=0xFFFFFFF;
4716 if (flagortable.containsKey(temp))
4717 ormask=((Integer)flagortable.get(temp)).intValue();
4718 if (flagandtable.containsKey(temp))
4719 andmask=((Integer)flagandtable.get(temp)).intValue();
4720 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
4721 generateObjectDistribute(ffan, fm, lb, temp, output);
4725 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
4726 PrintWriter output, int ormask, int andmask) {
4727 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
4728 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4730 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4734 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
4735 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
4738 void generateOptionalHeader(PrintWriter headers) {
4741 headers.println("#include \"task.h\"\n\n");
4742 headers.println("#ifndef _OPTIONAL_STRUCT_");
4743 headers.println("#define _OPTIONAL_STRUCT_");
4745 //STRUCT PREDICATEMEMBER
4746 headers.println("struct predicatemember{");
4747 headers.println("int type;");
4748 headers.println("int numdnfterms;");
4749 headers.println("int * flags;");
4750 headers.println("int numtags;");
4751 headers.println("int * tags;\n};\n\n");
4753 //STRUCT OPTIONALTASKDESCRIPTOR
4754 headers.println("struct optionaltaskdescriptor{");
4755 headers.println("struct taskdescriptor * task;");
4756 headers.println("int index;");
4757 headers.println("int numenterflags;");
4758 headers.println("int * enterflags;");
4759 headers.println("int numpredicatemembers;");
4760 headers.println("struct predicatemember ** predicatememberarray;");
4761 headers.println("};\n\n");
4763 //STRUCT TASKFAILURE
4764 headers.println("struct taskfailure {");
4765 headers.println("struct taskdescriptor * task;");
4766 headers.println("int index;");
4767 headers.println("int numoptionaltaskdescriptors;");
4768 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4770 //STRUCT FSANALYSISWRAPPER
4771 headers.println("struct fsanalysiswrapper{");
4772 headers.println("int flags;");
4773 headers.println("int numtags;");
4774 headers.println("int * tags;");
4775 headers.println("int numtaskfailures;");
4776 headers.println("struct taskfailure ** taskfailurearray;");
4777 headers.println("int numoptionaltaskdescriptors;");
4778 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4780 //STRUCT CLASSANALYSISWRAPPER
4781 headers.println("struct classanalysiswrapper{");
4782 headers.println("int type;");
4783 headers.println("int numotd;");
4784 headers.println("struct optionaltaskdescriptor ** otdarray;");
4785 headers.println("int numfsanalysiswrappers;");
4786 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
4788 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
4790 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
4791 while(taskit.hasNext()) {
4792 TaskDescriptor td=(TaskDescriptor)taskit.next();
4793 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
4798 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
4799 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
4800 int predicateindex = 0;
4801 //iterate through the classes concerned by the predicate
4802 Set c_vard = predicate.vardescriptors;
4803 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
4806 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
4807 VarDescriptor vard = (VarDescriptor)vard_it.next();
4808 TypeDescriptor typed = vard.getType();
4810 //generate for flags
4811 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
4812 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4814 if (fen_hashset!=null) {
4815 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
4816 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
4818 DNFFlag dflag=fen.getDNF();
4819 numberterms+=dflag.size();
4821 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
4823 for(int j=0; j<dflag.size(); j++) {
4825 output.println(",");
4826 Vector term=dflag.get(j);
4829 for(int k=0; k<term.size(); k++) {
4830 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
4831 FlagDescriptor fd=dfa.getFlag();
4832 boolean negated=dfa.getNegated();
4833 int flagid=1<<((Integer)flags.get(fd)).intValue();
4838 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
4843 output.println("};\n");
4846 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
4847 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4850 for(int j=0; j<tagel.numTags(); j++) {
4852 output.println(",");
4853 TempDescriptor tmp=tagel.getTemp(j);
4854 if (!slotnumber.containsKey(tmp)) {
4855 Integer slotint=new Integer(current_slot++);
4856 slotnumber.put(tmp,slotint);
4858 int slot=slotnumber.get(tmp).intValue();
4859 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
4861 numtags = tagel.numTags();
4863 output.println("};");
4865 //store the result into a predicatemember struct
4866 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4867 output.println("/*type*/"+typed.getClassDesc().getId()+",");
4868 output.println("/* number of dnf terms */"+numberterms+",");
4869 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4870 output.println("/* number of tag */"+numtags+",");
4871 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4872 output.println("};\n");
4877 //generate an array that stores the entire predicate
4878 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4879 for( int j = 0; j<predicateindex; j++) {
4880 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4881 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4883 output.println("};\n");
4884 return predicateindex;
4888 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
4889 generateOptionalHeader(headers);
4891 output.println("#include \"optionalstruct.h\"\n\n");
4892 output.println("#include \"stdlib.h\"\n");
4894 HashSet processedcd = new HashSet();
4896 Enumeration e = safeexecution.keys();
4897 while (e.hasMoreElements()) {
4900 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
4901 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
4903 //Generate the struct of optionals
4904 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4905 numotd = c_otd.size();
4906 if(maxotd<numotd) maxotd = numotd;
4907 if( !c_otd.isEmpty() ) {
4908 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4909 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4911 //generate the int arrays for the predicate
4912 Predicate predicate = otd.predicate;
4913 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
4914 TreeSet<Integer> fsset=new TreeSet<Integer>();
4915 //iterate through possible FSes corresponding to
4916 //the state when entering
4918 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
4919 FlagState fs = (FlagState)fses.next();
4921 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4922 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4923 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4926 fsset.add(new Integer(flagid));
4927 //tag information not needed because tag
4928 //changes are not tolerated.
4931 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4932 boolean needcomma=false;
4933 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
4936 output.println(it.next());
4939 output.println("};\n");
4942 //generate optionaltaskdescriptor that actually
4943 //includes exit fses, predicate and the task
4945 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4946 output.println("&task_"+otd.td.getSafeSymbol()+",");
4947 output.println("/*index*/"+otd.getIndex()+",");
4948 output.println("/*number of enter flags*/"+fsset.size()+",");
4949 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4950 output.println("/*number of members */"+predicateindex+",");
4951 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4952 output.println("};\n");
4956 // if there are no optionals, there is no need to build the rest of the struct
4958 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
4959 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4960 if( !c_otd.isEmpty() ) {
4961 boolean needcomma=false;
4962 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4963 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4965 output.println(",");
4967 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4970 output.println("};\n");
4972 //get all the possible flagstates reachable by an object
4973 Hashtable hashtbtemp = safeexecution.get(cdtemp);
4975 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
4976 fsts.addAll(hashtbtemp.keySet());
4977 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
4978 FlagState fs = (FlagState)fsit.next();
4981 //get the set of OptionalTaskDescriptors corresponding
4982 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
4983 //iterate through the OptionalTaskDescriptors and
4984 //store the pointers to the optionals struct (see on
4985 //top) into an array
4987 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
4988 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
4989 OptionalTaskDescriptor mm = mos.next();
4991 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
4993 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4996 output.println("};\n");
4998 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
5001 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5002 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5003 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5007 //process tag information
5010 boolean first = true;
5011 Enumeration tag_enum = fs.getTags();
5012 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5013 while(tag_enum.hasMoreElements()) {
5015 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
5019 output.println(", ");
5020 output.println("/*tagid*/"+state.getTagId(tagd));
5022 output.println("};");
5024 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
5025 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5026 TaskIndex ti=itti.next();
5030 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
5032 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
5033 boolean needcomma=false;
5034 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
5035 OptionalTaskDescriptor otd=otdit.next();
5039 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5041 output.println("};");
5043 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
5044 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
5045 output.print(ti.getIndex()+", ");
5046 output.print(otdset.size()+", ");
5047 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
5048 output.println("};");
5051 tiset=sa.getTaskIndex(fs);
5052 boolean needcomma=false;
5054 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5055 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5056 TaskIndex ti=itti.next();
5057 if (ti.isRuntime()) {
5064 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
5066 output.println("};\n");
5068 //Store the result in fsanalysiswrapper
5070 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
5071 output.println("/*flag*/"+flagid+",");
5072 output.println("/* number of tags*/"+tagcounter+",");
5073 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5074 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
5075 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5076 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
5077 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
5078 output.println("};\n");
5082 //Build the array of fsanalysiswrappers
5083 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
5084 boolean needcomma=false;
5085 for(int i = 0; i<fscounter; i++) {
5086 if (needcomma) output.print(",");
5087 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
5090 output.println("};");
5092 //Build the classanalysiswrapper referring to the previous array
5093 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
5094 output.println("/*type*/"+cdtemp.getId()+",");
5095 output.println("/*numotd*/"+numotd+",");
5096 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
5097 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
5098 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
5099 processedcd.add(cdtemp);
5102 //build an array containing every classes for which code has been build
5103 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
5104 for(int i=0; i<state.numClasses(); i++) {
5105 ClassDescriptor cn=cdarray[i];
5108 if ((cn != null) && (processedcd.contains(cn)))
5109 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
5111 output.print("NULL");
5113 output.println("};");
5115 output.println("#define MAXOTD "+maxotd);
5116 headers.println("#endif");
5119 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
5120 Relation r=new Relation();
5121 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
5122 OptionalTaskDescriptor otd=otdit.next();
5123 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
5127 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
5128 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
5129 Set s=r.get(it.next());
5130 for(Iterator it2=s.iterator(); it2.hasNext();) {
5131 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
5139 protected void outputTransCode(PrintWriter output) {