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;
14 import Analysis.TaskStateAnalysis.FlagState;
15 import Analysis.TaskStateAnalysis.FlagComparator;
16 import Analysis.TaskStateAnalysis.OptionalTaskDescriptor;
17 import Analysis.TaskStateAnalysis.Predicate;
18 import Analysis.TaskStateAnalysis.SafetyAnalysis;
19 import Analysis.TaskStateAnalysis.TaskIndex;
20 import Analysis.Locality.LocalityAnalysis;
21 import Analysis.Locality.LocalityBinding;
22 import Analysis.Locality.DiscoverConflicts;
23 import Analysis.Locality.DCWrapper;
24 import Analysis.Locality.DelayComputation;
25 import Analysis.Locality.BranchAnalysis;
26 import Analysis.CallGraph.CallGraph;
27 import Analysis.Disjoint.AllocSite;
28 import Analysis.Disjoint.Effect;
29 import Analysis.Disjoint.ReachGraph;
30 import Analysis.Disjoint.Taint;
31 import Analysis.OoOJava.OoOJavaAnalysis;
32 import Analysis.Prefetch.*;
33 import Analysis.Loops.WriteBarrier;
34 import Analysis.Loops.GlobalFieldType;
35 import Analysis.Locality.TypeAnalysis;
36 import Analysis.MLP.ConflictGraph;
37 import Analysis.MLP.ConflictNode;
38 import Analysis.MLP.MLPAnalysis;
39 import Analysis.MLP.ParentChildConflictsMap;
40 import Analysis.MLP.SESELock;
41 import Analysis.MLP.SESEWaitingQueue;
42 import Analysis.MLP.VariableSourceToken;
43 import Analysis.MLP.VSTWrapper;
44 import Analysis.MLP.CodePlan;
45 import Analysis.MLP.SESEandAgePair;
46 import Analysis.MLP.WaitingElement;
48 public class BuildCode {
51 Hashtable paramstable;
56 String localsprefix="___locals___";
57 String localsprefixaddr="&"+localsprefix;
58 String localsprefixderef=localsprefix+".";
59 String fcrevert="___fcrevert___";
60 String paramsprefix="___params___";
61 String oidstr="___nextobject___";
62 String nextobjstr="___nextobject___";
63 String localcopystr="___localcopy___";
64 public static boolean GENERATEPRECISEGC=false;
65 public static String PREFIX="";
66 public static String arraytype="ArrayObject";
67 public static int flagcount = 0;
70 protected int maxtaskparams=0;
71 private int maxcount=0;
72 ClassDescriptor[] cdarray;
73 TypeDescriptor[] arraytable;
74 LocalityAnalysis locality;
75 Hashtable<LocalityBinding, TempDescriptor> reverttable;
76 Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>> backuptable;
81 String mlperrstr = "if(status != 0) { "+
82 "sprintf(errmsg, \"MLP error at %s:%d\", __FILE__, __LINE__); "+
83 "perror(errmsg); exit(-1); }";
84 boolean nonSESEpass=true;
85 RuntimeConflictResolver rcr = null;
88 DiscoverConflicts recorddc;
93 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa) {
94 this(st, temptovar, typeutil, null, sa, pa, null, null);
97 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
98 this(st, temptovar, typeutil, null, sa, pa, mlpa, oooa);
101 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
102 this(st, temptovar, typeutil, locality, null, pa, mlpa, oooa);
105 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, SafetyAnalysis sa, PrefetchAnalysis pa, MLPAnalysis mlpa, OoOJavaAnalysis oooa) {
111 callgraph=new CallGraph(state);
113 oidstr="___objlocation___";
114 this.temptovar=temptovar;
115 paramstable=new Hashtable();
116 tempstable=new Hashtable();
117 fieldorder=new Hashtable();
118 flagorder=new Hashtable();
119 this.typeutil=typeutil;
120 virtualcalls=new Virtual(state,locality);
121 if (locality!=null) {
122 this.locality=locality;
123 this.reverttable=new Hashtable<LocalityBinding, TempDescriptor>();
124 this.backuptable=new Hashtable<LocalityBinding, Hashtable<TempDescriptor, TempDescriptor>>();
125 this.wb=new WriteBarrier(locality, st);
127 if (state.SINGLETM&&state.DCOPTS) {
128 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
129 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
130 this.dc=new DiscoverConflicts(locality, st, typeanalysis, gft);
133 if (state.DELAYCOMP) {
134 //TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
135 TypeAnalysis typeanalysis=new TypeAnalysis(locality, st, typeutil,callgraph);
136 GlobalFieldType gft=new GlobalFieldType(callgraph, st, typeutil.getMain());
137 delaycomp=new DCWrapper(locality, st, typeanalysis, gft);
138 dc=delaycomp.getConflicts();
139 recorddc=new DiscoverConflicts(locality, st, typeanalysis, delaycomp.getCannotDelayMap(), true, true, null);
140 recorddc.doAnalysis();
144 /** The buildCode method outputs C code for all the methods. The Flat
145 * versions of the methods must already be generated and stored in
146 * the State object. */
147 PrintWriter outsandbox=null;
149 public void buildCode() {
150 /* Create output streams to write to */
151 PrintWriter outclassdefs=null;
152 PrintWriter outstructs=null;
153 PrintWriter outrepairstructs=null;
154 PrintWriter outmethodheader=null;
155 PrintWriter outmethod=null;
156 PrintWriter outvirtual=null;
157 PrintWriter outtask=null;
158 PrintWriter outtaskdefs=null;
159 PrintWriter outoptionalarrays=null;
160 PrintWriter optionalheaders=null;
164 outsandbox=new PrintWriter(new FileOutputStream(PREFIX+"sandboxdefs.c"), true);
166 outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
167 outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
168 outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
169 outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
170 outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
172 outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
173 outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
174 if (state.OPTIONAL) {
175 outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
176 optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
179 if (state.structfile!=null) {
180 outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
182 } catch (Exception e) {
187 /* Build the virtual dispatch tables */
188 buildVirtualTables(outvirtual);
190 /* Output includes */
191 outmethodheader.println("#ifndef METHODHEADERS_H");
192 outmethodheader.println("#define METHODHEADERS_H");
193 outmethodheader.println("#include \"structdefs.h\"");
195 outmethodheader.println("#include \"dstm.h\"");
197 outmethodheader.println("#include \"sandbox.h\"");
199 if (state.EVENTMONITOR) {
200 outmethodheader.println("#include \"monitor.h\"");
202 if (state.SINGLETM) {
203 outmethodheader.println("#include \"tm.h\"");
204 outmethodheader.println("#include \"delaycomp.h\"");
205 outmethodheader.println("#include \"inlinestm.h\"");
207 if (state.ABORTREADERS) {
208 outmethodheader.println("#include \"abortreaders.h\"");
209 outmethodheader.println("#include <setjmp.h>");
211 if (state.MLP || state.OOOJAVA) {
212 outmethodheader.println("#include <stdlib.h>");
213 outmethodheader.println("#include <stdio.h>");
214 outmethodheader.println("#include <string.h>");
215 outmethodheader.println("#include \"mlp_runtime.h\"");
216 outmethodheader.println("#include \"psemaphore.h\"");
219 /* Output Structures */
220 outputStructs(outstructs);
222 // Output the C class declarations
223 // These could mutually reference each other
226 outclassdefs.println("#ifndef __CLASSDEF_H_");
227 outclassdefs.println("#define __CLASSDEF_H_");
228 outputClassDeclarations(outclassdefs);
230 // Output function prototypes and structures for parameters
231 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
232 while(it.hasNext()) {
233 ClassDescriptor cn=(ClassDescriptor)it.next();
234 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader);
236 outclassdefs.println("#endif");
237 outclassdefs.close();
240 /* Map flags to integers */
241 /* The runtime keeps track of flags using these integers */
242 it=state.getClassSymbolTable().getDescriptorsIterator();
243 while(it.hasNext()) {
244 ClassDescriptor cn=(ClassDescriptor)it.next();
248 generateTaskStructs(outstructs, outmethodheader);
250 /* Outputs generic task structures if this is a task
252 outputTaskTypes(outtask);
255 if( state.MLP || state.OOOJAVA) {
256 // have to initialize some SESE compiler data before
257 // analyzing normal methods, which must happen before
258 // generating SESE internal code
260 Iterator<FlatSESEEnterNode> seseit;
262 seseit=mlpa.getAllSESEs().iterator();
264 seseit=oooa.getAllSESEs().iterator();
267 //TODO signal the object that will report errors
270 rcr = new RuntimeConflictResolver(PREFIX);
272 catch (FileNotFoundException e) {
273 System.out.println("Runtime Conflict Resolver could not create output file.");
277 while(seseit.hasNext()){
278 FlatSESEEnterNode fsen = seseit.next();
279 initializeSESE( fsen );
281 if(state.RCR && rcr != null){
282 Analysis.OoOJava.ConflictGraph conflictGraph;
283 Hashtable<Taint, Set<Effect>> conflicts;
284 if(!fsen.getIsCallerSESEplaceholder() && fsen.getParent()!=null &&
285 (conflictGraph = oooa.getConflictGraph(fsen.getParent())) != null &&
286 (conflicts = conflictGraph.getConflictEffectSet(fsen)) != null){
288 FlatMethod fm=fsen.getfmEnclosing();
291 ReachGraph rg=oooa.getDisjointAnalysis().getReachGraph(fm.getMethod());
294 rg.writeGraph("RCR_RG_SESE_DEBUG");
298 Hashtable<Taint, Set<Effect>> effects=oooa.getDisjointAnalysis().getEffectsAnalysis().get(fsen);
300 rcr.traverseSESEBlock(fsen, effects, conflicts, rg);
306 /* Build the actual methods */
307 outputMethods(outmethod);
309 // Output function prototypes and structures for SESE's and code
310 if( state.MLP || state.OOOJAVA ) {
312 // used to differentiate, during code generation, whether we are
313 // passing over SESE body code, or non-SESE code
316 // first generate code for each sese's internals
317 Iterator<FlatSESEEnterNode> seseit;
319 seseit=mlpa.getAllSESEs().iterator();
321 seseit=oooa.getAllSESEs().iterator();
324 while(seseit.hasNext()) {
325 FlatSESEEnterNode fsen = seseit.next();
326 generateMethodSESE(fsen, null, outstructs, outmethodheader, outmethod);
329 // then write the invokeSESE switch to decouple scheduler
330 // from having to do unique details of sese invocation
331 generateSESEinvocationMethod(outmethodheader, outmethod);
335 /* Output code for tasks */
336 outputTaskCode(outtaskdefs, outmethod);
338 /* Record maximum number of task parameters */
339 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
340 } else if (state.main!=null) {
341 /* Generate main method */
342 outputMainMethod(outmethod);
345 /* Generate information for task with optional parameters */
346 if (state.TASK&&state.OPTIONAL) {
347 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
348 outoptionalarrays.close();
351 /* Output structure definitions for repair tool */
352 if (state.structfile!=null) {
353 buildRepairStructs(outrepairstructs);
354 outrepairstructs.close();
358 outmethodheader.println("#endif");
359 outmethodheader.close();
361 outstructs.println("#endif");
365 System.out.println("Runtime Conflict Resolver Done.");
370 /* This code just generates the main C method for java programs.
371 * The main C method packs up the arguments into a string array
372 * and passes it to the java main method. */
374 private void outputMainMethod(PrintWriter outmethod) {
375 outmethod.println("int main(int argc, const char *argv[]) {");
376 outmethod.println(" int i;");
378 if (state.MLP || state.OOOJAVA) {
379 //outmethod.println(" pthread_once( &mlpOnceObj, mlpInitOncePerThread );");
381 outmethod.println(" workScheduleInit( "+state.MLP_NUMCORES+", invokeSESEmethod );");
383 //initializes data structures needed for the RCR traverser
385 outmethod.println(" initializeStructsRCR();");
390 if (state.DSMRECOVERYSTATS) {
391 outmethod.println("#ifdef RECOVERYSTATS \n");
392 outmethod.println("handle();\n");
393 outmethod.println("#endif\n");
395 outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
396 outmethod.println("handle();\n");
397 outmethod.println("#endif\n");
401 if (state.THREAD||state.DSM||state.SINGLETM) {
402 outmethod.println("initializethreads();");
405 outmethod.println("if (dstmStartup(argv[1])) {");
406 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
407 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
409 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
412 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
413 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
415 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
419 outmethod.println(" for(i=2;i<argc;i++) {");
421 outmethod.println(" for(i=1;i<argc;i++) {");
422 outmethod.println(" int length=strlen(argv[i]);");
423 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
424 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
426 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
429 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-2]=newstring;");
431 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
432 outmethod.println(" }");
434 MethodDescriptor md=typeutil.getMain();
435 ClassDescriptor cd=typeutil.getMainClass();
437 outmethod.println(" {");
438 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
439 if (state.DSM||state.SINGLETM) {
440 outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
442 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
443 outmethod.println("1, NULL,"+"stringarray};");
444 if (state.DSM||state.SINGLETM)
445 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
447 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
449 if (state.DSM||state.SINGLETM)
450 outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
452 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
454 outmethod.println(" }");
457 outmethod.println("}");
460 if (state.THREAD||state.DSM||state.SINGLETM) {
461 outmethod.println("pthread_mutex_lock(&gclistlock);");
462 outmethod.println("threadcount--;");
463 outmethod.println("pthread_cond_signal(&gccond);");
464 outmethod.println("pthread_mutex_unlock(&gclistlock);");
467 if (state.DSM||state.SINGLETM) {
468 //outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
469 outmethod.println("#if defined(TRANSSTATS) \n");
470 outmethod.println("printf(\"****** Transaction Stats ******\\n\");");
471 outmethod.println("printf(\"numTransCommit= %d\\n\", numTransCommit);");
472 outmethod.println("printf(\"numTransAbort= %d\\n\", numTransAbort);");
473 outmethod.println("printf(\"nSoftAbort= %d\\n\", nSoftAbort);");
475 outmethod.println("printf(\"nchashSearch= %d\\n\", nchashSearch);");
476 outmethod.println("printf(\"nmhashSearch= %d\\n\", nmhashSearch);");
477 outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);");
478 outmethod.println("printf(\"ndirtyCacheObj= %d\\n\", ndirtyCacheObj);");
479 outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);");
480 outmethod.println("printf(\"bytesSent= %d\\n\", bytesSent);");
481 outmethod.println("printf(\"bytesRecv= %d\\n\", bytesRecv);");
482 outmethod.println("printf(\"totalObjSize= %d\\n\", totalObjSize);");
483 outmethod.println("printf(\"sendRemoteReq= %d\\n\", sendRemoteReq);");
484 outmethod.println("printf(\"getResponse= %d\\n\", getResponse);");
485 } else if (state.SINGLETM) {
486 outmethod.println("printf(\"nSoftAbortAbort= %d\\n\", nSoftAbortAbort);");
487 outmethod.println("printf(\"nSoftAbortCommit= %d\\n\", nSoftAbortCommit);");
488 outmethod.println("#ifdef STMSTATS\n");
489 outmethod.println("for(i=0; i<TOTALNUMCLASSANDARRAY; i++) {\n");
490 outmethod.println(" printf(\"typesCausingAbort[%2d] numaccess= %5d numabort= %3d\\n\", i, typesCausingAbort[i].numaccess, typesCausingAbort[i].numabort);\n");
491 outmethod.println("}\n");
492 outmethod.println("#endif\n");
493 outmethod.println("fflush(stdout);");
495 outmethod.println("#endif\n");
498 if (state.EVENTMONITOR) {
499 outmethod.println("dumpdata();");
502 if (state.THREAD||state.SINGLETM)
503 outmethod.println("pthread_exit(NULL);");
505 if (state.MLP || state.OOOJAVA ) {
506 outmethod.println(" workScheduleBegin();");
509 outmethod.println("}");
512 /* This method outputs code for each task. */
514 private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
515 /* Compile task based program */
516 outtaskdefs.println("#include \"task.h\"");
517 outtaskdefs.println("#include \"methodheaders.h\"");
518 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
519 while(taskit.hasNext()) {
520 TaskDescriptor td=(TaskDescriptor)taskit.next();
521 FlatMethod fm=state.getMethodFlat(td);
522 generateFlatMethod(fm, null, outmethod);
523 generateTaskDescriptor(outtaskdefs, fm, td);
526 //Output task descriptors
527 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
528 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
530 while(taskit.hasNext()) {
531 TaskDescriptor td=(TaskDescriptor)taskit.next();
535 outtaskdefs.println(",");
536 outtaskdefs.print("&task_"+td.getSafeSymbol());
538 outtaskdefs.println("};");
540 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
543 /* This method outputs most of the methods.c file. This includes
544 * some standard includes and then an array with the sizes of
545 * objets and array that stores supertype and then the code for
546 * the Java methods.. */
548 protected void outputMethods(PrintWriter outmethod) {
549 outmethod.println("#include \"methodheaders.h\"");
550 outmethod.println("#include \"virtualtable.h\"");
551 outmethod.println("#include \"runtime.h\"");
553 outmethod.println("#include \"sandboxdefs.c\"");
556 outmethod.println("#include \"addPrefetchEnhance.h\"");
557 outmethod.println("#include \"localobjects.h\"");
559 if (state.FASTCHECK) {
560 outmethod.println("#include \"localobjects.h\"");
562 if(state.MULTICORE) {
563 outmethod.println("#include \"task.h\"");
564 outmethod.println("#include \"multicoreruntime.h\"");
565 outmethod.println("#include \"runtime_arch.h\"");
567 if (state.THREAD||state.DSM||state.SINGLETM)
568 outmethod.println("#include <thread.h>");
569 if (state.main!=null) {
570 outmethod.println("#include <string.h>");
572 if (state.CONSCHECK) {
573 outmethod.println("#include \"checkers.h\"");
575 if (state.MLP || state.OOOJAVA ) {
576 outmethod.println("#include <stdlib.h>");
577 outmethod.println("#include <stdio.h>");
578 outmethod.println("#include \"mlp_runtime.h\"");
579 outmethod.println("#include \"psemaphore.h\"");
582 outmethod.println("#include \"RuntimeConflictResolver.h\"");
585 if (state.COREPROF) {
586 outmethod.println("#include \"coreprof.h\"");
589 //Store the sizes of classes & array elements
590 generateSizeArray(outmethod);
592 //Store table of supertypes
593 generateSuperTypeTable(outmethod);
595 //Store the layout of classes
596 generateLayoutStructs(outmethod);
598 /* Generate code for methods */
599 if (state.DSM||state.SINGLETM) {
600 for(Iterator<LocalityBinding> lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) {
601 LocalityBinding lb=lbit.next();
602 MethodDescriptor md=lb.getMethod();
603 FlatMethod fm=state.getMethodFlat(md);
605 if (!md.getModifiers().isNative()) {
606 generateFlatMethod(fm, lb, outmethod);
607 //System.out.println("fm= " + fm + " md= " + md);
611 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
612 while(classit.hasNext()) {
613 ClassDescriptor cn=(ClassDescriptor)classit.next();
614 Iterator methodit=cn.getMethods();
615 while(methodit.hasNext()) {
616 /* Classify parameters */
617 MethodDescriptor md=(MethodDescriptor)methodit.next();
618 FlatMethod fm=state.getMethodFlat(md);
619 if (!md.getModifiers().isNative()) {
620 generateFlatMethod(fm, null, outmethod);
627 protected void outputStructs(PrintWriter outstructs) {
628 outstructs.println("#ifndef STRUCTDEFS_H");
629 outstructs.println("#define STRUCTDEFS_H");
630 outstructs.println("#include \"classdefs.h\"");
631 outstructs.println("#ifndef INTPTR");
632 outstructs.println("#ifdef BIT64");
633 outstructs.println("#define INTPTR long");
634 outstructs.println("#else");
635 outstructs.println("#define INTPTR int");
636 outstructs.println("#endif");
637 outstructs.println("#endif");
638 if( state.MLP || state.OOOJAVA ) {
639 outstructs.println("#include \"mlp_runtime.h\"");
640 outstructs.println("#include \"psemaphore.h\"");
643 /* Output #defines that the runtime uses to determine type
644 * numbers for various objects it needs */
645 outstructs.println("#define MAXCOUNT "+maxcount);
646 if (state.DSM||state.SINGLETM) {
647 LocalityBinding lbrun=new LocalityBinding(typeutil.getRun(), false);
649 lbrun.setGlobalThis(LocalityAnalysis.GLOBAL);
651 else if (state.SINGLETM) {
652 lbrun.setGlobalThis(LocalityAnalysis.NORMAL);
654 outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lbrun));
658 LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
660 lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
661 else if( state.SINGLETM)
662 lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
663 outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
666 outstructs.println("#define STRINGARRAYTYPE "+
667 (state.getArrayNumber(
668 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
670 outstructs.println("#define OBJECTARRAYTYPE "+
671 (state.getArrayNumber(
672 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
675 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
676 outstructs.println("#define CHARARRAYTYPE "+
677 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
679 outstructs.println("#define BYTEARRAYTYPE "+
680 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
682 outstructs.println("#define BYTEARRAYARRAYTYPE "+
683 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
685 outstructs.println("#define NUMCLASSES "+state.numClasses());
686 int totalClassSize = state.numClasses() + state.numArrays();
687 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
689 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
690 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
691 outstructs.println("#define TAGARRAYTYPE "+
692 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
696 protected void outputClassDeclarations(PrintWriter outclassdefs) {
697 if (state.THREAD||state.DSM||state.SINGLETM)
698 outclassdefs.println("#include <pthread.h>");
699 outclassdefs.println("#ifndef INTPTR");
700 outclassdefs.println("#ifdef BIT64");
701 outclassdefs.println("#define INTPTR long");
702 outclassdefs.println("#else");
703 outclassdefs.println("#define INTPTR int");
704 outclassdefs.println("#endif");
705 outclassdefs.println("#endif");
707 outclassdefs.println("#include \"optionalstruct.h\"");
708 outclassdefs.println("struct "+arraytype+";");
709 /* Start by declaring all structs */
710 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
711 while(it.hasNext()) {
712 ClassDescriptor cn=(ClassDescriptor)it.next();
713 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
715 outclassdefs.println("");
716 //Print out definition for array type
717 outclassdefs.println("struct "+arraytype+" {");
718 outclassdefs.println(" int type;");
719 if(state.MLP || state.OOOJAVA ){
720 outclassdefs.println(" int oid;");
721 outclassdefs.println(" int allocsite;");
723 if (state.EVENTMONITOR) {
724 outclassdefs.println(" int objuid;");
727 outclassdefs.println(" pthread_t tid;");
728 outclassdefs.println(" void * lockentry;");
729 outclassdefs.println(" int lockcount;");
732 outclassdefs.println(" int flag;");
733 if(!state.MULTICORE) {
734 outclassdefs.println(" void * flagptr;");
736 outclassdefs.println(" int version;");
737 outclassdefs.println(" int * lock;"); // lock entry for this obj
738 outclassdefs.println(" int mutex;");
739 outclassdefs.println(" int lockcount;");
740 if(state.MULTICOREGC) {
741 outclassdefs.println(" int marked;");
745 outclassdefs.println(" int numfses;");
746 outclassdefs.println(" int * fses;");
749 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs);
751 if (state.STMARRAY) {
752 outclassdefs.println(" int lowindex;");
753 outclassdefs.println(" int highindex;");
756 outclassdefs.println(" int paddingforarray;");
757 if (state.DUALVIEW) {
758 outclassdefs.println(" int arrayversion;");
761 outclassdefs.println(" int ___length___;");
762 outclassdefs.println("};\n");
763 outclassdefs.println("extern int classsize[];");
764 outclassdefs.println("extern int hasflags[];");
765 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
766 outclassdefs.println("extern int supertypes[];");
769 /** Prints out definitions for generic task structures */
771 private void outputTaskTypes(PrintWriter outtask) {
772 outtask.println("#ifndef _TASK_H");
773 outtask.println("#define _TASK_H");
774 outtask.println("struct parameterdescriptor {");
775 outtask.println("int type;");
776 outtask.println("int numberterms;");
777 outtask.println("int *intarray;");
778 outtask.println("void * queue;");
779 outtask.println("int numbertags;");
780 outtask.println("int *tagarray;");
781 outtask.println("};");
783 outtask.println("struct taskdescriptor {");
784 outtask.println("void * taskptr;");
785 outtask.println("int numParameters;");
786 outtask.println(" int numTotal;");
787 outtask.println("struct parameterdescriptor **descriptorarray;");
788 outtask.println("char * name;");
789 outtask.println("};");
790 outtask.println("extern struct taskdescriptor * taskarray[];");
791 outtask.println("extern numtasks;");
792 outtask.println("#endif");
796 private void buildRepairStructs(PrintWriter outrepairstructs) {
797 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
798 while(classit.hasNext()) {
799 ClassDescriptor cn=(ClassDescriptor)classit.next();
800 outrepairstructs.println("structure "+cn.getSymbol()+" {");
801 outrepairstructs.println(" int __type__;");
803 outrepairstructs.println(" int __flag__;");
804 if(!state.MULTICORE) {
805 outrepairstructs.println(" int __flagptr__;");
808 printRepairStruct(cn, outrepairstructs);
809 outrepairstructs.println("}\n");
812 for(int i=0; i<state.numArrays(); i++) {
813 TypeDescriptor tdarray=arraytable[i];
814 TypeDescriptor tdelement=tdarray.dereference();
815 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
816 outrepairstructs.println(" int __type__;");
817 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
818 outrepairstructs.println(" int length;");
820 // Need to add support to repair tool for this
821 if (tdelement.isClass()||tdelement.isArray())
822 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
824 outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
826 outrepairstructs.println("}\n");
830 private void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
831 ClassDescriptor sp=cn.getSuperDesc();
833 printRepairStruct(sp, output);
835 Vector fields=(Vector)fieldorder.get(cn);
837 for(int i=0; i<fields.size(); i++) {
838 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
839 if (fd.getType().isArray()) {
840 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
841 } else if (fd.getType().isClass())
842 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
843 else if (fd.getType().isFloat())
844 output.println(" int "+fd.getSymbol()+"; /* really float */");
846 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
850 /** This method outputs TaskDescriptor information */
851 private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
852 for (int i=0; i<task.numParameters(); i++) {
853 VarDescriptor param_var=task.getParameter(i);
854 TypeDescriptor param_type=task.getParamType(i);
855 FlagExpressionNode param_flag=task.getFlag(param_var);
856 TagExpressionList param_tag=task.getTag(param_var);
859 if (param_flag==null) {
860 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
861 output.println("0x0, 0x0 };");
864 DNFFlag dflag=param_flag.getDNF();
865 dnfterms=dflag.size();
867 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
868 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
869 for(int j=0; j<dflag.size(); j++) {
872 Vector term=dflag.get(j);
875 for(int k=0; k<term.size(); k++) {
876 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
877 FlagDescriptor fd=dfa.getFlag();
878 boolean negated=dfa.getNegated();
879 int flagid=1<<((Integer)flags.get(fd)).intValue();
884 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
886 output.println("};");
889 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
890 //BUG...added next line to fix, test with any task program
892 for(int j=0; j<param_tag.numTags(); j++) {
895 /* for each tag we need */
896 /* which slot it is */
897 /* what type it is */
898 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
899 TempDescriptor tmp=param_tag.getTemp(j);
900 int slot=fm.getTagInt(tmp);
901 output.println(slot+", "+state.getTagId(tvd.getTag()));
903 output.println("};");
905 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
906 output.println("/* type */"+param_type.getClassDesc().getId()+",");
907 output.println("/* number of DNF terms */"+dnfterms+",");
908 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
909 output.println("0,");
910 //BUG, added next line to fix and else statement...test
911 //with any task program
913 output.println("/* number of tags */"+param_tag.numTags()+",");
915 output.println("/* number of tags */ 0,");
916 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
917 output.println("};");
921 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
922 for (int i=0; i<task.numParameters(); i++) {
925 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
927 output.println("};");
929 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
930 output.println("&"+task.getSafeSymbol()+",");
931 output.println("/* number of parameters */" +task.numParameters() + ",");
932 int numtotal=task.numParameters()+fm.numTags();
933 output.println("/* number total parameters */" +numtotal + ",");
934 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
935 output.println("\""+task.getSymbol()+"\"");
936 output.println("};");
940 /** The buildVirtualTables method outputs the virtual dispatch
941 * tables for methods. */
943 protected void buildVirtualTables(PrintWriter outvirtual) {
944 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
945 while(classit.hasNext()) {
946 ClassDescriptor cd=(ClassDescriptor)classit.next();
947 if (virtualcalls.getMethodCount(cd)>maxcount)
948 maxcount=virtualcalls.getMethodCount(cd);
950 MethodDescriptor[][] virtualtable=null;
951 LocalityBinding[][] lbvirtualtable=null;
952 if (state.DSM||state.SINGLETM)
953 lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount];
955 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
957 /* Fill in virtual table */
958 classit=state.getClassSymbolTable().getDescriptorsIterator();
959 while(classit.hasNext()) {
960 ClassDescriptor cd=(ClassDescriptor)classit.next();
961 if (state.DSM||state.SINGLETM)
962 fillinRow(cd, lbvirtualtable, cd.getId());
964 fillinRow(cd, virtualtable, cd.getId());
967 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
968 Iterator arrayit=state.getArrayIterator();
969 while(arrayit.hasNext()) {
970 TypeDescriptor td=(TypeDescriptor)arrayit.next();
971 int id=state.getArrayNumber(td);
972 if (state.DSM||state.SINGLETM)
973 fillinRow(objectcd, lbvirtualtable, id+state.numClasses());
975 fillinRow(objectcd, virtualtable, id+state.numClasses());
978 outvirtual.print("void * virtualtable[]={");
979 boolean needcomma=false;
980 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
981 for(int j=0; j<maxcount; j++) {
983 outvirtual.print(", ");
984 if ((state.DSM||state.SINGLETM)&&lbvirtualtable[i][j]!=null) {
985 LocalityBinding lb=lbvirtualtable[i][j];
986 MethodDescriptor md=lb.getMethod();
987 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
988 } else if (!(state.DSM||state.SINGLETM)&&virtualtable[i][j]!=null) {
989 MethodDescriptor md=virtualtable[i][j];
990 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
992 outvirtual.print("0");
996 outvirtual.println("");
998 outvirtual.println("};");
1002 private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
1003 /* Get inherited methods */
1004 if (cd.getSuperDesc()!=null)
1005 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
1006 /* Override them with our methods */
1007 for(Iterator it=cd.getMethods(); it.hasNext();) {
1008 MethodDescriptor md=(MethodDescriptor)it.next();
1009 if (md.isStatic()||md.getReturnType()==null)
1011 int methodnum=virtualcalls.getMethodNumber(md);
1012 virtualtable[rownum][methodnum]=md;
1016 private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
1017 /* Get inherited methods */
1018 if (cd.getSuperDesc()!=null)
1019 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
1020 /* Override them with our methods */
1021 if (locality.getClassBindings(cd)!=null)
1022 for(Iterator<LocalityBinding> lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext();) {
1023 LocalityBinding lb=lbit.next();
1024 MethodDescriptor md=lb.getMethod();
1025 //Is the method static or a constructor
1026 if (md.isStatic()||md.getReturnType()==null)
1028 int methodnum=virtualcalls.getLocalityNumber(lb);
1029 virtualtable[rownum][methodnum]=lb;
1033 /** Generate array that contains the sizes of class objects. The
1034 * object allocation functions in the runtime use this
1037 private void generateSizeArray(PrintWriter outclassdefs) {
1038 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
1039 outclassdefs.print("#ifdef TRANSSTATS \n");
1040 outclassdefs.print("extern int numTransAbort;\n");
1041 outclassdefs.print("extern int numTransCommit;\n");
1042 outclassdefs.print("extern int nSoftAbort;\n");
1044 outclassdefs.print("extern int nchashSearch;\n");
1045 outclassdefs.print("extern int nmhashSearch;\n");
1046 outclassdefs.print("extern int nprehashSearch;\n");
1047 outclassdefs.print("extern int ndirtyCacheObj;\n");
1048 outclassdefs.print("extern int nRemoteSend;\n");
1049 outclassdefs.print("extern int sendRemoteReq;\n");
1050 outclassdefs.print("extern int getResponse;\n");
1051 outclassdefs.print("extern int bytesSent;\n");
1052 outclassdefs.print("extern int bytesRecv;\n");
1053 outclassdefs.print("extern int totalObjSize;\n");
1054 outclassdefs.print("extern void handle();\n");
1055 } else if (state.SINGLETM) {
1056 outclassdefs.println("extern int nSoftAbortAbort;");
1057 outclassdefs.println("extern int nSoftAbortCommit;");
1058 outclassdefs.println("#ifdef STMSTATS\n");
1059 outclassdefs.println("extern objtypestat_t typesCausingAbort[];");
1060 outclassdefs.println("#endif\n");
1062 outclassdefs.print("#endif\n");
1064 outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n");
1065 if(this.state.MLP || state.OOOJAVA ){
1066 outclassdefs.print("extern __thread int oid;\n");
1067 outclassdefs.print("extern int numWorkers;\n");
1070 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1071 cdarray=new ClassDescriptor[state.numClasses()];
1073 while(it.hasNext()) {
1074 ClassDescriptor cd=(ClassDescriptor)it.next();
1075 cdarray[cd.getId()]=cd;
1078 arraytable=new TypeDescriptor[state.numArrays()];
1080 Iterator arrayit=state.getArrayIterator();
1081 while(arrayit.hasNext()) {
1082 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1083 int id=state.getArrayNumber(td);
1089 /* Print out types */
1090 outclassdefs.println("/* ");
1091 for(int i=0; i<state.numClasses(); i++) {
1092 ClassDescriptor cd=cdarray[i];
1094 outclassdefs.println("NULL " + i);
1096 outclassdefs.println(cd +" "+i);
1100 for(int i=0; i<state.numArrays(); i++) {
1101 TypeDescriptor arraytd=arraytable[i];
1102 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
1105 outclassdefs.println("*/");
1108 outclassdefs.print("int classsize[]={");
1110 boolean needcomma=false;
1111 for(int i=0; i<state.numClasses(); i++) {
1113 outclassdefs.print(", ");
1115 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1117 outclassdefs.print("0");
1123 for(int i=0; i<state.numArrays(); i++) {
1125 outclassdefs.print(", ");
1126 TypeDescriptor tdelement=arraytable[i].dereference();
1127 if (tdelement.isArray()||tdelement.isClass())
1128 outclassdefs.print("sizeof(void *)");
1130 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1134 outclassdefs.println("};");
1136 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1138 outclassdefs.print("int typearray[]={");
1139 for(int i=0; i<state.numClasses(); i++) {
1140 ClassDescriptor cd=cdarray[i];
1141 ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
1143 outclassdefs.print(", ");
1145 outclassdefs.print("-1");
1147 outclassdefs.print(supercd.getId());
1151 for(int i=0; i<state.numArrays(); i++) {
1152 TypeDescriptor arraytd=arraytable[i];
1153 ClassDescriptor arraycd=arraytd.getClassDesc();
1154 if (arraycd==null) {
1156 outclassdefs.print(", ");
1157 outclassdefs.print(objectclass.getId());
1161 ClassDescriptor cd=arraycd.getSuperDesc();
1164 TypeDescriptor supertd=new TypeDescriptor(cd);
1165 supertd.setArrayCount(arraytd.getArrayCount());
1166 type=state.getArrayNumber(supertd);
1168 type+=state.numClasses();
1171 cd=cd.getSuperDesc();
1174 outclassdefs.print(", ");
1175 outclassdefs.print(type);
1179 outclassdefs.println("};");
1184 outclassdefs.print("int typearray2[]={");
1185 for(int i=0; i<state.numArrays(); i++) {
1186 TypeDescriptor arraytd=arraytable[i];
1187 ClassDescriptor arraycd=arraytd.getClassDesc();
1188 if (arraycd==null) {
1190 outclassdefs.print(", ");
1191 outclassdefs.print("-1");
1195 ClassDescriptor cd=arraycd.getSuperDesc();
1196 int level=arraytd.getArrayCount()-1;
1198 for(; level>0; level--) {
1199 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1200 supertd.setArrayCount(level);
1201 type=state.getArrayNumber(supertd);
1203 type+=state.numClasses();
1208 outclassdefs.print(", ");
1209 outclassdefs.print(type);
1213 outclassdefs.println("};");
1216 /** Constructs params and temp objects for each method or task.
1217 * These objects tell the compiler which temps need to be
1220 protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
1221 MethodDescriptor md=fm.getMethod();
1222 TaskDescriptor task=fm.getTask();
1223 Set<TempDescriptor> saveset=lb!=null ? locality.getTempSet(lb) : null;
1224 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1226 paramstable.put(lb, objectparams);
1227 backuptable.put(lb, new Hashtable<TempDescriptor, TempDescriptor>());
1228 } else if (md!=null)
1229 paramstable.put(md, objectparams);
1231 paramstable.put(task, objectparams);
1233 for(int i=0; i<fm.numParameters(); i++) {
1234 TempDescriptor temp=fm.getParameter(i);
1235 TypeDescriptor type=temp.getType();
1236 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1237 objectparams.addPtr(temp);
1239 objectparams.addPrim(temp);
1240 if(lb!=null&&saveset.contains(temp)) {
1241 backuptable.get(lb).put(temp, temp.createNew());
1245 for(int i=0; i<fm.numTags(); i++) {
1246 TempDescriptor temp=fm.getTag(i);
1247 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1248 objectparams.addPtr(temp);
1250 objectparams.addPrim(temp);
1253 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1255 tempstable.put(lb, objecttemps);
1257 tempstable.put(md, objecttemps);
1259 tempstable.put(task, objecttemps);
1261 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext();) {
1262 FlatNode fn=(FlatNode)nodeit.next();
1263 TempDescriptor[] writes=fn.writesTemps();
1264 for(int i=0; i<writes.length; i++) {
1265 TempDescriptor temp=writes[i];
1266 TypeDescriptor type=temp.getType();
1267 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1268 objecttemps.addPtr(temp);
1270 objecttemps.addPrim(temp);
1271 if(lb!=null&&saveset.contains(temp)&&
1272 !backuptable.get(lb).containsKey(temp))
1273 backuptable.get(lb).put(temp, temp.createNew());
1277 /* Create backup temps */
1279 for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext();) {
1280 TempDescriptor tmp=tmpit.next();
1281 TypeDescriptor type=tmp.getType();
1282 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1283 objecttemps.addPtr(tmp);
1285 objecttemps.addPrim(tmp);
1287 /* Create temp to hold revert table */
1288 if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
1289 TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
1290 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1291 objecttemps.addPtr(reverttmp);
1293 objecttemps.addPrim(reverttmp);
1294 reverttable.put(lb, reverttmp);
1299 /** This method outputs the following information about classes
1301 * (1) For classes, what are the locations of pointers.
1302 * (2) For arrays, does the array contain pointers or primitives.
1303 * (3) For classes, does the class contain flags.
1306 private void generateLayoutStructs(PrintWriter output) {
1307 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1308 while(it.hasNext()) {
1309 ClassDescriptor cn=(ClassDescriptor)it.next();
1310 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1311 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1313 while(allit.hasNext()) {
1314 FieldDescriptor fd=(FieldDescriptor)allit.next();
1315 TypeDescriptor type=fd.getType();
1316 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1321 output.print(count);
1322 allit=cn.getFieldTable().getAllDescriptorsIterator();
1323 while(allit.hasNext()) {
1324 FieldDescriptor fd=(FieldDescriptor)allit.next();
1325 TypeDescriptor type=fd.getType();
1326 if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
1329 output.println(",");
1330 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))");
1333 output.println("};");
1335 output.println("unsigned INTPTR * pointerarray[]={");
1336 boolean needcomma=false;
1337 for(int i=0; i<state.numClasses(); i++) {
1338 ClassDescriptor cn=cdarray[i];
1340 output.println(",");
1343 output.print(cn.getSafeSymbol()+"_pointers");
1345 output.print("NULL");
1349 for(int i=0; i<state.numArrays(); i++) {
1351 output.println(", ");
1352 TypeDescriptor tdelement=arraytable[i].dereference();
1353 if (tdelement.isArray()||tdelement.isClass())
1354 output.print("((unsigned INTPTR *)1)");
1360 output.println("};");
1362 output.println("int hasflags[]={");
1363 for(int i=0; i<state.numClasses(); i++) {
1364 ClassDescriptor cn=cdarray[i];
1366 output.println(", ");
1368 if ((cn != null) && (cn.hasFlags()))
1373 output.println("};");
1376 /** Print out table to give us supertypes */
1377 private void generateSuperTypeTable(PrintWriter output) {
1378 output.println("int supertypes[]={");
1379 boolean needcomma=false;
1380 for(int i=0; i<state.numClasses(); i++) {
1381 ClassDescriptor cn=cdarray[i];
1383 output.println(",");
1385 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1386 ClassDescriptor cdsuper=cn.getSuperDesc();
1387 output.print(cdsuper.getId());
1391 output.println("};");
1394 /** Force consistent field ordering between inherited classes. */
1396 private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
1398 ClassDescriptor sp=cn.getSuperDesc();
1400 printClassStruct(sp, classdefout);
1402 if (!fieldorder.containsKey(cn)) {
1403 Vector fields=new Vector();
1404 fieldorder.put(cn,fields);
1405 Vector fieldvec=cn.getFieldVec();
1406 for(int i=0;i<fieldvec.size();i++) {
1407 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1408 if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol())))
1412 Vector fields=(Vector)fieldorder.get(cn);
1414 for(int i=0; i<fields.size(); i++) {
1415 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1416 if (fd.getType().isClass()||fd.getType().isArray())
1417 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1419 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1424 /* Map flags to integers consistently between inherited
1427 protected void mapFlags(ClassDescriptor cn) {
1428 ClassDescriptor sp=cn.getSuperDesc();
1432 if (!flagorder.containsKey(cn)) {
1433 Hashtable flags=new Hashtable();
1434 flagorder.put(cn,flags);
1436 Hashtable superflags=(Hashtable)flagorder.get(sp);
1437 Iterator superflagit=superflags.keySet().iterator();
1438 while(superflagit.hasNext()) {
1439 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1440 Integer number=(Integer)superflags.get(fd);
1441 flags.put(fd, number);
1442 if ((number.intValue()+1)>max)
1443 max=number.intValue()+1;
1447 Iterator flagit=cn.getFlags();
1448 while(flagit.hasNext()) {
1449 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1450 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1451 flags.put(fd, new Integer(max++));
1457 /** This function outputs (1) structures that parameters are
1458 * passed in (when PRECISE GC is enabled) and (2) function
1459 * prototypes for the methods */
1461 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) {
1462 /* Output class structure */
1463 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1464 classdefout.println(" int type;");
1465 if(state.MLP || state.OOOJAVA){
1466 classdefout.println(" int oid;");
1467 classdefout.println(" int allocsite;");
1469 if (state.EVENTMONITOR) {
1470 classdefout.println(" int objuid;");
1473 classdefout.println(" pthread_t tid;");
1474 classdefout.println(" void * lockentry;");
1475 classdefout.println(" int lockcount;");
1479 classdefout.println(" int flag;");
1480 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1481 classdefout.println(" void * flagptr;");
1482 } else if (state.MULTICORE) {
1483 classdefout.println(" int version;");
1484 classdefout.println(" int * lock;"); // lock entry for this obj
1485 classdefout.println(" int mutex;");
1486 classdefout.println(" int lockcount;");
1487 if(state.MULTICOREGC) {
1488 classdefout.println(" int marked;");
1491 if (state.OPTIONAL) {
1492 classdefout.println(" int numfses;");
1493 classdefout.println(" int * fses;");
1496 printClassStruct(cn, classdefout);
1497 classdefout.println("};\n");
1499 if (state.DSM||state.SINGLETM) {
1500 /* Cycle through LocalityBindings */
1501 HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
1502 Set<LocalityBinding> lbset=locality.getClassBindings(cn);
1504 for(Iterator<LocalityBinding> lbit=lbset.iterator(); lbit.hasNext();) {
1505 LocalityBinding lb=lbit.next();
1506 MethodDescriptor md=lb.getMethod();
1507 if (md.getModifiers().isNative()) {
1508 //make sure we only print a native method once
1509 if (nativemethods.contains(md)) {
1510 FlatMethod fm=state.getMethodFlat(md);
1511 generateTempStructs(fm, lb);
1514 nativemethods.add(md);
1516 generateMethod(cn, md, lb, headersout, output);
1519 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1520 MethodDescriptor md=(MethodDescriptor)methodit.next();
1521 if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
1522 //Need to build param structure for library code
1523 FlatMethod fm=state.getMethodFlat(md);
1524 generateTempStructs(fm, null);
1525 generateMethodParam(cn, md, null, output);
1530 for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
1531 MethodDescriptor md=(MethodDescriptor)methodit.next();
1532 generateMethod(cn, md, null, headersout, output);
1536 private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) {
1537 /* Output parameter structure */
1538 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1539 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1540 if ((state.DSM||state.SINGLETM)&&lb!=null)
1541 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1543 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1544 output.println(" int size;");
1545 output.println(" void * next;");
1546 for(int i=0; i<objectparams.numPointers(); i++) {
1547 TempDescriptor temp=objectparams.getPointer(i);
1548 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1550 output.println("};\n");
1554 private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
1555 FlatMethod fm=state.getMethodFlat(md);
1556 generateTempStructs(fm, lb);
1558 ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
1559 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
1561 generateMethodParam(cn, md, lb, output);
1563 /* Output temp structure */
1564 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1565 if (state.DSM||state.SINGLETM)
1566 output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1568 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1569 output.println(" int size;");
1570 output.println(" void * next;");
1571 for(int i=0; i<objecttemps.numPointers(); i++) {
1572 TempDescriptor temp=objecttemps.getPointer(i);
1573 if (temp.getType().isNull())
1574 output.println(" void * "+temp.getSafeSymbol()+";");
1576 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1578 output.println("};\n");
1581 /********* Output method declaration ***********/
1582 if (state.DSM||state.SINGLETM) {
1583 headersout.println("#define D"+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1585 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1587 /* First the return type */
1588 if (md.getReturnType()!=null) {
1589 if (md.getReturnType().isClass()||md.getReturnType().isArray())
1590 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1592 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1594 //catch the constructor case
1595 headersout.print("void ");
1597 /* Next the method name */
1598 if (state.DSM||state.SINGLETM) {
1599 headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1601 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1603 boolean printcomma=false;
1604 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1605 if (state.DSM||state.SINGLETM) {
1606 headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1608 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1612 /* Output parameter list*/
1613 for(int i=0; i<objectparams.numPrimitives(); i++) {
1614 TempDescriptor temp=objectparams.getPrimitive(i);
1616 headersout.print(", ");
1618 if (temp.getType().isClass()||temp.getType().isArray())
1619 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1621 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1623 headersout.println(");\n");
1627 /** This function outputs (1) structures that parameters are
1628 * passed in (when PRECISE GC is enabled) and (2) function
1629 * prototypes for the tasks */
1631 private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1632 /* Cycle through tasks */
1633 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1635 while(taskit.hasNext()) {
1636 /* Classify parameters */
1637 TaskDescriptor task=(TaskDescriptor)taskit.next();
1638 FlatMethod fm=state.getMethodFlat(task);
1639 generateTempStructs(fm, null);
1641 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1642 TempObject objecttemps=(TempObject) tempstable.get(task);
1644 /* Output parameter structure */
1645 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1646 output.println("struct "+task.getSafeSymbol()+"_params {");
1647 output.println(" int size;");
1648 output.println(" void * next;");
1649 for(int i=0; i<objectparams.numPointers(); i++) {
1650 TempDescriptor temp=objectparams.getPointer(i);
1651 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1654 output.println("};\n");
1655 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1656 maxtaskparams=objectparams.numPointers()+fm.numTags();
1660 /* Output temp structure */
1661 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1662 output.println("struct "+task.getSafeSymbol()+"_locals {");
1663 output.println(" int size;");
1664 output.println(" void * next;");
1665 for(int i=0; i<objecttemps.numPointers(); i++) {
1666 TempDescriptor temp=objecttemps.getPointer(i);
1667 if (temp.getType().isNull())
1668 output.println(" void * "+temp.getSafeSymbol()+";");
1669 else if(temp.getType().isTag())
1670 output.println(" struct "+
1671 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1673 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1675 output.println("};\n");
1678 /* Output task declaration */
1679 headersout.print("void " + task.getSafeSymbol()+"(");
1681 boolean printcomma=false;
1682 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1683 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1685 headersout.print("void * parameterarray[]");
1686 headersout.println(");\n");
1690 /***** Generate code for FlatMethod fm. *****/
1692 Hashtable<FlatAtomicEnterNode, AtomicRecord> atomicmethodmap;
1693 static int atomicmethodcount=0;
1696 BranchAnalysis branchanalysis;
1697 private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1698 if (State.PRINTFLAT)
1699 System.out.println(fm.printMethod());
1700 MethodDescriptor md=fm.getMethod();
1701 TaskDescriptor task=fm.getTask();
1702 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1703 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task);
1705 HashSet<AtomicRecord> arset=null;
1706 branchanalysis=null;
1708 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1710 if (atomicmethodmap==null)
1711 atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
1713 //fix these so we get right strings for local variables
1714 localsprefixaddr=localsprefix;
1715 localsprefixderef=localsprefix+"->";
1716 arset=new HashSet<AtomicRecord>();
1718 //build branchanalysis
1719 branchanalysis=new BranchAnalysis(locality, lb, delaycomp.getNotReady(lb), delaycomp.livecode(lb), state);
1721 //Generate commit methods here
1722 for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator();fnit.hasNext();) {
1723 FlatNode fn=fnit.next();
1724 if (fn.kind()==FKind.FlatAtomicEnterNode&&
1725 locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
1726 delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
1727 //We have an atomic enter
1728 FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
1729 Set<FlatNode> exitset=faen.getExits();
1731 String methodname=md.getSymbol()+(atomicmethodcount++);
1732 AtomicRecord ar=new AtomicRecord();
1736 atomicmethodmap.put(faen, ar);
1738 //build data structure declaration
1739 output.println("struct atomicprimitives_"+methodname+" {");
1741 Set<FlatNode> recordset=delaycomp.livecode(lb);
1742 Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
1743 Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
1744 Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
1746 ar.reallivein=new HashSet(liveinto);
1748 ar.liveoutvirtualread=liveoutvirtualread;
1751 for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext();) {
1752 TempDescriptor tmp=it.next();
1753 //remove the pointers
1754 if (tmp.getType().isPtr()) {
1757 //let's print it here
1758 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1761 for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext();) {
1762 TempDescriptor tmp=it.next();
1763 //remove the pointers
1764 if (tmp.getType().isPtr()) {
1766 } else if (!liveinto.contains(tmp)) {
1767 //let's print it here
1768 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1771 output.println("};");
1773 //print out method name
1774 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) {");
1775 //build code for commit method
1777 //first define local primitives
1778 Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
1779 for(Iterator<TempDescriptor> tmpit=alltemps.iterator();tmpit.hasNext();) {
1780 TempDescriptor tmp=tmpit.next();
1781 if (!tmp.getType().isPtr()) {
1782 if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
1783 //read from live into set
1784 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
1787 output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
1791 //turn off write barrier generation
1793 state.SINGLETM=false;
1794 generateCode(faen, fm, lb, exitset, output, false);
1795 state.SINGLETM=true;
1796 //turn on write barrier generation
1798 output.println("}\n\n");
1802 //redefine these back to normal
1804 localsprefixaddr="&"+localsprefix;
1805 localsprefixderef=localsprefix+".";
1807 generateHeader(fm, lb, md!=null ? md : task,output);
1808 TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1810 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
1811 for(Iterator<AtomicRecord> arit=arset.iterator();arit.hasNext();) {
1812 AtomicRecord ar=arit.next();
1813 output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
1817 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1818 if (md!=null&&(state.DSM||state.SINGLETM))
1819 output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1820 else if (md!=null&&!(state.DSM||state.SINGLETM))
1821 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1823 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1824 output.print(objecttemp.numPointers()+",");
1825 output.print(paramsprefix);
1826 for(int j=0; j<objecttemp.numPointers(); j++)
1827 output.print(", NULL");
1828 output.println("};");
1831 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1832 TempDescriptor td=objecttemp.getPrimitive(i);
1833 TypeDescriptor type=td.getType();
1835 output.println(" void * "+td.getSafeSymbol()+";");
1836 else if (type.isClass()||type.isArray())
1837 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1839 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1843 if( state.MLP || state.OOOJAVA ) {
1844 if( fm.getNext(0) instanceof FlatSESEEnterNode ) {
1845 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1846 if( (state.MLP && callerSESEplaceholder != mlpa.getMainSESE()) ||
1847 (state.OOOJAVA && callerSESEplaceholder != oooa.getMainSESE())
1849 // declare variables for naming static SESE's
1850 output.println(" /* static SESE names */");
1851 Iterator<SESEandAgePair> pItr = callerSESEplaceholder.getNeededStaticNames().iterator();
1852 while( pItr.hasNext() ) {
1853 SESEandAgePair pair = pItr.next();
1854 output.println(" void* "+pair+";");
1857 // declare variables for tracking dynamic sources
1858 output.println(" /* dynamic variable sources */");
1859 Iterator<TempDescriptor> dynSrcItr = callerSESEplaceholder.getDynamicVarSet().iterator();
1860 while( dynSrcItr.hasNext() ) {
1861 TempDescriptor dynSrcVar = dynSrcItr.next();
1862 output.println(" void* "+dynSrcVar+"_srcSESE;");
1863 output.println(" INTPTR "+dynSrcVar+"_srcOffset;");
1868 // set up related allocation sites's waiting queues
1871 ConflictGraph graph = null;
1872 graph = mlpa.getConflictGraphResults().get(fm);
1873 if (graph != null && graph.hasConflictEdge()) {
1874 output.println(" /* set up waiting queues */");
1875 output.println(" int numMemoryQueue=0;");
1876 output.println(" int memoryQueueItemID=0;");
1877 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
1879 System.out.println("#lockSet="+lockSet.hashCode());
1880 System.out.println("lockset="+lockSet);
1881 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1882 SESELock seseLock = (SESELock) iterator.next();
1883 System.out.println("id="+seseLock.getID());
1884 System.out.println("#="+seseLock);
1886 System.out.println("size="+lockSet.size());
1887 if (lockSet.size() > 0) {
1888 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1890 .println(" seseCaller->numMemoryQueue=numMemoryQueue;");
1892 .println(" seseCaller->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1897 FlatSESEEnterNode callerSESEplaceholder = (FlatSESEEnterNode) fm.getNext( 0 );
1898 if(callerSESEplaceholder!= oooa.getMainSESE()){
1899 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(callerSESEplaceholder);
1900 if (graph != null && graph.hasConflictEdge()) {
1901 output.println(" // set up waiting queues ");
1902 output.println(" int numMemoryQueue=0;");
1903 output.println(" int memoryQueueItemID=0;");
1904 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
1905 System.out.println("#lockSet="+lockSet.hashCode());
1906 System.out.println("lockset="+lockSet);
1907 for (Iterator iterator = lockSet.iterator(); iterator.hasNext();) {
1908 Analysis.OoOJava.SESELock seseLock = (Analysis.OoOJava.SESELock) iterator.next();
1909 System.out.println("id="+seseLock.getID());
1910 System.out.println("#="+seseLock);
1912 System.out.println("size="+lockSet.size());
1913 if (lockSet.size() > 0) {
1914 output.println(" numMemoryQueue=" + lockSet.size() + ";");
1916 .println(" seseCaller->numMemoryQueue=numMemoryQueue;");
1918 .println(" seseCaller->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
1928 /* Check to see if we need to do a GC if this is a
1929 * multi-threaded program...*/
1931 if (((state.MLP||state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
1932 || this.state.MULTICOREGC) {
1933 //Don't bother if we aren't in recursive methods...The loops case will catch it
1934 if (callgraph.getAllMethods(md).contains(md)) {
1935 if (state.DSM&&lb.isAtomic())
1936 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
1937 else if (this.state.MULTICOREGC) {
1938 output.println("if(gcflag) gc("+localsprefixaddr+");");
1940 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1945 generateCode(fm.getNext(0), fm, lb, null, output, true);
1947 output.println("}\n\n");
1951 protected void initializeSESE( FlatSESEEnterNode fsen ) {
1953 FlatMethod fm = fsen.getfmEnclosing();
1954 MethodDescriptor md = fm.getMethod();
1955 ClassDescriptor cn = md.getClassDesc();
1958 // Creates bogus method descriptor to index into tables
1959 Modifiers modBogus = new Modifiers();
1960 MethodDescriptor mdBogus =
1961 new MethodDescriptor( modBogus,
1962 new TypeDescriptor( TypeDescriptor.VOID ),
1963 "sese_"+fsen.getPrettyIdentifier()+fsen.getIdentifier()
1966 mdBogus.setClassDesc( fsen.getcdEnclosing() );
1967 FlatMethod fmBogus = new FlatMethod( mdBogus, null );
1968 fsen.setfmBogus( fmBogus );
1969 fsen.setmdBogus( mdBogus );
1971 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
1972 inSetAndOutSet.addAll( fsen.getInVarSet() );
1973 inSetAndOutSet.addAll( fsen.getOutVarSet() );
1975 // Build paramsobj for bogus method descriptor
1976 ParamsObject objectparams = new ParamsObject( mdBogus, tag++ );
1977 paramstable.put( mdBogus, objectparams );
1979 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
1980 while( itr.hasNext() ) {
1981 TempDescriptor temp = itr.next();
1982 TypeDescriptor type = temp.getType();
1983 if( type.isPtr() ) {
1984 objectparams.addPtr( temp );
1986 objectparams.addPrim( temp );
1990 // Build normal temp object for bogus method descriptor
1991 TempObject objecttemps = new TempObject( objectparams, mdBogus, tag++ );
1992 tempstable.put( mdBogus, objecttemps );
1994 for( Iterator nodeit = fsen.getNodeSet().iterator(); nodeit.hasNext(); ) {
1995 FlatNode fn = (FlatNode)nodeit.next();
1996 TempDescriptor[] writes = fn.writesTemps();
1998 for( int i = 0; i < writes.length; i++ ) {
1999 TempDescriptor temp = writes[i];
2000 TypeDescriptor type = temp.getType();
2002 if( type.isPtr() ) {
2003 objecttemps.addPtr( temp );
2005 objecttemps.addPrim( temp );
2011 // used when generating the specific SESE record struct
2012 // to remember the FIRST field name of sese records
2013 // that the current SESE depends on--we need to know the
2014 // offset to the first one for garbage collection
2015 protected void addingDepRecField( FlatSESEEnterNode fsen,
2017 if( fsen.getFirstDepRecField() == null ) {
2018 fsen.setFirstDepRecField( field );
2020 fsen.incNumDepRecs();
2023 protected void generateMethodSESE(FlatSESEEnterNode fsen,
2025 PrintWriter outputStructs,
2026 PrintWriter outputMethHead,
2027 PrintWriter outputMethods
2030 ParamsObject objectparams = (ParamsObject) paramstable.get( fsen.getmdBogus() );
2031 TempObject objecttemps = (TempObject) tempstable .get( fsen.getmdBogus() );
2033 // generate locals structure
2034 outputStructs.println("struct "+
2035 fsen.getcdEnclosing().getSafeSymbol()+
2036 fsen.getmdBogus().getSafeSymbol()+"_"+
2037 fsen.getmdBogus().getSafeMethodDescriptor()+
2039 outputStructs.println(" int size;");
2040 outputStructs.println(" void * next;");
2041 for(int i=0; i<objecttemps.numPointers(); i++) {
2042 TempDescriptor temp=objecttemps.getPointer(i);
2044 if (temp.getType().isNull())
2045 outputStructs.println(" void * "+temp.getSafeSymbol()+";");
2047 outputStructs.println(" struct "+
2048 temp.getType().getSafeSymbol()+" * "+
2049 temp.getSafeSymbol()+";");
2051 outputStructs.println("};\n");
2054 // divide in-set and out-set into objects and primitives to prep
2055 // for the record generation just below
2056 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
2057 inSetAndOutSet.addAll( fsen.getInVarSet() );
2058 inSetAndOutSet.addAll( fsen.getOutVarSet() );
2060 Set<TempDescriptor> inSetAndOutSetObjs = new HashSet<TempDescriptor>();
2061 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
2063 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
2064 while( itr.hasNext() ) {
2065 TempDescriptor temp = itr.next();
2066 TypeDescriptor type = temp.getType();
2067 if( type.isPtr() ) {
2068 inSetAndOutSetObjs.add( temp );
2070 inSetAndOutSetPrims.add( temp );
2075 // generate the SESE record structure
2076 outputStructs.println(fsen.getSESErecordName()+" {");
2078 // data common to any SESE, and it must be placed first so
2079 // a module that doesn't know what kind of SESE record this
2080 // is can cast the pointer to a common struct
2081 outputStructs.println(" SESEcommon common;");
2083 // then garbage list stuff
2084 outputStructs.println(" /* next is in-set and out-set objects that look like a garbage list */");
2085 outputStructs.println(" int size;");
2086 outputStructs.println(" void * next;");
2088 // I think that the set of TempDescriptors inSetAndOutSetObjs
2089 // calculated above should match the pointer object params
2090 // used in the following code, but let's just leave the working
2091 // implementation unless there is actually a problem...
2092 for(int i=0; i<objectparams.numPointers(); i++) {
2093 TempDescriptor temp=objectparams.getPointer(i);
2094 if (temp.getType().isNull())
2095 outputStructs.println(" void * "+temp.getSafeSymbol()+
2096 "; /* in-or-out-set obj in gl */");
2098 outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+
2099 temp.getSafeSymbol()+"; /* in-or-out-set obj in gl */");
2102 outputStructs.println(" /* next is primitives for in-set and out-set and dynamic tracking */");
2104 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
2105 while( itrPrims.hasNext() ) {
2106 TempDescriptor temp = itrPrims.next();
2107 TypeDescriptor type = temp.getType();
2108 if(type.isPrimitive()){
2109 outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()+"; /* in-set or out-set primitive */");
2113 // note that the sese record pointer will be added below, just primitive part of tracking here
2114 Iterator<TempDescriptor> itrDynInVars = fsen.getDynamicInVarSet().iterator();
2115 while( itrDynInVars.hasNext() ) {
2116 TempDescriptor dynInVar = itrDynInVars.next();
2117 outputStructs.println(" INTPTR "+dynInVar+"_srcOffset; /* dynamic tracking primitive */");
2121 outputStructs.println(" /* everything after this should be pointers to an SESE record */" );
2123 // other half of info for dynamic tracking, the SESE record pointer
2124 itrDynInVars = fsen.getDynamicInVarSet().iterator();
2125 while( itrDynInVars.hasNext() ) {
2126 TempDescriptor dynInVar = itrDynInVars.next();
2127 String depRecField = dynInVar+"_srcSESE";
2128 outputStructs.println(" void* "+depRecField+";");
2129 addingDepRecField( fsen, depRecField );
2132 // statically known sese sources are record pointers, too
2133 Iterator<SESEandAgePair> itrStaticInVarSrcs = fsen.getStaticInVarSrcs().iterator();
2134 while( itrStaticInVarSrcs.hasNext() ) {
2135 SESEandAgePair srcPair = itrStaticInVarSrcs.next();
2136 outputStructs.println(" "+srcPair.getSESE().getSESErecordName()+"* "+srcPair+";");
2137 addingDepRecField( fsen, srcPair.toString() );
2140 if( fsen.getFirstDepRecField() != null ) {
2141 outputStructs.println(" /* compiler believes first dependent SESE record field above is: "+
2142 fsen.getFirstDepRecField()+" */" );
2145 outputStructs.println("};\n");
2148 // write method declaration to header file
2149 outputMethHead.print("void ");
2150 outputMethHead.print(fsen.getSESEmethodName()+"(");
2151 outputMethHead.print(fsen.getSESErecordName()+"* "+paramsprefix);
2152 outputMethHead.println(");\n");
2155 generateFlatMethodSESE( fsen.getfmBogus(),
2156 fsen.getcdEnclosing(),
2162 private void generateFlatMethodSESE(FlatMethod fm,
2164 FlatSESEEnterNode fsen,
2165 FlatSESEExitNode seseExit,
2169 MethodDescriptor md=fm.getMethod();
2171 output.print("void ");
2172 output.print(fsen.getSESEmethodName()+"(");
2173 output.print(fsen.getSESErecordName()+"* "+paramsprefix);
2174 output.println("){\n");
2176 TempObject objecttemp=(TempObject) tempstable.get(md);
2178 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2179 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
2180 output.print(objecttemp.numPointers()+",");
2181 output.print("&(((SESEcommon*)(___params___))[1])");
2182 for(int j=0; j<objecttemp.numPointers(); j++)
2183 output.print(", NULL");
2184 output.println("};");
2187 output.println(" /* regular local primitives */");
2188 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2189 TempDescriptor td=objecttemp.getPrimitive(i);
2190 TypeDescriptor type=td.getType();
2192 output.println(" void * "+td.getSafeSymbol()+";");
2193 else if (type.isClass()||type.isArray())
2194 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2196 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2200 // declare variables for naming static SESE's
2201 output.println(" /* static SESE names */");
2202 Iterator<SESEandAgePair> pItr = fsen.getNeededStaticNames().iterator();
2203 while( pItr.hasNext() ) {
2204 SESEandAgePair pair = pItr.next();
2205 output.println(" void* "+pair+";");
2208 // declare variables for tracking dynamic sources
2209 output.println(" /* dynamic variable sources */");
2210 Iterator<TempDescriptor> dynSrcItr = fsen.getDynamicVarSet().iterator();
2211 while( dynSrcItr.hasNext() ) {
2212 TempDescriptor dynSrcVar = dynSrcItr.next();
2213 output.println(" void* "+dynSrcVar+"_srcSESE;");
2214 output.println(" INTPTR "+dynSrcVar+"_srcOffset;");
2217 // declare local temps for in-set primitives, and if it is
2218 // a ready-source variable, get the value from the record
2219 output.println(" /* local temps for in-set primitives */");
2220 Iterator<TempDescriptor> itrInSet = fsen.getInVarSet().iterator();
2221 while( itrInSet.hasNext() ) {
2222 TempDescriptor temp = itrInSet.next();
2223 TypeDescriptor type = temp.getType();
2224 if( !type.isPtr() ) {
2225 if( fsen.getReadyInVarSet().contains( temp ) ) {
2226 output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
2228 output.println(" "+type+" "+temp+";");
2233 // declare local temps for out-set primitives if its not already
2234 // in the in-set, and it's value will get written so no problem
2235 output.println(" /* local temp for out-set prim, not already in the in-set */");
2236 Iterator<TempDescriptor> itrOutSet = fsen.getOutVarSet().iterator();
2237 while( itrOutSet.hasNext() ) {
2238 TempDescriptor temp = itrOutSet.next();
2239 TypeDescriptor type = temp.getType();
2240 if( !type.isPtr() && !fsen.getInVarSet().contains( temp ) ) {
2241 output.println(" "+type+" "+temp+";");
2245 // setup memory queue
2248 output.println(" // set up memory queues ");
2249 output.println(" int numMemoryQueue=0;");
2250 output.println(" int memoryQueueItemID=0;");
2251 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(fsen);
2252 if (graph != null && graph.hasConflictEdge()) {
2253 output.println(" {");
2255 .println(" SESEcommon* parentCommon = &(___params___->common);");
2256 Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
2257 System.out.println("#lockSet="+lockSet);
2258 if (lockSet.size() > 0) {
2259 output.println(" numMemoryQueue=" + lockSet.size() + ";");
2261 .println(" parentCommon->numMemoryQueue=numMemoryQueue;");
2263 .println(" parentCommon->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2266 output.println(" }");
2269 output.println(" // set up memory queues ");
2270 output.println(" int numMemoryQueue=0;");
2271 output.println(" int memoryQueueItemID=0;");
2272 ConflictGraph graph = null;
2273 graph = mlpa.getConflictGraphResults().get(fsen);
2274 if (graph != null && graph.hasConflictEdge()) {
2275 output.println(" {");
2277 .println(" SESEcommon* parentCommon = &(___params___->common);");
2278 HashSet<SESELock> lockSet = mlpa.getConflictGraphLockMap().get(
2280 System.out.println("#lockSet="+lockSet);
2282 if (lockSet.size() > 0) {
2283 output.println(" numMemoryQueue=" + lockSet.size() + "; ");
2285 .println(" parentCommon->numMemoryQueue=numMemoryQueue;");
2287 .println(" parentCommon->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
2290 output.println(" }");
2296 // copy in-set into place, ready vars were already
2297 // copied when the SESE was issued
2298 Iterator<TempDescriptor> tempItr;
2300 // static vars are from a known SESE
2301 tempItr = fsen.getStaticInVarSet().iterator();
2302 while( tempItr.hasNext() ) {
2303 TempDescriptor temp = tempItr.next();
2304 VariableSourceToken vst = fsen.getStaticInVarSrc( temp );
2305 SESEandAgePair srcPair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2307 // can't grab something from this source until it is done
2308 output.println(" {");
2310 If we are running, everything is done. This check is redundant.
2312 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+srcPair+";" );
2313 output.println(" pthread_mutex_lock( &(com->lock) );");
2314 output.println(" while( com->doneExecuting == FALSE ) {");
2315 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2316 output.println(" }");
2317 output.println(" pthread_mutex_unlock( &(com->lock) );");
2319 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2320 " = "+paramsprefix+"->"+srcPair+"->"+vst.getAddrVar()+";");
2322 output.println(" }");
2325 // dynamic vars come from an SESE and src
2326 tempItr = fsen.getDynamicInVarSet().iterator();
2327 while( tempItr.hasNext() ) {
2328 TempDescriptor temp = tempItr.next();
2329 TypeDescriptor type = temp.getType();
2331 // go grab it from the SESE source
2332 output.println(" if( "+paramsprefix+"->"+temp+"_srcSESE != NULL ) {");
2334 // gotta wait until the source is done
2335 output.println(" SESEcommon* com = (SESEcommon*)"+paramsprefix+"->"+temp+"_srcSESE;" );
2337 If we are running, everything is done!
2338 output.println(" pthread_mutex_lock( &(com->lock) );");
2339 output.println(" while( com->doneExecuting == FALSE ) {");
2340 output.println(" pthread_cond_wait( &(com->doneCond), &(com->lock) );");
2341 output.println(" }");
2342 output.println(" pthread_mutex_unlock( &(com->lock) );");
2346 if( type.isNull() ) {
2348 } else if( type.isClass() || type.isArray() ) {
2349 typeStr = "struct "+type.getSafeSymbol()+"*";
2351 typeStr = type.getSafeSymbol();
2354 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2355 " = *(("+typeStr+"*) ("+
2356 paramsprefix+"->"+temp+"_srcSESE + "+
2357 paramsprefix+"->"+temp+"_srcOffset));");
2359 // or if the source was our parent, its in the record to grab
2360 output.println(" } else {");
2361 output.println(" "+generateTemp( fsen.getfmBogus(), temp, null )+
2362 " = "+paramsprefix+"->"+temp+";");
2363 output.println(" }");
2366 // Check to see if we need to do a GC if this is a
2367 // multi-threaded program...
2368 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2369 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2370 //Don't bother if we aren't in recursive methods...The loops case will catch it
2371 // if (callgraph.getAllMethods(md).contains(md)) {
2372 // if(this.state.MULTICOREGC) {
2373 // output.println("if(gcflag) gc("+localsprefixaddr+");");
2375 // output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2380 // initialize thread-local var to a non-zero, invalid address
2381 output.println(" seseCaller = (SESEcommon*) 0x2;");
2384 output.println(" CP_LOGEVENT( CP_EVENTID_TASKEXECUTE, CP_EVENTTYPE_BEGIN );");
2386 HashSet<FlatNode> exitset=new HashSet<FlatNode>();
2387 exitset.add(seseExit);
2388 generateCode(fsen.getNext(0), fm, null, exitset, output, true);
2389 output.println("}\n\n");
2394 // when a new mlp thread is created for an issued SESE, it is started
2395 // by running this method which blocks on a cond variable until
2396 // it is allowed to transition to execute. Then a case statement
2397 // allows it to invoke the method with the proper SESE body, and after
2398 // exiting the SESE method, executes proper SESE exit code before the
2399 // thread can be destroyed
2400 private void generateSESEinvocationMethod(PrintWriter outmethodheader,
2401 PrintWriter outmethod
2404 outmethodheader.println("void* invokeSESEmethod( void* seseRecord );");
2405 outmethod.println( "void* invokeSESEmethod( void* seseRecord ) {");
2406 outmethod.println( " int status;");
2407 outmethod.println( " char errmsg[128];");
2409 // generate a case for each SESE class that can be invoked
2410 outmethod.println( " switch( *((int*)seseRecord) ) {");
2411 outmethod.println( " ");
2412 Iterator<FlatSESEEnterNode> seseit;
2414 seseit=mlpa.getAllSESEs().iterator();
2416 seseit=oooa.getAllSESEs().iterator();
2418 while(seseit.hasNext()){
2419 FlatSESEEnterNode fsen = seseit.next();
2421 outmethod.println( " /* "+fsen.getPrettyIdentifier()+" */");
2422 outmethod.println( " case "+fsen.getIdentifier()+":");
2423 outmethod.println( " "+fsen.getSESEmethodName()+"( seseRecord );");
2425 if( (state.MLP && fsen.equals( mlpa.getMainSESE() )) ||
2426 (state.OOOJAVA && fsen.equals( oooa.getMainSESE() ))
2428 outmethod.println( " /* work scheduler works forever, explicitly exit */");
2429 if (state.COREPROF) {
2430 outmethod.println(" CP_EXIT();");
2431 outmethod.println(" CP_DUMP();");
2433 outmethod.println( " workScheduleExit();");
2434 outmethod.println( " exit( 0 );");
2437 outmethod.println( " break;");
2438 outmethod.println( "");
2441 // default case should never be taken, error out
2442 outmethod.println( " default:");
2443 outmethod.println( " printf(\"Error: unknown SESE class ID in invoke method.\\n\");");
2444 outmethod.println( " exit(-30);");
2445 outmethod.println( " break;");
2446 outmethod.println( " }");
2447 outmethod.println( " return NULL;");
2448 outmethod.println( "}\n\n");
2452 protected void generateCode(FlatNode first,
2455 Set<FlatNode> stopset,
2456 PrintWriter output, boolean firstpass) {
2458 /* Assign labels to FlatNode's if necessary.*/
2460 Hashtable<FlatNode, Integer> nodetolabel;
2462 if (state.DELAYCOMP&&!firstpass)
2463 nodetolabel=dcassignLabels(first, stopset);
2465 nodetolabel=assignLabels(first, stopset);
2467 Set<FlatNode> storeset=null;
2468 HashSet<FlatNode> genset=null;
2469 HashSet<FlatNode> refset=null;
2470 Set<FlatNode> unionset=null;
2472 if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
2473 storeset=delaycomp.livecode(lb);
2474 genset=new HashSet<FlatNode>();
2475 if (state.STMARRAY&&!state.DUALVIEW) {
2476 refset=new HashSet<FlatNode>();
2477 refset.addAll(delaycomp.getDeref(lb));
2478 refset.removeAll(delaycomp.getCannotDelay(lb));
2479 refset.removeAll(delaycomp.getOther(lb));
2482 genset.addAll(delaycomp.getCannotDelay(lb));
2483 genset.addAll(delaycomp.getOther(lb));
2485 genset.addAll(delaycomp.getNotReady(lb));
2486 if (state.STMARRAY&&!state.DUALVIEW) {
2487 genset.removeAll(refset);
2490 unionset=new HashSet<FlatNode>();
2491 unionset.addAll(storeset);
2492 unionset.addAll(genset);
2493 if (state.STMARRAY&&!state.DUALVIEW)
2494 unionset.addAll(refset);
2497 /* Do the actual code generation */
2498 FlatNode current_node=null;
2499 HashSet tovisit=new HashSet();
2500 HashSet visited=new HashSet();
2502 tovisit.add(first.getNext(0));
2505 while(current_node!=null||!tovisit.isEmpty()) {
2506 if (current_node==null) {
2507 current_node=(FlatNode)tovisit.iterator().next();
2508 tovisit.remove(current_node);
2509 } else if (tovisit.contains(current_node)) {
2510 tovisit.remove(current_node);
2512 visited.add(current_node);
2513 if (nodetolabel.containsKey(current_node)) {
2514 output.println("L"+nodetolabel.get(current_node)+":");
2516 if (state.INSTRUCTIONFAILURE) {
2517 if (state.THREAD||state.DSM||state.SINGLETM) {
2518 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2520 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2522 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2524 if (!state.DELAYCOMP||firstpass) {
2525 generateFlatNode(fm, lb, current_node, output);
2527 //store primitive variables in out set
2528 AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
2529 Set<TempDescriptor> liveout=ar.liveout;
2530 for(Iterator<TempDescriptor> tmpit=liveout.iterator();tmpit.hasNext();) {
2531 TempDescriptor tmp=tmpit.next();
2532 output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
2535 if ((state.MLP || state.OOOJAVA) && stopset!=null) {
2536 assert first.getPrev( 0 ) instanceof FlatSESEEnterNode;
2537 assert current_node instanceof FlatSESEExitNode;
2538 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev( 0 );
2539 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2540 assert fsen.getFlatExit().equals( fsxn );
2541 assert fsxn.getFlatEnter().equals( fsen );
2543 if (current_node.kind()!=FKind.FlatReturnNode) {
2544 output.println(" return;");
2547 } else if(current_node.numNext()==1) {
2549 if ((state.MLP|| state.OOOJAVA) &&
2550 current_node.kind()==FKind.FlatSESEEnterNode &&
2551 !((FlatSESEEnterNode)current_node).getIsCallerSESEplaceholder()
2553 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2554 generateFlatNode(fm, lb, current_node, output);
2555 nextnode=fsen.getFlatExit().getNext(0);
2556 } else if (state.DELAYCOMP) {
2557 boolean specialprimitive=false;
2558 //skip literals...no need to add extra overhead
2559 if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
2560 TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
2561 if (!typedesc.isClass()&&!typedesc.isArray()) {
2562 specialprimitive=true;
2566 if (genset==null||genset.contains(current_node)||specialprimitive)
2567 generateFlatNode(fm, lb, current_node, output);
2568 if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
2569 //need to acquire lock
2570 handleArrayDeref(fm, lb, current_node, output, firstpass);
2572 if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
2573 TempDescriptor wrtmp=current_node.writesTemps()[0];
2575 //need to store value written by previous node
2576 if (wrtmp.getType().isPtr()) {
2577 //only lock the objects that may actually need locking
2578 if (recorddc.getNeedTrans(lb, current_node)&&
2579 (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
2580 wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
2581 output.println("STOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2583 output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2586 output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+");/* "+current_node.nodeid+" */");
2589 //need to read value read by previous node
2590 if (wrtmp.getType().isPtr()) {
2591 output.println("RESTOREPTR("+generateTemp(fm, wrtmp,lb)+");/* "+current_node.nodeid+" */");
2593 output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp, lb)+"); /* "+current_node.nodeid+" */");
2597 nextnode=current_node.getNext(0);
2600 generateFlatNode(fm, lb, current_node, output);
2601 nextnode=current_node.getNext(0);
2603 if (visited.contains(nextnode)) {
2604 output.println("goto L"+nodetolabel.get(nextnode)+";");
2607 current_node=nextnode;
2608 } else if (current_node.numNext()==2) {
2610 if (state.DELAYCOMP) {
2611 boolean computeside=false;
2613 //need to record which way it should go
2614 if (genset==null||genset.contains(current_node)) {
2615 if (storeset!=null&&storeset.contains(current_node)) {
2616 //need to store which way branch goes
2617 generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2619 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2621 //which side to execute
2625 if (genset.contains(current_node)) {
2626 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2627 } else if (storeset.contains(current_node)) {
2629 branchanalysis.generateGroupCode(current_node, output, nodetolabel);
2631 //which side to execute
2636 Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
2638 if (leftset.size()==0)
2640 if (visited.contains(current_node.getNext(branch))) {
2641 //already visited -- build jump
2642 output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
2645 current_node=current_node.getNext(branch);
2648 if (!visited.contains(current_node.getNext(1)))
2649 tovisit.add(current_node.getNext(1));
2650 if (visited.contains(current_node.getNext(0))) {
2651 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2654 current_node=current_node.getNext(0);
2658 generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2659 if (!visited.contains(current_node.getNext(1)))
2660 tovisit.add(current_node.getNext(1));
2661 if (visited.contains(current_node.getNext(0))) {
2662 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2665 current_node=current_node.getNext(0);
2667 } else throw new Error();
2671 protected void handleArrayDeref(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output, boolean firstpass) {
2672 if (fn.kind()==FKind.FlatSetElementNode) {
2673 FlatSetElementNode fsen=(FlatSetElementNode) fn;
2674 String dst=generateTemp(fm, fsen.getDst(), lb);
2675 String src=generateTemp(fm, fsen.getSrc(), lb);
2676 String index=generateTemp(fm, fsen.getIndex(), lb);
2677 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2679 if (elementtype.isArray()||elementtype.isClass())
2682 type=elementtype.getSafeSymbol()+" ";
2684 output.println("STOREARRAY("+dst+","+index+","+type+")");
2686 output.println("{");
2687 output.println(" struct ArrayObject *array;");
2688 output.println(" int index;");
2689 output.println(" RESTOREARRAY(array,index);");
2690 output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
2691 output.println("}");
2693 } else if (fn.kind()==FKind.FlatElementNode) {
2694 FlatElementNode fen=(FlatElementNode) fn;
2695 String src=generateTemp(fm, fen.getSrc(), lb);
2696 String index=generateTemp(fm, fen.getIndex(), lb);
2697 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2698 String dst=generateTemp(fm, fen.getDst(), lb);
2700 if (elementtype.isArray()||elementtype.isClass())
2703 type=elementtype.getSafeSymbol()+" ";
2705 output.println("STOREARRAY("+src+","+index+","+type+")");
2707 output.println("{");
2708 output.println(" struct ArrayObject *array;");
2709 output.println(" int index;");
2710 output.println(" RESTOREARRAY(array,index);");
2711 output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
2712 output.println("}");
2716 /** Special label assignment for delaycomputation */
2717 protected Hashtable<FlatNode, Integer> dcassignLabels(FlatNode first, Set<FlatNode> lastset) {
2718 HashSet tovisit=new HashSet();
2719 HashSet visited=new HashSet();
2721 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2723 //Label targets of branches
2724 Set<FlatNode> targets=branchanalysis.getTargets();
2725 for(Iterator<FlatNode> it=targets.iterator();it.hasNext();) {
2726 nodetolabel.put(it.next(), new Integer(labelindex++));
2731 /*Assign labels first. A node needs a label if the previous
2732 * node has two exits or this node is a join point. */
2734 while(!tovisit.isEmpty()) {
2735 FlatNode fn=(FlatNode)tovisit.iterator().next();
2740 if(lastset!=null&&lastset.contains(fn)) {
2741 // if last is not null and matches, don't go
2742 // any further for assigning labels
2746 for(int i=0; i<fn.numNext(); i++) {
2747 FlatNode nn=fn.getNext(i);
2750 //1) Edge >1 of node
2751 nodetolabel.put(nn,new Integer(labelindex++));
2753 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2757 nodetolabel.put(nn,new Integer(labelindex++));
2765 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first) {
2766 return assignLabels(first, null);
2769 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2770 HashSet tovisit=new HashSet();
2771 HashSet visited=new HashSet();
2773 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2776 /*Assign labels first. A node needs a label if the previous
2777 * node has two exits or this node is a join point. */
2779 while(!tovisit.isEmpty()) {
2780 FlatNode fn=(FlatNode)tovisit.iterator().next();
2785 if(lastset!=null&&lastset.contains(fn)) {
2786 // if last is not null and matches, don't go
2787 // any further for assigning labels
2791 for(int i=0; i<fn.numNext(); i++) {
2792 FlatNode nn=fn.getNext(i);
2795 //1) Edge >1 of node
2796 nodetolabel.put(nn,new Integer(labelindex++));
2798 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2802 nodetolabel.put(nn,new Integer(labelindex++));
2810 /** Generate text string that corresponds to the TempDescriptor td. */
2811 protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
2812 MethodDescriptor md=fm.getMethod();
2813 TaskDescriptor task=fm.getTask();
2814 TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
2816 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2817 return td.getSafeSymbol();
2820 if (objecttemps.isLocalPtr(td)) {
2821 return localsprefixderef+td.getSafeSymbol();
2824 if (objecttemps.isParamPtr(td)) {
2825 return paramsprefix+"->"+td.getSafeSymbol();
2831 protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) {
2833 // insert pre-node actions from the code plan
2834 if( state.MLP|| state.OOOJAVA ) {
2838 cp = mlpa.getCodePlan( fn );
2840 cp = oooa.getCodePlan(fn);
2845 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
2847 // for each sese and age pair that this parent statement
2848 // must stall on, take that child's stall semaphore, the
2849 // copying of values comes after the statement
2850 Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
2851 while( vstItr.hasNext() ) {
2852 VariableSourceToken vst = vstItr.next();
2854 SESEandAgePair pair = new SESEandAgePair( vst.getSESE(), vst.getAge() );
2856 output.println(" {");
2857 output.println(" SESEcommon* common = (SESEcommon*) "+pair+";");
2858 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
2859 output.println(" pthread_mutex_lock( &(common->lock) );");
2860 output.println(" while( common->doneExecuting == FALSE ) {");
2861 output.println(" pthread_cond_wait( &(common->doneCond), &(common->lock) );");
2862 output.println(" }");
2863 output.println(" pthread_mutex_unlock( &(common->lock) );");
2865 // copy things we might have stalled for
2866 output.println(" "+pair.getSESE().getSESErecordName()+"* child = ("+
2867 pair.getSESE().getSESErecordName()+"*) "+pair+";");
2869 Iterator<TempDescriptor> tdItr = cp.getCopySet( vst ).iterator();
2870 while( tdItr.hasNext() ) {
2871 TempDescriptor td = tdItr.next();
2872 FlatMethod fmContext;
2873 if( currentSESE.getIsCallerSESEplaceholder() ) {
2874 fmContext = currentSESE.getfmEnclosing();
2876 fmContext = currentSESE.getfmBogus();
2878 output.println(" "+generateTemp( fmContext, td, null )+
2879 " = child->"+vst.getAddrVar().getSafeSymbol()+";");
2882 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
2883 output.println(" }");
2886 // for each variable with a dynamic source, stall just for that variable
2887 Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
2888 while( dynItr.hasNext() ) {
2889 TempDescriptor dynVar = dynItr.next();
2891 // only stall if the dynamic source is not yourself, denoted by src==NULL
2892 // otherwise the dynamic write nodes will have the local var up-to-date
2893 output.println(" {");
2894 output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
2895 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
2896 output.println(" SESEcommon* common = (SESEcommon*) "+dynVar+"_srcSESE;");
2897 output.println(" psem_take( &(common->stallSem) );");
2899 FlatMethod fmContext;
2900 if( currentSESE.getIsCallerSESEplaceholder() ) {
2901 fmContext = currentSESE.getfmEnclosing();
2903 fmContext = currentSESE.getfmBogus();
2906 TypeDescriptor type=dynVar.getType();
2908 if( type.isNull() ) {
2910 } else if( type.isClass() || type.isArray() ) {
2911 typeStr = "struct "+type.getSafeSymbol()+"*";
2913 typeStr = type.getSafeSymbol();
2916 output.println(" "+generateTemp( fmContext, dynVar, null )+
2917 " = *(("+typeStr+"*) ("+
2918 dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
2919 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
2920 output.println(" }");
2921 output.println(" }");
2924 // for each assignment of a variable to rhs that has a dynamic source,
2925 // copy the dynamic sources
2926 Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
2927 while( dynAssignItr.hasNext() ) {
2928 Map.Entry me = (Map.Entry) dynAssignItr.next();
2929 TempDescriptor lhs = (TempDescriptor) me.getKey();
2930 TempDescriptor rhs = (TempDescriptor) me.getValue();
2931 output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
2932 output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
2935 // for each lhs that is dynamic from a non-dynamic source, set the
2936 // dynamic source vars to the current SESE
2937 dynItr = cp.getDynAssignCurr().iterator();
2938 while( dynItr.hasNext() ) {
2939 TempDescriptor dynVar = dynItr.next();
2940 assert currentSESE.getDynamicVarSet().contains( dynVar );
2941 output.println(" "+dynVar+"_srcSESE = NULL;");
2945 // handling stall site
2946 if (state.OOOJAVA) {
2947 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(currentSESE);
2949 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
2950 Set<Analysis.OoOJava.WaitingElement> waitingElementSet =
2951 graph.getStallSiteWaitingElementSet(fn, seseLockSet);
2953 if(waitingElementSet.size()>0){
2954 output.println("// stall on parent's stall sites ");
2955 output.println(" {");
2956 output.println(" REntry* rentry;");
2958 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
2959 Analysis.OoOJava.WaitingElement waitingElement = (Analysis.OoOJava.WaitingElement) iterator.next();
2961 if(state.RCR && rcr != null){
2962 Analysis.OoOJava.ConflictGraph conflictGraph = graph;
2963 Hashtable<Taint, Set<Effect>> conflicts;
2964 ReachGraph rg = oooa.getDisjointAnalysis().getReachGraph(currentSESE.getmdEnclosing());
2965 if(rcr.cSideDebug) {
2966 rg.writeGraph("RCR_RG_STALLSITE_DEBUG");
2968 if((conflictGraph != null) &&
2969 (conflicts = graph.getConflictEffectSet(fn)) != null &&
2973 Hashtable<Taint, Set<Effect>> effects=oooa.getDisjointAnalysis().getEffectsAnalysis().get(fn);
2974 rcr.traverseStallSite(fn, waitingElement.getTempDesc(), effects, conflicts, rg);
2978 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
2979 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", seseCaller);");
2981 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller, (void*)&" +generateTemp(fm,waitingElement.getTempDesc(),lb)+ ");");
2983 output.println(" psem_init( &(rentry->parentStallSem) );");
2984 output.println(" rentry->queue=seseCaller->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
2985 output.println(" if(ADDRENTRY(seseCaller->memoryQueueArray["+ waitingElement.getQueueID()
2986 + "],rentry)==NOTREADY){");
2987 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
2988 output.println(" psem_take( &(rentry->parentStallSem) );");
2989 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
2990 output.println(" } ");
2992 if(state.RCR && rcr != null) {
2993 output.println(" "+rcr.getTraverserInvocation(waitingElement.getTempDesc(),
2994 generateTemp(fm, waitingElement.getTempDesc(), null), fn));
2997 output.println(" }");
3001 ParentChildConflictsMap conflictsMap = mlpa.getConflictsResults().get(fn);
3002 if (conflictsMap != null) {
3003 Set<Long> allocSet = conflictsMap.getAllocationSiteIDSetofStallSite();
3004 if (allocSet.size() > 0) {
3005 FlatNode enclosingFlatNode=null;
3006 if( currentSESE.getIsCallerSESEplaceholder() && currentSESE.getParent()==null){
3007 enclosingFlatNode=currentSESE.getfmEnclosing();
3009 enclosingFlatNode=currentSESE;
3011 ConflictGraph graph=mlpa.getConflictGraphResults().get(enclosingFlatNode);
3012 HashSet<SESELock> seseLockSet=mlpa.getConflictGraphLockMap().get(graph);
3013 Set<WaitingElement> waitingElementSet=graph.getStallSiteWaitingElementSet(conflictsMap, seseLockSet);
3015 if(waitingElementSet.size()>0){
3016 output.println("// stall on parent's stall sites ");
3017 output.println(" {");
3018 output.println(" REntry* rentry;");
3020 for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
3021 WaitingElement waitingElement = (WaitingElement) iterator.next();
3023 if( waitingElement.getStatus() >= ConflictNode.COARSE ){
3024 // HERE! a parent might conflict with a child
3025 output.println(" rentry=mlpCreateREntry("+ waitingElement.getStatus()+ ", seseCaller);");
3027 output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller, (void*)&___locals___."+ waitingElement.getDynID() + ");");
3028 // output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ ", seseCaller, ___locals___."+ waitingElement.getDynID() + "->oid);");
3030 output.println(" psem_init( &(rentry->parentStallSem) );");
3031 output.println(" rentry->queue=seseCaller->memoryQueueArray["+ waitingElement.getQueueID()+ "];");
3033 .println(" if(ADDRENTRY(seseCaller->memoryQueueArray["+ waitingElement.getQueueID()
3034 + "],rentry)==NOTREADY){");
3035 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
3036 output.println(" psem_take( &(rentry->parentStallSem) );");
3037 //output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
3038 output.println(" } ");
3040 output.println(" }");
3049 case FKind.FlatAtomicEnterNode:
3050 generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output);
3053 case FKind.FlatAtomicExitNode:
3054 generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output);
3057 case FKind.FlatInstanceOfNode:
3058 generateFlatInstanceOfNode(fm, lb, (FlatInstanceOfNode)fn, output);
3061 case FKind.FlatSESEEnterNode:
3062 generateFlatSESEEnterNode(fm, lb, (FlatSESEEnterNode)fn, output);
3065 case FKind.FlatSESEExitNode:
3066 generateFlatSESEExitNode(fm, lb, (FlatSESEExitNode)fn, output);
3069 case FKind.FlatWriteDynamicVarNode:
3070 generateFlatWriteDynamicVarNode(fm, lb, (FlatWriteDynamicVarNode)fn, output);
3073 case FKind.FlatGlobalConvNode:
3074 generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output);
3077 case FKind.FlatTagDeclaration:
3078 generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output);
3081 case FKind.FlatCall:
3082 generateFlatCall(fm, lb, (FlatCall) fn,output);
3085 case FKind.FlatFieldNode:
3086 generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output);
3089 case FKind.FlatElementNode:
3090 generateFlatElementNode(fm, lb, (FlatElementNode) fn,output);
3093 case FKind.FlatSetElementNode:
3094 generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output);
3097 case FKind.FlatSetFieldNode:
3098 generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output);
3102 generateFlatNew(fm, lb, (FlatNew) fn,output);
3105 case FKind.FlatOpNode:
3106 generateFlatOpNode(fm, lb, (FlatOpNode) fn,output);
3109 case FKind.FlatCastNode:
3110 generateFlatCastNode(fm, lb, (FlatCastNode) fn,output);
3113 case FKind.FlatLiteralNode:
3114 generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output);
3117 case FKind.FlatReturnNode:
3118 generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output);
3122 output.println("/* nop */");
3125 case FKind.FlatExit:
3126 output.println("/* exit */");
3129 case FKind.FlatBackEdge:
3130 if (state.SINGLETM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3131 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3133 if(state.DSM&&state.SANDBOX&&(locality.getAtomic(lb).get(fn).intValue()>0)) {
3134 output.println("if (unlikely((--transaction_check_counter)<=0)) checkObjects();");
3136 if (((state.MLP|| state.OOOJAVA||state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)
3137 || (this.state.MULTICOREGC)) {
3138 if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) {
3139 output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
3140 } else if(this.state.MULTICOREGC) {
3141 output.println("if (gcflag) gc("+localsprefixaddr+");");
3143 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3146 output.println("/* nop */");
3149 case FKind.FlatCheckNode:
3150 generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output);
3153 case FKind.FlatFlagActionNode:
3154 generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output);
3157 case FKind.FlatPrefetchNode:
3158 generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output);
3161 case FKind.FlatOffsetNode:
3162 generateFlatOffsetNode(fm, lb, (FlatOffsetNode)fn, output);
3169 // insert post-node actions from the code-plan
3172 CodePlan cp = mlpa.getCodePlan( fn );
3180 public void generateFlatOffsetNode(FlatMethod fm, LocalityBinding lb, FlatOffsetNode fofn, PrintWriter output) {
3181 output.println("/* FlatOffsetNode */");
3182 FieldDescriptor fd=fofn.getField();
3183 output.println(generateTemp(fm, fofn.getDst(),lb)+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+ fd.getSafeSymbol()+");");
3184 output.println("/* offset */");
3187 public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) {
3188 if (state.PREFETCH) {
3189 Vector oids = new Vector();
3190 Vector fieldoffset = new Vector();
3191 Vector endoffset = new Vector();
3192 int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
3193 for(Iterator it = fpn.hspp.iterator(); it.hasNext();) {
3194 PrefetchPair pp = (PrefetchPair) it.next();
3195 Integer statusbase = locality.getNodePreTempInfo(lb,fpn).get(pp.base);
3196 /* Find prefetches that can generate oid */
3197 if(statusbase == LocalityAnalysis.GLOBAL) {
3198 generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false);
3200 } else if (statusbase == LocalityAnalysis.LOCAL) {
3201 generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
3208 System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
3209 output.println("{");
3210 output.println("/* prefetch */");
3211 output.println("/* prefetchid_" + fpn.siteid + " */");
3212 output.println("void * prefptr;");
3213 output.println("int tmpindex;");
3215 output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {");
3216 /*Create C code for oid array */
3217 output.print(" unsigned int oidarray_[] = {");
3218 boolean needcomma=false;
3219 for (Iterator it = oids.iterator(); it.hasNext();) {
3222 output.print(it.next());
3225 output.println("};");
3227 /*Create C code for endoffset values */
3228 output.print(" unsigned short endoffsetarry_[] = {");
3230 for (Iterator it = endoffset.iterator(); it.hasNext();) {
3233 output.print(it.next());
3236 output.println("};");
3238 /*Create C code for Field Offset Values */
3239 output.print(" short fieldarry_[] = {");
3241 for (Iterator it = fieldoffset.iterator(); it.hasNext();) {
3244 output.print(it.next());
3247 output.println("};");
3248 /* make the prefetch call to Runtime */
3249 output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {");
3250 output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;");
3251 output.println(" }");
3252 output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);");
3253 output.println(" } else {");
3254 output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;");
3255 output.println(" }");
3256 output.println("}");
3260 public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) {
3261 short offsetcount = 0;
3265 } else if (localbase) {
3266 for(; breakindex<pp.desc.size(); breakindex++) {
3267 Descriptor desc=pp.getDescAt(breakindex);
3268 if (desc instanceof FieldDescriptor) {
3269 FieldDescriptor fd=(FieldDescriptor)desc;
3270 if (fd.isGlobal()) {
3278 if (breakindex>pp.desc.size()) //all local
3281 TypeDescriptor lasttype=pp.base.getType();
3282 String basestr=generateTemp(fm, pp.base, lb);
3284 boolean maybenull=fm.getMethod().isStatic()||
3285 !pp.base.equals(fm.getParameter(0));
3287 for(int i=0; i<breakindex; i++) {
3288 String indexcheck="";
3290 Descriptor desc=pp.getDescAt(i);
3291 if (desc instanceof FieldDescriptor) {
3292 FieldDescriptor fd=(FieldDescriptor)desc;
3294 if (!teststr.equals(""))
3296 teststr+="((prefptr="+basestr+")!=NULL)";
3297 basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
3299 basestr=basestr+"->"+fd.getSafeSymbol();
3302 lasttype=fd.getType();
3304 IndexDescriptor id=(IndexDescriptor)desc;
3305 indexcheck="((tmpindex=";
3306 for(int j=0; j<id.tddesc.size(); j++) {
3307 indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
3309 indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
3311 if (!teststr.equals(""))
3313 teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck;
3314 basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]";
3316 lasttype=lasttype.dereference();
3321 if (teststr.equals("")) {
3322 oid="((unsigned int)"+basestr+")";
3324 oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))";
3328 for(int i = breakindex; i < pp.desc.size(); i++) {
3329 String newfieldoffset;
3330 Object desc = pp.getDescAt(i);
3331 if(desc instanceof FieldDescriptor) {
3332 FieldDescriptor fd=(FieldDescriptor)desc;
3333 newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
3334 lasttype=fd.getType();
3336 newfieldoffset = "";
3337 IndexDescriptor id=(IndexDescriptor)desc;
3338 for(int j = 0; j < id.tddesc.size(); j++) {
3339 newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+";
3341 newfieldoffset += id.offset.toString();
3342 lasttype=lasttype.dereference();
3344 fieldoffset.add(newfieldoffset);
3347 int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0;
3348 base+=pp.desc.size()-breakindex;
3349 endoffset.add(new Short((short)base));
3354 public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) {
3355 if (lb!=fgcn.getLocality())
3357 /* Have to generate flat globalconv */
3358 if (fgcn.getMakePtr()) {
3360 //DEBUG: output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+",\" "+fm+":"+fgcn+"\");");
3361 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3363 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fgcn)||state.READSET&&dc.getNeedWriteTrans(lb, fgcn)) {
3364 //need to do translation
3365 output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+", (void *)("+localsprefixaddr+"));");
3366 } else if (state.READSET&&dc.getNeedTrans(lb, fgcn)) {
3367 if (state.HYBRID&&delaycomp.getConv(lb).contains(fgcn)) {
3368 output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3370 output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc(),lb)+", "+generateTemp(fm, fgcn.getSrc(),lb)+");");
3374 /* Need to convert to OID */
3375 if ((dc==null)||dc.getNeedSrcTrans(lb,fgcn)) {
3376 if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(lb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
3377 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");");
3379 output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=NULL;");
3385 public void generateFlatInstanceOfNode(FlatMethod fm, LocalityBinding lb, FlatInstanceOfNode fion, PrintWriter output) {
3387 if (fion.getType().isArray()) {
3388 type=state.getArrayNumber(fion.getType())+state.numClasses();
3390 type=fion.getType().getClassDesc().getId();
3393 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
3394 output.println(generateTemp(fm, fion.getDst(), lb)+"=1;");
3396 output.println(generateTemp(fm, fion.getDst(), lb)+"=instanceof("+generateTemp(fm,fion.getSrc(),lb)+","+type+");");
3399 int sandboxcounter=0;
3400 public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) {
3401 /* Check to see if we need to generate code for this atomic */
3402 if (locality==null) {
3403 if (GENERATEPRECISEGC) {
3404 output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
3405 output.println("stopforgc((struct garbagelist *) &___locals___);");
3406 output.println("pthread_mutex_lock(&atomiclock);");
3407 output.println("restartaftergc();");
3408 output.println("}");
3410 output.println("pthread_mutex_lock(&atomiclock);");
3415 if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0)
3419 if (state.SANDBOX) {
3420 outsandbox.println("int atomiccounter"+sandboxcounter+"=LOW_CHECK_FREQUENCY;");
3421 output.println("counter_reset_pointer=&atomiccounter"+sandboxcounter+";");
3424 if (state.DELAYCOMP&&delaycomp.needsFission(lb, faen)) {
3425 AtomicRecord ar=atomicmethodmap.get(faen);
3427 for(Iterator<TempDescriptor> tmpit=ar.livein.iterator();tmpit.hasNext();) {
3428 TempDescriptor tmp=tmpit.next();
3429 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3432 //copy outs that depend on path
3433 for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator();tmpit.hasNext();) {
3434 TempDescriptor tmp=tmpit.next();
3435 if (!ar.livein.contains(tmp))
3436 output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
3440 /* Backup the temps. */
3441 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3442 TempDescriptor tmp=tmpit.next();
3443 output.println(generateTemp(fm, backuptable.get(lb).get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";");
3446 output.println("goto transstart"+faen.getIdentifier()+";");
3448 /******* Print code to retry aborted transaction *******/
3449 output.println("transretry"+faen.getIdentifier()+":");
3452 for(Iterator<TempDescriptor> tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) {
3453 TempDescriptor tmp=tmpit.next();
3454 output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(lb).get(tmp),lb)+";");
3458 /********* Need to revert local object store ********/
3459 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3461 output.println("while ("+revertptr+") {");
3462 output.println("struct ___Object___ * tmpptr;");
3463 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3464 output.println("REVERT_OBJ("+revertptr+");");
3465 output.println(revertptr+"=tmpptr;");
3466 output.println("}");
3468 /******* Tell the runtime to start the transaction *******/
3470 output.println("transstart"+faen.getIdentifier()+":");
3471 if (state.SANDBOX) {
3472 output.println("transaction_check_counter=*counter_reset_pointer;");
3475 output.println("transStart();");
3477 if (state.ABORTREADERS||state.SANDBOX) {
3479 output.println("abortenabled=1;");
3480 output.println("if (_setjmp(aborttrans)) {");
3481 output.println(" goto transretry"+faen.getIdentifier()+"; }");
3485 public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) {
3486 /* Check to see if we need to generate code for this atomic */
3487 if (locality==null) {
3488 output.println("pthread_mutex_unlock(&atomiclock);");
3491 if (locality.getAtomic(lb).get(faen).intValue()>0)
3493 //store the revert list before we lose the transaction object
3496 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
3497 output.println(revertptr+"=revertlist;");
3498 output.println("if (transCommit()) {");
3499 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3500 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3501 output.println("} else {");
3502 /* Need to commit local object store */
3503 output.println("while ("+revertptr+") {");
3504 output.println("struct ___Object___ * tmpptr;");
3505 output.println("tmpptr="+revertptr+"->"+nextobjstr+";");
3506 output.println("COMMIT_OBJ("+revertptr+");");
3507 output.println(revertptr+"=tmpptr;");
3508 output.println("}");
3509 output.println("}");
3513 if (!state.DELAYCOMP) {
3515 output.println("if (transCommit()) {");
3516 /* Transaction aborts if it returns true */
3517 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3518 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3519 output.println("}");
3521 if (delaycomp.optimizeTrans(lb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
3522 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3523 output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
3525 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3526 TempDescriptor tmp=tmpit.next();
3527 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3529 } else if (delaycomp.needsFission(lb, faen.getAtomicEnter())) {
3530 AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
3532 output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
3533 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3534 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3535 output.println("}");
3537 output.println("else {");
3538 for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator();tmpit.hasNext();) {
3539 TempDescriptor tmp=tmpit.next();
3540 output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
3542 output.println("}");
3544 output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
3545 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
3546 output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
3547 output.println("}");
3552 public void generateFlatSESEEnterNode( FlatMethod fm,
3554 FlatSESEEnterNode fsen,
3557 // if MLP flag is off, okay that SESE nodes are in IR graph,
3558 // just skip over them and code generates exactly the same
3559 if( !(state.MLP || state.OOOJAVA) ) {
3562 // there may be an SESE in an unreachable method, skip over
3563 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
3564 (state.OOOJAVA && !oooa.getAllSESEs().contains(fsen))
3569 // also, if we have encountered a placeholder, just skip it
3570 if( fsen.getIsCallerSESEplaceholder() ) {
3574 output.println(" {");
3577 output.println("CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_BEGIN );");
3579 // set up the parent
3580 if( (state.MLP && fsen == mlpa.getMainSESE()) ||
3581 (state.OOOJAVA && fsen == oooa.getMainSESE())
3583 output.println(" SESEcommon* parentCommon = NULL;");
3585 if( fsen.getParent() == null ) {
3586 System.out.println( "in "+fm+", "+fsen+" has null parent" );
3588 assert fsen.getParent() != null;
3589 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3590 output.println(" SESEcommon* parentCommon = &("+paramsprefix+"->common);");
3592 //output.println(" SESEcommon* parentCommon = (SESEcommon*) peekItem( seseCallStack );");
3593 output.println(" SESEcommon* parentCommon = seseCaller;");
3597 // before doing anything, lock your own record and increment the running children
3598 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3599 (state.OOOJAVA && fsen != oooa.getMainSESE())
3601 output.println(" atomic_inc(&parentCommon->numRunningChildren);");
3604 // allocate the space for this record
3606 fsen.getSESErecordName()+"* seseToIssue = ("+
3607 fsen.getSESErecordName()+"*) mlpAllocSESErecord( sizeof( "+
3608 fsen.getSESErecordName()+" ) );");
3610 // set up the SESE in-set and out-set objects, which look
3611 // like a garbage list
3612 output.println(" struct garbagelist * gl= (struct garbagelist *)&(((SESEcommon*)(seseToIssue))[1]);");
3613 output.println(" gl->size="+calculateSizeOfSESEParamList(fsen)+";");
3614 output.println(" gl->next = NULL;");
3616 // there are pointers to SESE records the newly-issued SESE
3617 // will use to get values it depends on them for--how many
3618 // are there, and what is the offset from the total SESE
3619 // record to the first dependent record pointer?
3620 output.println(" seseToIssue->common.numDependentSESErecords="+
3621 fsen.getNumDepRecs()+";");
3623 // we only need this (and it will only compile) when the number of dependent
3624 // SESE records is non-zero
3625 if( fsen.getFirstDepRecField() != null ) {
3626 output.println(" seseToIssue->common.offsetToDepSESErecords=(INTPTR)sizeof("+
3627 fsen.getSESErecordName()+") - (INTPTR)&((("+
3628 fsen.getSESErecordName()+"*)0)->"+fsen.getFirstDepRecField()+");"
3633 // and keep the thread-local sese stack up to date (jjenista--this still relevant??)
3634 //output.println(" addNewItem( seseCallStack, (void*) seseToIssue);");
3636 // fill in common data
3637 output.println(" int localCount=0;");
3638 output.println(" seseToIssue->common.classID = "+fsen.getIdentifier()+";");
3639 output.println(" psem_init( &(seseToIssue->common.stallSem) );");
3641 output.println(" seseToIssue->common.forwardList = createQueue();");
3642 output.println(" seseToIssue->common.unresolvedDependencies = 10000;");
3643 output.println(" pthread_cond_init( &(seseToIssue->common.doneCond), NULL );");
3644 output.println(" seseToIssue->common.doneExecuting = FALSE;");
3645 output.println(" pthread_cond_init( &(seseToIssue->common.runningChildrenCond), NULL );");
3646 output.println(" seseToIssue->common.numRunningChildren = 0;");
3647 output.println(" seseToIssue->common.parent = parentCommon;");
3649 // all READY in-vars should be copied now and be done with it
3650 Iterator<TempDescriptor> tempItr = fsen.getReadyInVarSet().iterator();
3651 while( tempItr.hasNext() ) {
3652 TempDescriptor temp = tempItr.next();
3654 // when we are issuing the main SESE or an SESE with placeholder
3655 // caller SESE as parent, generate temp child child's eclosing method,
3656 // otherwise use the parent's enclosing method as the context
3657 boolean useParentContext = false;
3659 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3660 (state.OOOJAVA && fsen != oooa.getMainSESE())
3662 assert fsen.getParent() != null;
3663 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3664 useParentContext = true;
3668 if( useParentContext ) {
3669 output.println(" seseToIssue->"+temp+" = "+
3670 generateTemp( fsen.getParent().getfmBogus(), temp, null )+";");
3672 output.println(" seseToIssue->"+temp+" = "+
3673 generateTemp( fsen.getfmEnclosing(), temp, null )+";");
3677 // before potentially adding this SESE to other forwarding lists,
3678 // create it's lock and take it immediately
3679 output.println(" pthread_mutex_init( &(seseToIssue->common.lock), NULL );");
3680 // output.println(" pthread_mutex_lock( &(seseToIssue->common.lock) );");
3682 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3683 (state.OOOJAVA && fsen != oooa.getMainSESE())
3685 // count up outstanding dependencies, static first, then dynamic
3686 Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
3687 while( staticSrcsItr.hasNext() ) {
3688 SESEandAgePair srcPair = staticSrcsItr.next();
3689 output.println(" {");
3690 output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
3692 if(GENERATEPRECISEGC){
3693 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3695 output.println(" pthread_mutex_lock( &(src->lock) );");
3696 if(GENERATEPRECISEGC){
3697 output.println(" restartaftergc();");
3699 output.println(" if( !isEmpty( src->forwardList ) &&");
3700 output.println(" seseToIssue == peekItem( src->forwardList ) ) {");
3701 output.println(" printf( \"This shouldnt already be here\\n\");");
3702 output.println(" exit( -1 );");
3703 output.println(" }");
3704 output.println(" if( !src->doneExecuting ) {");
3705 output.println(" addNewItem( src->forwardList, seseToIssue );");
3706 // output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3707 output.println(" ++(localCount);");
3708 output.println(" }");
3709 output.println(" pthread_mutex_unlock( &(src->lock) );");
3710 output.println(" }");
3712 // whether or not it is an outstanding dependency, make sure
3713 // to pass the static name to the child's record
3714 output.println(" seseToIssue->"+srcPair+" = "+srcPair+";");
3717 // dynamic sources might already be accounted for in the static list,
3718 // so only add them to forwarding lists if they're not already there
3719 Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
3720 while( dynVarsItr.hasNext() ) {
3721 TempDescriptor dynInVar = dynVarsItr.next();
3722 output.println(" {");
3723 output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
3725 // the dynamic source is NULL if it comes from your own space--you can't pass
3726 // the address off to the new child, because you're not done executing and
3727 // might change the variable, so copy it right now
3728 output.println(" if( src != NULL ) {");
3730 if(GENERATEPRECISEGC){
3731 output.println(" stopforgc((struct garbagelist *)&___locals___);");
3733 output.println(" pthread_mutex_lock( &(src->lock) );");
3734 if(GENERATEPRECISEGC){
3735 output.println(" restartaftergc();");
3737 output.println(" if( isEmpty( src->forwardList ) ||");
3738 output.println(" seseToIssue != peekItem( src->forwardList ) ) {");
3739 output.println(" if( !src->doneExecuting ) {");
3740 output.println(" addNewItem( src->forwardList, seseToIssue );");
3741 // output.println(" ++(seseToIssue->common.unresolvedDependencies);");
3742 output.println(" ++(localCount);");
3743 output.println(" }");
3744 output.println(" }");
3745 output.println(" pthread_mutex_unlock( &(src->lock) );");
3746 output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
3747 output.println(" } else {");
3749 boolean useParentContext = false;
3750 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
3751 (state.OOOJAVA && fsen != oooa.getMainSESE())
3753 assert fsen.getParent() != null;
3754 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3755 useParentContext = true;
3758 if( useParentContext ) {
3759 output.println(" seseToIssue->"+dynInVar+" = "+
3760 generateTemp( fsen.getParent().getfmBogus(), dynInVar, null )+";");
3762 output.println(" seseToIssue->"+dynInVar+" = "+
3763 generateTemp( fsen.getfmEnclosing(), dynInVar, null )+";");
3766 output.println(" }");
3767 output.println(" }");
3769 // even if the value is already copied, make sure your NULL source
3770 // gets passed so child knows it already has the dynamic value
3771 output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
3774 // maintain pointers for finding dynamic SESE
3775 // instances from static names
3776 SESEandAgePair pair = new SESEandAgePair( fsen, 0 );
3777 if( fsen.getParent() != null &&
3778 //!fsen.getParent().getIsCallerSESEplaceholder() &&
3779 fsen.getParent().getNeededStaticNames().contains( pair )
3782 for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
3783 SESEandAgePair pair1 = new SESEandAgePair( fsen, i );
3784 SESEandAgePair pair2 = new SESEandAgePair( fsen, i-1 );
3785 output.println(" "+pair1+" = "+pair2+";");
3787 output.println(" "+pair+" = seseToIssue;");
3791 // count up memory conflict dependencies,
3795 FlatSESEEnterNode parent = fsen.getParent();
3796 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(parent);
3797 if (graph != null && graph.hasConflictEdge()) {
3798 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
3800 output.println(" //add memory queue element");
3801 Analysis.OoOJava.SESEWaitingQueue seseWaitingQueue=
3802 graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet);
3803 if(seseWaitingQueue.getWaitingElementSize()>0){
3804 output.println(" {");
3805 output.println(" REntry* rentry=NULL;");
3806 output.println(" INTPTR* pointer=NULL;");
3807 output.println(" seseToIssue->common.rentryIdx=0;");
3809 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
3810 for (Iterator iterator = queueIDSet.iterator(); iterator
3812 Integer key = (Integer) iterator.next();
3813 int queueID=key.intValue();
3814 Set<Analysis.OoOJava.WaitingElement> waitingQueueSet =
3815 seseWaitingQueue.getWaitingElementSet(queueID);
3816 int enqueueType=seseWaitingQueue.getType(queueID);
3817 if(enqueueType==SESEWaitingQueue.EXCEPTION){
3818 output.println(" INITIALIZEBUF(parentCommon->memoryQueueArray["
3821 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2
3823 Analysis.OoOJava.WaitingElement waitingElement
3824 = (Analysis.OoOJava.WaitingElement) iterator2.next();
3825 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
3826 output.println(" rentry=mlpCreateREntry("
3827 + waitingElement.getStatus()
3828 + ", seseToIssue);");
3830 TempDescriptor td = waitingElement
3832 // decide whether waiting element is dynamic or static
3833 if (fsen.getDynamicInVarSet().contains(td)) {
3834 // dynamic in-var case
3835 output.println(" pointer=seseToIssue->"
3836 + waitingElement.getDynID()
3837 + "_srcSESE+seseToIssue->"
3838 + waitingElement.getDynID()
3841 .println(" rentry=mlpCreateFineREntry("
3844 + ", seseToIssue, pointer );");
3845 } else if (fsen.getStaticInVarSet()
3847 // static in-var case
3848 VariableSourceToken vst = fsen
3849 .getStaticInVarSrc(td);
3852 String srcId = "SESE_"
3854 .getPrettyIdentifier()
3855 + vst.getSESE().getIdentifier()
3856 + "_" + vst.getAge();
3858 .println(" pointer=(void*)&seseToIssue->"
3865 .println(" rentry=mlpCreateFineREntry("
3868 + ", seseToIssue, pointer );");
3873 .println(" rentry=mlpCreateFineREntry("
3876 + ", seseToIssue, (void*)&seseToIssue->"
3877 + waitingElement.getDynID()
3882 .println(" rentry->queue=parentCommon->memoryQueueArray["
3883 + waitingElement.getQueueID()
3886 if(enqueueType==SESEWaitingQueue.NORMAL){
3888 .println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
3890 .println(" if(ADDRENTRY(parentCommon->memoryQueueArray["
3891 + waitingElement.getQueueID()
3892 + "],rentry)==NOTREADY){");
3893 output.println(" ++(localCount);");
3894 output.println(" }");
3896 // Trying to execute the dynamic coarse grain conflict strategy...
3897 if(state.RCR && rcr != null) {
3898 boolean useParentContext = false;
3900 if( (state.MLP &&fsen != mlpa.getMainSESE()) ||
3901 (state.OOOJAVA &&fsen != oooa.getMainSESE())) {
3902 assert fsen.getParent() != null;
3903 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
3904 useParentContext = true;
3908 for (TempDescriptor invar : fsen.getInVarsForDynamicCoarseConflictResolution()) {
3910 if( useParentContext ) {
3911 varString = generateTemp( fsen.getParent().getfmBogus(), invar, null );
3913 varString = generateTemp( fsen.getfmEnclosing(), invar, null );
3915 output.println(" "+rcr.getTraverserInvocation(invar, varString, fsen));
3920 .println(" ADDRENTRYTOBUF(parentCommon->memoryQueueArray["
3921 + waitingElement.getQueueID()
3925 if(enqueueType!=SESEWaitingQueue.NORMAL){
3926 output.println(" localCount+=RESOLVEBUF(parentCommon->memoryQueueArray["
3927 + queueID+ "],&seseToIssue->common);");
3930 output.println(" }");
3936 ConflictGraph graph = null;
3937 FlatSESEEnterNode parent = fsen.getParent();
3938 if (parent != null) {
3939 if (parent.isCallerSESEplaceholder) {
3940 graph = mlpa.getConflictGraphResults().get(parent.getfmEnclosing());
3942 graph = mlpa.getConflictGraphResults().get(parent);
3945 if (graph != null && graph.hasConflictEdge()) {
3946 HashSet<SESELock> seseLockSet = mlpa.getConflictGraphLockMap()
3949 output.println(" //add memory queue element");
3950 SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(fsen.getIdentifier(),
3952 if(seseWaitingQueue.getWaitingElementSize()>0){
3953 output.println(" {");
3954 output.println(" REntry* rentry=NULL;");
3955 output.println(" INTPTR* pointer=NULL;");
3956 output.println(" seseToIssue->common.rentryIdx=0;");
3958 Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
3959 for (Iterator iterator = queueIDSet.iterator(); iterator
3961 Integer key = (Integer) iterator.next();
3962 int queueID=key.intValue();
3963 Set<WaitingElement> waitingQueueSet = seseWaitingQueue.getWaitingElementSet(queueID);
3964 int enqueueType=seseWaitingQueue.getType(queueID);
3965 if(enqueueType==SESEWaitingQueue.EXCEPTION){
3966 output.println(" INITIALIZEBUF(parentCommon->memoryQueueArray["
3969 for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2
3971 WaitingElement waitingElement = (WaitingElement) iterator2
3973 if (waitingElement.getStatus() >= ConflictNode.COARSE) {
3974 output.println(" rentry=mlpCreateREntry("
3975 + waitingElement.getStatus()
3976 + ", seseToIssue);");
3978 TempDescriptor td = waitingElement
3980 // decide whether waiting element is dynamic or
3982 if (fsen.getDynamicInVarSet().contains(td)) {
3983 // dynamic in-var case
3984 output.println(" pointer=seseToIssue->"
3985 + waitingElement.getDynID()
3986 + "_srcSESE+seseToIssue->"
3987 + waitingElement.getDynID()
3990 .println(" rentry=mlpCreateFineREntry("
3993 + ", seseToIssue, pointer );");
3994 } else if (fsen.getStaticInVarSet()
3996 // static in-var case
3997 VariableSourceToken vst = fsen
3998 .getStaticInVarSrc(td);
4001 String srcId = "SESE_"
4003 .getPrettyIdentifier()
4004 + vst.getSESE().getIdentifier()
4005 + "_" + vst.getAge();
4007 .println(" pointer=(void*)&seseToIssue->"
4014 .println(" rentry=mlpCreateFineREntry("
4017 + ", seseToIssue, pointer );");
4022 .println(" rentry=mlpCreateFineREntry("
4025 + ", seseToIssue, (void*)&seseToIssue->"
4026 + waitingElement.getDynID()
4031 .println(" rentry->queue=parentCommon->memoryQueueArray["
4032 + waitingElement.getQueueID()
4035 if(enqueueType==SESEWaitingQueue.NORMAL){
4037 .println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
4039 .println(" if(ADDRENTRY(parentCommon->memoryQueueArray["
4040 + waitingElement.getQueueID()
4041 + "],rentry)==NOTREADY){");
4042 output.println(" ++(localCount);");
4043 output.println(" } ");
4046 .println(" ADDRENTRYTOBUF(parentCommon->memoryQueueArray["
4047 + waitingElement.getQueueID()
4051 if(enqueueType!=SESEWaitingQueue.NORMAL){
4052 output.println(" localCount+=RESOLVEBUF(parentCommon->memoryQueueArray["
4053 + queueID+ "],&seseToIssue->common);");
4056 output.println(" }");
4064 // release this SESE for siblings to update its dependencies or,
4065 // eventually, for it to mark itself finished
4066 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
4068 // if there were no outstanding dependencies, issue here
4069 output.println(" if( atomic_sub_and_test(10000-localCount,&(seseToIssue->common.unresolvedDependencies) ) ) {");
4070 output.println(" workScheduleSubmit( (void*)seseToIssue );");
4071 output.println(" }");
4073 output.println(" if( seseToIssue->common.unresolvedDependencies == 0 ) {");
4074 output.println(" workScheduleSubmit( (void*)seseToIssue );");
4075 output.println(" }");
4077 // release this SESE for siblings to update its dependencies or,
4078 // eventually, for it to mark itself finished
4079 // output.println(" pthread_mutex_unlock( &(seseToIssue->common.lock) );");
4082 output.println("CP_LOGEVENT( CP_EVENTID_TASKDISPATCH, CP_EVENTTYPE_END );");
4084 output.println(" }");
4088 public void generateFlatSESEExitNode( FlatMethod fm,
4090 FlatSESEExitNode fsexn,
4094 // if MLP flag is off, okay that SESE nodes are in IR graph,
4095 // just skip over them and code generates exactly the same
4096 if( ! (state.MLP || state.OOOJAVA) ) {
4100 // get the enter node for this exit that has meta data embedded
4101 FlatSESEEnterNode fsen = fsexn.getFlatEnter();
4103 // there may be an SESE in an unreachable method, skip over
4104 if( (state.MLP && !mlpa.getAllSESEs().contains( fsen )) ||
4105 (state.OOOJAVA && !oooa.getAllSESEs().contains( fsen ))
4110 // also, if we have encountered a placeholder, just jump it
4111 if( fsen.getIsCallerSESEplaceholder() ) {
4115 output.println(" CP_LOGEVENT( CP_EVENTID_TASKEXECUTE, CP_EVENTTYPE_END );");
4117 output.println(" /* SESE exiting */");
4118 output.println(" CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_BEGIN );");
4120 String com = paramsprefix+"->common";
4122 // this SESE cannot be done until all of its children are done
4123 // so grab your own lock with the condition variable for watching
4124 // that the number of your running children is greater than zero
4125 if (GENERATEPRECISEGC){
4126 output.println(" stopforgc((struct garbagelist *)&___locals___);");
4128 output.println(" pthread_mutex_lock( &("+com+".lock) );");
4129 if (GENERATEPRECISEGC){
4130 output.println(" restartaftergc();");
4132 output.println(" while( "+com+".numRunningChildren > 0 ) {");
4133 if (GENERATEPRECISEGC){
4134 // output.println(" stopforgc((struct garbagelist *)&(((SESEcommon*)(___params___))[1]));");
4135 output.println(" stopforgc((struct garbagelist *)&___locals___);");
4137 output.println(" pthread_cond_wait( &("+com+".runningChildrenCond), &("+com+".lock) );");
4138 if (GENERATEPRECISEGC){
4139 output.println(" restartaftergc();");
4141 output.println(" }");
4144 // copy out-set from local temps into the sese record
4145 Iterator<TempDescriptor> itr = fsen.getOutVarSet().iterator();
4146 while( itr.hasNext() ) {
4147 TempDescriptor temp = itr.next();
4149 // only have to do this for primitives non-arrays
4151 temp.getType().isPrimitive() && !temp.getType().isArray()
4157 // have to determine the context enclosing this sese
4158 boolean useParentContext = false;
4160 if( (state.MLP &&fsen != mlpa.getMainSESE()) ||
4161 (state.OOOJAVA &&fsen != oooa.getMainSESE())
4163 assert fsen.getParent() != null;
4164 if( !fsen.getParent().getIsCallerSESEplaceholder() ) {
4165 useParentContext = true;
4170 if( useParentContext ) {
4171 from = generateTemp( fsen.getParent().getfmBogus(), temp, null );
4173 from = generateTemp( fsen.getfmEnclosing(), temp, null );
4176 output.println(" "+paramsprefix+
4177 "->"+temp.getSafeSymbol()+
4181 // mark yourself done, your SESE data is now read-only
4182 output.println(" "+com+".doneExecuting = TRUE;");
4183 output.println(" pthread_cond_signal( &("+com+".doneCond) );");
4184 output.println(" pthread_mutex_unlock( &("+com+".lock) );");
4186 // decrement dependency count for all SESE's on your forwarding list
4187 output.println(" while( !isEmpty( "+com+".forwardList ) ) {");
4188 output.println(" SESEcommon* consumer = (SESEcommon*) getItem( "+com+".forwardList );");
4191 output.println(" if(consumer->rentryIdx>0){");
4192 output.println(" // resolved null pointer");
4193 output.println(" int idx;");
4194 output.println(" for(idx=0;idx<consumer->rentryIdx;idx++){");
4195 output.println(" resolvePointer(consumer->rentryArray[idx]);");
4196 output.println(" }");
4197 output.println(" }");
4200 // output.println(" pthread_mutex_lock( &(consumer->lock) );");
4201 // output.println(" --(consumer->unresolvedDependencies);");
4202 // output.println(" if( consumer->unresolvedDependencies == 0 ) {");
4203 output.println(" if( atomic_sub_and_test(1, &(consumer->unresolvedDependencies)) ){");
4204 output.println(" workScheduleSubmit( (void*)consumer );");
4205 output.println(" }");
4206 // output.println(" pthread_mutex_unlock( &(consumer->lock) );");
4207 output.println(" }");
4211 // clean up its lock element from waiting queue, and decrement dependency count for next SESE block
4212 if( (state.MLP && fsen != mlpa.getMainSESE()) ||
4213 (state.OOOJAVA && fsen != oooa.getMainSESE())
4217 output.println(" /* check memory dependency*/");
4218 output.println(" {");
4219 output.println(" int idx;");
4220 output.println(" for(idx=0;idx<___params___->common.rentryIdx;idx++){");
4221 output.println(" REntry* re=___params___->common.rentryArray[idx];");
4222 output.println(" RETIRERENTRY(re->queue,re);");
4223 output.println(" }");
4224 output.println(" }");
4228 // if parent is stalling on you, let them know you're done
4229 if( (state.MLP && fsexn.getFlatEnter() != mlpa.getMainSESE()) ||
4230 (state.OOOJAVA && fsexn.getFlatEnter() != oooa.getMainSESE())
4232 output.println(" psem_give( &("+paramsprefix+"->common.stallSem) );");
4235 // last of all, decrement your parent's number of running children
4236 output.println(" if( "+paramsprefix+"->common.parent != NULL ) {");
4237 output.println(" if (atomic_sub_and_test(1, &"+paramsprefix+"->common.parent->numRunningChildren)) {");
4238 if (GENERATEPRECISEGC){
4239 output.println(" stopforgc((struct garbagelist *)&___locals___);");
4241 output.println(" pthread_mutex_lock( &("+paramsprefix+"->common.parent->lock) );");
4242 if (GENERATEPRECISEGC){
4243 output.println(" restartaftergc();");
4245 output.println(" pthread_cond_signal( &("+paramsprefix+"->common.parent->runningChildrenCond) );");
4246 output.println(" pthread_mutex_unlock( &("+paramsprefix+"->common.parent->lock) );");
4247 output.println(" }");
4248 output.println(" }");
4250 // this is a thread-only variable that can be handled when critical sese-to-sese
4251 // data has been taken care of--set sese pointer to remember self over method
4252 // calls to a non-zero, invalid address
4253 output.println(" seseCaller = (SESEcommon*) 0x1;");
4256 output.println(" CP_LOGEVENT( CP_EVENTID_TASKRETIRE, CP_EVENTTYPE_END );");
4259 public void generateFlatWriteDynamicVarNode( FlatMethod fm,
4261 FlatWriteDynamicVarNode fwdvn,
4264 if( !(state.MLP || state.OOOJAVA) ) {
4265 // should node should not be in an IR graph if the
4266 // MLP flag is not set
4267 throw new Error("Unexpected presence of FlatWriteDynamicVarNode");
4270 Hashtable<TempDescriptor, VSTWrapper> writeDynamic = fwdvn.getVar2src();
4272 assert writeDynamic != null;
4274 Iterator wdItr = writeDynamic.entrySet().iterator();
4275 while( wdItr.hasNext() ) {
4276 Map.Entry me = (Map.Entry) wdItr.next();
4277 TempDescriptor refVar = (TempDescriptor) me.getKey();
4278 VSTWrapper vstW = (VSTWrapper) me.getValue();
4279 VariableSourceToken vst = vstW.vst;
4282 // only do this if the variable in question should be tracked,
4283 // meaning that it was explicitly added to the dynamic var set
4284 if( !current.getDynamicVarSet().contains( vst.getAddrVar() ) ) {
4290 // if there is no given source, this variable is ready so
4291 // mark src pointer NULL to signify that the var is up-to-date
4292 output.println(" "+refVar+"_srcSESE = NULL;");
4296 // otherwise we track where it will come from
4297 SESEandAgePair instance = new SESEandAgePair( vst.getSESE(), vst.getAge() );
4298 output.println(" "+refVar+"_srcSESE = "+instance+";");
4299 output.println(" "+refVar+"_srcOffset = (INTPTR) &((("+
4300 vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
4305 private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) {
4306 if (state.CONSCHECK) {
4307 String specname=fcn.getSpec();
4308 String varname="repairstate___";
4309 output.println("{");
4310 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
4312 TempDescriptor[] temps=fcn.getTemps();
4313 String[] vars=fcn.getVars();
4314 for(int i=0; i<temps.length; i++) {
4315 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";");
4318 output.println("if (doanalysis"+specname+"("+varname+")) {");
4319 output.println("free"+specname+"_state("+varname+");");
4320 output.println("} else {");
4321 output.println("/* Bad invariant */");
4322 output.println("free"+specname+"_state("+varname+");");
4323 output.println("abort_task();");
4324 output.println("}");
4325 output.println("}");
4329 private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) {
4331 if( (state.MLP && !nonSESEpass) ||
4332 (state.OOOJAVA && !nonSESEpass)
4334 output.println(" seseCaller = (SESEcommon*)"+paramsprefix+";");
4337 MethodDescriptor md=fc.getMethod();
4338 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? locality.getBinding(lb, fc) : md);
4339 ClassDescriptor cn=md.getClassDesc();
4340 output.println("{");
4341 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4343 LocalityBinding fclb=locality.getBinding(lb, fc);
4344 output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4346 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
4347 output.print(objectparams.numPointers());
4348 output.print(", "+localsprefixaddr);
4349 if (md.getThis()!=null) {
4351 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb));
4353 if (fc.getThis()!=null&&md.getThis()==null) {
4354 System.out.println("WARNING!!!!!!!!!!!!");
4355 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
4359 for(int i=0; i<fc.numArgs(); i++) {
4360 Descriptor var=md.getParameter(i);
4361 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4362 if (objectparams.isParamPtr(paramtemp)) {
4363 TempDescriptor targ=fc.getArg(i);
4365 TypeDescriptor td=md.getParamType(i);
4367 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4369 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
4372 output.println("};");
4377 if (fc.getReturnTemp()!=null)
4378 output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
4380 /* Do we need to do virtual dispatch? */
4381 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
4384 LocalityBinding fclb=locality.getBinding(lb, fc);
4385 output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4387 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
4392 if (md.getReturnType().isClass()||md.getReturnType().isArray())
4393 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
4395 output.print(md.getReturnType().getSafeSymbol()+" ");
4396 output.print("(*)(");
4398 boolean printcomma=false;
4399 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4401 LocalityBinding fclb=locality.getBinding(lb, fc);
4402 output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4404 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
4408 for(int i=0; i<objectparams.numPrimitives(); i++) {
4409 TempDescriptor temp=objectparams.getPrimitive(i);
4413 if (temp.getType().isClass()||temp.getType().isArray())
4414 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
4416 output.print(temp.getType().getSafeSymbol());
4421 LocalityBinding fclb=locality.getBinding(lb, fc);
4422 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
4424 output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
4428 boolean needcomma=false;
4429 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4430 output.print("&__parameterlist__");
4434 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
4435 if (fc.getThis()!=null) {
4436 TypeDescriptor ptd=md.getThis().getType();
4439 if (ptd.isClass()&&!ptd.isArray())
4440 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4441 output.print(generateTemp(fm,fc.getThis(),lb));
4446 for(int i=0; i<fc.numArgs(); i++) {
4447 Descriptor var=md.getParameter(i);
4448 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
4449 if (objectparams.isParamPrim(paramtemp)) {
4450 TempDescriptor targ=fc.getArg(i);
4454 TypeDescriptor ptd=md.getParamType(i);
4455 if (ptd.isClass()&&!ptd.isArray())
4456 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
4457 output.print(generateTemp(fm, targ,lb));
4461 output.println(");");
4462 output.println(" }");
4465 private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
4466 Set subclasses=typeutil.getSubClasses(thiscd);
4467 if (subclasses==null)
4469 for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
4470 ClassDescriptor cd=(ClassDescriptor)classit.next();
4471 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
4472 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
4473 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
4474 if (md.matches(matchmd))
4481 private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
4482 if (state.SINGLETM) {
4483 //single machine transactional memory case
4484 String field=ffn.getField().getSafeSymbol();
4485 String src=generateTemp(fm, ffn.getSrc(),lb);
4486 String dst=generateTemp(fm, ffn.getDst(),lb);
4488 output.println(dst+"="+ src +"->"+field+ ";");
4489 if (ffn.getField().getType().isPtr()&&locality.getAtomic(lb).get(ffn).intValue()>0&&
4490 locality.getNodePreTempInfo(lb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
4491 if ((dc==null)||(!state.READSET&&dc.getNeedTrans(lb, ffn))||
4492 (state.READSET&&dc.getNeedWriteTrans(lb, ffn))) {
4493 output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
4494 } else if (state.READSET&&dc.getNeedTrans(lb, ffn)) {
4495 if (state.HYBRID&&delaycomp.getConv(lb).contains(ffn)) {
4496 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4498 output.println("TRANSREADRD("+dst+", "+dst+");");
4501 } else if (state.DSM) {
4502 Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
4503 if (status==LocalityAnalysis.GLOBAL) {
4504 String field=ffn.getField().getSafeSymbol();
4505 String src=generateTemp(fm, ffn.getSrc(),lb);
4506 String dst=generateTemp(fm, ffn.getDst(),lb);
4508 if (ffn.getField().getType().isPtr()) {
4510 //TODO: Uncomment this when we have runtime support
4511 //if (ffn.getSrc()==ffn.getDst()) {
4512 //output.println("{");
4513 //output.println("void * temp="+src+";");
4514 //output.println("if (temp&0x1) {");
4515 //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
4516 //output.println(src+"->"+field+"="+temp+";");
4517 //output.println("}");
4518 //output.println(dst+"=temp;");
4519 //output.println("}");
4521 output.println(dst+"="+ src +"->"+field+ ";");
4522 //output.println("if ("+dst+"&0x1) {");
4523 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4524 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4525 //output.println(src+"->"+field+"="+src+"->"+field+";");
4526 //output.println("}");
4529 output.println(dst+"="+ src+"->"+field+";");
4531 } else if (status==LocalityAnalysis.LOCAL) {
4532 if (ffn.getField().getType().isPtr()&&
4533 ffn.getField().isGlobal()) {
4534 String field=ffn.getField().getSafeSymbol();
4535 String src=generateTemp(fm, ffn.getSrc(),lb);
4536 String dst=generateTemp(fm, ffn.getDst(),lb);
4537 output.println(dst+"="+ src +"->"+field+ ";");
4538 if (locality.getAtomic(lb).get(ffn).intValue()>0)
4539 //DEBUG: output.println("TRANSREAD("+dst+", (unsigned int) "+dst+",\""+fm+":"+ffn+"\");");
4540 output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
4542 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4543 } else if (status==LocalityAnalysis.EITHER) {
4544 //Code is reading from a null pointer
4545 output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {");
4546 output.println("#ifndef RAW");
4547 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4548 output.println("#endif");
4549 //This should throw a suitable null pointer error
4550 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4552 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4554 // DEBUG if(!ffn.getDst().getType().isPrimitive()){
4555 // DEBUG output.println("within((void*)"+generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+");");
4557 output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";");
4562 private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) {
4563 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
4564 throw new Error("Can't set array length");
4565 if (state.SINGLETM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4566 //Single Machine Transaction Case
4567 boolean srcptr=fsfn.getSrc().getType().isPtr();
4568 String src=generateTemp(fm,fsfn.getSrc(),lb);
4569 String dst=generateTemp(fm,fsfn.getDst(),lb);
4570 output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
4571 if (srcptr&&!fsfn.getSrc().getType().isNull()) {
4572 output.println("{");
4573 if ((dc==null)||dc.getNeedSrcTrans(lb, fsfn)&&
4574 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
4575 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4577 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4580 if (wb.needBarrier(fsfn)&&
4581 locality.getNodePreTempInfo(lb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
4582 if (state.EVENTMONITOR) {
4583 output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
4585 output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
4587 if (srcptr&!fsfn.getSrc().getType().isNull()) {
4588 output.println("*((unsigned INTPTR *)&("+dst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4589 output.println("}");
4591 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4593 } else if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) {
4594 Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc());
4595 Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst());
4596 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4598 String src=generateTemp(fm,fsfn.getSrc(),lb);
4599 String dst=generateTemp(fm,fsfn.getDst(),lb);
4601 output.println("{");
4602 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4604 if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
4607 if (wb.needBarrier(fsfn))
4608 output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
4610 output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
4612 output.println(glbdst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4613 } else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
4614 /** Check if we need to copy */
4615 output.println("if(!"+dst+"->"+localcopystr+") {");
4616 /* Link object into list */
4617 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4618 output.println(revertptr+"=revertlist;");
4619 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4620 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4622 output.println("COPY_OBJ("+dst+");");
4623 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4624 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4625 output.println("}");
4627 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4629 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4630 } else if (statusdst.equals(LocalityAnalysis.EITHER)) {
4631 //writing to a null...bad
4632 output.println("if ("+dst+") {");
4633 output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
4635 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
4637 output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";");
4640 output.println("}");
4643 if (state.FASTCHECK) {
4644 String dst=generateTemp(fm, fsfn.getDst(),lb);
4645 output.println("if(!"+dst+"->"+localcopystr+") {");
4646 /* Link object into list */
4647 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4648 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4650 output.println("COPY_OBJ("+dst+");");
4651 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4652 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4653 output.println("}");
4656 // DEBUG if(!fsfn.getField().getType().isPrimitive()){
4657 // DEBUG output.println("within((void*)"+generateTemp(fm,fsfn.getSrc(),lb)+");");
4659 output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";");
4663 private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) {
4664 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
4667 if (elementtype.isArray()||elementtype.isClass())
4670 type=elementtype.getSafeSymbol()+" ";
4672 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
4673 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex(),lb)+") >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___))");
4674 output.println("failedboundschk();");
4676 if (state.SINGLETM) {
4677 //Single machine transaction case
4678 String dst=generateTemp(fm, fen.getDst(),lb);
4679 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))) {
4680 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4682 output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc(),lb)+", "+generateTemp(fm, fen.getIndex(),lb)+", "+type+");");
4685 if (elementtype.isPtr()&&locality.getAtomic(lb).get(fen).intValue()>0&&
4686 locality.getNodePreTempInfo(lb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
4687 if ((dc==null)||!state.READSET&&dc.getNeedTrans(lb, fen)||state.READSET&&dc.getNeedWriteTrans(lb, fen)) {
4688 output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
4689 } else if (state.READSET&&dc.getNeedTrans(lb, fen)) {
4690 if (state.HYBRID&&delaycomp.getConv(lb).contains(fen)) {
4691 output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
4693 output.println("TRANSREADRD("+dst+", "+dst+");");
4696 } else if (state.DSM) {
4697 Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc());
4698 if (status==LocalityAnalysis.GLOBAL) {
4699 String dst=generateTemp(fm, fen.getDst(),lb);
4700 if (elementtype.isPtr()) {
4701 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4702 //DEBUG: output.println("TRANSREAD("+dst+", "+dst+",\""+fm+":"+fen+"\");");
4703 output.println("TRANSREAD("+dst+", "+dst+");");
4705 output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4707 } else if (status==LocalityAnalysis.LOCAL) {
4708 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4709 } else if (status==LocalityAnalysis.EITHER) {
4710 //Code is reading from a null pointer
4711 output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {");
4712 output.println("#ifndef RAW");
4713 output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
4714 output.println("#endif");
4715 //This should throw a suitable null pointer error
4716 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4718 throw new Error("Read from non-global/non-local in:"+lb.getExplanation());
4720 // DEBUG output.println("within((void*)"+generateTemp(fm,fen.getSrc(),lb)+");");
4721 output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];");
4725 private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) {
4726 //TODO: need dynamic check to make sure this assignment is actually legal
4727 //Because Object[] could actually be something more specific...ie. Integer[]
4729 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
4732 if (elementtype.isArray()||elementtype.isClass())
4735 type=elementtype.getSafeSymbol()+" ";
4737 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
4738 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex(),lb)+") >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___))");
4739 output.println("failedboundschk();");
4742 if (state.SINGLETM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4743 //Transaction set element case
4744 if (wb.needBarrier(fsen)&&
4745 locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
4746 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___objstatus___))|=DIRTY;");
4748 if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
4749 output.println("{");
4750 String src=generateTemp(fm, fsen.getSrc(), lb);
4751 if ((dc==null)||dc.getNeedSrcTrans(lb, fsen)&&
4752 locality.getNodePreTempInfo(lb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
4753 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4755 output.println("INTPTR srcoid=(INTPTR)"+src+";");
4757 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4758 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", srcoid, INTPTR);");
4760 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4762 output.println("}");
4764 if (state.STMARRAY&&locality.getNodePreTempInfo(lb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(lb).get(fsen).intValue()>0) {
4765 output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst(),lb)+", "+generateTemp(fm, fsen.getIndex(),lb)+", "+ generateTemp(fm, fsen.getSrc(), lb) +", "+type+");");
4767 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4770 } else if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) {
4771 Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc());
4772 Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst());
4773 boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL;
4774 boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL;
4775 boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
4778 if (wb.needBarrier(fsen))
4779 output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;");
4780 } else if (dstlocal) {
4781 /** Check if we need to copy */
4782 String dst=generateTemp(fm, fsen.getDst(),lb);
4783 output.println("if(!"+dst+"->"+localcopystr+") {");
4784 /* Link object into list */
4785 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4786 output.println(revertptr+"=revertlist;");
4787 if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
4788 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4790 output.println("COPY_OBJ("+dst+");");
4791 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4792 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4793 output.println("}");
4795 System.out.println("Node: "+fsen);
4796 System.out.println(lb);
4797 System.out.println("statusdst="+statusdst);
4798 System.out.println(fm.printMethod());
4799 throw new Error("Unknown array type");
4802 output.println("{");
4803 String src=generateTemp(fm, fsen.getSrc(), lb);
4804 output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
4805 output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;");
4806 output.println("}");
4808 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4811 if (state.FASTCHECK) {
4812 String dst=generateTemp(fm, fsen.getDst(),lb);
4813 output.println("if(!"+dst+"->"+localcopystr+") {");
4814 /* Link object into list */
4815 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
4816 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
4818 output.println("COPY_OBJ("+dst+");");
4819 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4820 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4821 output.println("}");
4823 // DEBUG output.println("within((void*)"+generateTemp(fm,fsen.getDst(),lb)+");");
4824 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";");
4828 protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) {
4829 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4830 //Stash pointer in case of GC
4831 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4832 output.println(revertptr+"=revertlist;");
4834 if (state.SINGLETM) {
4835 if (fn.getType().isArray()) {
4836 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4837 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4838 //inside transaction
4839 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4841 //outside transaction
4842 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4845 if (locality.getAtomic(lb).get(fn).intValue()>0) {
4846 //inside transaction
4847 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4849 //outside transaction
4850 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4853 } else if (fn.getType().isArray()) {
4854 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
4855 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4856 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4857 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4858 if(this.state.MLP || state.OOOJAVA){
4859 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray_mlp("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
4860 output.println(" oid += numWorkers;");
4862 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4865 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");");
4868 if (fn.isGlobal()&&(state.DSM||state.SINGLETM)) {
4869 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
4870 } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4871 if (this.state.MLP || state.OOOJAVA){
4872 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new_mlp("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+", oid, "+oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+");");
4873 output.println(" oid += numWorkers;");
4875 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
4878 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
4881 if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) {
4882 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4883 String dst=generateTemp(fm,fn.getDst(),lb);
4884 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4885 output.println(dst+"->"+nextobjstr+"="+revertptr+";");
4886 output.println("revertlist=(struct ___Object___ *)"+dst+";");
4888 if (state.FASTCHECK) {
4889 String dst=generateTemp(fm,fn.getDst(),lb);
4890 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
4891 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
4892 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
4896 private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) {
4897 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4898 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
4900 output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");");
4904 private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, FlatOpNode fon, PrintWriter output) {
4905 if (fon.getRight()!=null) {
4906 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
4907 if (fon.getLeft().getType().isLong())
4908 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4910 output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";");
4912 } else if (dc!=null) {
4913 output.print(generateTemp(fm, fon.getDest(),lb)+" = (");
4914 if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4915 output.print("(void *)");
4916 if (dc.getNeedLeftSrcTrans(lb, fon))
4917 output.print("("+generateTemp(fm, fon.getLeft(),lb)+"!=NULL?"+generateTemp(fm, fon.getLeft(),lb)+"->"+oidstr+":NULL)");
4919 output.print(generateTemp(fm, fon.getLeft(),lb));
4920 output.print(")"+fon.getOp().toString()+"(");
4921 if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
4922 output.print("(void *)");
4923 if (dc.getNeedRightSrcTrans(lb, fon))
4924 output.println("("+generateTemp(fm, fon.getRight(),lb)+"!=NULL?"+generateTemp(fm, fon.getRight(),lb)+"->"+oidstr+":NULL));");
4926 output.println(generateTemp(fm,fon.getRight(),lb)+");");
4928 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";");
4929 } else if (fon.getOp().getOp()==Operation.ASSIGN)
4930 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4931 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
4932 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";");
4933 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
4934 output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";");
4935 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
4936 output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";");
4937 else if (fon.getOp().getOp()==Operation.COMP)
4938 output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";");
4939 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
4940 output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;");
4942 output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";");
4945 private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) {
4946 /* TODO: Do type check here */
4947 if (fcn.getType().isArray()) {
4948 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4949 } else if (fcn.getType().isClass())
4950 output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";");
4952 output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";");
4955 private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) {
4956 if (fln.getValue()==null)
4957 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4958 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
4959 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
4960 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4961 //Stash pointer in case of GC
4962 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4963 output.println(revertptr+"=revertlist;");
4965 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4966 if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) {
4967 //Stash pointer in case of GC
4968 String revertptr=generateTemp(fm, reverttable.get(lb),lb);
4969 output.println("revertlist="+revertptr+";");
4972 output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
4974 } else if (fln.getType().isBoolean()) {
4975 if (((Boolean)fln.getValue()).booleanValue())
4976 output.println(generateTemp(fm, fln.getDst(),lb)+"=1;");
4978 output.println(generateTemp(fm, fln.getDst(),lb)+"=0;");
4979 } else if (fln.getType().isChar()) {
4980 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
4981 output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';");
4982 } else if (fln.getType().isLong()) {
4983 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;");
4985 output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";");
4988 protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
4989 if (frn.getReturnTemp()!=null) {
4990 if (frn.getReturnTemp().getType().isPtr())
4991 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4993 output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
4995 output.println("return;");
4999 protected void generateStoreFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
5002 //only record if this group has more than one exit
5003 if (branchanalysis.numJumps(fcb)>1) {
5004 left=branchanalysis.jumpValue(fcb, 0);
5005 right=branchanalysis.jumpValue(fcb, 1);
5007 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") {");
5009 output.println("STOREBRANCH("+right+");");
5010 output.println("goto "+label+";");
5011 output.println("}");
5013 output.println("STOREBRANCH("+left+");");
5016 protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) {
5017 output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";");
5020 /** This method generates header information for the method or
5021 * task referenced by the Descriptor des. */
5022 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
5023 generateHeader(fm, lb, des, output, false);
5026 private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output, boolean addSESErecord) {
5028 ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
5029 MethodDescriptor md=null;
5030 TaskDescriptor task=null;
5031 if (des instanceof MethodDescriptor)
5032 md=(MethodDescriptor) des;
5034 task=(TaskDescriptor) des;
5036 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
5038 if (md!=null&&md.getReturnType()!=null) {
5039 if (md.getReturnType().isClass()||md.getReturnType().isArray())
5040 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
5042 output.print(md.getReturnType().getSafeSymbol()+" ");
5044 //catch the constructor case
5045 output.print("void ");
5047 if (state.DSM||state.SINGLETM) {
5048 output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5050 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
5052 output.print(task.getSafeSymbol()+"(");
5054 boolean printcomma=false;
5055 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
5057 if (state.DSM||state.SINGLETM) {
5058 output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5060 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
5062 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
5068 for(int i=0; i<objectparams.numPrimitives(); i++) {
5069 TempDescriptor temp=objectparams.getPrimitive(i);
5073 if (temp.getType().isClass()||temp.getType().isArray())
5074 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
5076 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
5078 output.println(") {");
5079 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
5080 /* Imprecise Task */
5081 output.println("void * parameterarray[]) {");
5082 /* Unpack variables */
5083 for(int i=0; i<objectparams.numPrimitives(); i++) {
5084 TempDescriptor temp=objectparams.getPrimitive(i);
5085 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
5087 for(int i=0; i<fm.numTags(); i++) {
5088 TempDescriptor temp=fm.getTag(i);
5089 int offset=i+objectparams.numPrimitives();
5090 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
5093 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
5094 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
5095 } else output.println(") {");
5098 public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) {
5099 output.println("/* FlatFlagActionNode */");
5102 /* Process tag changes */
5103 Relation tagsettable=new Relation();
5104 Relation tagcleartable=new Relation();
5106 Iterator tagsit=ffan.getTempTagPairs();
5107 while (tagsit.hasNext()) {
5108 TempTagPair ttp=(TempTagPair) tagsit.next();
5109 TempDescriptor objtmp=ttp.getTemp();
5110 TagDescriptor tag=ttp.getTag();
5111 TempDescriptor tagtmp=ttp.getTagTemp();
5112 boolean tagstatus=ffan.getTagChange(ttp);
5114 tagsettable.put(objtmp, tagtmp);
5116 tagcleartable.put(objtmp, tagtmp);
5121 Hashtable flagandtable=new Hashtable();
5122 Hashtable flagortable=new Hashtable();
5124 /* Process flag changes */
5125 Iterator flagsit=ffan.getTempFlagPairs();
5126 while(flagsit.hasNext()) {
5127 TempFlagPair tfp=(TempFlagPair)flagsit.next();
5128 TempDescriptor temp=tfp.getTemp();
5129 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
5130 FlagDescriptor flag=tfp.getFlag();
5132 //Newly allocate objects that don't set any flags case
5133 if (flagortable.containsKey(temp)) {
5137 flagortable.put(temp,new Integer(mask));
5139 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
5140 boolean flagstatus=ffan.getFlagChange(tfp);
5143 if (flagortable.containsKey(temp)) {
5144 mask=((Integer)flagortable.get(temp)).intValue();
5147 flagortable.put(temp,new Integer(mask));
5149 int mask=0xFFFFFFFF;
5150 if (flagandtable.containsKey(temp)) {
5151 mask=((Integer)flagandtable.get(temp)).intValue();
5153 mask&=(0xFFFFFFFF^flagid);
5154 flagandtable.put(temp,new Integer(mask));
5160 HashSet flagtagset=new HashSet();
5161 flagtagset.addAll(flagortable.keySet());
5162 flagtagset.addAll(flagandtable.keySet());
5163 flagtagset.addAll(tagsettable.keySet());
5164 flagtagset.addAll(tagcleartable.keySet());
5166 Iterator ftit=flagtagset.iterator();
5167 while(ftit.hasNext()) {
5168 TempDescriptor temp=(TempDescriptor)ftit.next();
5171 Set tagtmps=tagcleartable.get(temp);
5172 if (tagtmps!=null) {
5173 Iterator tagit=tagtmps.iterator();
5174 while(tagit.hasNext()) {
5175 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5176 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5177 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5179 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5183 tagtmps=tagsettable.get(temp);
5184 if (tagtmps!=null) {
5185 Iterator tagit=tagtmps.iterator();
5186 while(tagit.hasNext()) {
5187 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
5188 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
5189 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");");
5191 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");");
5196 int andmask=0xFFFFFFF;
5198 if (flagortable.containsKey(temp))
5199 ormask=((Integer)flagortable.get(temp)).intValue();
5200 if (flagandtable.containsKey(temp))
5201 andmask=((Integer)flagandtable.get(temp)).intValue();
5202 generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask);
5203 generateObjectDistribute(ffan, fm, lb, temp, output);
5207 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
5208 PrintWriter output, int ormask, int andmask) {
5209 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
5210 output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5212 output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
5216 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) {
5217 output.println("enqueueObject("+generateTemp(fm, temp, lb)+");");
5220 void generateOptionalHeader(PrintWriter headers) {
5223 headers.println("#include \"task.h\"\n\n");
5224 headers.println("#ifndef _OPTIONAL_STRUCT_");
5225 headers.println("#define _OPTIONAL_STRUCT_");
5227 //STRUCT PREDICATEMEMBER
5228 headers.println("struct predicatemember{");
5229 headers.println("int type;");
5230 headers.println("int numdnfterms;");
5231 headers.println("int * flags;");
5232 headers.println("int numtags;");
5233 headers.println("int * tags;\n};\n\n");
5235 //STRUCT OPTIONALTASKDESCRIPTOR
5236 headers.println("struct optionaltaskdescriptor{");
5237 headers.println("struct taskdescriptor * task;");
5238 headers.println("int index;");
5239 headers.println("int numenterflags;");
5240 headers.println("int * enterflags;");
5241 headers.println("int numpredicatemembers;");
5242 headers.println("struct predicatemember ** predicatememberarray;");
5243 headers.println("};\n\n");
5245 //STRUCT TASKFAILURE
5246 headers.println("struct taskfailure {");
5247 headers.println("struct taskdescriptor * task;");
5248 headers.println("int index;");
5249 headers.println("int numoptionaltaskdescriptors;");
5250 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5252 //STRUCT FSANALYSISWRAPPER
5253 headers.println("struct fsanalysiswrapper{");
5254 headers.println("int flags;");
5255 headers.println("int numtags;");
5256 headers.println("int * tags;");
5257 headers.println("int numtaskfailures;");
5258 headers.println("struct taskfailure ** taskfailurearray;");
5259 headers.println("int numoptionaltaskdescriptors;");
5260 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
5262 //STRUCT CLASSANALYSISWRAPPER
5263 headers.println("struct classanalysiswrapper{");
5264 headers.println("int type;");
5265 headers.println("int numotd;");
5266 headers.println("struct optionaltaskdescriptor ** otdarray;");
5267 headers.println("int numfsanalysiswrappers;");
5268 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
5270 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
5272 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
5273 while(taskit.hasNext()) {
5274 TaskDescriptor td=(TaskDescriptor)taskit.next();
5275 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
5280 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
5281 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
5282 int predicateindex = 0;
5283 //iterate through the classes concerned by the predicate
5284 Set c_vard = predicate.vardescriptors;
5285 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
5288 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();) {
5289 VarDescriptor vard = (VarDescriptor)vard_it.next();
5290 TypeDescriptor typed = vard.getType();
5292 //generate for flags
5293 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
5294 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5296 if (fen_hashset!=null) {
5297 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext();) {
5298 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
5300 DNFFlag dflag=fen.getDNF();
5301 numberterms+=dflag.size();
5303 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
5305 for(int j=0; j<dflag.size(); j++) {
5307 output.println(",");
5308 Vector term=dflag.get(j);
5311 for(int k=0; k<term.size(); k++) {
5312 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
5313 FlagDescriptor fd=dfa.getFlag();
5314 boolean negated=dfa.getNegated();
5315 int flagid=1<<((Integer)flags.get(fd)).intValue();
5320 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
5325 output.println("};\n");
5328 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
5329 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5332 for(int j=0; j<tagel.numTags(); j++) {
5334 output.println(",");
5335 TempDescriptor tmp=tagel.getTemp(j);
5336 if (!slotnumber.containsKey(tmp)) {
5337 Integer slotint=new Integer(current_slot++);
5338 slotnumber.put(tmp,slotint);
5340 int slot=slotnumber.get(tmp).intValue();
5341 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
5343 numtags = tagel.numTags();
5345 output.println("};");
5347 //store the result into a predicatemember struct
5348 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5349 output.println("/*type*/"+typed.getClassDesc().getId()+",");
5350 output.println("/* number of dnf terms */"+numberterms+",");
5351 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5352 output.println("/* number of tag */"+numtags+",");
5353 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5354 output.println("};\n");
5359 //generate an array that stores the entire predicate
5360 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5361 for( int j = 0; j<predicateindex; j++) {
5362 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5363 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5365 output.println("};\n");
5366 return predicateindex;
5370 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
5371 generateOptionalHeader(headers);
5373 output.println("#include \"optionalstruct.h\"\n\n");
5374 output.println("#include \"stdlib.h\"\n");
5376 HashSet processedcd = new HashSet();
5378 Enumeration e = safeexecution.keys();
5379 while (e.hasMoreElements()) {
5382 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
5383 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
5385 //Generate the struct of optionals
5386 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5387 numotd = c_otd.size();
5388 if(maxotd<numotd) maxotd = numotd;
5389 if( !c_otd.isEmpty() ) {
5390 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5391 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5393 //generate the int arrays for the predicate
5394 Predicate predicate = otd.predicate;
5395 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
5396 TreeSet<Integer> fsset=new TreeSet<Integer>();
5397 //iterate through possible FSes corresponding to
5398 //the state when entering
5400 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext();) {
5401 FlagState fs = (FlagState)fses.next();
5403 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5404 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5405 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5408 fsset.add(new Integer(flagid));
5409 //tag information not needed because tag
5410 //changes are not tolerated.
5413 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
5414 boolean needcomma=false;
5415 for(Iterator<Integer> it=fsset.iterator(); it.hasNext();) {
5418 output.println(it.next());
5421 output.println("};\n");
5424 //generate optionaltaskdescriptor that actually
5425 //includes exit fses, predicate and the task
5427 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
5428 output.println("&task_"+otd.td.getSafeSymbol()+",");
5429 output.println("/*index*/"+otd.getIndex()+",");
5430 output.println("/*number of enter flags*/"+fsset.size()+",");
5431 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5432 output.println("/*number of members */"+predicateindex+",");
5433 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5434 output.println("};\n");
5438 // if there are no optionals, there is no need to build the rest of the struct
5440 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
5441 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
5442 if( !c_otd.isEmpty() ) {
5443 boolean needcomma=false;
5444 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();) {
5445 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
5447 output.println(",");
5449 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5452 output.println("};\n");
5454 //get all the possible flagstates reachable by an object
5455 Hashtable hashtbtemp = safeexecution.get(cdtemp);
5457 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
5458 fsts.addAll(hashtbtemp.keySet());
5459 for(Iterator fsit=fsts.iterator(); fsit.hasNext();) {
5460 FlagState fs = (FlagState)fsit.next();
5463 //get the set of OptionalTaskDescriptors corresponding
5464 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
5465 //iterate through the OptionalTaskDescriptors and
5466 //store the pointers to the optionals struct (see on
5467 //top) into an array
5469 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
5470 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext();) {
5471 OptionalTaskDescriptor mm = mos.next();
5473 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
5475 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
5478 output.println("};\n");
5480 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
5483 for(Iterator flags = fs.getFlags(); flags.hasNext();) {
5484 FlagDescriptor flagd = (FlagDescriptor)flags.next();
5485 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
5489 //process tag information
5492 boolean first = true;
5493 Enumeration tag_enum = fs.getTags();
5494 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5495 while(tag_enum.hasMoreElements()) {
5497 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
5501 output.println(", ");
5502 output.println("/*tagid*/"+state.getTagId(tagd));
5504 output.println("};");
5506 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
5507 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5508 TaskIndex ti=itti.next();
5512 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
5514 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
5515 boolean needcomma=false;
5516 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext();) {
5517 OptionalTaskDescriptor otd=otdit.next();
5521 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
5523 output.println("};");
5525 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
5526 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
5527 output.print(ti.getIndex()+", ");
5528 output.print(otdset.size()+", ");
5529 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
5530 output.println("};");
5533 tiset=sa.getTaskIndex(fs);
5534 boolean needcomma=false;
5536 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
5537 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext();) {
5538 TaskIndex ti=itti.next();
5539 if (ti.isRuntime()) {
5546 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
5548 output.println("};\n");
5550 //Store the result in fsanalysiswrapper
5552 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
5553 output.println("/*flag*/"+flagid+",");
5554 output.println("/* number of tags*/"+tagcounter+",");
5555 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5556 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
5557 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
5558 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
5559 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
5560 output.println("};\n");
5564 //Build the array of fsanalysiswrappers
5565 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
5566 boolean needcomma=false;
5567 for(int i = 0; i<fscounter; i++) {
5568 if (needcomma) output.print(",");
5569 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
5572 output.println("};");
5574 //Build the classanalysiswrapper referring to the previous array
5575 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
5576 output.println("/*type*/"+cdtemp.getId()+",");
5577 output.println("/*numotd*/"+numotd+",");
5578 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
5579 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
5580 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
5581 processedcd.add(cdtemp);
5584 //build an array containing every classes for which code has been build
5585 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
5586 for(int i=0; i<state.numClasses(); i++) {
5587 ClassDescriptor cn=cdarray[i];
5590 if ((cn != null) && (processedcd.contains(cn)))
5591 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
5593 output.print("NULL");
5595 output.println("};");
5597 output.println("#define MAXOTD "+maxotd);
5598 headers.println("#endif");
5601 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
5602 Relation r=new Relation();
5603 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext();) {
5604 OptionalTaskDescriptor otd=otdit.next();
5605 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
5609 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
5610 for(Iterator it=r.keySet().iterator(); it.hasNext();) {
5611 Set s=r.get(it.next());
5612 for(Iterator it2=s.iterator(); it2.hasNext();) {
5613 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
5621 protected void outputTransCode(PrintWriter output) {
5624 private int calculateSizeOfSESEParamList(FlatSESEEnterNode fsen){
5626 Set<TempDescriptor> tdSet=new HashSet<TempDescriptor>();
5628 for (Iterator iterator = fsen.getInVarSet().iterator(); iterator.hasNext();) {
5629 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5630 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5631 tdSet.add(tempDescriptor);
5635 for (Iterator iterator = fsen.getOutVarSet().iterator(); iterator.hasNext();) {
5636 TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
5637 if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()){
5638 tdSet.add(tempDescriptor);
5642 return tdSet.size();
5645 private String calculateSizeOfSESEParamSize(FlatSESEEnterNode fsen){
5646 HashMap <String,Integer> map=new HashMap();
5647 HashSet <TempDescriptor> processed=new HashSet<TempDescriptor>();
5650 // space for all in and out set primitives
5651 Set<TempDescriptor> inSetAndOutSet = new HashSet<TempDescriptor>();
5652 inSetAndOutSet.addAll( fsen.getInVarSet() );
5653 inSetAndOutSet.addAll( fsen.getOutVarSet() );
5655 Set<TempDescriptor> inSetAndOutSetPrims = new HashSet<TempDescriptor>();
5657 Iterator<TempDescriptor> itr = inSetAndOutSet.iterator();
5658 while( itr.hasNext() ) {
5659 TempDescriptor temp = itr.next();
5660 TypeDescriptor type = temp.getType();
5661 if( !type.isPtr() ) {
5662 inSetAndOutSetPrims.add( temp );
5666 Iterator<TempDescriptor> itrPrims = inSetAndOutSetPrims.iterator();
5667 while( itrPrims.hasNext() ) {
5668 TempDescriptor temp = itrPrims.next();
5669 TypeDescriptor type = temp.getType();
5670 if(type.isPrimitive()){
5671 Integer count=map.get(type.getSymbol());
5673 count=new Integer(1);
5674 map.put(type.getSymbol(), count);
5676 map.put(type.getSymbol(), new Integer(count.intValue()+1));
5681 Set<String> keySet=map.keySet();
5682 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
5683 String key = (String) iterator.next();
5684 rtr+="+sizeof("+key+")*"+map.get(key);