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("#endif\n");
427 if (state.EVENTMONITOR) {
428 outmethod.println("dumpdata();");
431 if (state.THREAD||state.SINGLETM)
432 outmethod.println("pthread_exit(NULL);");
435 outmethod.println(" workScheduleBegin();");
438 outmethod.println("}");
441 /* This method outputs code for each task. */
443 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
444 /* Compile task based program */
445 outtaskdefs.println("#include \"task.h\"");
446 outtaskdefs.println("#include \"methodheaders.h\"");
447 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
448 while(taskit.hasNext()) {
449 TaskDescriptor td=(TaskDescriptor)taskit.next();
450 FlatMethod fm=state.getMethodFlat(td);
451 generateFlatMethod(fm, null, outmethod);
452 generateTaskDescriptor(outtaskdefs, fm, td);
455 //Output task descriptors
456 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
457 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
459 while(taskit.hasNext()) {
460 TaskDescriptor td=(TaskDescriptor)taskit.next();
464 outtaskdefs.println(",");
465 outtaskdefs.print("&task_"+td.getSafeSymbol());
467 outtaskdefs.println("};");
469 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
472 /* This method outputs most of the methods.c file. This includes
473 * some standard includes and then an array with the sizes of
474 * objets and array that stores supertype and then the code for
475 * the Java methods.. */
477 protected void outputMethods(PrintWriter outmethod) {
478 outmethod.println("#include \"methodheaders.h\"");
479 outmethod.println("#include \"virtualtable.h\"");
480 outmethod.println("#include \"runtime.h\"");
482 outmethod.println("#include \"sandboxdefs.c\"");
485 outmethod.println("#include \"addPrefetchEnhance.h\"");
486 outmethod.println("#include \"localobjects.h\"");
488 if (state.FASTCHECK) {
489 outmethod.println("#include \"localobjects.h\"");
491 if(state.MULTICORE) {
492 outmethod.println("#include \"task.h\"");
493 outmethod.println("#include \"multicoreruntime.h\"");
494 outmethod.println("#include \"runtime_arch.h\"");
496 if (state.THREAD||state.DSM||state.SINGLETM)
497 outmethod.println("#include <thread.h>");
498 if (state.main!=null) {
499 outmethod.println("#include <string.h>");
501 if (state.CONSCHECK) {
502 outmethod.println("#include \"checkers.h\"");
505 outmethod.println("#include <stdlib.h>");
506 outmethod.println("#include <stdio.h>");
507 outmethod.println("#include \"mlp_runtime.h\"");
508 outmethod.println("#include \"psemaphore.h\"");
512 //Store the sizes of classes & array elements
513 generateSizeArray(outmethod);
515 //Store table of supertypes
516 generateSuperTypeTable(outmethod);
518 //Store the layout of classes
519 generateLayoutStructs(outmethod);
521 /* Generate code for methods */
522 if (state.DSM||state.SINGLETM) {
523 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
524 LocalityBinding lb=lbit.next();
525 MethodDescriptor md=lb.getMethod();
526 FlatMethod fm=state.getMethodFlat(md);
528 if (!md.getModifiers().isNative()) {
529 generateFlatMethod(fm, lb, outmethod);
530 //System.out.println("fm= " + fm + " md= " + md);
534 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
535 while(classit.hasNext()) {
536 ClassDescriptor cn=(ClassDescriptor)classit.next();
537 Iterator methodit=cn.getMethods();
538 while(methodit.hasNext()) {
539 /* Classify parameters */
540 MethodDescriptor md=(MethodDescriptor)methodit.next();
541 FlatMethod fm=state.getMethodFlat(md);
542 if (!md.getModifiers().isNative()) {
543 generateFlatMethod(fm, null, outmethod);
550 protected void outputStructs(PrintWriter outstructs) {
551 outstructs.println("#ifndef STRUCTDEFS_H");
552 outstructs.println("#define STRUCTDEFS_H");
553 outstructs.println("#include \"classdefs.h\"");
554 outstructs.println("#ifndef INTPTR");
555 outstructs.println("#ifdef BIT64");
556 outstructs.println("#define INTPTR long");
557 outstructs.println("#else");
558 outstructs.println("#define INTPTR int");
559 outstructs.println("#endif");
560 outstructs.println("#endif");
562 outstructs.println("#include \"mlp_runtime.h\"");
563 outstructs.println("#include \"psemaphore.h\"");
566 /* Output #defines that the runtime uses to determine type
567 * numbers for various objects it needs */
568 outstructs.println("#define MAXCOUNT "+maxcount);
569 if (state.DSM||state.SINGLETM) {
570 LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
572 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
574 else if (state.SINGLETM) {
575 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
577 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
581 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
583 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
584 else if( state.SINGLETM)
585 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
586 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
589 outstructs.println("#define STRINGARRAYTYPE "+
590 (state.getArrayNumber(
591 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
593 outstructs.println("#define OBJECTARRAYTYPE "+
594 (state.getArrayNumber(
595 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
598 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
599 outstructs.println("#define CHARARRAYTYPE "+
600 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
602 outstructs.println("#define BYTEARRAYTYPE "+
603 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
605 outstructs.println("#define BYTEARRAYARRAYTYPE "+
606 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
608 outstructs.println("#define NUMCLASSES "+state.numClasses());
609 int totalClassSize = state.numClasses() + state.numArrays();
610 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
612 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
613 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
614 outstructs.println("#define TAGARRAYTYPE "+
615 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
619 protected void outputClassDeclarations(PrintWriter outclassdefs) {
620 if (state.THREAD||state.DSM||state.SINGLETM)
621 outclassdefs.println("#include <pthread.h>");
622 outclassdefs.println("#ifndef INTPTR");
623 outclassdefs.println("#ifdef BIT64");
624 outclassdefs.println("#define INTPTR long");
625 outclassdefs.println("#else");
626 outclassdefs.println("#define INTPTR int");
627 outclassdefs.println("#endif");
628 outclassdefs.println("#endif");
630 outclassdefs.println("#include \"optionalstruct.h\"");
631 outclassdefs.println("struct "+arraytype+";");
632 /* Start by declaring all structs */
633 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
634 while(it.hasNext()) {
635 ClassDescriptor cn=(ClassDescriptor)it.next();
636 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
638 outclassdefs.println("");
639 //Print out definition for array type
640 outclassdefs.println("struct "+arraytype+" {");
641 outclassdefs.println(" int type;");
642 if (state.EVENTMONITOR) {
643 outclassdefs.println(" int objuid;");
646 outclassdefs.println(" pthread_t tid;");
647 outclassdefs.println(" void * lockentry;");
648 outclassdefs.println(" int lockcount;");
651 outclassdefs.println(" int flag;");
652 if(!state.MULTICORE) {
653 outclassdefs.println(" void * flagptr;");
655 outclassdefs.println(" int version;");
656 outclassdefs.println(" int * lock;"); // lock entry for this obj
657 outclassdefs.println(" int mutex;");
658 outclassdefs.println(" int lockcount;");
659 if(state.MULTICOREGC) {
660 outclassdefs.println(" int marked;");
664 outclassdefs.println(" int numfses;");
665 outclassdefs.println(" int * fses;");
668 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
670 if (state.STMARRAY) {
671 outclassdefs.println(" int lowindex;");
672 outclassdefs.println(" int highindex;");
675 outclassdefs.println(" int paddingforarray;");
676 if (state.DUALVIEW) {
677 outclassdefs.println(" int arrayversion;");
680 outclassdefs.println(" int ___length___;");
681 outclassdefs.println("};\n");
682 outclassdefs.println("extern int classsize[];");
683 outclassdefs.println("extern int hasflags[];");
684 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
685 outclassdefs.println("extern int supertypes[];");
688 /** Prints out definitions for generic task structures */
690 private void outputTaskTypes(PrintWriter outtask) {
691 outtask.println("#ifndef _TASK_H");
692 outtask.println("#define _TASK_H");
693 outtask.println("struct parameterdescriptor {");
694 outtask.println("int type;");
695 outtask.println("int numberterms;");
696 outtask.println("int *intarray;");
697 outtask.println("void * queue;");
698 outtask.println("int numbertags;");
699 outtask.println("int *tagarray;");
700 outtask.println("};");
702 outtask.println("struct taskdescriptor {");
703 outtask.println("void * taskptr;");
704 outtask.println("int numParameters;");
705 outtask.println(" int numTotal;");
706 outtask.println("struct parameterdescriptor **descriptorarray;");
707 outtask.println("char * name;");
708 outtask.println("};");
709 outtask.println("extern struct taskdescriptor * taskarray[];");
710 outtask.println("extern numtasks;");
711 outtask.println("#endif");
715 private void buildRepairStructs(PrintWriter outrepairstructs) {
716 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
717 while(classit.hasNext()) {
718 ClassDescriptor cn=(ClassDescriptor)classit.next();
719 outrepairstructs.println("structure "+cn.getSymbol()+" {");
720 outrepairstructs.println(" int __type__;");
722 outrepairstructs.println(" int __flag__;");
723 if(!state.MULTICORE) {
724 outrepairstructs.println(" int __flagptr__;");
727 printRepairStruct(cn, outrepairstructs);
728 outrepairstructs.println("}\n");
731 for(int i=0; i<state.numArrays(); i++) {
732 TypeDescriptor tdarray=arraytable[i];
733 TypeDescriptor tdelement=tdarray.dereference();
734 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
735 outrepairstructs.println(" int __type__;");
736 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
737 outrepairstructs.println(" int length;");
739 // Need to add support to repair tool for this
740 if (tdelement.isClass()||tdelement.isArray())
741 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
743 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
745 outrepairstructs.println("}\n");
749 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
750 ClassDescriptor sp=cn.getSuperDesc();
752 printRepairStruct(sp, output);
754 Vector fields=(Vector)fieldorder.get(cn);
756 for(int i=0; i<fields.size(); i++) {
757 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
758 if (fd.getType().isArray()) {
759 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
760 } else if (fd.getType().isClass())
761 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
762 else if (fd.getType().isFloat())
763 output.println(" int "+fd.getSymbol()+"; /* really float */");
765 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
769 /** This method outputs TaskDescriptor information */
770 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
771 for (int i=0; i<task.numParameters(); i++) {
772 VarDescriptor param_var=task.getParameter(i);
773 TypeDescriptor param_type=task.getParamType(i);
774 FlagExpressionNode param_flag=task.getFlag(param_var);
775 TagExpressionList param_tag=task.getTag(param_var);
778 if (param_flag==null) {
779 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
780 output.println("0x0, 0x0 };");
783 DNFFlag dflag=param_flag.getDNF();
784 dnfterms=dflag.size();
786 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
787 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
788 for(int j=0; j<dflag.size(); j++) {
791 Vector term=dflag.get(j);
794 for(int k=0; k<term.size(); k++) {
795 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
796 FlagDescriptor fd=dfa.getFlag();
797 boolean negated=dfa.getNegated();
798 int flagid=1<<((Integer)flags.get(fd)).intValue();
803 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
805 output.println("};");
808 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
809 //BUG...added next line to fix, test with any task program
811 for(int j=0; j<param_tag.numTags(); j++) {
814 /* for each tag we need */
815 /* which slot it is */
816 /* what type it is */
817 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
818 TempDescriptor tmp=param_tag.getTemp(j);
819 int slot=fm.getTagInt(tmp);
820 output.println(slot+", "+state.getTagId(tvd.getTag()));
822 output.println("};");
824 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
825 output.println("/* type */"+param_type.getClassDesc().getId()+",");
826 output.println("/* number of DNF terms */"+dnfterms+",");
827 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
828 output.println("0,");
829 //BUG, added next line to fix and else statement...test
830 //with any task program
832 output.println("/* number of tags */"+param_tag.numTags()+",");
834 output.println("/* number of tags */ 0,");
835 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
836 output.println("};");
840 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
841 for (int i=0; i<task.numParameters(); i++) {
844 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
846 output.println("};");
848 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
849 output.println("&"+task.getSafeSymbol()+",");
850 output.println("/* number of parameters */" +task.numParameters() + ",");
851 int numtotal=task.numParameters()+fm.numTags();
852 output.println("/* number total parameters */" +numtotal + ",");
853 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
854 output.println("\""+task.getSymbol()+"\"");
855 output.println("};");
859 /** The buildVirtualTables method outputs the virtual dispatch
860 * tables for methods. */
862 protected void buildVirtualTables(PrintWriter outvirtual) {
863 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
864 while(classit.hasNext()) {
865 ClassDescriptor cd=(ClassDescriptor)classit.next();
866 if (virtualcalls.getMethodCount(cd)>maxcount)
867 maxcount=virtualcalls.getMethodCount(cd);
869 MethodDescriptor[][] virtualtable=null;
870 LocalityBinding[][] lbvirtualtable=null;
871 if (state.DSM||state.SINGLETM)
872 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
874 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
876 /* Fill in virtual table */
877 classit=state.getClassSymbolTable().getDescriptorsIterator();
878 while(classit.hasNext()) {
879 ClassDescriptor cd=(ClassDescriptor)classit.next();
880 if (state.DSM||state.SINGLETM)
881 fillinRow(cd, lbvirtualtable, cd.getId());
883 fillinRow(cd, virtualtable, cd.getId());
886 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
887 Iterator arrayit=state.getArrayIterator();
888 while(arrayit.hasNext()) {
889 TypeDescriptor td=(TypeDescriptor)arrayit.next();
890 int id=state.getArrayNumber(td);
891 if (state.DSM||state.SINGLETM)
892 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
894 fillinRow(objectcd, virtualtable, id+state.numClasses());
897 outvirtual.print("void * virtualtable[]={");
898 boolean needcomma=false;
899 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
900 for(int j=0; j<maxcount; j++) {
902 outvirtual.print(", ");
903 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
904 LocalityBinding lb=lbvirtualtable[i][j];
905 MethodDescriptor md=lb.getMethod();
906 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
907 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
908 MethodDescriptor md=virtualtable[i][j];
909 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
911 outvirtual.print("0");
915 outvirtual.println("");
917 outvirtual.println("};");
921 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
922 /* Get inherited methods */
923 if (cd.getSuperDesc()!=null)
924 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
925 /* Override them with our methods */
926 for(Iterator it=cd.getMethods(); it.hasNext();) {
927 MethodDescriptor md=(MethodDescriptor)it.next();
928 if (md.isStatic()||md.getReturnType()==null)
930 int methodnum=virtualcalls.getMethodNumber(md);
931 virtualtable[rownum][methodnum]=md;
935 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
936 /* Get inherited methods */
937 if (cd.getSuperDesc()!=null)
938 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
939 /* Override them with our methods */
940 if (locality.getClassBindings(cd)!=null)
941 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
942 LocalityBinding lb=lbit.next();
943 MethodDescriptor md=lb.getMethod();
944 //Is the method static or a constructor
945 if (md.isStatic()||md.getReturnType()==null)
947 int methodnum=virtualcalls.getLocalityNumber(lb);
948 virtualtable[rownum][methodnum]=lb;
952 /** Generate array that contains the sizes of class objects. The
953 * object allocation functions in the runtime use this
956 private void generateSizeArray(PrintWriter outclassdefs) {
957 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
958 outclassdefs.print("#ifdef TRANSSTATS \n");
959 outclassdefs.print("extern int numTransAbort;\n");
960 outclassdefs.print("extern int numTransCommit;\n");
961 outclassdefs.print("extern int nSoftAbort;\n");
963 outclassdefs.print("extern int nchashSearch;\n");
964 outclassdefs.print("extern int nmhashSearch;\n");
965 outclassdefs.print("extern int nprehashSearch;\n");
966 outclassdefs.print("extern int ndirtyCacheObj;\n");
967 outclassdefs.print("extern int nRemoteSend;\n");
968 outclassdefs.print("extern int sendRemoteReq;\n");
969 outclassdefs.print("extern int getResponse;\n");
970 outclassdefs.print("extern int bytesSent;\n");
971 outclassdefs.print("extern int bytesRecv;\n");
972 outclassdefs.print("extern int totalObjSize;\n");
973 outclassdefs.print("extern void handle();\n");
974 } else if (state.SINGLETM) {
975 outclassdefs.println("extern int nSoftAbortAbort;");
976 outclassdefs.println("extern int nSoftAbortCommit;");
977 outclassdefs.println("#ifdef STMSTATS\n");
978 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
979 outclassdefs.println("#endif\n");
981 outclassdefs.print("#endif\n");
983 if(state.DSMRECOVERYSTATS) {
984 outclassdefs.print("#ifdef RECOVERYSTATS\n");
985 outclassdefs.print("extern int numRecovery;\n");
986 outclassdefs.print("extern unsigned int deadMachine[8];\n");
987 outclassdefs.print("extern double elapsedTime[8];\n");
988 outclassdefs.print("#endif\n");
990 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
992 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
993 cdarray=new ClassDescriptor[state.numClasses()];
995 while(it.hasNext()) {
996 ClassDescriptor cd=(ClassDescriptor)it.next();
997 cdarray[cd.getId()]=cd;
1000 arraytable=new TypeDescriptor[state.numArrays()];
1002 Iterator arrayit=state.getArrayIterator();
1003 while(arrayit.hasNext()) {
1004 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1005 int id=state.getArrayNumber(td);
1011 /* Print out types */
1012 outclassdefs.println("/* ");
1013 for(int i=0; i<state.numClasses(); i++) {
1014 ClassDescriptor cd=cdarray[i];
1016 outclassdefs.println("NULL " + i);
1018 outclassdefs.println(cd +" "+i);
1022 for(int i=0; i<state.numArrays(); i++) {
1023 TypeDescriptor arraytd=arraytable[i];
1024 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
1027 outclassdefs.println("*/");
1030 outclassdefs.print("int classsize[]={");
1032 boolean needcomma=false;
1033 for(int i=0; i<state.numClasses(); i++) {
1035 outclassdefs.print(", ");
1037 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1039 outclassdefs.print("0");
1045 for(int i=0; i<state.numArrays(); i++) {
1047 outclassdefs.print(", ");
1048 TypeDescriptor tdelement=arraytable[i].dereference();
1049 if (tdelement.isArray()||tdelement.isClass())
1050 outclassdefs.print("sizeof(void *)");
1052 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1056 outclassdefs.println("};");
1058 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1060 outclassdefs.print("int typearray[]={");
1061 for(int i=0; i<state.numClasses(); i++) {
1062 ClassDescriptor cd=cdarray[i];
1063 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1065 outclassdefs.print(", ");
1067 outclassdefs.print("-1");
1069 outclassdefs.print(supercd.getId());
1073 for(int i=0; i<state.numArrays(); i++) {
1074 TypeDescriptor arraytd=arraytable[i];
1075 ClassDescriptor arraycd=arraytd.getClassDesc();
1076 if (arraycd==null) {
1078 outclassdefs.print(", ");
1079 outclassdefs.print(objectclass.getId());
1083 ClassDescriptor cd=arraycd.getSuperDesc();
1086 TypeDescriptor supertd=new TypeDescriptor(cd);
1087 supertd.setArrayCount(arraytd.getArrayCount());
1088 type=state.getArrayNumber(supertd);
1090 type+=state.numClasses();
1093 cd=cd.getSuperDesc();
1096 outclassdefs.print(", ");
1097 outclassdefs.print(type);
1101 outclassdefs.println("};");
1106 outclassdefs.print("int typearray2[]={");
1107 for(int i=0; i<state.numArrays(); i++) {
1108 TypeDescriptor arraytd=arraytable[i];
1109 ClassDescriptor arraycd=arraytd.getClassDesc();
1110 if (arraycd==null) {
1112 outclassdefs.print(", ");
1113 outclassdefs.print("-1");
1117 ClassDescriptor cd=arraycd.getSuperDesc();
1118 int level=arraytd.getArrayCount()-1;
1120 for(; level>0; level--) {
1121 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1122 supertd.setArrayCount(level);
1123 type=state.getArrayNumber(supertd);
1125 type+=state.numClasses();
1130 outclassdefs.print(", ");
1131 outclassdefs.print(type);
1135 outclassdefs.println("};");
1138 /** Constructs params and temp objects for each method or task.
1139 * These objects tell the compiler which temps need to be
1142 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1143 MethodDescriptor md=fm.getMethod();
1144 TaskDescriptor task=fm.getTask();
1145 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1146 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1148 paramstable.put(lb, objectparams);
1149 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1150 } else if (md!=null)
1151 paramstable.put(md, objectparams);
1153 paramstable.put(task, objectparams);
1155 for(int i=0; i<fm.numParameters(); i++) {
1156 TempDescriptor temp=fm.getParameter(i);
1157 TypeDescriptor type=temp.getType();
1158 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1159 objectparams.addPtr(temp);
1161 objectparams.addPrim(temp);
1162 if(lb!=null&&saveset.contains(temp)) {
1163 backuptable.get(lb).put(temp, temp.createNew());
1167 for(int i=0; i<fm.numTags(); i++) {
1168 TempDescriptor temp=fm.getTag(i);
1169 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1170 objectparams.addPtr(temp);
1172 objectparams.addPrim(temp);
1175 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1177 tempstable.put(lb, objecttemps);
1179 tempstable.put(md, objecttemps);
1181 tempstable.put(task, objecttemps);
1183 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1184 FlatNode fn=(FlatNode)nodeit.next();
1185 TempDescriptor[] writes=fn.writesTemps();
1186 for(int i=0; i<writes.length; i++) {
1187 TempDescriptor temp=writes[i];
1188 TypeDescriptor type=temp.getType();
1189 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1190 objecttemps.addPtr(temp);
1192 objecttemps.addPrim(temp);
1193 if(lb!=null&&saveset.contains(temp)&&
1194 !backuptable.get(lb).containsKey(temp))
1195 backuptable.get(lb).put(temp, temp.createNew());
1199 /* Create backup temps */
1201 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1202 TempDescriptor tmp=tmpit.next();
1203 TypeDescriptor type=tmp.getType();
1204 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1205 objecttemps.addPtr(tmp);
1207 objecttemps.addPrim(tmp);
1209 /* Create temp to hold revert table */
1210 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1211 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1212 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1213 objecttemps.addPtr(reverttmp);
1215 objecttemps.addPrim(reverttmp);
1216 reverttable.put(lb, reverttmp);
1221 /** This method outputs the following information about classes
1223 * (1) For classes, what are the locations of pointers.
1224 * (2) For arrays, does the array contain pointers or primitives.
1225 * (3) For classes, does the class contain flags.
1228 private void generateLayoutStructs(PrintWriter output) {
1229 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1230 while(it.hasNext()) {
1231 ClassDescriptor cn=(ClassDescriptor)it.next();
1232 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1233 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1235 while(allit.hasNext()) {
1236 FieldDescriptor fd=(FieldDescriptor)allit.next();
1237 TypeDescriptor type=fd.getType();
1238 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1243 output.print(count);
1244 allit=cn.getFieldTable().getAllDescriptorsIterator();
1245 while(allit.hasNext()) {
1246 FieldDescriptor fd=(FieldDescriptor)allit.next();
1247 TypeDescriptor type=fd.getType();
1248 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1251 output.println(",");
1252 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1255 output.println("};");
1257 output.println("unsigned INTPTR * pointerarray[]={");
1258 boolean needcomma=false;
1259 for(int i=0; i<state.numClasses(); i++) {
1260 ClassDescriptor cn=cdarray[i];
1262 output.println(",");
1265 output.print(cn.getSafeSymbol()+"_pointers");
1267 output.print("NULL");
1271 for(int i=0; i<state.numArrays(); i++) {
1273 output.println(", ");
1274 TypeDescriptor tdelement=arraytable[i].dereference();
1275 if (tdelement.isArray()||tdelement.isClass())
1276 output.print("((unsigned INTPTR *)1)");
1282 output.println("};");
1284 output.println("int hasflags[]={");
1285 for(int i=0; i<state.numClasses(); i++) {
1286 ClassDescriptor cn=cdarray[i];
1288 output.println(", ");
1290 if ((cn != null) && (cn.hasFlags()))
1295 output.println("};");
1298 /** Print out table to give us supertypes */
1299 private void generateSuperTypeTable(PrintWriter output) {
1300 output.println("int supertypes[]={");
1301 boolean needcomma=false;
1302 for(int i=0; i<state.numClasses(); i++) {
1303 ClassDescriptor cn=cdarray[i];
1305 output.println(",");
1307 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1308 ClassDescriptor cdsuper=cn.getSuperDesc();
1309 output.print(cdsuper.getId());
1313 output.println("};");
1316 /** Force consistent field ordering between inherited classes. */
1318 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1320 ClassDescriptor sp=cn.getSuperDesc();
1322 printClassStruct(sp, classdefout);
1324 if (!fieldorder.containsKey(cn)) {
1325 Vector fields=new Vector();
1326 fieldorder.put(cn,fields);
1327 Vector fieldvec=cn.getFieldVec();
1328 for(int i=0;i<fieldvec.size();i++) {
1329 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1330 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1334 Vector fields=(Vector)fieldorder.get(cn);
1336 for(int i=0; i<fields.size(); i++) {
1337 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1338 if (fd.getType().isClass()||fd.getType().isArray())
1339 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1341 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1346 /* Map flags to integers consistently between inherited
1349 protected void mapFlags(ClassDescriptor cn) {
1350 ClassDescriptor sp=cn.getSuperDesc();
1354 if (!flagorder.containsKey(cn)) {
1355 Hashtable flags=new Hashtable();
1356 flagorder.put(cn,flags);
1358 Hashtable superflags=(Hashtable)flagorder.get(sp);
1359 Iterator superflagit=superflags.keySet().iterator();
1360 while(superflagit.hasNext()) {
1361 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1362 Integer number=(Integer)superflags.get(fd);
1363 flags.put(fd, number);
1364 if ((number.intValue()+1)>max)
1365 max=number.intValue()+1;
1369 Iterator flagit=cn.getFlags();
1370 while(flagit.hasNext()) {
1371 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1372 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1373 flags.put(fd, new Integer(max++));
1379 /** This function outputs (1) structures that parameters are
1380 * passed in (when PRECISE GC is enabled) and (2) function
1381 * prototypes for the methods */
1383 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1384 /* Output class structure */
1385 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1386 classdefout.println(" int type;");
1387 if (state.EVENTMONITOR) {
1388 classdefout.println(" int objuid;");
1391 classdefout.println(" pthread_t tid;");
1392 classdefout.println(" void * lockentry;");
1393 classdefout.println(" int lockcount;");
1397 classdefout.println(" int flag;");
1398 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1399 classdefout.println(" void * flagptr;");
1400 } else if (state.MULTICORE) {
1401 classdefout.println(" int version;");
1402 classdefout.println(" int * lock;"); // lock entry for this obj
1403 classdefout.println(" int mutex;");
1404 classdefout.println(" int lockcount;");
1405 if(state.MULTICOREGC) {
1406 classdefout.println(" int marked;");
1409 if (state.OPTIONAL) {
1410 classdefout.println(" int numfses;");
1411 classdefout.println(" int * fses;");
1414 printClassStruct(cn, classdefout);
1415 classdefout.println("};\n");
1417 if (state.DSM||state.SINGLETM) {
1418 /* Cycle through LocalityBindings */
1419 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1420 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1422 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1423 LocalityBinding lb=lbit.next();
1424 MethodDescriptor md=lb.getMethod();
1425 if (md.getModifiers().isNative()) {
1426 //make sure we only print a native method once
1427 if (nativemethods.contains(md)) {
1428 FlatMethod fm=state.getMethodFlat(md);
1429 generateTempStructs(fm, lb);
1432 nativemethods.add(md);
1434 generateMethod(cn, md, lb, headersout, output);
1437 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1438 MethodDescriptor md=(MethodDescriptor)methodit.next();
1439 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1440 //Need to build param structure for library code
1441 FlatMethod fm=state.getMethodFlat(md);
1442 generateTempStructs(fm, null);
1443 generateMethodParam(cn, md, null, output);
1448 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1449 MethodDescriptor md=(MethodDescriptor)methodit.next();
1450 generateMethod(cn, md, null, headersout, output);
1454 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1455 /* Output parameter structure */
1456 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1457 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1458 if ((state.DSM||state.SINGLETM)&&lb!=null)
1459 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1461 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1462 output.println(" INTPTR size;");
1463 output.println(" void * next;");
1464 for(int i=0; i<objectparams.numPointers(); i++) {
1465 TempDescriptor temp=objectparams.getPointer(i);
1466 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1468 output.println("};\n");
1472 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1473 FlatMethod fm=state.getMethodFlat(md);
1474 generateTempStructs(fm, lb);
1476 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1477 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1479 generateMethodParam(cn, md, lb, output);
1481 /* Output temp structure */
1482 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1483 if (state.DSM||state.SINGLETM)
1484 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1486 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1487 output.println(" INTPTR size;");
1488 output.println(" void * next;");
1489 for(int i=0; i<objecttemps.numPointers(); i++) {
1490 TempDescriptor temp=objecttemps.getPointer(i);
1491 if (temp.getType().isNull())
1492 output.println(" void * "+temp.getSafeSymbol()+";");
1494 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1496 output.println("};\n");
1499 /********* Output method declaration ***********/
1500 if (state.DSM||state.SINGLETM) {
1501 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1503 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1505 /* First the return type */
1506 if (md.getReturnType()!=null) {
1507 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1508 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1510 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1512 //catch the constructor case
1513 headersout.print("void ");
1515 /* Next the method name */
1516 if (state.DSM||state.SINGLETM) {
1517 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1519 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1521 boolean printcomma=false;
1522 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1523 if (state.DSM||state.SINGLETM) {
1524 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1526 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1530 /* Output parameter list*/
1531 for(int i=0; i<objectparams.numPrimitives(); i++) {
1532 TempDescriptor temp=objectparams.getPrimitive(i);
1534 headersout.print(", ");
1536 if (temp.getType().isClass()||temp.getType().isArray())
1537 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1539 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1541 headersout.println(");\n");
1545 /** This function outputs (1) structures that parameters are
1546 * passed in (when PRECISE GC is enabled) and (2) function
1547 * prototypes for the tasks */
1549 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1550 /* Cycle through tasks */
1551 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1553 while(taskit.hasNext()) {
1554 /* Classify parameters */
1555 TaskDescriptor task=(TaskDescriptor)taskit.next();
1556 FlatMethod fm=state.getMethodFlat(task);
1557 generateTempStructs(fm, null);
1559 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1560 TempObject objecttemps=(TempObject) tempstable.get(task);
1562 /* Output parameter structure */
1563 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1564 output.println("struct "+task.getSafeSymbol()+"_params {");
1566 output.println(" INTPTR size;");
1567 output.println(" void * next;");
1568 for(int i=0; i<objectparams.numPointers(); i++) {
1569 TempDescriptor temp=objectparams.getPointer(i);
1570 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1573 output.println("};\n");
1574 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1575 maxtaskparams=objectparams.numPointers()+fm.numTags();
1579 /* Output temp structure */
1580 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1581 output.println("struct "+task.getSafeSymbol()+"_locals {");
1582 output.println(" INTPTR size;");
1583 output.println(" void * next;");
1584 for(int i=0; i<objecttemps.numPointers(); i++) {
1585 TempDescriptor temp=objecttemps.getPointer(i);
1586 if (temp.getType().isNull())
1587 output.println(" void * "+temp.getSafeSymbol()+";");
1588 else if(temp.getType().isTag())
1589 output.println(" struct "+
1590 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1592 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1594 output.println("};\n");
1597 /* Output task declaration */
1598 headersout.print("void " + task.getSafeSymbol()+"(");
1600 boolean printcomma=false;
1601 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1602 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1604 headersout.print("void * parameterarray[]");
1605 headersout.println(");\n");
1609 /***** Generate code for FlatMethod fm. *****/
1611 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1612 static int atomicmethodcount=0;
1615 BranchAnalysis branchanalysis;
1616 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1617 if (State.PRINTFLAT)
1618 System.out.println(fm.printMethod());
1619 MethodDescriptor md=fm.getMethod();
1620 TaskDescriptor task=fm.getTask();
1621 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1622 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1624 HashSet<AtomicRecord> arset=null;
1625 branchanalysis=null;
1627 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1629 if (atomicmethodmap==null)
1630 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1632 //fix these so we get right strings for local variables
1633 localsprefixaddr=localsprefix;
1634 localsprefixderef=localsprefix+"->";
1635 arset=new HashSet<AtomicRecord>();
1637 //build branchanalysis
1638 branchanalysis=new BranchAnalysis(locality, lb, delaycomp.getNotReady(lb), delaycomp.livecode(lb), state);
1640 //Generate commit methods here
1641 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1642 FlatNode fn=fnit.next();
1643 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1644 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
1645 delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
1646 //We have an atomic enter
1647 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1648 Set<FlatNode> exitset=faen.getExits();
1650 String methodname=md.getSymbol()+(atomicmethodcount++);
1651 AtomicRecord ar=new AtomicRecord();
1655 atomicmethodmap.put(faen, ar);
1657 //build data structure declaration
1658 output.println("struct atomicprimitives_"+methodname+" {");
1660 Set<FlatNode> recordset=delaycomp.livecode(lb);
1661 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1662 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1663 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1665 ar.reallivein=new HashSet(liveinto);
1667 ar.liveoutvirtualread=liveoutvirtualread;
1670 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1671 TempDescriptor tmp=it.next();
1672 //remove the pointers
1673 if (tmp.getType().isPtr()) {
1676 //let's print it here
1677 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1680 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1681 TempDescriptor tmp=it.next();
1682 //remove the pointers
1683 if (tmp.getType().isPtr()) {
1685 } else if (!liveinto.contains(tmp)) {
1686 //let's print it here
1687 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1690 output.println("};");
1692 //print out method name
1693 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) {");
1694 //build code for commit method
1696 //first define local primitives
1697 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1698 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1699 TempDescriptor tmp=tmpit.next();
1700 if (!tmp.getType().isPtr()) {
1701 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1702 //read from live into set
1703 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1706 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1710 //turn off write barrier generation
1712 state.SINGLETM=false;
1713 generateCode(faen, fm, lb, exitset, output, false);
1714 state.SINGLETM=true;
1715 //turn on write barrier generation
1717 output.println("}\n\n");
1721 //redefine these back to normal
1723 localsprefixaddr="&"+localsprefix;
1724 localsprefixderef=localsprefix+".";
1726 generateHeader(fm, lb, md!=null ? md : task,output);
1727 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1729 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1730 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1731 AtomicRecord ar=arit.next();
1732 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1736 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1737 if (md!=null&&(state.DSM||state.SINGLETM))
1738 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1739 else if (md!=null&&!(state.DSM||state.SINGLETM))
1740 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1742 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1744 output.print(objecttemp.numPointers()+",");
1745 output.print(paramsprefix);
1746 for(int j=0; j<objecttemp.numPointers(); j++)
1747 output.print(", NULL");
1748 output.println("};");
1751 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1752 TempDescriptor td=objecttemp.getPrimitive(i);
1753 TypeDescriptor type=td.getType();
1755 output.println(" void * "+td.getSafeSymbol()+";");
1756 else if (type.isClass()||type.isArray())
1757 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1759 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1764 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1765 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1766 if( callerSESEplaceholder != mlpa.getMainSESE() ) {
1767 // declare variables for naming static SESE's
1768 output.println(" /* static SESE names */");
1769 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1770 while( pItr.hasNext() ) {
1771 SESEandAgePair p = pItr.next();
1772 output.println(" void* "+p+";");
1775 // declare variables for tracking dynamic sources
1776 output.println(" /* dynamic variable sources */");
1777 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1778 while( dynSrcItr.hasNext() ) {
1779 TempDescriptor dynSrcVar = dynSrcItr.next();
1780 output.println(" void* "+dynSrcVar+"_srcSESE;");
1781 output.println(" int "+dynSrcVar+"_srcOffset;");
1786 // set up related allocation sites's waiting queues
1788 output.println(" /* set up waiting queues */");
1789 output.println(" int numRelatedWaitingQueue=0;");
1790 output.println(" int waitingQueueItemID=0;");
1791 ConflictGraph graph=null;
1792 graph=mlpa.getConflictGraphResults().get(fm);
1794 HashSet<SESELock> lockSet=mlpa.getConflictGraphLockMap().get(graph);
1796 if(lockSet.size()>0){
1797 output.println(" numRelatedWaitingQueue="+lockSet.size()+";");
1798 output.println(" seseCaller->numRelatedWaitingQueue=numRelatedWaitingQueue;");
1799 output.println(" seseCaller->allocSiteArray=mlpCreateAllocSiteArray(numRelatedWaitingQueue);");
1801 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1802 SESELock seseLock = (SESELock) iterator.next();
1803 output.println(" seseCaller->allocSiteArray["+idx+"].id="+seseLock.getID()+";");
1813 /* Check to see if we need to do a GC if this is a
1814 * multi-threaded program...*/
1816 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1817 || this.state.MULTICOREGC) {
1818 //Don't bother if we aren't in recursive methods...The loops case will catch it
1819 if (callgraph.getAllMethods(md).contains(md)) {
1820 if (state.DSM&&lb.isAtomic())
1821 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1822 else if (this.state.MULTICOREGC) {
1823 output.println("if(gcflag) gc("+localsprefixaddr+");");
1825 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1830 generateCode(fm.getNext(0), fm, lb, null, output, true);
1832 output.println("}\n\n");
1836 protected void initializeSESE( FlatSESEEnterNode fsen ) {
1838 FlatMethod fm = fsen.getfmEnclosing();
1839 MethodDescriptor md = fm.getMethod();
1840 ClassDescriptor cn = md.getClassDesc();
1843 // Creates bogus method descriptor to index into tables
1844 Modifiers modBogus = new Modifiers();
1845 MethodDescriptor mdBogus =
1846 new MethodDescriptor( modBogus,
1847 new TypeDescriptor( TypeDescriptor.VOID ),
1848 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1851 mdBogus.setClassDesc( fsen.getcdEnclosing() );
1852 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1853 fsen.setfmBogus( fmBogus );
1854 fsen.setmdBogus( mdBogus );
1856 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1857 inSetAndOutSet.addAll( fsen.getInVarSet() );
1858 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1860 // Build paramsobj for bogus method descriptor
1861 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
1862 paramstable.put( mdBogus, objectparams );
1864 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1865 while( itr.hasNext() ) {
1866 TempDescriptor temp = itr.next();
1867 TypeDescriptor type = temp.getType();
1868 if( type.isPtr() ) {
1869 objectparams.addPtr( temp );
1871 objectparams.addPrim( temp );
1875 // Build normal temp object for bogus method descriptor
1876 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
1877 tempstable.put( mdBogus, objecttemps );
1879 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
1880 FlatNode fn = (FlatNode)nodeit.next();
1881 TempDescriptor[] writes = fn.writesTemps();
1883 for( int i = 0; i < writes.length; i++ ) {
1884 TempDescriptor temp = writes[i];
1885 TypeDescriptor type = temp.getType();
1887 if( type.isPtr() ) {
1888 objecttemps.addPtr( temp );
1890 objecttemps.addPrim( temp );
1896 protected void generateMethodSESE(FlatSESEEnterNode fsen,
1898 PrintWriter outputStructs,
1899 PrintWriter outputMethHead,
1900 PrintWriter outputMethods
1903 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
1904 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
1906 // generate locals structure
1907 outputStructs.println("struct "+
1908 fsen.getcdEnclosing().getSafeSymbol()+
1909 fsen.getmdBogus().getSafeSymbol()+"_"+
1910 fsen.getmdBogus().getSafeMethodDescriptor()+
1912 outputStructs.println(" INTPTR size;");
1913 outputStructs.println(" void * next;");
1914 for(int i=0; i<objecttemps.numPointers(); i++) {
1915 TempDescriptor temp=objecttemps.getPointer(i);
1917 if( fsen.getPrettyIdentifier().equals( "calc" ) ) {
1918 System.out.println( " got a pointer "+temp );
1921 if (temp.getType().isNull())
1922 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1924 outputStructs.println(" struct "+
1925 temp.getType().getSafeSymbol()+" * "+
1926 temp.getSafeSymbol()+";");
1928 outputStructs.println("};\n");
1931 // generate the SESE record structure
1932 outputStructs.println(fsen.getSESErecordName()+" {");
1934 // data common to any SESE, and it must be placed first so
1935 // a module that doesn't know what kind of SESE record this
1936 // is can cast the pointer to a common struct
1937 outputStructs.println(" SESEcommon common;");
1939 // then garbage list stuff
1940 outputStructs.println(" INTPTR size;");
1941 outputStructs.println(" void * next;");
1943 // in-set source tracking
1944 // in-vars that are READY come from parent, don't need anything
1945 // stuff STATIC needs a custom SESE pointer for each age pair
1946 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
1947 while( itrStaticInVarSrcs.hasNext() ) {
1948 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
1949 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
1952 // DYNAMIC stuff needs a source SESE ptr and offset
1953 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
1954 while( itrDynInVars.hasNext() ) {
1955 TempDescriptor dynInVar = itrDynInVars.next();
1956 outputStructs.println(" void* "+dynInVar+"_srcSESE;");
1957 outputStructs.println(" int "+dynInVar+"_srcOffset;");
1960 // space for all in and out set primitives
1961 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1962 inSetAndOutSet.addAll( fsen.getInVarSet() );
1963 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1965 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
1967 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1968 while( itr.hasNext() ) {
1969 TempDescriptor temp = itr.next();
1970 TypeDescriptor type = temp.getType();
1971 if( !type.isPtr() ) {
1972 inSetAndOutSetPrims.add( temp );
1976 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
1977 while( itrPrims.hasNext() ) {
1978 TempDescriptor temp = itrPrims.next();
1979 TypeDescriptor type = temp.getType();
1980 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+";");
1983 for(int i=0; i<objectparams.numPointers(); i++) {
1984 TempDescriptor temp=objectparams.getPointer(i);
1985 if (temp.getType().isNull())
1986 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
1988 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1991 outputStructs.println("};\n");
1994 // write method declaration to header file
1995 outputMethHead.print("void ");
1996 outputMethHead.print(fsen.getSESEmethodName()+"(");
1997 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
1998 outputMethHead.println(");\n");
2001 generateFlatMethodSESE( fsen.getfmBogus(),
2002 fsen.getcdEnclosing(),
2008 private void generateFlatMethodSESE(FlatMethod fm,
2010 FlatSESEEnterNode fsen,
2011 FlatSESEExitNode seseExit,
2015 MethodDescriptor md=fm.getMethod();
2017 output.print("void ");
2018 output.print(fsen.getSESEmethodName()+"(");
2019 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
2020 output.println("){\n");
2022 TempObject objecttemp=(TempObject) tempstable.get(md);
2024 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2025 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2026 output.print(objecttemp.numPointers()+",");
2027 output.print("(void*) &("+paramsprefix+"->size)");
2028 for(int j=0; j<objecttemp.numPointers(); j++)
2029 output.print(", NULL");
2030 output.println("};");
2033 output.println(" /* regular local primitives */");
2034 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2035 TempDescriptor td=objecttemp.getPrimitive(i);
2036 TypeDescriptor type=td.getType();
2038 output.println(" void * "+td.getSafeSymbol()+";");
2039 else if (type.isClass()||type.isArray())
2040 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2042 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2046 // declare variables for naming static SESE's
2047 output.println(" /* static SESE names */");
2048 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
2049 while( pItr.hasNext() ) {
2050 SESEandAgePair p = pItr.next();
2051 output.println(" void* "+p+";");
2054 // declare variables for tracking dynamic sources
2055 output.println(" /* dynamic variable sources */");
2056 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
2057 while( dynSrcItr.hasNext() ) {
2058 TempDescriptor dynSrcVar = dynSrcItr.next();
2059 output.println(" void* "+dynSrcVar+"_srcSESE;");
2060 output.println(" int "+dynSrcVar+"_srcOffset;");
2063 // declare local temps for in-set primitives, and if it is
2064 // a ready-source variable, get the value from the record
2065 output.println(" /* local temps for in-set primitives */");
2066 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2067 while( itrInSet.hasNext() ) {
2068 TempDescriptor temp = itrInSet.next();
2069 TypeDescriptor type = temp.getType();
2070 if( !type.isPtr() ) {
2071 if( fsen.getReadyInVarSet().contains( temp ) ) {
2072 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2074 output.println(" "+type+" "+temp+";");
2079 // declare local temps for out-set primitives if its not already
2080 // in the in-set, and it's value will get written so no problem
2081 output.println(" /* local temp for out-set prim, not already in the in-set */");
2082 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2083 while( itrOutSet.hasNext() ) {
2084 TempDescriptor temp = itrOutSet.next();
2085 TypeDescriptor type = temp.getType();
2086 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2087 output.println(" "+type+" "+temp+";");
2091 // set up related allocation sites's waiting queues
2093 output.println(" /* set up waiting queues */");
2094 output.println(" int numRelatedWaitingQueue=0;");
2095 output.println(" int waitingQueueItemID=0;");
2096 ConflictGraph graph=null;
2097 graph=mlpa.getConflictGraphResults().get(fsen);
2098 if (graph != null) {
2099 output.println(" {");
2100 output.println(" SESEcommon* parentCommon = &(___params___->common);");
2101 HashSet<SESELock> lockSet=mlpa.getConflictGraphLockMap().get(graph);
2103 if (lockSet.size() > 0) {
2104 output.println(" numRelatedWaitingQueue=" + lockSet.size()
2107 .println(" parentCommon->numRelatedWaitingQueue=numRelatedWaitingQueue;");
2109 .println(" parentCommon->allocSiteArray=mlpCreateAllocSiteArray(numRelatedWaitingQueue);");
2111 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
2112 SESELock seseLock = (SESELock) iterator.next();
2113 output.println(" parentCommon->allocSiteArray[" + idx
2114 + "].id=" + seseLock.getID() + ";");
2119 output.println(" }");
2122 // copy in-set into place, ready vars were already
2123 // copied when the SESE was issued
2124 Iterator<TempDescriptor> tempItr;
2126 // static vars are from a known SESE
2127 tempItr = fsen.getStaticInVarSet().iterator();
2128 while( tempItr.hasNext() ) {
2129 TempDescriptor temp = tempItr.next();
2130 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2131 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2133 // can't grab something from this source until it is done
2134 output.println(" {");
2135 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+srcPair+";" );
2136 output.println(" pthread_mutex_lock( &(com->lock) );");
2137 output.println(" while( com->doneExecuting == FALSE ) {");
2138 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2139 output.println(" }");
2140 output.println(" pthread_mutex_unlock( &(com->lock) );");
2142 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2143 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2145 output.println(" }");
2148 // dynamic vars come from an SESE and src
2149 tempItr = fsen.getDynamicInVarSet().iterator();
2150 while( tempItr.hasNext() ) {
2151 TempDescriptor temp = tempItr.next();
2152 TypeDescriptor type = temp.getType();
2154 // go grab it from the SESE source
2155 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2157 // gotta wait until the source is done
2158 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+temp+"_srcSESE;" );
2159 output.println(" pthread_mutex_lock( &(com->lock) );");
2160 output.println(" while( com->doneExecuting == FALSE ) {");
2161 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2162 output.println(" }");
2163 output.println(" pthread_mutex_unlock( &(com->lock) );");
2166 if( type.isNull() ) {
2168 } else if( type.isClass() || type.isArray() ) {
2169 typeStr = "struct "+type.getSafeSymbol()+"*";
2171 typeStr = type.getSafeSymbol();
2174 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2175 " = *(("+typeStr+"*) ("+
2176 paramsprefix+"->"+temp+"_srcSESE + "+
2177 paramsprefix+"->"+temp+"_srcOffset));");
2179 // or if the source was our parent, its in the record to grab
2180 output.println(" } else {");
2181 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2182 " = "+paramsprefix+"->"+temp+";");
2183 output.println(" }");
2186 // Check to see if we need to do a GC if this is a
2187 // multi-threaded program...
2188 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2189 //Don't bother if we aren't in recursive methods...The loops case will catch it
2190 if (callgraph.getAllMethods(md).contains(md)) {
2191 if(this.state.MULTICOREGC) {
2192 output.println("if(gcflag) gc("+localsprefixaddr+");");
2194 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2199 // initialize thread-local var to a non-zero, invalid address
2200 output.println(" seseCaller = (SESEcommon*) 0x2;");
2201 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2202 exitset.add(seseExit);
2203 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2204 output.println("}\n\n");
2209 // when a new mlp thread is created for an issued SESE, it is started
2210 // by running this method which blocks on a cond variable until
2211 // it is allowed to transition to execute. Then a case statement
2212 // allows it to invoke the method with the proper SESE body, and after
2213 // exiting the SESE method, executes proper SESE exit code before the
2214 // thread can be destroyed
2215 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2216 PrintWriter outmethod
2219 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2220 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2221 outmethod.println( " int status;");
2222 outmethod.println( " char errmsg[128];");
2224 // generate a case for each SESE class that can be invoked
2225 outmethod.println( " switch( *((int*)seseRecord) ) {");
2226 outmethod.println( " ");
2227 for(Iterator<FlatSESEEnterNode> seseit=mlpa.getAllSESEs().iterator();seseit.hasNext();) {
2228 FlatSESEEnterNode fsen = seseit.next();
2230 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2231 outmethod.println( " case "+fsen.getIdentifier()+":");
2232 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2234 if( fsen.equals( mlpa.getMainSESE() ) ) {
2235 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2236 outmethod.println( " exit( 0 );");
2239 outmethod.println( " break;");
2240 outmethod.println( "");
2243 // default case should never be taken, error out
2244 outmethod.println( " default:");
2245 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2246 outmethod.println( " exit(-30);");
2247 outmethod.println( " break;");
2248 outmethod.println( " }");
2249 outmethod.println( " return NULL;");
2250 outmethod.println( "}\n\n");
2254 protected void generateCode(FlatNode first,
2257 Set<FlatNode> stopset,
2258 PrintWriter output, boolean firstpass) {
2260 /* Assign labels to FlatNode's if necessary.*/
2262 Hashtable<FlatNode, Integer> nodetolabel;
2264 if (state.DELAYCOMP&&!firstpass)
2265 nodetolabel=dcassignLabels(first, stopset);
2267 nodetolabel=assignLabels(first, stopset);
2269 Set<FlatNode> storeset=null;
2270 HashSet<FlatNode> genset=null;
2271 HashSet<FlatNode> refset=null;
2272 Set<FlatNode> unionset=null;
2274 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2275 storeset=delaycomp.livecode(lb);
2276 genset=new HashSet<FlatNode>();
2277 if (state.STMARRAY&&!state.DUALVIEW) {
2278 refset=new HashSet<FlatNode>();
2279 refset.addAll(delaycomp.getDeref(lb));
2280 refset.removeAll(delaycomp.getCannotDelay(lb));
2281 refset.removeAll(delaycomp.getOther(lb));
2284 genset.addAll(delaycomp.getCannotDelay(lb));
2285 genset.addAll(delaycomp.getOther(lb));
2287 genset.addAll(delaycomp.getNotReady(lb));
2288 if (state.STMARRAY&&!state.DUALVIEW) {
2289 genset.removeAll(refset);
2292 unionset=new HashSet<FlatNode>();
2293 unionset.addAll(storeset);
2294 unionset.addAll(genset);
2295 if (state.STMARRAY&&!state.DUALVIEW)
2296 unionset.addAll(refset);
2299 /* Do the actual code generation */
2300 FlatNode current_node=null;
2301 HashSet tovisit=new HashSet();
2302 HashSet visited=new HashSet();
2304 tovisit.add(first.getNext(0));
2307 while(current_node!=null||!tovisit.isEmpty()) {
2308 if (current_node==null) {
2309 current_node=(FlatNode)tovisit.iterator().next();
2310 tovisit.remove(current_node);
2311 } else if (tovisit.contains(current_node)) {
2312 tovisit.remove(current_node);
2314 visited.add(current_node);
2315 if (nodetolabel.containsKey(current_node)) {
2316 output.println("L"+nodetolabel.get(current_node)+":");
2318 if (state.INSTRUCTIONFAILURE) {
2319 if (state.THREAD||state.DSM||state.SINGLETM) {
2320 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2322 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2324 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2326 if (!state.DELAYCOMP||firstpass) {
2327 generateFlatNode(fm, lb, current_node, output);
2329 //store primitive variables in out set
2330 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2331 Set<TempDescriptor> liveout=ar.liveout;
2332 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2333 TempDescriptor tmp=tmpit.next();
2334 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2337 if (state.MLP && stopset!=null) {
2338 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2339 assert current_node instanceof FlatSESEExitNode;
2340 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2341 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2342 assert fsen.getFlatExit().equals( fsxn );
2343 assert fsxn.getFlatEnter().equals( fsen );
2345 if (current_node.kind()!=FKind.FlatReturnNode) {
2346 output.println(" return;");
2349 } else if(current_node.numNext()==1) {
2352 current_node.kind()==FKind.FlatSESEEnterNode &&
2353 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2355 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2356 generateFlatNode(fm, lb, current_node, output);
2357 nextnode=fsen.getFlatExit().getNext(0);
2358 } else if (state.DELAYCOMP) {
2359 boolean specialprimitive=false;
2360 //skip literals...no need to add extra overhead
2361 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2362 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2363 if (!typedesc.isClass()&&!typedesc.isArray()) {
2364 specialprimitive=true;
2368 if (genset==null||genset.contains(current_node)||specialprimitive)
2369 generateFlatNode(fm, lb, current_node, output);
2370 if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2371 //need to acquire lock
2372 handleArrayDeref(fm, lb, current_node, output, firstpass);
2374 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2375 TempDescriptor wrtmp=current_node.writesTemps()[0];
2377 //need to store value written by previous node
2378 if (wrtmp.getType().isPtr()) {
2379 //only lock the objects that may actually need locking
2380 if (recorddc.getNeedTrans(lb, current_node)&&
2381 (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2382 wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2383 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2385 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2388 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2391 //need to read value read by previous node
2392 if (wrtmp.getType().isPtr()) {
2393 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2395 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");
2399 nextnode=current_node.getNext(0);
2402 generateFlatNode(fm, lb, current_node, output);
2403 nextnode=current_node.getNext(0);
2405 if (visited.contains(nextnode)) {
2406 output.println("goto L"+nodetolabel.get(nextnode)+";");
2409 current_node=nextnode;
2410 } else if (current_node.numNext()==2) {
2412 if (state.DELAYCOMP) {
2413 boolean computeside=false;
2415 //need to record which way it should go
2416 if (genset==null||genset.contains(current_node)) {
2417 if (storeset!=null&&storeset.contains(current_node)) {
2418 //need to store which way branch goes
2419 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2421 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2423 //which side to execute
2427 if (genset.contains(current_node)) {
2428 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2429 } else if (storeset.contains(current_node)) {
2431 branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2433 //which side to execute
2438 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2440 if (leftset.size()==0)
2442 if (visited.contains(current_node.getNext(branch))) {
2443 //already visited -- build jump
2444 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2447 current_node=current_node.getNext(branch);
2450 if (!visited.contains(current_node.getNext(1)))
2451 tovisit.add(current_node.getNext(1));
2452 if (visited.contains(current_node.getNext(0))) {
2453 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2456 current_node=current_node.getNext(0);
2460 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2461 if (!visited.contains(current_node.getNext(1)))
2462 tovisit.add(current_node.getNext(1));
2463 if (visited.contains(current_node.getNext(0))) {
2464 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2467 current_node=current_node.getNext(0);
2469 } else throw new Error();
2473 protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2474 if (fn.kind()==FKind.FlatSetElementNode) {
2475 FlatSetElementNode fsen=(FlatSetElementNode) fn;
2476 String dst=generateTemp(fm, fsen.getDst(), lb);
2477 String src=generateTemp(fm, fsen.getSrc(), lb);
2478 String index=generateTemp(fm, fsen.getIndex(), lb);
2479 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2481 if (elementtype.isArray()||elementtype.isClass())
2484 type=elementtype.getSafeSymbol()+" ";
2486 output.println("STOREARRAY("+dst+","+index+","+type+")");
2488 output.println("{");
2489 output.println(" struct ArrayObject *array;");
2490 output.println(" int index;");
2491 output.println(" RESTOREARRAY(array,index);");
2492 output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2493 output.println("}");
2495 } else if (fn.kind()==FKind.FlatElementNode) {
2496 FlatElementNode fen=(FlatElementNode) fn;
2497 String src=generateTemp(fm, fen.getSrc(), lb);
2498 String index=generateTemp(fm, fen.getIndex(), lb);
2499 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2500 String dst=generateTemp(fm, fen.getDst(), lb);
2502 if (elementtype.isArray()||elementtype.isClass())
2505 type=elementtype.getSafeSymbol()+" ";
2507 output.println("STOREARRAY("+src+","+index+","+type+")");
2509 output.println("{");
2510 output.println(" struct ArrayObject *array;");
2511 output.println(" int index;");
2512 output.println(" RESTOREARRAY(array,index);");
2513 output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2514 output.println("}");
2518 /** Special label assignment for delaycomputation */
2519 protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2520 HashSet tovisit=new HashSet();
2521 HashSet visited=new HashSet();
2523 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2525 //Label targets of branches
2526 Set<FlatNode> targets=branchanalysis.getTargets();
2527 for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2528 nodetolabel.put(it.next(), new Integer(labelindex++));
2533 /*Assign labels first. A node needs a label if the previous
2534 * node has two exits or this node is a join point. */
2536 while(!tovisit.isEmpty()) {
2537 FlatNode fn=(FlatNode)tovisit.iterator().next();
2542 if(lastset!=null&&lastset.contains(fn)) {
2543 // if last is not null and matches, don't go
2544 // any further for assigning labels
2548 for(int i=0; i<fn.numNext(); i++) {
2549 FlatNode nn=fn.getNext(i);
2552 //1) Edge >1 of node
2553 nodetolabel.put(nn,new Integer(labelindex++));
2555 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2559 nodetolabel.put(nn,new Integer(labelindex++));
2567 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2568 return assignLabels(first, null);
2571 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2572 HashSet tovisit=new HashSet();
2573 HashSet visited=new HashSet();
2575 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2578 /*Assign labels first. A node needs a label if the previous
2579 * node has two exits or this node is a join point. */
2581 while(!tovisit.isEmpty()) {
2582 FlatNode fn=(FlatNode)tovisit.iterator().next();
2587 if(lastset!=null&&lastset.contains(fn)) {
2588 // if last is not null and matches, don't go
2589 // any further for assigning labels
2593 for(int i=0; i<fn.numNext(); i++) {
2594 FlatNode nn=fn.getNext(i);
2597 //1) Edge >1 of node
2598 nodetolabel.put(nn,new Integer(labelindex++));
2600 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2604 nodetolabel.put(nn,new Integer(labelindex++));
2612 /** Generate text string that corresponds to the TempDescriptor td. */
2613 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2614 MethodDescriptor md=fm.getMethod();
2615 TaskDescriptor task=fm.getTask();
2616 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2618 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2619 //System.out.println("generateTemp returns " + td.getSafeSymbol());
2620 return td.getSafeSymbol();
2623 if (objecttemps.isLocalPtr(td)) {
2624 return localsprefixderef+td.getSafeSymbol();
2627 if (objecttemps.isParamPtr(td)) {
2628 return paramsprefix+"->"+td.getSafeSymbol();
2634 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2636 // insert pre-node actions from the code plan
2639 CodePlan cp = mlpa.getCodePlan( fn );
2642 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2644 // for each sese and age pair that this parent statement
2645 // must stall on, take that child's stall semaphore, the
2646 // copying of values comes after the statement
2647 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2648 while( vstItr.hasNext() ) {
2649 VariableSourceToken vst = vstItr.next();
2651 SESEandAgePair p = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2653 output.println(" {");
2654 output.println(" SESEcommon* common = (SESEcommon*) "+p+";");
2656 output.println(" pthread_mutex_lock( &(common->lock) );");
2657 output.println(" while( common->doneExecuting == FALSE ) {");
2658 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2659 output.println(" }");
2660 output.println(" pthread_mutex_unlock( &(common->lock) );");
2662 //output.println(" psem_take( &(common->stallSem) );");
2664 // copy things we might have stalled for
2665 output.println(" "+p.getSESE().getSESErecordName()+"* child = ("+
2666 p.getSESE().getSESErecordName()+"*) "+p+";");
2668 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2669 while( tdItr.hasNext() ) {
2670 TempDescriptor td = tdItr.next();
2671 FlatMethod fmContext;
2672 if( currentSESE.getIsCallerSESEplaceholder() ) {
2673 fmContext = currentSESE.getfmEnclosing();
2675 fmContext = currentSESE.getfmBogus();
2677 output.println(" "+generateTemp( fmContext, td, null )+
2678 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2681 output.println(" }");
2684 // for each variable with a dynamic source, stall just for that variable
2685 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2686 while( dynItr.hasNext() ) {
2687 TempDescriptor dynVar = dynItr.next();
2689 // only stall if the dynamic source is not yourself, denoted by src==NULL
2690 // otherwise the dynamic write nodes will have the local var up-to-date
2691 output.println(" {");
2692 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2693 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2694 output.println(" psem_take( &(common->stallSem) );");
2696 FlatMethod fmContext;
2697 if( currentSESE.getIsCallerSESEplaceholder() ) {
2698 fmContext = currentSESE.getfmEnclosing();
2700 fmContext = currentSESE.getfmBogus();
2702 output.println(" "+generateTemp( fmContext, dynVar, null )+
2703 " = *(("+dynVar.getType()+"*) ("+
2704 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2706 output.println(" }");
2707 output.println(" }");
2710 // for each assignment of a variable to rhs that has a dynamic source,
2711 // copy the dynamic sources
2712 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2713 while( dynAssignItr.hasNext() ) {
2714 Map.Entry me = (Map.Entry) dynAssignItr.next();
2715 TempDescriptor lhs = (TempDescriptor) me.getKey();
2716 TempDescriptor rhs = (TempDescriptor) me.getValue();
2717 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
2718 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2721 // for each lhs that is dynamic from a non-dynamic source, set the
2722 // dynamic source vars to the current SESE
2723 dynItr = cp.getDynAssignCurr().iterator();
2724 while( dynItr.hasNext() ) {
2725 TempDescriptor dynVar = dynItr.next();
2726 output.println(" "+dynVar+"_srcSESE = NULL;");
2730 // handling stall site
2732 ParentChildConflictsMap conflictsMap=mlpa.getConflictsResults().get(fn);
2734 if (conflictsMap != null) {
2736 Set<Long> allocSet = conflictsMap
2737 .getAllocationSiteIDSetofStallSite();
2739 if (allocSet.size() > 0) {
2741 FlatNode enclosingFlatNode=null;
2742 if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
2743 enclosingFlatNode=currentSESE.getfmEnclosing();
2745 enclosingFlatNode=currentSESE;
2748 ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
2749 HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
2750 Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
2752 if(waitingElementSet.size()>0){
2753 output.println(" /* stall on parent's stall sites */");
2754 output.println(" {");
2755 output.println(" pthread_mutex_lock( &(seseCaller->lock) );");
2756 output.println(" ConflictNode* node;");
2757 output.println(" struct Queue* list=NULL;");
2758 output.println(" WaitingElement* newElement=NULL;");
2759 output.println(" struct QueueItem* newQItem=NULL;");
2760 output.println(" waitingQueueItemID++;");
2761 output.println(" psem_init( &(seseCaller->memoryStallSiteSem) );");
2762 output.println(" int qIdx;");
2763 output.println(" int takeCount=0;");
2764 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
2765 WaitingElement waitingElement = (WaitingElement) iterator.next();
2767 output.println(" qIdx=getQueueIdx(seseCaller->allocSiteArray,numRelatedWaitingQueue,"
2768 + waitingElement.getWaitingID() + ");");
2769 output.println(" if(qIdx!=-1 && !isEmpty(seseCaller->allocSiteArray[qIdx].waitingQueue)){");
2770 output.println(" list=createQueue();");
2771 for (Iterator iterator2 = waitingElement.getAllocList().iterator(); iterator2.hasNext();) {
2772 Integer allocID = (Integer) iterator2 .next();
2773 output.println(" node=mlpCreateConflictNode( "+ allocID + " );");
2774 output.println(" addNewItem(list,node);");
2776 output.println(" newElement=mlpCreateWaitingElement( "+ waitingElement.getStatus()
2777 + ", seseCaller, list, waitingQueueItemID );");
2778 output.println(" addNewItemBack(seseCaller->allocSiteArray[qIdx].waitingQueue,newElement);");
2779 output.println(" takeCount++;");
2780 output.println(" }");
2784 output.println(" pthread_mutex_unlock( &(seseCaller->lock) );");
2785 output.println(" if( takeCount>0 ){");
2786 output.println(" psem_take( &(seseCaller->memoryStallSiteSem) );");
2787 output.println(" }");
2788 output.println(" }");
2792 } // end of if (conflictsMap != null) {
2797 case FKind.FlatAtomicEnterNode:
2798 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
2801 case FKind.FlatAtomicExitNode:
2802 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
2805 case FKind.FlatInstanceOfNode:
2806 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
2809 case FKind.FlatSESEEnterNode:
2810 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
2813 case FKind.FlatSESEExitNode:
2814 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
2817 case FKind.FlatWriteDynamicVarNode:
2818 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
2821 case FKind.FlatGlobalConvNode:
2822 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
2825 case FKind.FlatTagDeclaration:
2826 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
2829 case FKind.FlatCall:
2830 generateFlatCall(fm, lb, (FlatCall) fn,output);
2833 case FKind.FlatFieldNode:
2834 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
2837 case FKind.FlatElementNode:
2838 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
2841 case FKind.FlatSetElementNode:
2842 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
2845 case FKind.FlatSetFieldNode:
2846 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
2850 generateFlatNew(fm, lb, (FlatNew) fn,output);
2853 case FKind.FlatOpNode:
2854 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
2857 case FKind.FlatCastNode:
2858 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
2861 case FKind.FlatLiteralNode:
2862 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
2865 case FKind.FlatReturnNode:
2866 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
2870 output.println("/* nop */");
2873 case FKind.FlatExit:
2874 output.println("/* exit */");
2877 case FKind.FlatBackEdge:
2878 if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
2879 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
2881 if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
2882 || (this.state.MULTICOREGC)) {
2883 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
2884 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
2885 } else if(this.state.MULTICOREGC) {
2886 output.println("if (gcflag) gc("+localsprefixaddr+");");
2888 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2891 output.println("/* nop */");
2894 case FKind.FlatCheckNode:
2895 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
2898 case FKind.FlatFlagActionNode:
2899 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
2902 case FKind.FlatPrefetchNode:
2903 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
2906 case FKind.FlatOffsetNode:
2907 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
2914 // insert post-node actions from the code-plan
2916 CodePlan cp = mlpa.getCodePlan( fn );
2923 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
2924 output.println("/* FlatOffsetNode */");
2925 FieldDescriptor fd=fofn.getField();
2926 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
2927 output.println("/* offset */");
2930 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
2931 if (state.PREFETCH) {
2932 Vector oids = new Vector();
2933 Vector fieldoffset = new Vector();
2934 Vector endoffset = new Vector();
2935 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
2936 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
2937 PrefetchPair pp = (PrefetchPair) it.next();
2938 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
2939 /* Find prefetches that can generate oid */
2940 if(statusbase == LocalityAnalysis.GLOBAL) {
2941 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
2943 } else if (statusbase == LocalityAnalysis.LOCAL) {
2944 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
2951 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
2952 output.println("{");
2953 output.println("/* prefetch */");
2954 output.println("/* prefetchid_" + fpn.siteid + " */");
2955 output.println("void * prefptr;");
2956 output.println("int tmpindex;");
2958 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
2959 /*Create C code for oid array */
2960 output.print(" unsigned int oidarray_[] = {");
2961 boolean needcomma=false;
2962 for (Iterator it = oids.iterator(); it.hasNext();) {
2965 output.print(it.next());
2968 output.println("};");
2970 /*Create C code for endoffset values */
2971 output.print(" unsigned short endoffsetarry_[] = {");
2973 for (Iterator it = endoffset.iterator(); it.hasNext();) {
2976 output.print(it.next());
2979 output.println("};");
2981 /*Create C code for Field Offset Values */
2982 output.print(" short fieldarry_[] = {");
2984 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
2987 output.print(it.next());
2990 output.println("};");
2991 /* make the prefetch call to Runtime */
2992 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
2993 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
2994 output.println(" }");
2995 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
2996 output.println(" } else {");
2997 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
2998 output.println(" }");
2999 output.println("}");
3003 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
3004 short offsetcount = 0;
3008 } else if (localbase) {
3009 for(; breakindex<pp.desc.size(); breakindex++) {
3010 Descriptor desc=pp.getDescAt(breakindex);
3011 if (desc instanceof FieldDescriptor) {
3012 FieldDescriptor fd=(FieldDescriptor)desc;
3013 if (fd.isGlobal()) {
3021 if (breakindex>pp.desc.size()) //all local
3024 TypeDescriptor lasttype=pp.base.getType();
3025 String basestr=generateTemp(fm, pp.base, lb);
3027 boolean maybenull=fm.getMethod().isStatic()||
3028 !pp.base.equals(fm.getParameter(0));
3030 for(int i=0; i<breakindex; i++) {
3031 String indexcheck="";
3033 Descriptor desc=pp.getDescAt(i);
3034 if (desc instanceof FieldDescriptor) {
3035 FieldDescriptor fd=(FieldDescriptor)desc;
3037 if (!teststr.equals(""))
3039 teststr+="((prefptr="+basestr+")!=NULL)";
3040 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3042 basestr=basestr+"->"+fd.getSafeSymbol();
3045 lasttype=fd.getType();
3047 IndexDescriptor id=(IndexDescriptor)desc;
3048 indexcheck="((tmpindex=";
3049 for(int j=0; j<id.tddesc.size(); j++) {
3050 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3052 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3054 if (!teststr.equals(""))
3056 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3057 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3059 lasttype=lasttype.dereference();
3064 if (teststr.equals("")) {
3065 oid="((unsigned int)"+basestr+")";
3067 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3071 for(int i = breakindex; i < pp.desc.size(); i++) {
3072 String newfieldoffset;
3073 Object desc = pp.getDescAt(i);
3074 if(desc instanceof FieldDescriptor) {
3075 FieldDescriptor fd=(FieldDescriptor)desc;
3076 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3077 lasttype=fd.getType();
3079 newfieldoffset = "";
3080 IndexDescriptor id=(IndexDescriptor)desc;
3081 for(int j = 0; j < id.tddesc.size(); j++) {
3082 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3084 newfieldoffset += id.offset.toString();
3085 lasttype=lasttype.dereference();
3087 fieldoffset.add(newfieldoffset);
3090 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3091 base+=pp.desc.size()-breakindex;
3092 endoffset.add(new Short((short)base));
3097 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3098 if (lb!=fgcn.getLocality())
3100 /* Have to generate flat globalconv */
3101 if (fgcn.getMakePtr()) {
3103 //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3104 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3106 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3107 //need to do translation
3108 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3109 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3110 if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3111 output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3113 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3117 /* Need to convert to OID */
3118 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3119 if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3120 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3122 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3128 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3130 if (fion.getType().isArray()) {
3131 type=state.getArrayNumber(fion.getType())+state.numClasses();
3133 type=fion.getType().getClassDesc().getId();
3136 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3137 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3139 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3142 int sandboxcounter=0;
3143 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3144 /* Check to see if we need to generate code for this atomic */
3145 if (locality==null) {
3146 if (GENERATEPRECISEGC) {
3147 output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3148 output.println("stopforgc((struct garbagelist *) &___locals___);");
3149 output.println("pthread_mutex_lock(&atomiclock);");
3150 output.println("restartaftergc();");
3151 output.println("}");
3153 output.println("pthread_mutex_lock(&atomiclock);");
3158 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3162 if (state.SANDBOX) {
3163 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3164 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3167 if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3168 AtomicRecord ar=atomicmethodmap.get(faen);
3170 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3171 TempDescriptor tmp=tmpit.next();
3172 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3175 //copy outs that depend on path
3176 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3177 TempDescriptor tmp=tmpit.next();
3178 if (!ar.livein.contains(tmp))
3179 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3183 /* Backup the temps. */
3184 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3185 TempDescriptor tmp=tmpit.next();
3186 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3189 output.println("goto transstart"+faen.getIdentifier()+";");
3191 /******* Print code to retry aborted transaction *******/
3192 output.println("transretry"+faen.getIdentifier()+":");
3195 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3196 TempDescriptor tmp=tmpit.next();
3197 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3201 /********* Need to revert local object store ********/
3202 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3204 output.println("while ("+revertptr+") {");
3205 output.println("struct ___Object___ * tmpptr;");
3206 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3207 output.println("REVERT_OBJ("+revertptr+");");
3208 output.println(revertptr+"=tmpptr;");
3209 output.println("}");
3211 /******* Tell the runtime to start the transaction *******/
3213 output.println("transstart"+faen.getIdentifier()+":");
3214 if (state.SANDBOX) {
3215 output.println("transaction_check_counter=*counter_reset_pointer;");
3218 output.println("transStart();");
3220 if (state.ABORTREADERS||state.SANDBOX) {
3222 output.println("abortenabled=1;");
3223 output.println("if (_setjmp(aborttrans)) {");
3224 output.println(" goto transretry"+faen.getIdentifier()+"; }");
3228 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3229 /* Check to see if we need to generate code for this atomic */
3230 if (locality==null) {
3231 output.println("pthread_mutex_unlock(&atomiclock);");
3234 if (locality.getAtomic(lb).get(faen).intValue()>0)
3236 //store the revert list before we lose the transaction object
3239 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3240 output.println(revertptr+"=revertlist;");
3241 output.println("if (transCommit()) {");
3242 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3243 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3244 output.println("} else {");
3245 /* Need to commit local object store */
3246 output.println("while ("+revertptr+") {");
3247 output.println("struct ___Object___ * tmpptr;");
3248 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3249 output.println("COMMIT_OBJ("+revertptr+");");
3250 output.println(revertptr+"=tmpptr;");
3251 output.println("}");
3252 output.println("}");
3256 if (!state.DELAYCOMP) {
3258 output.println("if (transCommit()) {");
3259 /* Transaction aborts if it returns true */
3260 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3261 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3262 output.println("}");
3264 if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
3265 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3266 output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3268 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3269 TempDescriptor tmp=tmpit.next();
3270 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3272 } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3273 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3275 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3276 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3277 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3278 output.println("}");
3280 output.println("else {");
3281 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3282 TempDescriptor tmp=tmpit.next();
3283 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3285 output.println("}");
3287 output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3288 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3289 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3290 output.println("}");
3295 public void generateFlatSESEEnterNode( FlatMethod fm,
3297 FlatSESEEnterNode fsen,
3301 // if MLP flag is off, okay that SESE nodes are in IR graph,
3302 // just skip over them and code generates exactly the same
3307 // there may be an SESE in an unreachable method, skip over
3308 if( !mlpa.getAllSESEs().contains( fsen ) ) {
3312 // also, if we have encountered a placeholder, just skip it
3313 if( fsen.getIsCallerSESEplaceholder() ) {
3317 output.println(" {");
3319 // set up the parent
3320 if( fsen == mlpa.getMainSESE() ) {
3321 output.println(" SESEcommon* parentCommon = NULL;");
3323 if( fsen.getParent() == null ) {
3324 System.out.println( "in "+fm+", "+fsen+" has null parent" );
3326 assert fsen.getParent() != null;
3327 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3328 output.println(" SESEcommon* parentCommon = &("+paramsprefix+"->common);");
3330 //output.println(" SESEcommon* parentCommon = (SESEcommon*) peekItem( seseCallStack );");
3331 output.println(" SESEcommon* parentCommon = seseCaller;");
3335 // before doing anything, lock your own record and increment the running children
3336 if( fsen != mlpa.getMainSESE() ) {
3337 output.println(" pthread_mutex_lock( &(parentCommon->lock) );");
3338 output.println(" ++(parentCommon->numRunningChildren);");
3339 output.println(" pthread_mutex_unlock( &(parentCommon->lock) );");
3342 // just allocate the space for this record
3343 output.println(" "+fsen.getSESErecordName()+"* seseToIssue = ("+
3344 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3345 fsen.getSESErecordName()+" ) );");
3347 // and keep the thread-local sese stack up to date
3348 //output.println(" addNewItem( seseCallStack, (void*) seseToIssue);");
3350 // fill in common data
3351 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3352 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
3354 output.println(" seseToIssue->common.forwardList = createQueue();");
3356 output.println(" seseToIssue->common.connectedList = createQueue();");
3358 output.println(" seseToIssue->common.unresolvedDependencies = 0;");
3359 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3360 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3361 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3362 output.println(" seseToIssue->common.numRunningChildren = 0;");
3363 output.println(" seseToIssue->common.parent = parentCommon;");
3365 // all READY in-vars should be copied now and be done with it
3366 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3367 while( tempItr.hasNext() ) {
3368 TempDescriptor temp = tempItr.next();
3370 // when we are issuing the main SESE or an SESE with placeholder
3371 // caller SESE as parent, generate temp child child's eclosing method,
3372 // otherwise use the parent's enclosing method as the context
3373 boolean useParentContext = false;
3375 if( fsen != mlpa.getMainSESE() ) {
3376 assert fsen.getParent() != null;
3377 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3378 useParentContext = true;
3382 if( useParentContext ) {
3383 output.println(" seseToIssue->"+temp+" = "+
3384 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3386 output.println(" seseToIssue->"+temp+" = "+
3387 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3391 // count up memory conflict dependencies,
3393 ConflictGraph graph=null;
3394 FlatSESEEnterNode parent=fsen.getParent();
3396 if(parent.isCallerSESEplaceholder){
3397 graph=mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
3399 graph=mlpa.getConflictGraphResults().get(parent);
3402 if (graph != null) {
3404 HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
3407 output.println(" /*add waiting queue element*/");
3408 output.println(" struct Queue* newWaitingItemQueue=createQueue();");
3410 Set<WaitingElement> waitingQueueSet=graph.getWaitingElementSetBySESEID(fsen
3411 .getIdentifier(),seseLockSet);
3412 if (waitingQueueSet.size() > 0) {
3413 output.println(" {");
3414 output.println(" waitingQueueItemID++;");
3415 output.println(" ConflictNode* node;");
3416 output.println(" WaitingElement* newElement=NULL;");
3417 output.println(" struct Queue* list=NULL;");
3418 output.println(" struct QueueItem* newQItem=NULL;");
3420 .println(" pthread_mutex_lock( &(parentCommon->lock) );");
3421 for (Iterator iterator = waitingQueueSet.iterator(); iterator
3423 WaitingElement waitingElement = (WaitingElement) iterator.next();
3424 output.println(" list=createQueue();");
3425 for (Iterator iterator2 = waitingElement.getAllocList().iterator(); iterator2
3427 Integer allocID = (Integer) iterator2
3429 output.println(" node=mlpCreateConflictNode( "+allocID+" );");
3430 output.println(" addNewItem(list,node);");
3432 output.println(" seseToIssue->common.waitingQueueItemID=waitingQueueItemID;");
3433 output.println(" newElement=mlpCreateWaitingElement( "+waitingElement.getStatus()+", seseToIssue, list, waitingQueueItemID );");
3436 .println(" newQItem=addWaitingQueueElement(parentCommon->allocSiteArray,numRelatedWaitingQueue,"
3437 + waitingElement.getWaitingID() + ",newElement);");
3439 .println(" addNewItem(newWaitingItemQueue,newQItem);");
3441 .println(" ++(seseToIssue->common.unresolvedDependencies);");
3446 .println(" pthread_mutex_unlock( &(parentCommon->lock) );");
3447 output.println(" }");
3450 output.println(" /*decide whether it is runnable or not in regarding to memory conflicts*/");
3451 output.println(" {");
3452 output.println(" pthread_mutex_lock( &(parentCommon->lock) );");
3453 output.println(" if( !isEmpty(newWaitingItemQueue) ){");
3454 output.println(" int idx;");
3455 output.println(" for(idx = 0 ; idx < numRelatedWaitingQueue ; idx++){");
3456 output.println(" struct Queue *allocQueue=parentCommon->allocSiteArray[idx].waitingQueue;");
3457 output.println(" if( !isEmpty(allocQueue) ){");
3458 output.println(" struct QueueItem* nextQItem=getHead(allocQueue);");
3459 output.println(" while( nextQItem != NULL ){");
3460 output.println(" if(contains(newWaitingItemQueue,nextQItem) && isRunnable(allocQueue,nextQItem)){");
3461 output.println(" --(seseToIssue->common.unresolvedDependencies);");
3462 output.println(" }");
3463 output.println(" nextQItem=getNextQueueItem(nextQItem);");
3464 output.println(" }");
3465 output.println(" }");
3466 output.println(" }");
3467 output.println(" pthread_mutex_unlock( &(parentCommon->lock) );");
3468 output.println(" }");
3469 output.println(" }");
3474 // before potentially adding this SESE to other forwarding lists,
3475 // create it's lock and take it immediately
3476 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3477 output.println(" pthread_mutex_lock( &(seseToIssue->common.lock) );");
3479 if( fsen != mlpa.getMainSESE() ) {
3480 // count up outstanding dependencies, static first, then dynamic
3481 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3482 while( staticSrcsItr.hasNext() ) {
3483 SESEandAgePair srcPair = staticSrcsItr.next();
3484 output.println(" {");
3485 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3486 output.println(" pthread_mutex_lock( &(src->lock) );");
3487 output.println(" if( !isEmpty( src->forwardList ) &&");
3488 output.println(" seseToIssue == peekItem( src->forwardList ) ) {");
3489 output.println(" printf( \"This shouldnt already be here\\n\");");
3490 output.println(" exit( -1 );");
3491 output.println(" }");
3492 output.println(" if( !src->doneExecuting ) {");
3493 output.println(" addNewItem( src->forwardList, seseToIssue );");
3494 output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3495 output.println(" }");
3496 output.println(" pthread_mutex_unlock( &(src->lock) );");
3497 output.println(" }");
3499 // whether or not it is an outstanding dependency, make sure
3500 // to pass the static name to the child's record
3501 output.println(" seseToIssue->"+srcPair+" = "+srcPair+";");
3504 // dynamic sources might already be accounted for in the static list,
3505 // so only add them to forwarding lists if they're not already there
3506 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3507 while( dynVarsItr.hasNext() ) {
3508 TempDescriptor dynInVar = dynVarsItr.next();
3509 output.println(" {");
3510 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3512 // the dynamic source is NULL if it comes from your own space--you can't pass
3513 // the address off to the new child, because you're not done executing and
3514 // might change the variable, so copy it right now
3515 output.println(" if( src != NULL ) {");
3516 output.println(" pthread_mutex_lock( &(src->lock) );");
3517 output.println(" if( isEmpty( src->forwardList ) ||");
3518 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3519 output.println(" if( !src->doneExecuting ) {");
3520 output.println(" addNewItem( src->forwardList, seseToIssue );");
3521 output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3522 output.println(" }");
3523 output.println(" }");
3524 output.println(" pthread_mutex_unlock( &(src->lock) );");
3525 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3526 output.println(" } else {");
3528 boolean useParentContext = false;
3529 if( fsen != mlpa.getMainSESE() ) {
3530 assert fsen.getParent() != null;
3531 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3532 useParentContext = true;
3535 if( useParentContext ) {
3536 output.println(" seseToIssue->"+dynInVar+" = "+
3537 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3539 output.println(" seseToIssue->"+dynInVar+" = "+
3540 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3543 output.println(" }");
3544 output.println(" }");
3546 // even if the value is already copied, make sure your NULL source
3547 // gets passed so child knows it already has the dynamic value
3548 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3551 // maintain pointers for for finding dynamic SESE
3552 // instances from static names
3553 SESEandAgePair p = new SESEandAgePair( fsen, 0 );
3554 if( fsen.getParent() != null &&
3555 //!fsen.getParent().getIsCallerSESEplaceholder() &&
3556 fsen.getParent().getNeededStaticNames().contains( p )
3559 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3560 SESEandAgePair p1 = new SESEandAgePair( fsen, i );
3561 SESEandAgePair p2 = new SESEandAgePair( fsen, i-1 );
3562 output.println(" "+p1+" = "+p2+";");
3564 output.println(" "+p+" = seseToIssue;");
3569 // if there were no outstanding dependencies, issue here
3570 output.println(" if( seseToIssue->common.unresolvedDependencies == 0 ) {");
3571 output.println(" workScheduleSubmit( (void*)seseToIssue );");
3572 output.println(" }");
3574 // release this SESE for siblings to update its dependencies or,
3575 // eventually, for it to mark itself finished
3576 output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
3577 output.println(" }");
3581 public void generateFlatSESEExitNode( FlatMethod fm,
3583 FlatSESEExitNode fsexn,
3587 // if MLP flag is off, okay that SESE nodes are in IR graph,
3588 // just skip over them and code generates exactly the same
3593 // get the enter node for this exit that has meta data embedded
3594 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
3596 // there may be an SESE in an unreachable method, skip over
3597 if( !mlpa.getAllSESEs().contains( fsen ) ) {
3601 // also, if we have encountered a placeholder, just jump it
3602 if( fsen.getIsCallerSESEplaceholder() ) {
3606 output.println(" /* SESE exiting */");
3608 String com = paramsprefix+"->common";
3610 // this SESE cannot be done until all of its children are done
3611 // so grab your own lock with the condition variable for watching
3612 // that the number of your running children is greater than zero
3613 output.println(" pthread_mutex_lock( &("+com+".lock) );");
3614 output.println(" while( "+com+".numRunningChildren > 0 ) {");
3615 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
3616 output.println(" }");
3618 // copy out-set from local temps into the sese record
3619 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
3620 while( itr.hasNext() ) {
3621 TempDescriptor temp = itr.next();
3623 // only have to do this for primitives
3624 if( !temp.getType().isPrimitive() ) {
3628 // have to determine the context enclosing this sese
3629 boolean useParentContext = false;
3631 if( fsen != mlpa.getMainSESE() ) {
3632 assert fsen.getParent() != null;
3633 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3634 useParentContext = true;
3639 if( useParentContext ) {
3640 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
3642 from = generateTemp( fsen.getfmEnclosing(), temp, null );
3645 output.println(" "+paramsprefix+
3646 "->"+temp.getSafeSymbol()+
3650 // mark yourself done, your SESE data is now read-only
3651 output.println(" "+com+".doneExecuting = TRUE;");
3652 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
3653 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
3655 // decrement dependency count for all SESE's on your forwarding list
3656 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
3657 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
3658 output.println(" pthread_mutex_lock( &(consumer->lock) );");
3659 output.println(" --(consumer->unresolvedDependencies);");
3660 output.println(" if( consumer->unresolvedDependencies == 0 ) {");
3661 output.println(" workScheduleSubmit( (void*)consumer );");
3662 output.println(" }");
3663 output.println(" pthread_mutex_unlock( &(consumer->lock) );");
3664 output.println(" }");
3667 // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
3668 if( fsen != mlpa.getMainSESE() ) {
3671 output.println(" /* check memory dependency*/");
3672 output.println(" {");
3673 output.println(" pthread_mutex_lock( &(___params___->common.parent->lock) );");
3674 output.println(" int idx;");
3675 output.println(" int giveCount=0;");
3676 output.println(" struct Queue* launchQueue=createQueue();");
3677 output.println(" struct QueueItem* nextQueueItem;");
3678 output.println(" for(idx = 0 ; idx < ___params___->common.parent->numRelatedWaitingQueue ; idx++){");
3679 output.println(" if(!isEmpty(___params___->common.parent->allocSiteArray[idx].waitingQueue)){");
3680 output.println(" struct QueueItem* qItem=getHead(___params___->common.parent->allocSiteArray[idx].waitingQueue);");
3681 output.println(" while(qItem!=NULL){");
3682 output.println(" WaitingElement* item=qItem->objectptr;");
3683 output.println(" SESEcommon* seseItem=(SESEcommon*)item->seseRec;");
3684 output.println(" if(seseItem->classID==___params___->common.classID && item->id==___params___->common.waitingQueueItemID){");
3685 output.println(" removeItem(___params___->common.parent->allocSiteArray[idx].waitingQueue,qItem);");
3686 output.println(" }");
3687 output.println(" qItem=getNextQueueItem(qItem);");
3688 output.println(" }");
3689 output.println(" if( !isEmpty(___params___->common.parent->allocSiteArray[idx].waitingQueue) ){");
3691 output.println(" struct QueueItem* nextQItem=getHead(___params___->common.parent->allocSiteArray[idx].waitingQueue);");
3692 output.println(" while(nextQItem!=NULL){");
3693 output.println(" WaitingElement* nextItem=nextQItem->objectptr;");
3694 output.println(" SESEcommon* seseNextItem=(SESEcommon*)nextItem->seseRec;");
3695 // output.println(" int isResolved=resolveWaitingQueue(___params___->common.parent->allocSiteArray[idx].waitingQueue,nextQItem);");
3696 output.println(" int isResolved=isRunnable(___params___->common.parent->allocSiteArray[idx].waitingQueue,nextQItem);");
3697 output.println(" if(seseNextItem->classID==___params___->common.parent->classID){"); // stall site
3698 output.println(" if(isResolved){");
3699 output.println(" struct QueueItem* stallItem=findItem(___params___->common.parent->allocSiteArray[idx].waitingQueue,nextItem);");
3700 output.println(" removeItem(___params___->common.parent->allocSiteArray[idx].waitingQueue,stallItem);");
3701 output.println(" giveCount++;");
3702 output.println(" }");
3703 output.println(" if(!isEmpty(___params___->common.parent->allocSiteArray[idx].waitingQueue)){");
3704 // output.println(" nextQItem=getHead(___params___->common.parent->allocSiteArray[idx].waitingQueue);");
3705 output.println(" nextQItem=getNextQueueItem(nextQItem);");
3706 output.println(" }else{");
3707 output.println(" nextQItem=NULL;");
3708 output.println(" }");
3709 output.println(" }else{");
3710 output.println(" if(isResolved){");
3711 output.println(" pthread_mutex_lock( &(seseNextItem->lock) );");
3712 output.println(" if(seseNextItem->unresolvedDependencies > 0){");
3713 output.println(" --(seseNextItem->unresolvedDependencies);");
3714 output.println(" if( seseNextItem->unresolvedDependencies == 0){");
3715 //output.println(" workScheduleSubmit( (void*)nextItem);");
3716 output.println(" addNewItem(launchQueue,(void*)seseNextItem);");
3717 output.println(" }");
3718 output.println(" }");
3719 output.println(" pthread_mutex_unlock( &(seseNextItem->lock) );");
3720 output.println(" }");
3721 output.println(" nextQItem=getNextQueueItem(nextQItem);");
3722 output.println(" }");
3723 output.println(" } "); // end of while(nextQItem!=NULL)
3724 output.println(" }");
3725 output.println(" }");
3726 // output.println(" }");
3727 output.println(" }");
3728 output.println(" pthread_mutex_unlock( &(___params___->common.parent->lock) );");
3729 output.println(" if(!isEmpty(launchQueue)){");
3730 output.println(" struct QueueItem* qItem=getHead(launchQueue);");
3731 output.println(" while(qItem!=NULL){");
3732 output.println(" workScheduleSubmit(qItem->objectptr);");
3733 output.println(" qItem=getNextQueueItem(qItem);");
3734 output.println(" }");
3735 output.println(" }");
3736 output.println(" if(giveCount>0){");
3737 output.println(" psem_give(&(___params___->common.parent->memoryStallSiteSem));");
3738 output.println(" }");
3739 output.println(" }");
3743 // if parent is stalling on you, let them know you're done
3744 if( fsexn.getFlatEnter() != mlpa.getMainSESE() ) {
3745 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
3748 // last of all, decrement your parent's number of running children
3749 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
3750 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
3751 output.println(" --("+paramsprefix+"->common.parent->numRunningChildren);");
3752 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
3753 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
3754 output.println(" }");
3756 // this is a thread-only variable that can be handled when critical sese-to-sese
3757 // data has been taken care of--set sese pointer to remember self over method
3758 // calls to a non-zero, invalid address
3759 output.println(" seseCaller = (SESEcommon*) 0x1;");
3763 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
3765 FlatWriteDynamicVarNode fwdvn,
3769 // should node should not be in an IR graph if the
3770 // MLP flag is not set
3771 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
3774 Hashtable<TempDescriptor, VariableSourceToken> writeDynamic =
3777 assert writeDynamic != null;
3779 Iterator wdItr = writeDynamic.entrySet().iterator();
3780 while( wdItr.hasNext() ) {
3781 Map.Entry me = (Map.Entry) wdItr.next();
3782 TempDescriptor refVar = (TempDescriptor) me.getKey();
3783 VariableSourceToken vst = (VariableSourceToken) me.getValue();
3785 FlatSESEEnterNode current = fwdvn.getEnclosingSESE();
3787 // only do this if the variable in question should be tracked,
3788 // meaning that it was explicitly added to the dynamic var set
3789 if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
3793 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
3795 output.println(" {");
3797 if( current.equals( vst.getSESE() ) ) {
3798 // if the src comes from this SESE, it's a method local variable,
3799 // mark src pointer NULL to signify that the var is up-to-date
3800 output.println(" "+vst.getAddrVar()+"_srcSESE = NULL;");
3803 // otherwise we track where it will come from
3804 output.println(" "+vst.getAddrVar()+"_srcSESE = "+instance+";");
3805 output.println(" "+vst.getAddrVar()+"_srcOffset = (int) &((("+
3806 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
3809 output.println(" }");
3814 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
3815 if (state.CONSCHECK) {
3816 String specname=fcn.getSpec();
3817 String varname="repairstate___";
3818 output.println("{");
3819 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
3821 TempDescriptor[] temps=fcn.getTemps();
3822 String[] vars=fcn.getVars();
3823 for(int i=0; i<temps.length; i++) {
3824 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
3827 output.println("if (doanalysis"+specname+"("+varname+")) {");
3828 output.println("free"+specname+"_state("+varname+");");
3829 output.println("} else {");
3830 output.println("/* Bad invariant */");
3831 output.println("free"+specname+"_state("+varname+");");
3832 output.println("abort_task();");
3833 output.println("}");
3834 output.println("}");
3838 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
3840 if( state.MLP && !nonSESEpass ) {
3841 output.println(" seseCaller = (SESEcommon*)"+paramsprefix+";");
3844 MethodDescriptor md=fc.getMethod();
3845 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
3846 ClassDescriptor cn=md.getClassDesc();
3847 output.println("{");
3848 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3850 LocalityBinding fclb=locality.getBinding(lb, fc);
3851 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3853 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
3855 output.print(objectparams.numPointers());
3856 output.print(", "+localsprefixaddr);
3857 if (md.getThis()!=null) {
3859 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
3861 if (fc.getThis()!=null&&md.getThis()==null) {
3862 System.out.println("WARNING!!!!!!!!!!!!");
3863 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
3867 for(int i=0; i<fc.numArgs(); i++) {
3868 Descriptor var=md.getParameter(i);
3869 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3870 if (objectparams.isParamPtr(paramtemp)) {
3871 TempDescriptor targ=fc.getArg(i);
3873 TypeDescriptor td=md.getParamType(i);
3875 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3877 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
3880 output.println("};");
3885 if (fc.getReturnTemp()!=null)
3886 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
3888 /* Do we need to do virtual dispatch? */
3889 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
3892 LocalityBinding fclb=locality.getBinding(lb, fc);
3893 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3895 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
3900 if (md.getReturnType().isClass()||md.getReturnType().isArray())
3901 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
3903 output.print(md.getReturnType().getSafeSymbol()+" ");
3904 output.print("(*)(");
3906 boolean printcomma=false;
3907 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3909 LocalityBinding fclb=locality.getBinding(lb, fc);
3910 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3912 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
3916 for(int i=0; i<objectparams.numPrimitives(); i++) {
3917 TempDescriptor temp=objectparams.getPrimitive(i);
3921 if (temp.getType().isClass()||temp.getType().isArray())
3922 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
3924 output.print(temp.getType().getSafeSymbol());
3929 LocalityBinding fclb=locality.getBinding(lb, fc);
3930 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
3932 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
3936 boolean needcomma=false;
3937 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
3938 output.print("&__parameterlist__");
3942 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
3943 if (fc.getThis()!=null) {
3944 TypeDescriptor ptd=md.getThis().getType();
3947 if (ptd.isClass()&&!ptd.isArray())
3948 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3949 output.print(generateTemp(fm,fc.getThis(),lb));
3954 for(int i=0; i<fc.numArgs(); i++) {
3955 Descriptor var=md.getParameter(i);
3956 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
3957 if (objectparams.isParamPrim(paramtemp)) {
3958 TempDescriptor targ=fc.getArg(i);
3962 TypeDescriptor ptd=md.getParamType(i);
3963 if (ptd.isClass()&&!ptd.isArray())
3964 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
3965 output.print(generateTemp(fm, targ,lb));
3969 output.println(");");
3970 output.println(" }");
3973 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
3974 Set subclasses=typeutil.getSubClasses(thiscd);
3975 if (subclasses==null)
3977 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
3978 ClassDescriptor cd=(ClassDescriptor)classit.next();
3979 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
3980 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
3981 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
3982 if (md.matches(matchmd))
3989 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
3990 if (state.SINGLETM) {
3991 //single machine transactional memory case
3992 String field=ffn.getField().getSafeSymbol();
3993 String src=generateTemp(fm, ffn.getSrc(),lb);
3994 String dst=generateTemp(fm, ffn.getDst(),lb);
3996 output.println(dst+"="+ src +"->"+field+ ";");
3997 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
3998 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
3999 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
4000 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
4001 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
4002 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
4003 if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
4004 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4006 output.println("TRANSREADRD("+dst+", "+dst+");");
4009 } else if (state.DSM) {
4010 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
4011 if (status==LocalityAnalysis.GLOBAL) {
4012 String field=ffn.getField().getSafeSymbol();
4013 String src=generateTemp(fm, ffn.getSrc(),lb);
4014 String dst=generateTemp(fm, ffn.getDst(),lb);
4016 if (ffn.getField().getType().isPtr()) {
4018 //TODO: Uncomment this when we have runtime support
4019 //if (ffn.getSrc()==ffn.getDst()) {
4020 //output.println("{");
4021 //output.println("void * temp="+src+";");
4022 //output.println("if (temp&0x1) {");
4023 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
4024 //output.println(src+"->"+field+"="+temp+";");
4025 //output.println("}");
4026 //output.println(dst+"=temp;");
4027 //output.println("}");
4029 output.println(dst+"="+ src +"->"+field+ ";");
4030 //output.println("if ("+dst+"&0x1) {");
4031 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4032 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4033 //output.println(src+"->"+field+"="+src+"->"+field+";");
4034 //output.println("}");
4037 output.println(dst+"="+ src+"->"+field+";");
4039 } else if (status==LocalityAnalysis.LOCAL) {
4040 if (ffn.getField().getType().isPtr()&&
4041 ffn.getField().isGlobal()) {
4042 String field=ffn.getField().getSafeSymbol();
4043 String src=generateTemp(fm, ffn.getSrc(),lb);
4044 String dst=generateTemp(fm, ffn.getDst(),lb);
4045 output.println(dst+"="+ src +"->"+field+ ";");
4046 if (locality.getAtomic(lb).get(ffn).intValue()>0)
4047 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4048 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4050 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4051 } else if (status==LocalityAnalysis.EITHER) {
4052 //Code is reading from a null pointer
4053 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
4054 output.println("#ifndef RAW");
4055 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4056 output.println("#endif");
4057 //This should throw a suitable null pointer error
4058 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4060 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4062 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4066 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
4067 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
4068 throw new Error("Can't set array length");
4069 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4070 //Single Machine Transaction Case
4071 boolean srcptr=fsfn.getSrc().getType().isPtr();
4072 String src=generateTemp(fm,fsfn.getSrc(),lb);
4073 String dst=generateTemp(fm,fsfn.getDst(),lb);
4074 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
4075 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
4076 output.println("{");
4077 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
4078 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
4079 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4081 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4084 if (wb.needBarrier(fsfn)&&
4085 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
4086 if (state.EVENTMONITOR) {
4087 output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
4089 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
4091 if (srcptr&!fsfn.getSrc().getType().isNull()) {
4092 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4093 output.println("}");
4095 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4097 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4098 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
4099 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
4100 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4102 String src=generateTemp(fm,fsfn.getSrc(),lb);
4103 String dst=generateTemp(fm,fsfn.getDst(),lb);
4105 output.println("{");
4106 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4108 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
4111 if (wb.needBarrier(fsfn))
4112 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
4114 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4116 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4117 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
4118 /** Check if we need to copy */
4119 output.println("if(!"+dst+"->"+localcopystr+") {");
4120 /* Link object into list */
4121 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4122 output.println(revertptr+"=revertlist;");
4123 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4124 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4126 output.println("COPY_OBJ("+dst+");");
4127 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4128 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4129 output.println("}");
4131 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4133 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4134 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
4135 //writing to a null...bad
4136 output.println("if ("+dst+") {");
4137 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
4139 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4141 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4144 output.println("}");
4147 if (state.FASTCHECK) {
4148 String dst=generateTemp(fm, fsfn.getDst(),lb);
4149 output.println("if(!"+dst+"->"+localcopystr+") {");
4150 /* Link object into list */
4151 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4152 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4154 output.println("COPY_OBJ("+dst+");");
4155 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4156 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4157 output.println("}");
4159 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4163 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
4164 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
4167 if (elementtype.isArray()||elementtype.isClass())
4170 type=elementtype.getSafeSymbol()+" ";
4172 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
4173 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
4174 output.println("failedboundschk();");
4176 if (state.SINGLETM) {
4177 //Single machine transaction case
4178 String dst=generateTemp(fm, fen.getDst(),lb);
4179 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))) {
4180 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4182 output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
4185 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
4186 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
4187 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
4188 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
4189 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
4190 if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
4191 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4193 output.println("TRANSREADRD("+dst+", "+dst+");");
4196 } else if (state.DSM) {
4197 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
4198 if (status==LocalityAnalysis.GLOBAL) {
4199 String dst=generateTemp(fm, fen.getDst(),lb);
4200 if (elementtype.isPtr()) {
4201 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4202 //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
4203 output.println("TRANSREAD("+dst+", "+dst+");");
4205 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4207 } else if (status==LocalityAnalysis.LOCAL) {
4208 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4209 } else if (status==LocalityAnalysis.EITHER) {
4210 //Code is reading from a null pointer
4211 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
4212 output.println("#ifndef RAW");
4213 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4214 output.println("#endif");
4215 //This should throw a suitable null pointer error
4216 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4218 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4220 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4224 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
4225 //TODO: need dynamic check to make sure this assignment is actually legal
4226 //Because Object[] could actually be something more specific...ie. Integer[]
4228 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
4231 if (elementtype.isArray()||elementtype.isClass())
4234 type=elementtype.getSafeSymbol()+" ";
4236 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
4237 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
4238 output.println("failedboundschk();");
4241 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4242 //Transaction set element case
4243 if (wb.needBarrier(fsen)&&
4244 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
4245 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
4247 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
4248 output.println("{");
4249 String src=generateTemp(fm, fsen.getSrc(), lb);
4250 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
4251 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
4252 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4254 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4256 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4257 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
4259 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4261 output.println("}");
4263 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4264 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
4266 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4269 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4270 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
4271 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
4272 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4273 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
4274 boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
4277 if (wb.needBarrier(fsen))
4278 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
4279 } else if (dstlocal) {
4280 /** Check if we need to copy */
4281 String dst=generateTemp(fm, fsen.getDst(),lb);
4282 output.println("if(!"+dst+"->"+localcopystr+") {");
4283 /* Link object into list */
4284 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4285 output.println(revertptr+"=revertlist;");
4286 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
4287 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4289 output.println("COPY_OBJ("+dst+");");
4290 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4291 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4292 output.println("}");
4294 System.out.println("Node: "+fsen);
4295 System.out.println(lb);
4296 System.out.println("statusdst="+statusdst);
4297 System.out.println(fm.printMethod());
4298 throw new Error("Unknown array type");
4301 output.println("{");
4302 String src=generateTemp(fm, fsen.getSrc(), lb);
4303 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4304 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4305 output.println("}");
4307 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4310 if (state.FASTCHECK) {
4311 String dst=generateTemp(fm, fsen.getDst(),lb);
4312 output.println("if(!"+dst+"->"+localcopystr+") {");
4313 /* Link object into list */
4314 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4315 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4317 output.println("COPY_OBJ("+dst+");");
4318 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4319 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4320 output.println("}");
4322 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4326 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
4327 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4328 //Stash pointer in case of GC
4329 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4330 output.println(revertptr+"=revertlist;");
4332 if (state.SINGLETM) {
4333 if (fn.getType().isArray()) {
4334 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4335 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4336 //inside transaction
4337 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4339 //outside transaction
4340 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4343 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4344 //inside transaction
4345 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4347 //outside transaction
4348 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4351 } else if (fn.getType().isArray()) {
4352 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4353 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4354 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4355 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4356 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4358 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4361 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4362 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
4363 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4364 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4366 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
4369 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4370 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4371 String dst=generateTemp(fm,fn.getDst(),lb);
4372 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4373 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4374 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4376 if (state.FASTCHECK) {
4377 String dst=generateTemp(fm,fn.getDst(),lb);
4378 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4379 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4380 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4384 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
4385 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4386 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
4388 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
4392 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
4393 if (fon.getRight()!=null) {
4394 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
4395 if (fon.getLeft().getType().isLong())
4396 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4398 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4400 } else if (dc!=null) {
4401 output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
4402 if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4403 output.print("(void *)");
4404 if (dc.getNeedLeftSrcTrans(lb, fon))
4405 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
4407 output.print(generateTemp(fm, fon.getLeft(),lb));
4408 output.print(")"+fon.getOp().toString()+"(");
4409 if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4410 output.print("(void *)");
4411 if (dc.getNeedRightSrcTrans(lb, fon))
4412 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
4414 output.println(generateTemp(fm,fon.getRight(),lb)+");");
4416 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
4417 } else if (fon.getOp().getOp()==Operation.ASSIGN)
4418 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4419 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
4420 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4421 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
4422 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
4423 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
4424 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
4425 else if (fon.getOp().getOp()==Operation.COMP)
4426 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
4427 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
4428 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
4430 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
4433 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
4434 /* TODO: Do type check here */
4435 if (fcn.getType().isArray()) {
4436 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4437 } else if (fcn.getType().isClass())
4438 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4440 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
4443 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
4444 if (fln.getValue()==null)
4445 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4446 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
4447 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4448 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4449 //Stash pointer in case of GC
4450 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4451 output.println(revertptr+"=revertlist;");
4453 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4454 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4455 //Stash pointer in case of GC
4456 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4457 output.println("revertlist="+revertptr+";");
4460 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4462 } else if (fln.getType().isBoolean()) {
4463 if (((Boolean)fln.getValue()).booleanValue())
4464 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
4466 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4467 } else if (fln.getType().isChar()) {
4468 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
4469 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
4470 } else if (fln.getType().isLong()) {
4471 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
4473 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
4476 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
4477 if (frn.getReturnTemp()!=null) {
4478 if (frn.getReturnTemp().getType().isPtr())
4479 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4481 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4483 output.println("return;");
4487 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4490 //only record if this group has more than one exit
4491 if (branchanalysis.numJumps(fcb)>1) {
4492 left=branchanalysis.jumpValue(fcb, 0);
4493 right=branchanalysis.jumpValue(fcb, 1);
4495 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
4497 output.println("STOREBRANCH("+right+");");
4498 output.println("goto "+label+";");
4499 output.println("}");
4501 output.println("STOREBRANCH("+left+");");
4504 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
4505 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
4508 /** This method generates header information for the method or
4509 * task referenced by the Descriptor des. */
4510 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
4511 generateHeader(fm, lb, des, output, false);
4514 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
4516 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
4517 MethodDescriptor md=null;
4518 TaskDescriptor task=null;
4519 if (des instanceof MethodDescriptor)
4520 md=(MethodDescriptor) des;
4522 task=(TaskDescriptor) des;
4524 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
4526 if (md!=null&&md.getReturnType()!=null) {
4527 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4528 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4530 output.print(md.getReturnType().getSafeSymbol()+" ");
4532 //catch the constructor case
4533 output.print("void ");
4535 if (state.DSM||state.SINGLETM) {
4536 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4538 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
4540 output.print(task.getSafeSymbol()+"(");
4542 boolean printcomma=false;
4543 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4545 if (state.DSM||state.SINGLETM) {
4546 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4548 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
4550 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
4556 for(int i=0; i<objectparams.numPrimitives(); i++) {
4557 TempDescriptor temp=objectparams.getPrimitive(i);
4561 if (temp.getType().isClass()||temp.getType().isArray())
4562 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
4564 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
4566 output.println(") {");
4567 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4568 /* Imprecise Task */
4569 output.println("void * parameterarray[]) {");
4570 /* Unpack variables */
4571 for(int i=0; i<objectparams.numPrimitives(); i++) {
4572 TempDescriptor temp=objectparams.getPrimitive(i);
4573 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
4575 for(int i=0; i<fm.numTags(); i++) {
4576 TempDescriptor temp=fm.getTag(i);
4577 int offset=i+objectparams.numPrimitives();
4578 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
4581 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
4582 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
4583 } else output.println(") {");
4586 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
4587 output.println("/* FlatFlagActionNode */");
4590 /* Process tag changes */
4591 Relation tagsettable=new Relation();
4592 Relation tagcleartable=new Relation();
4594 Iterator tagsit=ffan.getTempTagPairs();
4595 while (tagsit.hasNext()) {
4596 TempTagPair ttp=(TempTagPair) tagsit.next();
4597 TempDescriptor objtmp=ttp.getTemp();
4598 TagDescriptor tag=ttp.getTag();
4599 TempDescriptor tagtmp=ttp.getTagTemp();
4600 boolean tagstatus=ffan.getTagChange(ttp);
4602 tagsettable.put(objtmp, tagtmp);
4604 tagcleartable.put(objtmp, tagtmp);
4609 Hashtable flagandtable=new Hashtable();
4610 Hashtable flagortable=new Hashtable();
4612 /* Process flag changes */
4613 Iterator flagsit=ffan.getTempFlagPairs();
4614 while(flagsit.hasNext()) {
4615 TempFlagPair tfp=(TempFlagPair)flagsit.next();
4616 TempDescriptor temp=tfp.getTemp();
4617 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
4618 FlagDescriptor flag=tfp.getFlag();
4620 //Newly allocate objects that don't set any flags case
4621 if (flagortable.containsKey(temp)) {
4625 flagortable.put(temp,new Integer(mask));
4627 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
4628 boolean flagstatus=ffan.getFlagChange(tfp);
4631 if (flagortable.containsKey(temp)) {
4632 mask=((Integer)flagortable.get(temp)).intValue();
4635 flagortable.put(temp,new Integer(mask));
4637 int mask=0xFFFFFFFF;
4638 if (flagandtable.containsKey(temp)) {
4639 mask=((Integer)flagandtable.get(temp)).intValue();
4641 mask&=(0xFFFFFFFF^flagid);
4642 flagandtable.put(temp,new Integer(mask));
4648 HashSet flagtagset=new HashSet();
4649 flagtagset.addAll(flagortable.keySet());
4650 flagtagset.addAll(flagandtable.keySet());
4651 flagtagset.addAll(tagsettable.keySet());
4652 flagtagset.addAll(tagcleartable.keySet());
4654 Iterator ftit=flagtagset.iterator();
4655 while(ftit.hasNext()) {
4656 TempDescriptor temp=(TempDescriptor)ftit.next();
4659 Set tagtmps=tagcleartable.get(temp);
4660 if (tagtmps!=null) {
4661 Iterator tagit=tagtmps.iterator();
4662 while(tagit.hasNext()) {
4663 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4664 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4665 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4667 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4671 tagtmps=tagsettable.get(temp);
4672 if (tagtmps!=null) {
4673 Iterator tagit=tagtmps.iterator();
4674 while(tagit.hasNext()) {
4675 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
4676 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
4677 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
4679 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
4684 int andmask=0xFFFFFFF;
4686 if (flagortable.containsKey(temp))
4687 ormask=((Integer)flagortable.get(temp)).intValue();
4688 if (flagandtable.containsKey(temp))
4689 andmask=((Integer)flagandtable.get(temp)).intValue();
4690 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
4691 generateObjectDistribute(ffan, fm, lb, temp, output);
4695 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
4696 PrintWriter output, int ormask, int andmask) {
4697 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
4698 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4700 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
4704 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
4705 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
4708 void generateOptionalHeader(PrintWriter headers) {
4711 headers.println("#include \"task.h\"\n\n");
4712 headers.println("#ifndef _OPTIONAL_STRUCT_");
4713 headers.println("#define _OPTIONAL_STRUCT_");
4715 //STRUCT PREDICATEMEMBER
4716 headers.println("struct predicatemember{");
4717 headers.println("int type;");
4718 headers.println("int numdnfterms;");
4719 headers.println("int * flags;");
4720 headers.println("int numtags;");
4721 headers.println("int * tags;\n};\n\n");
4723 //STRUCT OPTIONALTASKDESCRIPTOR
4724 headers.println("struct optionaltaskdescriptor{");
4725 headers.println("struct taskdescriptor * task;");
4726 headers.println("int index;");
4727 headers.println("int numenterflags;");
4728 headers.println("int * enterflags;");
4729 headers.println("int numpredicatemembers;");
4730 headers.println("struct predicatemember ** predicatememberarray;");
4731 headers.println("};\n\n");
4733 //STRUCT TASKFAILURE
4734 headers.println("struct taskfailure {");
4735 headers.println("struct taskdescriptor * task;");
4736 headers.println("int index;");
4737 headers.println("int numoptionaltaskdescriptors;");
4738 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4740 //STRUCT FSANALYSISWRAPPER
4741 headers.println("struct fsanalysiswrapper{");
4742 headers.println("int flags;");
4743 headers.println("int numtags;");
4744 headers.println("int * tags;");
4745 headers.println("int numtaskfailures;");
4746 headers.println("struct taskfailure ** taskfailurearray;");
4747 headers.println("int numoptionaltaskdescriptors;");
4748 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
4750 //STRUCT CLASSANALYSISWRAPPER
4751 headers.println("struct classanalysiswrapper{");
4752 headers.println("int type;");
4753 headers.println("int numotd;");
4754 headers.println("struct optionaltaskdescriptor ** otdarray;");
4755 headers.println("int numfsanalysiswrappers;");
4756 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
4758 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
4760 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
4761 while(taskit.hasNext()) {
4762 TaskDescriptor td=(TaskDescriptor)taskit.next();
4763 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
4768 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
4769 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
4770 int predicateindex = 0;
4771 //iterate through the classes concerned by the predicate
4772 Set c_vard = predicate.vardescriptors;
4773 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
4776 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
4777 VarDescriptor vard = (VarDescriptor)vard_it.next();
4778 TypeDescriptor typed = vard.getType();
4780 //generate for flags
4781 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
4782 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4784 if (fen_hashset!=null) {
4785 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
4786 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
4788 DNFFlag dflag=fen.getDNF();
4789 numberterms+=dflag.size();
4791 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
4793 for(int j=0; j<dflag.size(); j++) {
4795 output.println(",");
4796 Vector term=dflag.get(j);
4799 for(int k=0; k<term.size(); k++) {
4800 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
4801 FlagDescriptor fd=dfa.getFlag();
4802 boolean negated=dfa.getNegated();
4803 int flagid=1<<((Integer)flags.get(fd)).intValue();
4808 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
4813 output.println("};\n");
4816 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
4817 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4820 for(int j=0; j<tagel.numTags(); j++) {
4822 output.println(",");
4823 TempDescriptor tmp=tagel.getTemp(j);
4824 if (!slotnumber.containsKey(tmp)) {
4825 Integer slotint=new Integer(current_slot++);
4826 slotnumber.put(tmp,slotint);
4828 int slot=slotnumber.get(tmp).intValue();
4829 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
4831 numtags = tagel.numTags();
4833 output.println("};");
4835 //store the result into a predicatemember struct
4836 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4837 output.println("/*type*/"+typed.getClassDesc().getId()+",");
4838 output.println("/* number of dnf terms */"+numberterms+",");
4839 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4840 output.println("/* number of tag */"+numtags+",");
4841 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4842 output.println("};\n");
4847 //generate an array that stores the entire predicate
4848 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4849 for( int j = 0; j<predicateindex; j++) {
4850 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4851 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4853 output.println("};\n");
4854 return predicateindex;
4858 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
4859 generateOptionalHeader(headers);
4861 output.println("#include \"optionalstruct.h\"\n\n");
4862 output.println("#include \"stdlib.h\"\n");
4864 HashSet processedcd = new HashSet();
4866 Enumeration e = safeexecution.keys();
4867 while (e.hasMoreElements()) {
4870 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
4871 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
4873 //Generate the struct of optionals
4874 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4875 numotd = c_otd.size();
4876 if(maxotd<numotd) maxotd = numotd;
4877 if( !c_otd.isEmpty() ) {
4878 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4879 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4881 //generate the int arrays for the predicate
4882 Predicate predicate = otd.predicate;
4883 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
4884 TreeSet<Integer> fsset=new TreeSet<Integer>();
4885 //iterate through possible FSes corresponding to
4886 //the state when entering
4888 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
4889 FlagState fs = (FlagState)fses.next();
4891 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4892 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4893 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4896 fsset.add(new Integer(flagid));
4897 //tag information not needed because tag
4898 //changes are not tolerated.
4901 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
4902 boolean needcomma=false;
4903 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
4906 output.println(it.next());
4909 output.println("};\n");
4912 //generate optionaltaskdescriptor that actually
4913 //includes exit fses, predicate and the task
4915 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
4916 output.println("&task_"+otd.td.getSafeSymbol()+",");
4917 output.println("/*index*/"+otd.getIndex()+",");
4918 output.println("/*number of enter flags*/"+fsset.size()+",");
4919 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4920 output.println("/*number of members */"+predicateindex+",");
4921 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4922 output.println("};\n");
4926 // if there are no optionals, there is no need to build the rest of the struct
4928 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
4929 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
4930 if( !c_otd.isEmpty() ) {
4931 boolean needcomma=false;
4932 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
4933 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
4935 output.println(",");
4937 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
4940 output.println("};\n");
4942 //get all the possible flagstates reachable by an object
4943 Hashtable hashtbtemp = safeexecution.get(cdtemp);
4945 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
4946 fsts.addAll(hashtbtemp.keySet());
4947 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
4948 FlagState fs = (FlagState)fsit.next();
4951 //get the set of OptionalTaskDescriptors corresponding
4952 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
4953 //iterate through the OptionalTaskDescriptors and
4954 //store the pointers to the optionals struct (see on
4955 //top) into an array
4957 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
4958 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
4959 OptionalTaskDescriptor mm = mos.next();
4961 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
4963 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
4966 output.println("};\n");
4968 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
4971 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
4972 FlagDescriptor flagd = (FlagDescriptor)flags.next();
4973 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
4977 //process tag information
4980 boolean first = true;
4981 Enumeration tag_enum = fs.getTags();
4982 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
4983 while(tag_enum.hasMoreElements()) {
4985 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
4989 output.println(", ");
4990 output.println("/*tagid*/"+state.getTagId(tagd));
4992 output.println("};");
4994 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
4995 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
4996 TaskIndex ti=itti.next();
5000 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
5002 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
5003 boolean needcomma=false;
5004 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
5005 OptionalTaskDescriptor otd=otdit.next();
5009 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5011 output.println("};");
5013 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
5014 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
5015 output.print(ti.getIndex()+", ");
5016 output.print(otdset.size()+", ");
5017 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
5018 output.println("};");
5021 tiset=sa.getTaskIndex(fs);
5022 boolean needcomma=false;
5024 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5025 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5026 TaskIndex ti=itti.next();
5027 if (ti.isRuntime()) {
5034 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
5036 output.println("};\n");
5038 //Store the result in fsanalysiswrapper
5040 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
5041 output.println("/*flag*/"+flagid+",");
5042 output.println("/* number of tags*/"+tagcounter+",");
5043 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5044 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
5045 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5046 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
5047 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
5048 output.println("};\n");
5052 //Build the array of fsanalysiswrappers
5053 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
5054 boolean needcomma=false;
5055 for(int i = 0; i<fscounter; i++) {
5056 if (needcomma) output.print(",");
5057 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
5060 output.println("};");
5062 //Build the classanalysiswrapper referring to the previous array
5063 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
5064 output.println("/*type*/"+cdtemp.getId()+",");
5065 output.println("/*numotd*/"+numotd+",");
5066 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
5067 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
5068 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
5069 processedcd.add(cdtemp);
5072 //build an array containing every classes for which code has been build
5073 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
5074 for(int i=0; i<state.numClasses(); i++) {
5075 ClassDescriptor cn=cdarray[i];
5078 if ((cn != null) && (processedcd.contains(cn)))
5079 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
5081 output.print("NULL");
5083 output.println("};");
5085 output.println("#define MAXOTD "+maxotd);
5086 headers.println("#endif");
5089 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
5090 Relation r=new Relation();
5091 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
5092 OptionalTaskDescriptor otd=otdit.next();
5093 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
5097 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
5098 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
5099 Set s=r.get(it.next());
5100 for(Iterator it2=s.iterator(); it2.hasNext();) {
5101 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
5109 protected void outputTransCode(PrintWriter output) {