f247749ec14aec14520755219b7dafd603bb8af3
[IRC.git] / Robust / src / IR / Flat / BuildCodeMultiCore.java
1 package IR.Flat;
2
3 import java.io.FileOutputStream;
4 import java.io.PrintWriter;
5 import java.util.HashSet;
6 import java.util.Hashtable;
7 import java.util.Iterator;
8 import java.util.LinkedList;
9 import java.util.Queue;
10 import java.util.Set;
11 import java.util.Vector;
12
13 import Analysis.Locality.LocalityBinding;
14 import Analysis.Scheduling.Schedule;
15 import Analysis.TaskStateAnalysis.FEdge;
16 import Analysis.TaskStateAnalysis.FlagState;
17 import Analysis.TaskStateAnalysis.SafetyAnalysis;
18 import Analysis.OwnershipAnalysis.AllocationSite;
19 import Analysis.OwnershipAnalysis.OwnershipAnalysis;
20 import Analysis.Prefetch.*;
21 import IR.ClassDescriptor;
22 import IR.Descriptor;
23 import IR.FlagDescriptor;
24 import IR.MethodDescriptor;
25 import IR.State;
26 import IR.TagVarDescriptor;
27 import IR.TaskDescriptor;
28 import IR.TypeDescriptor;
29 import IR.TypeUtil;
30 import IR.VarDescriptor;
31 import IR.Tree.DNFFlag;
32 import IR.Tree.DNFFlagAtom;
33 import IR.Tree.FlagExpressionNode;
34 import IR.Tree.TagExpressionList;
35
36 public class BuildCodeMultiCore extends BuildCode {
37   private Vector<Schedule> scheduling;
38   int coreNum;
39   Schedule currentSchedule;
40   Hashtable[] fsate2qnames;
41   String objqarrayprefix= "objqueuearray4class";
42   String objqueueprefix = "objqueue4parameter_";
43   String paramqarrayprefix = "paramqueuearray4task";
44   String coreqarrayprefix = "paramqueuearrays_core";
45   String taskprefix = "task_";
46   String taskarrayprefix = "taskarray_core";
47   String otqueueprefix = "___otqueue";
48   int startupcorenum;    // record the core containing startup task, suppose only one core can hava startup object
49
50   private OwnershipAnalysis m_oa;
51   private Vector<Vector<Integer>> m_aliasSets;
52   Hashtable<Integer, Vector<FlatNew>> m_aliasFNTbl4Para;
53   Hashtable<FlatNew, Vector<FlatNew>> m_aliasFNTbl;
54   Hashtable<FlatNew, Vector<Integer>> m_aliaslocksTbl4FN;
55
56   public BuildCodeMultiCore(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, Vector<Schedule> scheduling, int coreNum, PrefetchAnalysis pa) {
57     super(st, temptovar, typeutil, sa, pa);
58     this.scheduling = scheduling;
59     this.coreNum = coreNum;
60     this.currentSchedule = null;
61     this.fsate2qnames = null;
62     this.startupcorenum = 0;
63
64     // sometimes there are extra cores then needed in scheduling
65     // TODO
66     // currently, it is guaranteed that in scheduling, the corenum
67     // is started from 0 and continuous.
68     // MAY need modification here in the future when take hardware
69     // information into account.
70     if(this.scheduling.size() < this.coreNum) {
71       this.coreNum = this.scheduling.size();
72     }
73
74     this.m_oa = null;
75     this.m_aliasSets = null;
76     this.m_aliasFNTbl4Para = null;
77     this.m_aliasFNTbl = null;
78     this.m_aliaslocksTbl4FN = null;
79   }
80
81   public void setOwnershipAnalysis(OwnershipAnalysis m_oa) {
82     this.m_oa = m_oa;
83   }
84
85   public void buildCode() {
86     /* Create output streams to write to */
87     PrintWriter outclassdefs=null;
88     PrintWriter outstructs=null;
89     PrintWriter outmethodheader=null;
90     PrintWriter outmethod=null;
91     PrintWriter outvirtual=null;
92     PrintWriter outtask=null;
93     PrintWriter outtaskdefs=null;
94     //PrintWriter outoptionalarrays=null;
95     //PrintWriter optionalheaders=null;
96
97     try {
98       outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true);
99       outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
100       outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true);
101       outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
102       outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true);
103       if (state.TASK) {
104         outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true);
105         outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
106         /* optional
107            if (state.OPTIONAL){
108             outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
109             optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
110            } */
111       }
112       /*if (state.structfile!=null) {
113           outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
114          }*/
115     } catch (Exception e) {
116       e.printStackTrace();
117       System.exit(-1);
118     }
119
120     /* Build the virtual dispatch tables */
121     super.buildVirtualTables(outvirtual);
122
123     /* Output includes */
124     outmethodheader.println("#ifndef METHODHEADERS_H");
125     outmethodheader.println("#define METHODHEADERS_H");
126     outmethodheader.println("#include \"structdefs.h\"");
127     /*if (state.DSM)
128         outmethodheader.println("#include \"dstm.h\"");*/
129
130     /* Output Structures */
131     super.outputStructs(outstructs);
132
133     // Output the C class declarations
134     // These could mutually reference each other
135     super.outputClassDeclarations(outclassdefs);
136
137     // Output function prototypes and structures for parameters
138     Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
139     int numclasses = 0;
140     while(it.hasNext()) {
141       ++numclasses;
142       ClassDescriptor cn=(ClassDescriptor)it.next();
143       super.generateCallStructs(cn, outclassdefs, outstructs, outmethodheader);
144     }
145     outclassdefs.close();
146
147     if (state.TASK) {
148       /* Map flags to integers */
149       /* The runtime keeps track of flags using these integers */
150       it=state.getClassSymbolTable().getDescriptorsIterator();
151       while(it.hasNext()) {
152         ClassDescriptor cn=(ClassDescriptor)it.next();
153         super.mapFlags(cn);
154       }
155       /* Generate Tasks */
156       generateTaskStructs(outstructs, outmethodheader);
157
158       /* Outputs generic task structures if this is a task
159          program */
160       outputTaskTypes(outtask);
161     }
162
163     /* Build the actual methods */
164     super.outputMethods(outmethod);
165
166     if (state.TASK) {
167       Iterator[] taskits = new Iterator[this.coreNum];
168       for(int i = 0; i < taskits.length; ++i) {
169         taskits[i] = null;
170       }
171       int[] numtasks = new int[this.coreNum];
172       int[][] numqueues = new int[this.coreNum][numclasses];
173       /* Output code for tasks */
174       for(int i = 0; i < this.scheduling.size(); ++i) {
175         this.currentSchedule = this.scheduling.elementAt(i);
176         outputTaskCode(outtaskdefs, outmethod, outtask, taskits, numtasks, numqueues);
177       }
178
179       // Output task descriptors
180       boolean comma = false;
181       outtaskdefs.println("struct parameterwrapper ** objectqueues[][NUMCLASSES] = {");
182       boolean needcomma = false;
183       for(int i = 0; i < numqueues.length ; ++i) {
184         if(needcomma) {
185           outtaskdefs.println(",");
186         } else {
187           needcomma = true;
188         }
189         outtaskdefs.println("/* object queue array for core " + i + "*/");
190         outtaskdefs.print("{");
191         comma = false;
192         for(int j = 0; j < numclasses; ++j) {
193           if(comma) {
194             outtaskdefs.println(",");
195           } else {
196             comma = true;
197           }
198           outtaskdefs.print(this.objqarrayprefix + j + "_core" + i);
199         }
200         outtaskdefs.print("}");
201       }
202       outtaskdefs.println("};");
203       needcomma = false;
204       outtaskdefs.println("int numqueues[][NUMCLASSES] = {");
205       for(int i = 0; i < numqueues.length; ++i) {
206         if(needcomma) {
207           outtaskdefs.println(",");
208         } else {
209           needcomma = true;
210         }
211         int[] tmparray = numqueues[i];
212         comma = false;
213         outtaskdefs.print("{");
214         for(int j = 0; j < tmparray.length; ++j) {
215           if(comma) {
216             outtaskdefs.print(",");
217           } else {
218             comma = true;
219           }
220           outtaskdefs.print(tmparray[j]);
221         }
222         outtaskdefs.print("}");
223       }
224       outtaskdefs.println("};");
225
226       /* parameter queue arrays for all the tasks*/
227       outtaskdefs.println("struct parameterwrapper *** paramqueues[] = {");
228       needcomma = false;
229       for(int i = 0; i < this.coreNum ; ++i) {
230         if(needcomma) {
231           outtaskdefs.println(",");
232         } else {
233           needcomma = true;
234         }
235         outtaskdefs.println("/* parameter queue array for core " + i + "*/");
236         outtaskdefs.print(this.coreqarrayprefix + i);
237       }
238       outtaskdefs.println("};");
239
240       for(int i = 0; i < taskits.length; ++i) {
241         outtaskdefs.println("struct taskdescriptor * " + this.taskarrayprefix + i + "[]={");
242         Iterator taskit = taskits[i];
243         if(taskit != null) {
244           boolean first=true;
245           while(taskit.hasNext()) {
246             TaskDescriptor td=(TaskDescriptor)taskit.next();
247             if (first)
248               first=false;
249             else
250               outtaskdefs.println(",");
251             outtaskdefs.print("&" + this.taskprefix +td.getCoreSafeSymbol(i));
252           }
253         }
254         outtaskdefs.println();
255         outtaskdefs.println("};");
256       }
257       outtaskdefs.println("struct taskdescriptor ** taskarray[]= {");
258       comma = false;
259       for(int i = 0; i < taskits.length; ++i) {
260         if (comma)
261           outtaskdefs.println(",");
262         else
263           comma = true;
264         outtaskdefs.print(this.taskarrayprefix + i);
265       }
266       outtaskdefs.println("};");
267
268       outtaskdefs.print("int numtasks[]= {");
269       comma = false;
270       for(int i = 0; i < taskits.length; ++i) {
271         if (comma)
272           outtaskdefs.print(",");
273         else
274           comma=true;
275         outtaskdefs.print(numtasks[i]);
276       }
277       outtaskdefs.println("};");
278       outtaskdefs.println("int corenum=0;");
279
280       outtaskdefs.close();
281       outtask.println("#endif");
282       outtask.close();
283       /* Record maximum number of task parameters */
284       outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
285       /* Record maximum number of all types, i.e. length of classsize[] */
286       outstructs.println("#define NUMTYPES "+(state.numClasses() + state.numArrays()));
287       /* Record number of cores */
288       outstructs.println("#define NUMCORES "+this.coreNum);
289       /* Record number of core containing startup task */
290       outstructs.println("#define STARTUPCORE "+this.startupcorenum);
291       //outstructs.println("#define STARTUPCORESTR \""+this.startupcorenum+"\"");
292     }     //else if (state.main!=null) {
293           /* Generate main method */
294           // outputMainMethod(outmethod);
295           //}
296
297     /* Generate information for task with optional parameters */
298     /*if (state.TASK&&state.OPTIONAL){
299         generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
300         outoptionalarrays.close();
301        } */
302
303     /* Output structure definitions for repair tool */
304     /*if (state.structfile!=null) {
305         buildRepairStructs(outrepairstructs);
306         outrepairstructs.close();
307        }*/
308
309     /* Close files */
310     outmethodheader.println("#endif");
311     outmethodheader.close();
312     outmethod.close();
313     outstructs.println("#endif");
314     outstructs.close();
315   }
316
317   /** This function outputs (1) structures that parameters are
318    * passed in (when PRECISE GC is enabled) and (2) function
319    * prototypes for the tasks */
320
321   private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
322     /* Cycle through tasks */
323     for(int i = 0; i < this.scheduling.size(); ++i) {
324       Schedule tmpschedule = this.scheduling.elementAt(i);
325       int num = tmpschedule.getCoreNum();
326       Iterator<TaskDescriptor> taskit = tmpschedule.getTasks().iterator();
327
328       while(taskit.hasNext()) {
329         /* Classify parameters */
330         TaskDescriptor task=taskit.next();
331         FlatMethod fm=state.getMethodFlat(task);
332         super.generateTempStructs(fm, null);
333
334         ParamsObject objectparams=(ParamsObject) paramstable.get(task);
335         TempObject objecttemps=(TempObject) tempstable.get(task);
336
337         /* Output parameter structure */
338         if (GENERATEPRECISEGC) {
339           output.println("struct "+task.getCoreSafeSymbol(num)+"_params {");
340           output.println("  int size;");
341           output.println("  void * next;");
342           for(int j=0; j<objectparams.numPointers(); j++) {
343             TempDescriptor temp=objectparams.getPointer(j);
344             output.println("  struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
345           }
346
347           output.println("};\n");
348           if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
349             maxtaskparams=objectparams.numPointers()+fm.numTags();
350           }
351         }
352
353         /* Output temp structure */
354         if (GENERATEPRECISEGC) {
355           output.println("struct "+task.getCoreSafeSymbol(num)+"_locals {");
356           output.println("  int size;");
357           output.println("  void * next;");
358           for(int j=0; j<objecttemps.numPointers(); j++) {
359             TempDescriptor temp=objecttemps.getPointer(j);
360             if (temp.getType().isNull())
361               output.println("  void * "+temp.getSafeSymbol()+";");
362             else if(temp.getType().isTag())
363               output.println("  struct "+
364                              (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
365             else
366               output.println("  struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
367           }
368           output.println("};\n");
369         }
370
371         /* Output task declaration */
372         headersout.print("void " + task.getCoreSafeSymbol(num)+"(");
373
374         if (GENERATEPRECISEGC) {
375           headersout.print("struct "+task.getCoreSafeSymbol(num)+"_params * "+paramsprefix);
376         } else
377           headersout.print("void * parameterarray[]");
378         headersout.println(");\n");
379       }
380     }
381
382   }
383
384   /* This method outputs code for each task. */
385
386   private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod, PrintWriter outtask, Iterator[] taskits, int[] numtasks,
387                               int[][] numqueues) {
388     /* Compile task based program */
389     outtaskdefs.println("#include \"task.h\"");
390     outtaskdefs.println("#include \"methodheaders.h\"");
391
392     /* Output object transfer queues into method.c*/
393     generateObjectTransQueues(outmethod);
394
395     //Vector[] qnames = new Vector[2];
396     int numclasses = numqueues[0].length;
397     Vector qnames[]= new Vector[numclasses];
398     for(int i = 0; i < qnames.length; ++i) {
399       qnames[i] = null;
400     }
401     Iterator<TaskDescriptor> taskit=this.currentSchedule.getTasks().iterator();
402     while(taskit.hasNext()) {
403       TaskDescriptor td=taskit.next();
404       FlatMethod fm=state.getMethodFlat(td);
405       generateTaskMethod(fm, null, outmethod);
406       generateTaskDescriptor(outtaskdefs, outtask, fm, td, qnames);
407     }
408
409     // generate queuearray for this core
410     int num = this.currentSchedule.getCoreNum();
411     boolean comma = false;
412     for(int i = 0; i < qnames.length; ++i) {
413       outtaskdefs.println("/* object queue array for class " + i + " on core " + num + "*/");
414       outtaskdefs.println("struct parameterwrapper * " + this.objqarrayprefix + i + "_core" + num + "[] = {");
415       comma = false;
416       Vector tmpvector = qnames[i];
417       if(tmpvector != null) {
418         for(int j = 0; j < tmpvector.size(); ++j) {
419           if(comma) {
420             outtaskdefs.println(",");
421           } else {
422             comma = true;
423           }
424           outtaskdefs.print("&" + tmpvector.elementAt(j));
425         }
426         numqueues[num][i] = tmpvector.size();
427       } else {
428         numqueues[num][i] = 0;
429       }
430       outtaskdefs.println("};");
431     }
432
433     /* All the queues for tasks residing on this core*/
434     comma = false;
435     outtaskdefs.println("/* object queue array for tasks on core " + num + "*/");
436     outtaskdefs.println("struct parameterwrapper ** " + this.coreqarrayprefix + num + "[] = {");
437     taskit=this.currentSchedule.getTasks().iterator();
438     while(taskit.hasNext()) {
439       if (comma) {
440         outtaskdefs.println(",");
441       } else {
442         comma = true;
443       }
444       TaskDescriptor td=taskit.next();
445       outtaskdefs.print(this.paramqarrayprefix + td.getCoreSafeSymbol(num));
446     }
447     outtaskdefs.println("};");
448
449     // record the iterator of tasks on this core
450     taskit=this.currentSchedule.getTasks().iterator();
451     taskits[num] = taskit;
452     numtasks[num] = this.currentSchedule.getTasks().size();
453   }
454
455   /** Prints out definitions for generic task structures */
456   private void outputTaskTypes(PrintWriter outtask) {
457     outtask.println("#ifndef _TASK_H");
458     outtask.println("#define _TASK_H");
459     outtask.println("#include \"ObjectHash.h\"");
460     outtask.println("#include \"structdefs.h\"");
461     outtask.println("#include \"Queue.h\"");
462     outtask.println("#include <string.h>");
463     outtask.println("#ifdef RAW");
464     outtask.println("#include <raw.h>");
465     outtask.println("#endif");
466     outtask.println();
467     outtask.println("struct tagobjectiterator {");
468     outtask.println("  int istag; /* 0 if object iterator, 1 if tag iterator */");
469     outtask.println("  struct ObjectIterator it; /* Object iterator */");
470     outtask.println("  struct ObjectHash * objectset;");
471     outtask.println("#ifdef OPTIONAL");
472     outtask.println("  int failedstate;");
473     outtask.println("#endif");
474     outtask.println("  int slot;");
475     outtask.println("  int tagobjindex; /* Index for tag or object depending on use */");
476     outtask.println("  /*if tag we have an object binding */");
477     outtask.println("  int tagid;");
478     outtask.println("  int tagobjectslot;");
479     outtask.println("  /*if object, we may have one or more tag bindings */");
480     outtask.println("  int numtags;");
481     outtask.println("  int tagbindings[MAXTASKPARAMS-1]; /* list slots */");
482     outtask.println("};");
483     outtask.println();
484     outtask.println("struct parameterwrapper {");
485     outtask.println("  //int type;");
486     outtask.println("  struct ObjectHash * objectset;");
487     outtask.println("  int numberofterms;");
488     outtask.println("  int * intarray;");
489     outtask.println("  int numbertags;");
490     outtask.println("  int * tagarray;");
491     outtask.println("  struct taskdescriptor * task;");
492     outtask.println("  int slot;");
493     outtask.println("  struct tagobjectiterator iterators[MAXTASKPARAMS-1];");
494     outtask.println("};");
495     outtask.println();
496     outtask.println("extern struct parameterwrapper ** objectqueues[][NUMCLASSES];");
497     outtask.println("extern int numqueues[][NUMCLASSES];");
498     outtask.println();
499     outtask.println("struct parameterdescriptor {");
500     outtask.println("  int type;");
501     outtask.println("  int numberterms;");
502     outtask.println("  int *intarray;");
503     outtask.println("  struct parameterwrapper * queue;");
504     outtask.println("  int numbertags;");
505     outtask.println("  int *tagarray;");
506     outtask.println("};");
507     outtask.println();
508     outtask.println("struct taskdescriptor {");
509     outtask.println("  void * taskptr;");
510     outtask.println("  int numParameters;");
511     outtask.println("  int numTotal;");
512     outtask.println("  struct parameterdescriptor **descriptorarray;");
513     outtask.println("  char * name;");
514     outtask.println("};");
515     outtask.println();
516     outtask.println("extern struct taskdescriptor ** taskarray[];");
517     outtask.println("extern int numtasks[];");
518     outtask.println("extern int corenum;");     // define corenum to identify different core
519     outtask.println("extern struct parameterwrapper *** paramqueues[];");
520     outtask.println();
521   }
522
523   private void generateObjectTransQueues(PrintWriter output) {
524     if(this.fsate2qnames == null) {
525       this.fsate2qnames = new Hashtable[this.coreNum];
526       for(int i = 0; i < this.fsate2qnames.length; ++i) {
527         this.fsate2qnames[i] = null;
528       }
529     }
530     int num = this.currentSchedule.getCoreNum();
531     assert(this.fsate2qnames[num] == null);
532     Hashtable<FlagState, String> flag2qname = new Hashtable<FlagState, String>();
533     this.fsate2qnames[num] = flag2qname;
534     Hashtable<FlagState, Queue<Integer>> targetCoreTbl = this.currentSchedule.getTargetCoreTable();
535     if(targetCoreTbl != null) {
536       Object[] keys = targetCoreTbl.keySet().toArray();
537       output.println();
538       output.println("/* Object transfer queues for core" + num + ".*/");
539       for(int i = 0; i < keys.length; ++i) {
540         FlagState tmpfstate = (FlagState)keys[i];
541         Object[] targetcores = targetCoreTbl.get(tmpfstate).toArray();
542         String queuename = this.otqueueprefix + tmpfstate.getClassDescriptor().getCoreSafeSymbol(num) + tmpfstate.getuid() + "___";
543         String queueins = queuename + "ins";
544         flag2qname.put(tmpfstate, queuename);
545         output.println("struct " + queuename + " {");
546         output.println("  int * cores;");
547         output.println("  int index;");
548         output.println("  int length;");
549         output.println("};");
550         output.print("int " + queuename + "cores[] = {");
551         for(int j = 0; j < targetcores.length; ++j) {
552           if(j > 0) {
553             output.print(", ");
554           }
555           output.print(((Integer)targetcores[j]).intValue());
556         }
557         output.println("};");
558         output.println("struct " + queuename + " " + queueins + "= {");
559         output.println(/*".cores = " + */ queuename + "cores,");
560         output.println(/*".index = " + */ "0,");
561         output.println(/*".length = " +*/ targetcores.length + "};");
562       }
563     }
564     output.println();
565   }
566
567   private void generateTaskMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
568     /*if (State.PRINTFLAT)
569         System.out.println(fm.printMethod());*/
570     TaskDescriptor task=fm.getTask();
571     assert(task != null);
572     int num = this.currentSchedule.getCoreNum();
573
574     //ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null?lb:task);
575     generateTaskHeader(fm, lb, task,output);
576     TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : task);
577     /*if (state.DSM&&lb.getHasAtomic()) {
578         output.println("transrecord_t * trans;");
579        }*/
580
581     if (GENERATEPRECISEGC) {
582       output.print("   struct "+task.getCoreSafeSymbol(num)+"_locals "+localsprefix+"={");
583
584       output.print(objecttemp.numPointers()+",");
585       output.print(paramsprefix);
586       for(int j=0; j<objecttemp.numPointers(); j++)
587         output.print(", NULL");
588       output.println("};");
589     }
590
591     for(int i=0; i<objecttemp.numPrimitives(); i++) {
592       TempDescriptor td=objecttemp.getPrimitive(i);
593       TypeDescriptor type=td.getType();
594       if (type.isNull())
595         output.println("   void * "+td.getSafeSymbol()+";");
596       else if (type.isClass()||type.isArray())
597         output.println("   struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
598       else
599         output.println("   "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
600     }
601
602     for(int i = 0; i < fm.numParameters(); ++i) {
603       TempDescriptor temp = fm.getParameter(i);
604       output.println("   int "+generateTempFlagName(fm, temp, lb)+" = "+super.generateTemp(fm, temp, lb)+
605                      "->flag;");
606     }
607
608     /* Assign labels to FlatNode's if necessary.*/
609
610     Hashtable<FlatNode, Integer> nodetolabel=super.assignLabels(fm);
611
612     /* Check to see if we need to do a GC if this is a
613      * multi-threaded program...*/
614
615     /*if ((state.THREAD||state.DSM)&&GENERATEPRECISEGC) {
616         if (state.DSM&&lb.isAtomic())
617             output.println("checkcollect2(&"+localsprefix+",trans);");
618         else
619             output.println("checkcollect(&"+localsprefix+");");
620        }*/
621
622     /* Create queues to store objects need to be transferred to other cores and their destination*/
623     output.println("   struct Queue * totransobjqueue = createQueue();");
624     output.println("   struct transObjInfo * tmpObjInfo = NULL;");
625
626     this.m_aliasSets = null;
627     this.m_aliasFNTbl4Para = null;
628     this.m_aliasFNTbl = null;
629     this.m_aliaslocksTbl4FN = null;
630     outputAliasLockCode(fm, lb, output);
631
632     /* generate print information for RAW version */
633     output.println("#ifdef RAW");
634     output.println("{");
635     output.println("int tmpsum = 0;");
636     output.println("char * taskname = \"" + task.getSymbol() + "\";");
637     output.println("int tmplen = " + task.getSymbol().length() + ";");
638     output.println("int tmpindex = 1;");
639     output.println("for(;tmpindex < tmplen; tmpindex++) {");
640     output.println("   tmpsum = tmpsum * 10 + *(taskname + tmpindex) - '0';");
641     output.println("}");
642     output.println("#ifdef RAWPATH");
643     output.println("raw_test_pass(0xAAAA);");
644     output.println("raw_test_pass_reg(tmpsum);");
645     output.println("#endif");
646     output.println("#ifdef RAWDEBUG");
647     output.println("raw_test_pass(0xAAAA);");
648     output.println("raw_test_pass_reg(tmpsum);");
649     output.println("#endif");
650     output.println("}");
651     output.println("#endif");
652
653     for(int i = 0; i < fm.numParameters(); ++i) {
654       TempDescriptor temp = fm.getParameter(i);
655       output.println("   ++" + super.generateTemp(fm, temp, lb)+"->version;");
656     }
657
658     /* Do the actual code generation */
659     FlatNode current_node=null;
660     HashSet tovisit=new HashSet();
661     HashSet visited=new HashSet();
662     tovisit.add(fm.getNext(0));
663     while(current_node!=null||!tovisit.isEmpty()) {
664       if (current_node==null) {
665         current_node=(FlatNode)tovisit.iterator().next();
666         tovisit.remove(current_node);
667       }
668       visited.add(current_node);
669       if (nodetolabel.containsKey(current_node))
670         output.println("L"+nodetolabel.get(current_node)+":");
671       /*if (state.INSTRUCTIONFAILURE) {
672           if (state.THREAD||state.DSM) {
673               output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
674           }
675           else
676               output.println("if ((--instructioncount)==0) injectinstructionfailure();");
677          }*/
678       if (current_node.numNext()==0) {
679         output.print("   ");
680         super.generateFlatNode(fm, lb, current_node, output);
681         if (current_node.kind()!=FKind.FlatReturnNode) {
682           //output.println("   flushAll();");
683           output.println("#ifdef RAW");
684           output.println("raw_user_interrupts_off();");
685           output.println("#ifdef RAWDEBUG");
686           output.println("raw_test_pass(0xec00);");
687           output.println("#endif");
688           output.println("raw_flush_entire_cache();");
689           output.println("#ifdef RAWDEBUG");
690           output.println("raw_test_pass(0xecff);");
691           output.println("#endif");
692           output.println("raw_user_interrupts_on();");
693           output.println("#endif");
694           outputTransCode(output);
695           output.println("   return;");
696         }
697         current_node=null;
698       } else if(current_node.numNext()==1) {
699         output.print("   ");
700         super.generateFlatNode(fm, lb, current_node, output);
701         FlatNode nextnode=current_node.getNext(0);
702         if (visited.contains(nextnode)) {
703           output.println("goto L"+nodetolabel.get(nextnode)+";");
704           current_node=null;
705         } else
706           current_node=nextnode;
707       } else if (current_node.numNext()==2) {
708         /* Branch */
709         output.print("   ");
710         super.generateFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
711         if (!visited.contains(current_node.getNext(1)))
712           tovisit.add(current_node.getNext(1));
713         if (visited.contains(current_node.getNext(0))) {
714           output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
715           current_node=null;
716         } else
717           current_node=current_node.getNext(0);
718       } else throw new Error();
719     }
720
721     output.println("}\n\n");
722   }
723
724   /** This method outputs TaskDescriptor information */
725   private void generateTaskDescriptor(PrintWriter output, PrintWriter outtask, FlatMethod fm, TaskDescriptor task, Vector[] qnames) {
726     int num = this.currentSchedule.getCoreNum();
727
728     output.println("/* TaskDescriptor information for task " + task.getSymbol() + " on core " + num + "*/");
729
730     for (int i=0; i<task.numParameters(); i++) {
731       VarDescriptor param_var=task.getParameter(i);
732       TypeDescriptor param_type=task.getParamType(i);
733       FlagExpressionNode param_flag=task.getFlag(param_var);
734       TagExpressionList param_tag=task.getTag(param_var);
735
736       int dnfterms;
737       if (param_flag==null) {
738         output.println("int parameterdnf_"+i+"_"+task.getCoreSafeSymbol(num)+"[]={");
739         output.println("0x0, 0x0 };");
740         dnfterms=1;
741       } else {
742         DNFFlag dflag=param_flag.getDNF();
743         dnfterms=dflag.size();
744
745         Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
746         output.println("int parameterdnf_"+i+"_"+task.getCoreSafeSymbol(num)+"[]={");
747         for(int j=0; j<dflag.size(); j++) {
748           if (j!=0)
749             output.println(",");
750           Vector term=dflag.get(j);
751           int andmask=0;
752           int checkmask=0;
753           for(int k=0; k<term.size(); k++) {
754             DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
755             FlagDescriptor fd=dfa.getFlag();
756             boolean negated=dfa.getNegated();
757             int flagid=1<<((Integer)flags.get(fd)).intValue();
758             andmask|=flagid;
759             if (!negated)
760               checkmask|=flagid;
761           }
762           output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
763         }
764         output.println("};");
765       }
766
767       output.println("int parametertag_"+i+"_"+task.getCoreSafeSymbol(num)+"[]={");
768       //BUG...added next line to fix, test with any task program
769       if (param_tag!=null)
770         for(int j=0; j<param_tag.numTags(); j++) {
771           if (j!=0)
772             output.println(",");
773           /* for each tag we need */
774           /* which slot it is */
775           /* what type it is */
776           TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
777           TempDescriptor tmp=param_tag.getTemp(j);
778           int slot=fm.getTagInt(tmp);
779           output.println(slot+", "+state.getTagId(tvd.getTag()));
780         }
781       output.println("};");
782
783       // generate object queue for this parameter
784       String qname = this.objqueueprefix+i+"_"+task.getCoreSafeSymbol(num);
785       if(param_type.getClassDesc().getSymbol().equals("StartupObject")) {
786         this.startupcorenum = num;
787       }
788       if(qnames[param_type.getClassDesc().getId()] == null) {
789         qnames[param_type.getClassDesc().getId()] = new Vector();
790       }
791       qnames[param_type.getClassDesc().getId()].addElement(qname);
792       outtask.println("extern struct parameterwrapper " + qname + ";");
793       output.println("struct parameterwrapper " + qname + "={");
794       output.println(".objectset = 0,");      // objectset
795       output.println("/* number of DNF terms */ .numberofterms = "+dnfterms+",");     // numberofterms
796       output.println(".intarray = parameterdnf_"+i+"_"+task.getCoreSafeSymbol(num)+",");    // intarray
797       // numbertags
798       if (param_tag!=null)
799         output.println("/* number of tags */ .numbertags = "+param_tag.numTags()+",");
800       else
801         output.println("/* number of tags */ .numbertags = 0,");
802       output.println(".tagarray = parametertag_"+i+"_"+task.getCoreSafeSymbol(num)+",");    // tagarray
803       output.println(".task = 0,");      // task
804       output.println(".slot = " + i + ",");    // slot
805       // iterators
806       output.println("};");
807
808       output.println("struct parameterdescriptor parameter_"+i+"_"+task.getCoreSafeSymbol(num)+"={");
809       output.println("/* type */"+param_type.getClassDesc().getId()+",");
810       output.println("/* number of DNF terms */"+dnfterms+",");
811       output.println("parameterdnf_"+i+"_"+task.getCoreSafeSymbol(num)+",");    // intarray
812       output.println("&" + qname + ",");     // queue
813       //BUG, added next line to fix and else statement...test
814       //with any task program
815       if (param_tag!=null)
816         output.println("/* number of tags */"+param_tag.numTags()+",");
817       else
818         output.println("/* number of tags */ 0,");
819       output.println("parametertag_"+i+"_"+task.getCoreSafeSymbol(num));     // tagarray
820       output.println("};");
821     }
822
823     /* parameter queues for this task*/
824     output.println("struct parameterwrapper * " + this.paramqarrayprefix + task.getCoreSafeSymbol(num)+"[] = {");
825     for (int i=0; i<task.numParameters(); i++) {
826       if (i!=0)
827         output.println(",");
828       output.print("&" + this.objqueueprefix + i + "_" + task.getCoreSafeSymbol(num));
829     }
830     output.println("};");
831
832     output.println("struct parameterdescriptor * parameterdescriptors_"+task.getCoreSafeSymbol(num)+"[] = {");
833     for (int i=0; i<task.numParameters(); i++) {
834       if (i!=0)
835         output.println(",");
836       output.print("&parameter_"+i+"_"+task.getCoreSafeSymbol(num));
837     }
838     output.println("};");
839
840     output.println("struct taskdescriptor " + this.taskprefix + task.getCoreSafeSymbol(num) + "={");
841     output.println("&"+task.getCoreSafeSymbol(num)+",");
842     output.println("/* number of parameters */" +task.numParameters() + ",");
843     int numtotal=task.numParameters()+fm.numTags();
844     output.println("/* number total parameters */" +numtotal + ",");
845     output.println("parameterdescriptors_"+task.getCoreSafeSymbol(num)+",");
846     output.println("\""+task.getSymbol()+"\"");
847     output.println("};");
848
849     output.println();
850   }
851
852   /** This method generates header information for the task
853    *  referenced by the Descriptor des. */
854
855   private void generateTaskHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) {
856     /* Print header */
857     ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des);
858     TaskDescriptor task=(TaskDescriptor) des;
859
860     int num = this.currentSchedule.getCoreNum();
861     //catch the constructor case
862     output.print("void ");
863     output.print(task.getCoreSafeSymbol(num)+"(");
864
865     boolean printcomma=false;
866     if (GENERATEPRECISEGC) {
867       output.print("struct "+task.getCoreSafeSymbol(num)+"_params * "+paramsprefix);
868       printcomma=true;
869     }
870
871     /*if (state.DSM&&lb.isAtomic()) {
872         if (printcomma)
873             output.print(", ");
874         output.print("transrecord_t * trans");
875         printcomma=true;
876        }*/
877
878     if (!GENERATEPRECISEGC) {
879       /* Imprecise Task */
880       output.println("void * parameterarray[]) {");
881       /* Unpack variables */
882       for(int i=0; i<objectparams.numPrimitives(); i++) {
883         TempDescriptor temp=objectparams.getPrimitive(i);
884         output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
885       }
886       for(int i=0; i<fm.numTags(); i++) {
887         TempDescriptor temp=fm.getTag(i);
888         int offset=i+objectparams.numPrimitives();
889         output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+i+"___=parameterarray["+offset+"];");     // add i to fix bugs of duplicate definition of tags
890       }
891
892       if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
893         maxtaskparams=objectparams.numPrimitives()+fm.numTags();
894     } else output.println(") {");
895   }
896
897   protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
898                                    PrintWriter output, int ormask, int andmask) {
899     if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
900       output.println("flagorandinit("+super.generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
901     } else {
902       int num = this.currentSchedule.getCoreNum();
903       ClassDescriptor cd = temp.getType().getClassDesc();
904       Vector<FlagState> initfstates = ffan.getInitFStates(cd);
905       for(int i = 0; i < initfstates.size(); ++i) {
906         FlagState tmpFState = initfstates.elementAt(i);
907         output.println("{");
908         QueueInfo qinfo = outputqueues(tmpFState, num, output, false);
909         output.println("flagorand("+super.generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+
910                        ", 0x"+Integer.toHexString(andmask)+", " + qinfo.qname +
911                        ", " + qinfo.length + ");");
912         output.println("}");
913       }
914     }
915   }
916
917   protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp,
918                                           PrintWriter output) {
919     ClassDescriptor cd = temp.getType().getClassDesc();
920     Vector<FlagState> initfstates = null;
921     Vector[] targetFStates = null;
922     if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
923       targetFStates = new Vector[1];
924       targetFStates[0] = ffan.getTargetFStates4NewObj(cd);
925     } else {
926       initfstates = ffan.getInitFStates(cd);
927       targetFStates = new Vector[initfstates.size()];
928       for(int i = 0; i < initfstates.size(); ++i) {
929         FlagState fs = initfstates.elementAt(i);
930         targetFStates[i] = ffan.getTargetFStates(fs);
931
932         if(!fs.isSetmask()) {
933           Hashtable flags=(Hashtable)flagorder.get(cd);
934           int andmask=0;
935           int checkmask=0;
936           Iterator it_flags = fs.getFlags();
937           while(it_flags.hasNext()) {
938             FlagDescriptor fd = (FlagDescriptor)it_flags.next();
939             int flagid=1<<((Integer)flags.get(fd)).intValue();
940             andmask|=flagid;
941             checkmask|=flagid;
942           }
943           fs.setAndmask(andmask);
944           fs.setCheckmask(checkmask);
945           fs.setSetmask(true);
946         }
947       }
948     }
949     boolean isolate = true;     // check if this flagstate can associate to some task with multiple params which can
950                                 // reside on multiple cores
951     if((this.currentSchedule == null) && (fm.getMethod().getClassDesc().getSymbol().equals("ServerSocket"))) {
952       // ServerSocket object will always reside on current core
953       for(int j = 0; j < targetFStates.length; ++j) {
954         if(initfstates != null) {
955           FlagState fs = initfstates.elementAt(j);
956           output.println("if(" + generateTempFlagName(fm, temp, lb) + "&(0x" + Integer.toHexString(fs.getAndmask())
957                          + ")==(0x" + Integer.toHexString(fs.getCheckmask()) + ")) {");
958         }
959         Vector<FlagState> tmpfstates = (Vector<FlagState>)targetFStates[j];
960         for(int i = 0; i < tmpfstates.size(); ++i) {
961           FlagState tmpFState = tmpfstates.elementAt(i);
962           // TODO
963           // may have bugs here
964           output.println("/* reside on this core*");
965           output.println("enqueueObject("+super.generateTemp(fm, temp, lb)+", NULL, 0);");
966         }
967         if(initfstates != null) {
968           output.println("}");
969         }
970       }
971       return;
972     }
973
974     int num = this.currentSchedule.getCoreNum();
975     Hashtable<FlagState, Queue<Integer>> targetCoreTbl = this.currentSchedule.getTargetCoreTable();
976     for(int j = 0; j < targetFStates.length; ++j) {
977       FlagState fs = null;
978       if(initfstates != null) {
979         fs = initfstates.elementAt(j);
980         output.println("if((" + generateTempFlagName(fm, temp, lb) + "&(0x" + Integer.toHexString(fs.getAndmask())
981                        + "))==(0x" + Integer.toHexString(fs.getCheckmask()) + ")) {");
982       }
983       Vector<FlagState> tmpfstates = (Vector<FlagState>)targetFStates[j];
984       for(int i = 0; i < tmpfstates.size(); ++i) {
985         FlagState tmpFState = tmpfstates.elementAt(i);
986
987         if(this.currentSchedule.getAllyCoreTable() == null) {
988           isolate = true;
989         } else {
990           isolate = (this.currentSchedule.getAllyCoreTable().get(tmpFState) == null) ||
991                     (this.currentSchedule.getAllyCoreTable().get(tmpFState).size() == 0);
992         }
993         if(!isolate) {
994           // indentify this object as a shared object
995           // isolate flag is initially set as 1, once this flag is set as 0, it is never reset to 1, i.e. once an object
996           // is shared, it maybe shared all the time afterwards
997           output.println("if(" + super.generateTemp(fm, temp, lb) + "->isolate == 1) {");
998           output.println("  " + super.generateTemp(fm, temp, lb) + "->isolate = 0;");
999           output.println("  " + super.generateTemp(fm, temp, lb) + "->original = (struct ___Object___ *)" + super.generateTemp(fm, temp, lb) + ";");
1000           output.println("}");
1001         }
1002
1003         Vector<TranObjInfo> sendto = new Vector<TranObjInfo>();
1004         Queue<Integer> queue = null;
1005         if(targetCoreTbl != null) {
1006           queue = targetCoreTbl.get(tmpFState);
1007         }
1008         if((queue != null) &&
1009            ((queue.size() != 1) ||
1010             ((queue.size() == 1) && (queue.element().intValue() != num)))) {
1011           // this object may be transferred to other cores
1012           String queuename = (String) this.fsate2qnames[num].get(tmpFState);
1013           String queueins = queuename + "ins";
1014
1015           Object[] cores = queue.toArray();
1016           String index = "0";
1017           Integer targetcore = (Integer)cores[0];
1018           if(queue.size() > 1) {
1019             index = queueins + ".index";
1020           }
1021           if(queue.size() > 1) {
1022             output.println("switch(" + queueins + ".index % " + queueins + ".length) {");
1023             for(int k = 0; k < cores.length; ++k) {
1024               output.println("case " + k + ":");
1025               targetcore = (Integer)cores[k];
1026               if(targetcore.intValue() == num) {
1027                 output.println("/* reside on this core*/");
1028                 if(isolate) {
1029                   output.println("{");
1030                   QueueInfo qinfo = outputqueues(tmpFState, num, output, true);
1031                   output.println("enqueueObject("+super.generateTemp(fm, temp, lb)+", " + qinfo.qname +
1032                                  ", " + qinfo.length + ");");
1033                   output.println("}");
1034                 } else {
1035                   // TODO
1036                   // really needed?
1037                   output.println("/* possibly needed by multi-parameter tasks on this core*/");
1038                   output.println("enqueueObject("+super.generateTemp(fm, temp, lb)+", NULL, 0);");
1039                 }
1040               } else {
1041                 if(!isolate) {
1042                   // TODO
1043                   // Is it possible to decide the actual queues?
1044                   output.println("/* possibly needed by multi-parameter tasks on this core*/");
1045                   output.println("enqueueObject("+super.generateTemp(fm, temp, lb)+", NULL, 0);");
1046                 }
1047                 output.println("/* transfer to core " + targetcore.toString() + "*/");
1048                 output.println("{");
1049                 // enqueue this object and its destinations for later process
1050                 // all the possible queues
1051                 QueueInfo qinfo = null;
1052                 TranObjInfo tmpinfo = new TranObjInfo();
1053                 tmpinfo.name = super.generateTemp(fm, temp, lb);
1054                 tmpinfo.targetcore = targetcore;
1055                 FlagState targetFS = this.currentSchedule.getTargetFState(tmpFState);
1056                 if(targetFS != null) {
1057                   tmpinfo.fs = targetFS;
1058                 } else {
1059                   tmpinfo.fs = tmpFState;
1060                 }
1061                 if(!contains(sendto, tmpinfo)) {
1062                   qinfo = outputtransqueues(tmpinfo.fs, targetcore, output);
1063                   output.println("tmpObjInfo = RUNMALLOC(sizeof(struct transObjInfo));");
1064                   output.println("tmpObjInfo->objptr = (void *)" + tmpinfo.name + ";");
1065                   output.println("tmpObjInfo->targetcore = "+targetcore.toString()+";");
1066                   output.println("tmpObjInfo->queues = " + qinfo.qname + ";");
1067                   output.println("tmpObjInfo->length = " + qinfo.length + ";");
1068                   output.println("addNewItem(totransobjqueue, (void*)tmpObjInfo);");
1069                   sendto.add(tmpinfo);
1070                 }
1071                 output.println("}");
1072               }
1073               output.println("break;");
1074             }
1075             output.println("}");
1076           } else {
1077             if(!isolate) {
1078               // TODO
1079               // Is it possible to decide the actual queues?
1080               output.println("/* possibly needed by multi-parameter tasks on this core*/");
1081               output.println("enqueueObject("+super.generateTemp(fm, temp, lb)+", NULL, 0);");
1082             }
1083             output.println("/* transfer to core " + targetcore.toString() + "*/");
1084             output.println("{");
1085             // enqueue this object and its destinations for later process
1086             // all the possible queues
1087             QueueInfo qinfo = null;
1088             TranObjInfo tmpinfo = new TranObjInfo();
1089             tmpinfo.name = super.generateTemp(fm, temp, lb);
1090             tmpinfo.targetcore = targetcore;
1091             FlagState targetFS = this.currentSchedule.getTargetFState(tmpFState);
1092             if(targetFS != null) {
1093               tmpinfo.fs = targetFS;
1094             } else {
1095               tmpinfo.fs = tmpFState;
1096             }
1097             if(!contains(sendto, tmpinfo)) {
1098               qinfo = outputtransqueues(tmpinfo.fs, targetcore, output);
1099               output.println("tmpObjInfo = RUNMALLOC(sizeof(struct transObjInfo));");
1100               output.println("tmpObjInfo->objptr = (void *)" + tmpinfo.name + ";");
1101               output.println("tmpObjInfo->targetcore = "+targetcore.toString()+";");
1102               output.println("tmpObjInfo->queues = " + qinfo.qname + ";");
1103               output.println("tmpObjInfo->length = " + qinfo.length + ";");
1104               output.println("addNewItem(totransobjqueue, (void*)tmpObjInfo);");
1105               sendto.add(tmpinfo);
1106             }
1107             output.println("}");
1108           }
1109           output.println("/* increase index*/");
1110           output.println("++" + queueins + ".index;");
1111         } else {
1112           // this object will reside on current core
1113           output.println("/* reside on this core*/");
1114           if(isolate) {
1115             output.println("{");
1116             QueueInfo qinfo = outputqueues(tmpFState, num, output, true);
1117             output.println("enqueueObject("+super.generateTemp(fm, temp, lb)+", " + qinfo.qname +
1118                            ", " + qinfo.length + ");");
1119             output.println("}");
1120           } else {
1121             // TODO
1122             // really needed?
1123             output.println("enqueueObject("+super.generateTemp(fm, temp, lb)+", NULL, 0);");
1124           }
1125         }
1126
1127         // codes for multi-params tasks
1128         if(!isolate) {
1129           // flagstate associated with some multi-params tasks
1130           // need to be send to other cores
1131           Vector<Integer> targetcores = this.currentSchedule.getAllyCores(tmpFState);
1132           output.println("/* send the shared object to possible queues on other cores*/");
1133           for(int k = 0; k < targetcores.size(); ++k) {
1134             // TODO
1135             // add the information of exactly which queue
1136             //if(!sendto.contains(targetcores.elementAt(i))) {
1137             // previously not sended to this target core
1138             // enqueue this object and its destinations for later process
1139             output.println("{");
1140             // all the possible queues
1141             QueueInfo qinfo = null;
1142             TranObjInfo tmpinfo = new TranObjInfo();
1143             tmpinfo.name = super.generateTemp(fm, temp, lb);
1144             tmpinfo.targetcore = targetcores.elementAt(i);
1145             FlagState targetFS = this.currentSchedule.getTargetFState(tmpFState);
1146             if(targetFS != null) {
1147               tmpinfo.fs = targetFS;
1148             } else {
1149               tmpinfo.fs = tmpFState;
1150             }
1151             if(!contains(sendto, tmpinfo)) {
1152               qinfo = outputtransqueues(tmpinfo.fs, targetcores.elementAt(i), output);
1153               output.println("tmpObjInfo = RUNMALLOC(sizeof(struct transObjInfo));");
1154               output.println("tmpObjInfo->objptr = (void *)" + tmpinfo.name + ";");
1155               output.println("tmpObjInfo->targetcore = "+targetcores.elementAt(i).toString()+";");
1156               output.println("tmpObjInfo->queues = " + qinfo.qname + ";");
1157               output.println("tmpObjInfo->length = " + qinfo.length + ";");
1158               output.println("addNewItem(totransobjqueue, (void*)tmpObjInfo);");
1159               sendto.add(tmpinfo);
1160             }
1161             output.println("}");
1162             //}
1163           }
1164         }
1165       }
1166
1167       if(initfstates != null) {
1168         output.println("}");
1169       }
1170     }
1171   }
1172
1173   private QueueInfo outputqueues(FlagState tmpFState, int num, PrintWriter output, boolean isEnqueue) {
1174     // queue array
1175     QueueInfo qinfo = new QueueInfo();
1176     qinfo.qname  = "queues_" + tmpFState.getLabel() + "_" + tmpFState.getiuid();
1177     output.println("struct parameterwrapper * " + qinfo.qname + "[] = {");
1178     Iterator it_edges = tmpFState.getEdgeVector().iterator();
1179     Vector<TaskDescriptor> residetasks = this.currentSchedule.getTasks();
1180     Vector<TaskDescriptor> tasks = new Vector<TaskDescriptor>();
1181     Vector<Integer> indexes = new Vector<Integer>();
1182     boolean comma = false;
1183     qinfo.length = 0;
1184     while(it_edges.hasNext()) {
1185       FEdge fe = (FEdge)it_edges.next();
1186       TaskDescriptor td = fe.getTask();
1187       int paraindex = fe.getIndex();
1188       if((!isEnqueue) || (isEnqueue && residetasks.contains(td))) {
1189         if((!tasks.contains(td)) ||
1190            ((tasks.contains(td)) && (paraindex != indexes.elementAt(tasks.indexOf(td)).intValue()))) {
1191           tasks.addElement(td);
1192           indexes.addElement(paraindex);
1193           if(comma) {
1194             output.println(",");
1195           } else {
1196             comma = true;
1197           }
1198           output.print("&" + this.objqueueprefix + paraindex + "_" + td.getCoreSafeSymbol(num));
1199           ++qinfo.length;
1200         }
1201       }
1202     }
1203     output.println("};");
1204     return qinfo;
1205   }
1206
1207   private QueueInfo outputtransqueues(FlagState tmpFState, int targetcore, PrintWriter output) {
1208     // queue array
1209     QueueInfo qinfo = new QueueInfo();
1210     qinfo.qname  = "queues_" + tmpFState.getLabel() + "_" + tmpFState.getiuid();
1211     output.println("int " + qinfo.qname + "_clone[] = {");
1212     Iterator it_edges = tmpFState.getEdgeVector().iterator();
1213     Vector<TaskDescriptor> residetasks = this.scheduling.get(targetcore).getTasks();
1214     Vector<TaskDescriptor> tasks = new Vector<TaskDescriptor>();
1215     Vector<Integer> indexes = new Vector<Integer>();
1216     boolean comma = false;
1217     qinfo.length = 0;
1218     while(it_edges.hasNext()) {
1219       FEdge fe = (FEdge)it_edges.next();
1220       TaskDescriptor td = fe.getTask();
1221       int paraindex = fe.getIndex();
1222       if(residetasks.contains(td)) {
1223         if((!tasks.contains(td)) ||
1224            ((tasks.contains(td)) && (paraindex != indexes.elementAt(tasks.indexOf(td)).intValue()))) {
1225           tasks.addElement(td);
1226           indexes.addElement(paraindex);
1227           if(comma) {
1228             output.println(",");
1229           } else {
1230             comma = true;
1231           }
1232           output.print(residetasks.indexOf(td) + ", ");
1233           output.print(paraindex);
1234           ++qinfo.length;
1235         }
1236       }
1237     }
1238     output.println("};");
1239     output.println("int * " + qinfo.qname + " = RUNMALLOC(sizeof(int) * " + qinfo.length * 2 + ");");
1240     output.println("memcpy(" + qinfo.qname + ", (int *)" + qinfo.qname + "_clone, sizeof(int) * " + qinfo.length * 2 + ");");
1241     return qinfo;
1242   }
1243
1244   private class QueueInfo {
1245     public int length;
1246     public String qname;
1247   }
1248
1249   private String generateTempFlagName(FlatMethod fm, TempDescriptor td, LocalityBinding lb) {
1250     MethodDescriptor md=fm.getMethod();
1251     TaskDescriptor task=fm.getTask();
1252     TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task);
1253
1254     if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
1255       return td.getSafeSymbol() + "_oldflag";
1256     }
1257
1258     if (objecttemps.isLocalPtr(td)) {
1259       return localsprefix+"_"+td.getSafeSymbol() + "_oldflag";
1260     }
1261
1262     if (objecttemps.isParamPtr(td)) {
1263       return paramsprefix+"_"+td.getSafeSymbol() + "_oldflag";
1264     }
1265     throw new Error();
1266   }
1267
1268   protected void outputTransCode(PrintWriter output) {
1269     output.println("while(0 == isEmpty(totransobjqueue)) {");
1270     output.println("   struct QueueItem * totransitem = getTail(totransobjqueue);");
1271
1272     output.println("   transferObject((struct transObjInfo *)(totransitem->objectptr));");
1273     output.println("   RUNFREE(((struct transObjInfo *)(totransitem->objectptr))->queues);");
1274     output.println("   RUNFREE(totransitem->objectptr);");
1275     output.println("   removeItem(totransobjqueue, totransitem);");
1276     output.println("}");
1277     output.println("freeQueue(totransobjqueue);");
1278   }
1279
1280   protected void outputAliasLockCode(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
1281     if(this.m_oa == null) {
1282       return;
1283     }
1284     TaskDescriptor td = fm.getTask();
1285     Object[] allocSites = this.m_oa.getFlaggedAllocationSitesReachableFromTask(td).toArray();
1286     Vector<Vector<Integer>> aliasSets = new Vector<Vector<Integer>>();
1287     Vector<Vector<FlatNew>> aliasFNSets = new Vector<Vector<FlatNew>>();
1288     Hashtable<Integer, Vector<FlatNew>> aliasFNTbl4Para = new Hashtable<Integer, Vector<FlatNew>>();
1289     Hashtable<FlatNew, Vector<FlatNew>> aliasFNTbl = new Hashtable<FlatNew, Vector<FlatNew>>();
1290     for( int i = 0; i < fm.numParameters(); ++i ) {
1291       // for the ith parameter check for aliases to all
1292       // higher numbered parameters
1293       aliasSets.add(null);
1294       for( int j = i + 1; j < fm.numParameters(); ++j ) {
1295         if(this.m_oa.createsPotentialAliases(td, i, j)) {
1296           // ith parameter and jth parameter has alias, create lock to protect them
1297           if(aliasSets.elementAt(i) == null) {
1298             aliasSets.setElementAt(new Vector<Integer>(), i);
1299           }
1300           aliasSets.elementAt(i).add(j);
1301         }
1302       }
1303
1304       // for the ith parameter, check for aliases against
1305       // the set of allocation sites reachable from this
1306       // task context
1307       aliasFNSets.add(null);
1308       for(int j = 0; j < allocSites.length; j++) {
1309         AllocationSite as = (AllocationSite)allocSites[j];
1310         if( this.m_oa.createsPotentialAliases(td, i, as) ) {
1311           // ith parameter and allocationsite as has alias
1312           if(aliasFNSets.elementAt(i) == null) {
1313             aliasFNSets.setElementAt(new Vector<FlatNew>(), i);
1314           }
1315           aliasFNSets.elementAt(i).add(as.getFlatNew());
1316         }
1317       }
1318     }
1319
1320     // for each allocation site check for aliases with
1321     // other allocation sites in the context of execution
1322     // of this task
1323     for( int i = 0; i < allocSites.length; ++i ) {
1324       AllocationSite as1 = (AllocationSite)allocSites[i];
1325       for(int j = i + 1; j < allocSites.length; j++) {
1326         AllocationSite as2 = (AllocationSite)allocSites[j];
1327
1328         if( this.m_oa.createsPotentialAliases(td, as1, as2) ) {
1329           // as1 and as2 has alias
1330           if(!aliasFNTbl.contains(as1.getFlatNew())) {
1331             aliasFNTbl.put(as1.getFlatNew(), new Vector<FlatNew>());
1332           }
1333           if(!aliasFNTbl.get(as1.getFlatNew()).contains(as2.getFlatNew())) {
1334             aliasFNTbl.get(as1.getFlatNew()).add(as2.getFlatNew());
1335           }
1336         }
1337       }
1338     }
1339
1340     // if FlatNew N1->N2->N3, we group N1, N2, N3 together
1341     Iterator<FlatNew> it = aliasFNTbl.keySet().iterator();
1342     Vector<FlatNew> visited = new Vector<FlatNew>();
1343     while(it.hasNext()) {
1344       FlatNew tmpfn = it.next();
1345       if(visited.contains(tmpfn)) {
1346         continue;
1347       }
1348       visited.add(tmpfn);
1349       Queue<FlatNew> tovisit = new LinkedList<FlatNew>();
1350       Vector<FlatNew> tmpv = aliasFNTbl.get(tmpfn);
1351       if(tmpv == null) {
1352         continue;
1353       }
1354
1355       for(int j = 0; j < tmpv.size(); j++) {
1356         tovisit.add(tmpv.elementAt(j));
1357       }
1358
1359       while(!tovisit.isEmpty()) {
1360         FlatNew fn = tovisit.poll();
1361         visited.add(fn);
1362         Vector<FlatNew> tmpset = aliasFNTbl.get(fn);
1363         if(tmpset != null) {
1364           // merge tmpset to the alias set of the ith parameter
1365           for(int j = 0; j < tmpset.size(); j++) {
1366             if(!tmpv.contains(tmpset.elementAt(j))) {
1367               tmpv.add(tmpset.elementAt(j));
1368               tovisit.add(tmpset.elementAt(j));
1369             }
1370           }
1371           aliasFNTbl.remove(fn);
1372         }
1373       }
1374       it = aliasFNTbl.keySet().iterator();
1375     }
1376
1377     // check alias between parameters and between parameter-flatnew
1378     for(int i = 0; i < aliasSets.size(); i++) {
1379       Queue<Integer> tovisit = new LinkedList<Integer>();
1380       Vector<Integer> tmpv = aliasSets.elementAt(i);
1381       if(tmpv == null) {
1382         continue;
1383       }
1384
1385       for(int j = 0; j < tmpv.size(); j++) {
1386         tovisit.add(tmpv.elementAt(j));
1387       }
1388
1389       while(!tovisit.isEmpty()) {
1390         int index = tovisit.poll().intValue();
1391         Vector<Integer> tmpset = aliasSets.elementAt(index);
1392         if(tmpset != null) {
1393           // merge tmpset to the alias set of the ith parameter
1394           for(int j = 0; j < tmpset.size(); j++) {
1395             if(!tmpv.contains(tmpset.elementAt(j))) {
1396               tmpv.add(tmpset.elementAt(j));
1397               tovisit.add(tmpset.elementAt(j));
1398             }
1399           }
1400           aliasSets.setElementAt(null, index);
1401         }
1402
1403         Vector<FlatNew> tmpFNSet = aliasFNSets.elementAt(index);
1404         if(tmpFNSet != null) {
1405           // merge tmpFNSet to the aliasFNSet of the ith parameter
1406           if(aliasFNSets.elementAt(i) == null) {
1407             aliasFNSets.setElementAt(tmpFNSet, i);
1408           } else {
1409             Vector<FlatNew> tmpFNv = aliasFNSets.elementAt(i);
1410             for(int j = 0; j < tmpFNSet.size(); j++) {
1411               if(!tmpFNv.contains(tmpFNSet.elementAt(j))) {
1412                 tmpFNv.add(tmpFNSet.elementAt(j));
1413               }
1414             }
1415           }
1416           aliasFNSets.setElementAt(null, index);
1417         }
1418       }
1419     }
1420
1421     int numlock = 0;
1422     int numparalock = 0;
1423     Vector<Vector<Integer>> tmpaliasSets = new Vector<Vector<Integer>>();
1424     for(int i = 0; i < aliasSets.size(); i++) {
1425       Vector<Integer> tmpv = aliasSets.elementAt(i);
1426       if(tmpv != null) {
1427         tmpv.add(0, i);
1428         tmpaliasSets.add(tmpv);
1429         numlock++;
1430       }
1431
1432       Vector<FlatNew> tmpFNv = aliasFNSets.elementAt(i);
1433       if(tmpFNv != null) {
1434         aliasFNTbl4Para.put(i, tmpFNv);
1435         if(tmpv == null) {
1436           numlock++;
1437         }
1438       }
1439     }
1440     numparalock = numlock;
1441     aliasSets.clear();
1442     aliasSets = null;
1443     this.m_aliasSets = tmpaliasSets;
1444     tmpaliasSets.clear();
1445     tmpaliasSets = null;
1446     aliasFNSets.clear();
1447     aliasFNSets = null;
1448     this.m_aliasFNTbl4Para = aliasFNTbl4Para;
1449     this.m_aliasFNTbl = aliasFNTbl;
1450     numlock += this.m_aliasFNTbl.size();
1451
1452     // create locks
1453     if(numlock > 0) {
1454       output.println("int aliaslocks[" + numlock + "];");
1455       output.println("int tmpi = 0;");
1456       output.println("for(tmpi = 0; tmpi < " + numlock + "; tmpi++) {");
1457       output.println("  aliaslocks[tmpi] = (int)(RUNMALLOC(sizeof(int)));");
1458       output.println("  *(int *)(aliaslocks[tmpi]) = 0;");
1459       output.println("}");
1460       // associate locks with parameters
1461       int lockindex = 0;
1462       for(int i = 0; i < this.m_aliasSets.size(); i++) {
1463         Vector<Integer> toadd = this.m_aliasSets.elementAt(i);
1464         for(int j = 0; j < toadd.size(); j++) {
1465           int para = toadd.elementAt(j).intValue();
1466           output.println("addAliasLock("  + super.generateTemp(fm, fm.getParameter(para), lb) + ", aliaslocks[" + i + "]);");
1467         }
1468         // check if this lock is also associated with any FlatNew nodes
1469         if(this.m_aliasFNTbl4Para.contains(toadd.elementAt(0))) {
1470           if(this.m_aliaslocksTbl4FN == null) {
1471             this.m_aliaslocksTbl4FN = new Hashtable<FlatNew, Vector<Integer>>();
1472           }
1473           Vector<FlatNew> tmpv = this.m_aliasFNTbl4Para.get(toadd.elementAt(0));
1474           for(int j = 0; j < tmpv.size(); j++) {
1475             FlatNew fn = tmpv.elementAt(j);
1476             if(!this.m_aliaslocksTbl4FN.contains(fn)) {
1477               this.m_aliaslocksTbl4FN.put(fn, new Vector<Integer>());
1478             }
1479             this.m_aliaslocksTbl4FN.get(fn).add(i);
1480           }
1481           this.m_aliasFNTbl4Para.remove(toadd.elementAt(0));
1482         }
1483         lockindex++;
1484       }
1485       Object[] key = this.m_aliasFNTbl4Para.keySet().toArray();
1486       for(int i = 0; i < key.length; i++) {
1487         int para = ((Integer)key[i]).intValue();
1488         output.println("addAliasLock(" + super.generateTemp(fm, fm.getParameter(para), lb) + ", aliaslocks[" + lockindex + "]);");
1489         Vector<FlatNew> tmpv = this.m_aliasFNTbl4Para.get(para);
1490         for(int j = 0; j < tmpv.size(); j++) {
1491           FlatNew fn = tmpv.elementAt(j);
1492           if(this.m_aliaslocksTbl4FN == null) {
1493             this.m_aliaslocksTbl4FN = new Hashtable<FlatNew, Vector<Integer>>();
1494           }
1495           if(!this.m_aliaslocksTbl4FN.contains(fn)) {
1496             this.m_aliaslocksTbl4FN.put(fn, new Vector<Integer>());
1497           }
1498           this.m_aliaslocksTbl4FN.get(fn).add(lockindex);
1499         }
1500         lockindex++;
1501       }
1502       // check m_aliasFNTbl for locks associated with FlatNew nodes
1503       Object[] FNkey = this.m_aliasFNTbl.keySet().toArray();
1504       for(int i = 0; i < FNkey.length; i++) {
1505         FlatNew fn = (FlatNew)FNkey[i];
1506         Vector<FlatNew> tmpv = this.m_aliasFNTbl.get(fn);
1507         if(this.m_aliaslocksTbl4FN == null) {
1508           this.m_aliaslocksTbl4FN = new Hashtable<FlatNew, Vector<Integer>>();
1509         }
1510         if(!this.m_aliaslocksTbl4FN.contains(fn)) {
1511           this.m_aliaslocksTbl4FN.put(fn, new Vector<Integer>());
1512         }
1513         this.m_aliaslocksTbl4FN.get(fn).add(lockindex);
1514         for(int j = 0; j < tmpv.size(); j++) {
1515           FlatNew tfn = tmpv.elementAt(j);
1516           if(!this.m_aliaslocksTbl4FN.contains(tfn)) {
1517             this.m_aliaslocksTbl4FN.put(tfn, new Vector<Integer>());
1518           }
1519           this.m_aliaslocksTbl4FN.get(tfn).add(lockindex);
1520         }
1521         lockindex++;
1522       }
1523     }
1524   }
1525
1526   protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) {
1527     if (frn.getReturnTemp()!=null) {
1528       if (frn.getReturnTemp().getType().isPtr())
1529         output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";");
1530       else
1531         output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";");
1532     } else {
1533       if(fm.getTask() != null) {
1534         //output.println("flushAll();");
1535         output.println("#ifdef RAW");
1536         output.println("raw_user_interrupts_off();");
1537         output.println("#ifdef RAWDEBUG");
1538         output.println("raw_test_pass(0xec00);");
1539         output.println("#endif");
1540         output.println("raw_flush_entire_cache();");
1541         output.println("#ifdef RAWDEBUG");
1542         output.println("raw_test_pass(0xecff);");
1543         output.println("#endif");
1544         output.println("raw_user_interrupts_on();");
1545         output.println("#endif");
1546         outputTransCode(output);
1547       }
1548       output.println("return;");
1549     }
1550   }
1551
1552   protected void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn,
1553                                  PrintWriter output) {
1554     if (state.DSM && locality.getAtomic(lb).get(fn).intValue() > 0
1555         && !fn.isGlobal()) {
1556       // Stash pointer in case of GC
1557       String revertptr = super.generateTemp(fm, reverttable.get(lb), lb);
1558       output.println(revertptr + "=trans->revertlist;");
1559     }
1560     if (fn.getType().isArray()) {
1561       int arrayid = state.getArrayNumber(fn.getType())
1562                     + state.numClasses();
1563       if (fn.isGlobal()) {
1564         output.println(super.generateTemp(fm, fn.getDst(), lb)
1565                        + "=allocate_newarrayglobal(trans, " + arrayid + ", "
1566                        + super.generateTemp(fm, fn.getSize(), lb) + ");");
1567       } else if (GENERATEPRECISEGC) {
1568         output.println(super.generateTemp(fm, fn.getDst(), lb)
1569                        + "=allocate_newarray(&" + localsprefix + ", "
1570                        + arrayid + ", " + super.generateTemp(fm, fn.getSize(), lb)
1571                        + ");");
1572       } else {
1573         output.println(super.generateTemp(fm, fn.getDst(), lb)
1574                        + "=allocate_newarray(" + arrayid + ", "
1575                        + super.generateTemp(fm, fn.getSize(), lb) + ");");
1576       }
1577     } else {
1578       if (fn.isGlobal()) {
1579         output.println(super.generateTemp(fm, fn.getDst(), lb)
1580                        + "=allocate_newglobal(trans, "
1581                        + fn.getType().getClassDesc().getId() + ");");
1582       } else if (GENERATEPRECISEGC) {
1583         output.println(super.generateTemp(fm, fn.getDst(), lb)
1584                        + "=allocate_new(&" + localsprefix + ", "
1585                        + fn.getType().getClassDesc().getId() + ");");
1586       } else {
1587         output.println(super.generateTemp(fm, fn.getDst(), lb)
1588                        + "=allocate_new("
1589                        + fn.getType().getClassDesc().getId() + ");");
1590       }
1591     }
1592     if (state.DSM && locality.getAtomic(lb).get(fn).intValue() > 0
1593         && !fn.isGlobal()) {
1594       String revertptr = super.generateTemp(fm, reverttable.get(lb), lb);
1595       output.println("trans->revertlist=" + revertptr + ";");
1596     }
1597     // create alias lock if necessary
1598     if((this.m_aliaslocksTbl4FN != null) && (this.m_aliaslocksTbl4FN.contains(fn))) {
1599       Vector<Integer> tmpv = this.m_aliaslocksTbl4FN.get(fn);
1600       for(int i = 0; i < tmpv.size(); i++) {
1601         output.println("addAliasLock(" + super.generateTemp(fm, fn.getDst(), lb) + ", aliaslocks[" + tmpv.elementAt(i).intValue() + "]);");
1602       }
1603     }
1604   }
1605
1606   class TranObjInfo {
1607     public String name;
1608     public int targetcore;
1609     public FlagState fs;
1610   }
1611
1612   private boolean contains(Vector<TranObjInfo> sendto, TranObjInfo t) {
1613     if(sendto.size() == 0) {
1614       return false;
1615     }
1616     for(int i = 0; i < sendto.size(); i++) {
1617       TranObjInfo tmp = sendto.elementAt(i);
1618       if(!tmp.name.equals(t.name)) {
1619         return false;
1620       }
1621       if(tmp.targetcore != t.targetcore) {
1622         return false;
1623       }
1624       if(tmp.fs != t.fs) {
1625         return false;
1626       }
1627     }
1628     return true;
1629   }
1630 }