Change lock strategy in multicore version code. Add '/' for 'ourjava' command in...
[IRC.git] / Robust / src / Main / Main.java
1 package Main;
2
3 import java.io.FileOutputStream;
4 import java.io.PrintStream;
5 import java.io.Reader;
6 import java.io.BufferedReader;
7 import java.io.FileReader;
8 import java.io.FileInputStream;
9 import java.util.Hashtable;
10 import java.util.Iterator;
11 import java.util.Set;
12 import java.util.Vector;
13
14 import IR.Tree.ParseNode;
15 import IR.Tree.BuildIR;
16 import IR.Tree.SemanticCheck;
17 import IR.Flat.BuildCodeMultiCore;
18 import IR.Flat.BuildFlat;
19 import IR.Flat.BuildCode;
20 import IR.ClassDescriptor;
21 import IR.State;
22 import IR.TaskDescriptor;
23 import IR.TypeUtil;
24 import Analysis.Scheduling.Schedule;
25 import Analysis.Scheduling.ScheduleAnalysis;
26 import Analysis.Scheduling.ScheduleSimulator;
27 import Analysis.TaskStateAnalysis.TaskAnalysis;
28 import Analysis.TaskStateAnalysis.TaskTagAnalysis;
29 import Analysis.TaskStateAnalysis.TaskGraph;
30 import Analysis.CallGraph.CallGraph;
31 import Analysis.TaskStateAnalysis.FEdge;
32 import Analysis.TaskStateAnalysis.FlagState;
33 import Analysis.TaskStateAnalysis.TagAnalysis;
34 import Analysis.TaskStateAnalysis.GarbageAnalysis;
35 import Analysis.TaskStateAnalysis.ExecutionGraph;
36 import Analysis.TaskStateAnalysis.SafetyAnalysis;
37 import Analysis.Locality.LocalityAnalysis;
38 import Analysis.Locality.GenerateConversions;
39 import Analysis.Prefetch.PrefetchAnalysis;
40 import Analysis.FlatIRGraph.FlatIRGraph;
41 import Analysis.OwnershipAnalysis.OwnershipAnalysis;
42 import Interface.*;
43 import Util.GraphNode;
44 import Util.GraphNode.DFS;
45 import Util.GraphNode.SCC;
46
47 public class Main {
48
49   /** Main method for the compiler.  */
50
51   public static void main(String args[]) throws Exception {
52     String ClassLibraryPrefix="./ClassLibrary/";
53     State state=new State();
54
55     for(int i=0; i<args.length; i++) {
56       String option=args[i];
57       if (option.equals("-precise"))
58         IR.Flat.BuildCode.GENERATEPRECISEGC=true;
59       else if (option.equals("-prefetch"))
60         state.PREFETCH=true;
61       else if (option.equals("-dir"))
62         IR.Flat.BuildCode.PREFIX=args[++i]+"/";
63       else if (option.equals("-selfloop"))
64         state.selfloops.add(args[++i]);
65       else if (option.equals("-excprefetch"))
66         state.excprefetch.add(args[++i]);
67       else if (option.equals("-classlibrary"))
68         ClassLibraryPrefix=args[++i]+"/";
69       else if(option.equals("-numcore")) {
70         ++i;
71         state.CORENUM = Integer.parseInt(args[i]);
72       } else if (option.equals("-mainclass"))
73         state.main=args[++i];
74       else if (option.equals("-trueprob")) {
75         state.TRUEPROB=Double.parseDouble(args[++i]);
76       } else if (option.equals("-printflat"))
77         State.PRINTFLAT=true;
78       else if (option.equals("-printscheduling"))
79         State.PRINTSCHEDULING=true;
80       else if (option.equals("-printschedulesim"))
81         State.PRINTSCHEDULESIM=true;
82       else if (option.equals("-struct"))
83         state.structfile=args[++i];
84       else if (option.equals("-conscheck"))
85         state.CONSCHECK=true;
86       else if (option.equals("-task"))
87         state.TASK=true;
88       else if (option.equals("-taskstate"))
89         state.TASKSTATE=true;
90       else if (option.equals("-tagstate"))
91         state.TAGSTATE=true;
92       else if (option.equals("-flatirtasks")) {
93         state.FLATIRGRAPH=true;
94         state.FLATIRGRAPHTASKS=true;
95       } else if (option.equals("-flatirusermethods")) {
96         state.FLATIRGRAPH=true;
97         state.FLATIRGRAPHUSERMETHODS=true;
98       } else if (option.equals("-flatirlibmethods")) {
99         state.FLATIRGRAPH=true;
100         state.FLATIRGRAPHLIBMETHODS=true;
101       } else if (option.equals("-multicore"))
102         state.MULTICORE=true;
103       else if (option.equals("-ownership"))
104         state.OWNERSHIP=true;
105       else if (option.equals("-ownallocdepth")) {
106         state.OWNERSHIPALLOCDEPTH=Integer.parseInt(args[++i]);
107       } else if (option.equals("-ownwritedots")) {
108         state.OWNERSHIPWRITEDOTS=true;
109         if (args[++i].equals("all")) {
110           state.OWNERSHIPWRITEALL=true;
111         }
112       } else if (option.equals("-ownaliasfile"))
113         state.OWNERSHIPALIASFILE=args[++i];
114       else if (option.equals("-optional"))
115         state.OPTIONAL=true;
116       else if (option.equals("-raw"))
117         state.RAW=true;
118       else if (option.equals("-scheduling"))
119         state.SCHEDULING=true;
120       else if (option.equals("-useprofile"))
121         state.USEPROFILE=true;
122       else if (option.equals("-thread"))
123         state.THREAD=true;
124       else if (option.equals("-dsm"))
125         state.DSM=true;
126       else if (option.equals("-webinterface"))
127         state.WEBINTERFACE=true;
128       else if (option.equals("-instructionfailures"))
129         state.INSTRUCTIONFAILURE=true;
130       else if (option.equals("-help")) {
131         System.out.println("-classlibrary classlibrarydirectory -- directory where classlibrary is located");
132         System.out.println("-selfloop task -- this task doesn't self loop its parameters forever");
133         System.out.println("-dir outputdirectory -- output code in outputdirectory");
134         System.out.println("-struct structfile -- output structure declarations for repair tool");
135         System.out.println("-mainclass -- main function to call");
136         System.out.println("-dsm -- distributed shared memory support");
137         System.out.println("-precise -- use precise garbage collection");
138         System.out.println("-conscheck -- turn on consistency checking");
139         System.out.println("-task -- compiler for tasks");
140         System.out.println("-thread -- threads");
141         System.out.println("-trueprob <d> -- probability of true branch");
142         System.out.println("-printflat -- print out flat representation");
143         System.out.println("-instructionfailures -- insert code for instruction level failures");
144         System.out.println("-taskstate -- do task state analysis");
145         System.out.println("-flatirtasks -- create dot files for flat IR graphs of tasks");
146         System.out.println("-flatirusermethods -- create dot files for flat IR graphs of user methods");
147         System.out.println("-flatirlibmethods -- create dot files for flat IR graphs of library class methods");
148         System.out.println("  note: -flatirusermethods or -flatirlibmethods currently generate all class method flat IR graphs");
149         System.out.println("-ownership -- do ownership analysis");
150         System.out.println("-ownallocdepth <d> -- set allocation depth for ownership analysis");
151         System.out.println("-ownwritedots <all/final> -- write ownership graphs; can be all results or just final results");
152         System.out.println("-ownaliasfile <filename> -- write a text file showing all detected aliases in program tasks");
153         System.out.println("-optional -- enable optional arguments");
154         System.out.println("-scheduling do task scheduling");
155         System.out.println("-multicore generate multi-core version binary");
156         System.out.println("-numcore set the number of cores (should be used together with -multicore), defaultly set as 1");
157         System.out.println("-raw generate raw version binary (should be used together with -multicore)");
158         System.out.println("-interrupt generate raw version binary with interruption (should be used togethere with -raw)");
159         System.out.println("-rawconfig config raw simulator as 4xn (should be used together with -raw)");
160         System.out.println("-rawpath print out execute path information for raw version (should be used together with -raw)");
161         System.out.println("-useprofile use profiling data for scheduling (should be used together with -raw)");
162         System.out.println("-threadsimulate generate multi-thread simulate version binary");
163         System.out.println("-rawuseio use standard io to output profiling data (should be used together with -raw and -profile), it only works with single core version");
164         System.out.println("-printscheduling -- print out scheduling graphs");
165         System.out.println("-printschedulesim -- print out scheduling simulation result graphs");
166         System.out.println("-webinterface -- enable web interface");
167         System.out.println("-help -- print out help");
168         System.exit(0);
169       } else {
170         readSourceFile(state, args[i]);
171       }
172     }
173
174
175     readSourceFile(state, ClassLibraryPrefix+"System.java");
176     readSourceFile(state, ClassLibraryPrefix+"String.java");
177     readSourceFile(state, ClassLibraryPrefix+"HashSet.java");
178     readSourceFile(state, ClassLibraryPrefix+"HashMap.java");
179     readSourceFile(state, ClassLibraryPrefix+"HashMapIterator.java");
180     readSourceFile(state, ClassLibraryPrefix+"HashEntry.java");
181     readSourceFile(state, ClassLibraryPrefix+"Integer.java");
182     readSourceFile(state, ClassLibraryPrefix+"StringBuffer.java");
183     //if(!state.RAW) {
184     readSourceFile(state, ClassLibraryPrefix+"FileInputStream.java");
185     readSourceFile(state, ClassLibraryPrefix+"InputStream.java");
186     readSourceFile(state, ClassLibraryPrefix+"OutputStream.java");
187     readSourceFile(state, ClassLibraryPrefix+"FileOutputStream.java");
188     readSourceFile(state, ClassLibraryPrefix+"File.java");
189     readSourceFile(state, ClassLibraryPrefix+"InetAddress.java");
190     readSourceFile(state, ClassLibraryPrefix+"SocketInputStream.java");
191     readSourceFile(state, ClassLibraryPrefix+"SocketOutputStream.java");
192     //}
193     readSourceFile(state, ClassLibraryPrefix+"Math.java");
194     readSourceFile(state, ClassLibraryPrefix+"gnu/Random.java");
195     readSourceFile(state, ClassLibraryPrefix+"Vector.java");
196     readSourceFile(state, ClassLibraryPrefix+"Enumeration.java");
197     readSourceFile(state, ClassLibraryPrefix+"Dictionary.java");
198     readSourceFile(state, ClassLibraryPrefix+"Writer.java");
199     readSourceFile(state, ClassLibraryPrefix+"BufferedWriter.java");
200     readSourceFile(state, ClassLibraryPrefix+"OutputStreamWriter.java");
201     readSourceFile(state, ClassLibraryPrefix+"FileWriter.java");
202     readSourceFile(state, ClassLibraryPrefix+"Date.java");
203
204     if (state.TASK) {
205       readSourceFile(state, ClassLibraryPrefix+"Object.java");
206       readSourceFile(state, ClassLibraryPrefix+"TagDescriptor.java");
207     } else if (state.DSM) {
208       readSourceFile(state, ClassLibraryPrefix+"ThreadDSM.java");
209       readSourceFile(state, ClassLibraryPrefix+"ObjectJavaDSM.java");
210       readSourceFile(state, ClassLibraryPrefix+"Barrier.java");
211     } else {
212       if (state.THREAD) {
213         readSourceFile(state, ClassLibraryPrefix+"Thread.java");
214         readSourceFile(state, ClassLibraryPrefix+"ObjectJava.java");
215       } else
216         readSourceFile(state, ClassLibraryPrefix+"ObjectJavaNT.java");
217     }
218
219     if (state.TASK) {
220       readSourceFile(state, ClassLibraryPrefix+"StartupObject.java");
221       readSourceFile(state, ClassLibraryPrefix+"Socket.java");
222       readSourceFile(state, ClassLibraryPrefix+"ServerSocket.java");
223     } else {
224       readSourceFile(state, ClassLibraryPrefix+"SocketJava.java");
225       readSourceFile(state, ClassLibraryPrefix+"ServerSocketJava.java");
226     }
227
228     BuildIR bir=new BuildIR(state);
229     bir.buildtree();
230
231     TypeUtil tu=new TypeUtil(state);
232
233     SemanticCheck sc=new SemanticCheck(state,tu);
234     sc.semanticCheck();
235     tu.createFullTable();
236
237     BuildFlat bf=new BuildFlat(state,tu);
238     bf.buildFlat();
239     SafetyAnalysis sa=null;
240     PrefetchAnalysis pa=null;
241
242     if (state.TAGSTATE) {
243       CallGraph callgraph=new CallGraph(state);
244       TagAnalysis taganalysis=new TagAnalysis(state, callgraph);
245       TaskTagAnalysis tta=new TaskTagAnalysis(state, taganalysis);
246     }
247
248     if (state.TASKSTATE) {
249       CallGraph callgraph=new CallGraph(state);
250       TagAnalysis taganalysis=new TagAnalysis(state, callgraph);
251       TaskAnalysis ta=new TaskAnalysis(state, taganalysis);
252       ta.taskAnalysis();
253       TaskGraph tg=new TaskGraph(state, ta);
254       tg.createDOTfiles();
255
256       if (state.OPTIONAL) {
257         ExecutionGraph et=new ExecutionGraph(state, ta);
258         et.createExecutionGraph();
259         sa = new SafetyAnalysis(et.getExecutionGraph(), state, ta);
260         sa.doAnalysis();
261         state.storeAnalysisResult(sa.getResult());
262         state.storeOptionalTaskDescriptors(sa.getOptionalTaskDescriptors());
263       }
264
265       if (state.WEBINTERFACE) {
266         GarbageAnalysis ga=new GarbageAnalysis(state, ta);
267         WebInterface wi=new WebInterface(state, ta, tg, ga, taganalysis);
268         JhttpServer serve=new JhttpServer(8000,wi);
269         serve.run();
270       }
271
272       if (state.SCHEDULING) {
273         // Indentify backedges
274         for(Iterator it_classes=state.getClassSymbolTable().getDescriptorsIterator(); it_classes.hasNext();) {
275           ClassDescriptor cd=(ClassDescriptor) it_classes.next();
276           if(cd.hasFlags()) {
277             Set<FlagState> fss = ta.getFlagStates(cd);
278             SCC scc=GraphNode.DFS.computeSCC(fss);
279             if (scc.hasCycles()) {
280               for(int i=0; i<scc.numSCC(); i++) {
281                 if (scc.hasCycle(i)) {
282                   Set cycleset = scc.getSCC(i);
283                   Iterator it_fs = cycleset.iterator();
284                   while(it_fs.hasNext()) {
285                     FlagState fs = (FlagState)it_fs.next();
286                     Iterator it_edges = fs.edges();
287                     while(it_edges.hasNext()) {
288                       FEdge edge = (FEdge)it_edges.next();
289                       if(cycleset.contains(edge.getTarget())) {
290                         // a backedge
291                         edge.setisbackedge(true);
292                       }
293                     }
294                   }
295                 }
296               }
297             }
298             fss = null;
299           }
300         }
301
302         // set up profiling data
303         if(state.USEPROFILE) {
304           // read in profile data and set
305           FileInputStream inStream = new FileInputStream("/scratch/profile.rst");
306           byte[] b = new byte[1024 * 100];
307           int length = inStream.read(b);
308           if(length < 0) {
309             System.out.print("No content in input file: /scratch/profile.rst\n");
310             System.exit(-1);
311           }
312           String profiledata = new String(b, 0, length);
313           java.util.Hashtable<String, TaskInfo> taskinfos = new java.util.Hashtable<String, TaskInfo>();
314
315           // profile data format:
316           //   taskname, numoftaskexits(; exetime, probability, numofnewobjtypes(, newobj type, num of objs)+)+
317           int inindex = profiledata.indexOf('\n');
318           while((inindex != -1) ) {
319             String inline = profiledata.substring(0, inindex);
320             profiledata = profiledata.substring(inindex + 1);
321             //System.printString(inline + "\n");
322             int tmpinindex = inline.indexOf(',');
323             if(tmpinindex == -1) {
324               break;
325             }
326             String inname = inline.substring(0, tmpinindex);
327             String inint = inline.substring(tmpinindex + 1);
328             while(inint.startsWith(" ")) {
329               inint = inint.substring(1);
330             }
331             tmpinindex = inint.indexOf(',');
332             if(tmpinindex == -1) {
333               break;
334             }
335             int numofexits = Integer.parseInt(inint.substring(0, tmpinindex));
336             TaskInfo tinfo = new TaskInfo(numofexits);
337             inint = inint.substring(tmpinindex + 1);
338             while(inint.startsWith(" ")) {
339               inint = inint.substring(1);
340             }
341             tmpinindex = inint.indexOf(';');
342             int byObj = Integer.parseInt(inint.substring(0, tmpinindex));
343             if(byObj != -1) {
344               tinfo.m_byObj = byObj;
345             }
346             inint = inint.substring(tmpinindex + 1);
347             while(inint.startsWith(" ")) {
348               inint = inint.substring(1);
349             }
350             for(int i = 0; i < numofexits; i++) {
351               String tmpinfo = null;
352               if(i < numofexits - 1) {
353                 tmpinindex = inint.indexOf(';');
354                 tmpinfo = inint.substring(0, tmpinindex);
355                 inint = inint.substring(tmpinindex + 1);
356                 while(inint.startsWith(" ")) {
357                   inint = inint.substring(1);
358                 }
359               } else {
360                 tmpinfo = inint;
361               }
362
363               tmpinindex = tmpinfo.indexOf(',');
364               tinfo.m_exetime[i] = Integer.parseInt(tmpinfo.substring(0, tmpinindex));
365               tmpinfo = tmpinfo.substring(tmpinindex + 1);
366               while(tmpinfo.startsWith(" ")) {
367                 tmpinfo = tmpinfo.substring(1);
368               }
369               tmpinindex = tmpinfo.indexOf(',');
370               tinfo.m_probability[i] = Double.parseDouble(tmpinfo.substring(0, tmpinindex));
371               tmpinfo = tmpinfo.substring(tmpinindex + 1);
372               while(tmpinfo.startsWith(" ")) {
373                 tmpinfo = tmpinfo.substring(1);
374               }
375               tmpinindex = tmpinfo.indexOf(',');
376               int numofnobjs = 0;
377               if(tmpinindex == -1) {
378                 numofnobjs = Integer.parseInt(tmpinfo);
379                 if(numofnobjs != 0) {
380                   System.err.println("Error profile data format!");
381                   System.exit(-1);
382                 }
383               } else {
384                 tinfo.m_newobjinfo.setElementAt(new Hashtable<String,Integer>(), i);
385                 numofnobjs = Integer.parseInt(tmpinfo.substring(0, tmpinindex));
386                 tmpinfo = tmpinfo.substring(tmpinindex + 1);
387                 while(tmpinfo.startsWith(" ")) {
388                   tmpinfo = tmpinfo.substring(1);
389                 }
390                 for(int j = 0; j < numofnobjs; j++) {
391                   tmpinindex = tmpinfo.indexOf(',');
392                   String nobjtype = tmpinfo.substring(0, tmpinindex);
393                   tmpinfo = tmpinfo.substring(tmpinindex + 1);
394                   while(tmpinfo.startsWith(" ")) {
395                     tmpinfo = tmpinfo.substring(1);
396                   }
397                   int objnum = 0;
398                   if(j < numofnobjs - 1) {
399                     tmpinindex = tmpinfo.indexOf(',');
400                     objnum  = Integer.parseInt(tmpinfo.substring(0, tmpinindex));
401                     tmpinfo = tmpinfo.substring(tmpinindex + 1);
402                     while(tmpinfo.startsWith(" ")) {
403                       tmpinfo = tmpinfo.substring(1);
404                     }
405                   } else {
406                     objnum = Integer.parseInt(tmpinfo);
407                   }
408                   tinfo.m_newobjinfo.elementAt(i).put(nobjtype, objnum);
409                 }
410               }
411             }
412             taskinfos.put(inname, tinfo);
413             inindex = profiledata.indexOf('\n');
414           }
415
416           java.util.Random r=new java.util.Random();
417           int tint = 0;
418           for(Iterator it_classes=state.getClassSymbolTable().getDescriptorsIterator(); it_classes.hasNext();) {
419             ClassDescriptor cd=(ClassDescriptor) it_classes.next();
420             if(cd.hasFlags()) {
421               Vector rootnodes=ta.getRootNodes(cd);
422               if(rootnodes!=null) {
423                 for(Iterator it_rootnodes=rootnodes.iterator(); it_rootnodes.hasNext();) {
424                   FlagState root=(FlagState)it_rootnodes.next();
425                   Vector allocatingTasks = root.getAllocatingTasks();
426                   if(allocatingTasks != null) {
427                     for(int k = 0; k < allocatingTasks.size(); k++) {
428                       TaskDescriptor td = (TaskDescriptor)allocatingTasks.elementAt(k);
429                       Vector<FEdge> fev = (Vector<FEdge>)ta.getFEdgesFromTD(td);
430                       int numEdges = fev.size();
431                       int total = 100;
432                       for(int j = 0; j < numEdges; j++) {
433                         FEdge pfe = fev.elementAt(j);
434                         TaskInfo taskinfo = taskinfos.get(td.getSymbol());
435                         tint = taskinfo.m_exetime[pfe.getTaskExitIndex()];
436                         pfe.setExeTime(tint);
437                         double idouble = taskinfo.m_probability[pfe.getTaskExitIndex()];
438                         pfe.setProbability(idouble);
439                         int newRate = 0;
440                         if((taskinfo.m_newobjinfo.elementAt(pfe.getTaskExitIndex()) != null)
441                            && (taskinfo.m_newobjinfo.elementAt(pfe.getTaskExitIndex()).containsKey(cd.getSymbol()))) {
442                           newRate = taskinfo.m_newobjinfo.elementAt(pfe.getTaskExitIndex()).get(cd.getSymbol());
443                         }
444                         pfe.addNewObjInfo(cd, newRate, idouble);
445                         if(taskinfo.m_byObj != -1) {
446                           ((FlagState)pfe.getSource()).setByObj(taskinfo.m_byObj);
447                         }
448                       }
449                       fev = null;
450                     }
451                   }
452                 }
453               }
454               Iterator it_flags = ta.getFlagStates(cd).iterator();
455               while(it_flags.hasNext()) {
456                 FlagState fs = (FlagState)it_flags.next();
457                 Iterator it_edges = fs.edges();
458                 int total = 100;
459                 while(it_edges.hasNext()) {
460                   FEdge edge = (FEdge)it_edges.next();
461                   TaskInfo taskinfo = taskinfos.get(edge.getTask().getSymbol());
462                   tint = taskinfo.m_exetime[edge.getTaskExitIndex()];
463                   edge.setExeTime(tint);
464                   double idouble = taskinfo.m_probability[edge.getTaskExitIndex()];
465                   edge.setProbability(idouble);
466                   if(taskinfo.m_byObj != -1) {
467                     ((FlagState)edge.getSource()).setByObj(taskinfo.m_byObj);
468                   }
469                 }
470               }
471             }
472           }
473           taskinfos = null;
474         } else {
475           // for test
476           // Randomly set the newRate and probability of FEdges
477           java.util.Random r=new java.util.Random();
478           int tint = 0;
479           for(Iterator it_classes=state.getClassSymbolTable().getDescriptorsIterator(); it_classes.hasNext();) {
480             ClassDescriptor cd=(ClassDescriptor) it_classes.next();
481             if(cd.hasFlags()) {
482               Vector rootnodes=ta.getRootNodes(cd);
483               if(rootnodes!=null) {
484                 for(Iterator it_rootnodes=rootnodes.iterator(); it_rootnodes.hasNext();) {
485                   FlagState root=(FlagState)it_rootnodes.next();
486                   Vector allocatingTasks = root.getAllocatingTasks();
487                   if(allocatingTasks != null) {
488                     for(int k = 0; k < allocatingTasks.size(); k++) {
489                       TaskDescriptor td = (TaskDescriptor)allocatingTasks.elementAt(k);
490                       Vector<FEdge> fev = (Vector<FEdge>)ta.getFEdgesFromTD(td);
491                       int numEdges = fev.size();
492                       int total = 100;
493                       for(int j = 0; j < numEdges; j++) {
494                         FEdge pfe = fev.elementAt(j);
495                         if(numEdges - j == 1) {
496                           pfe.setProbability(total);
497                         } else {
498                           if((total != 0) && (total != 1)) {
499                             do {
500                               tint = r.nextInt()%total;
501                             } while(tint <= 0);
502                           }
503                           pfe.setProbability(tint);
504                           total -= tint;
505                         }
506                         //do {
507                         //   tint = r.nextInt()%10;
508                         //  } while(tint <= 0);
509                         //int newRate = tint;
510                         //int newRate = (j+1)%2+1;
511                         int newRate = 1;
512                         String cdname = cd.getSymbol();
513                         if((cdname.equals("SeriesRunner")) ||
514                            (cdname.equals("MDRunner")) ||
515                            (cdname.equals("Stage")) ||
516                            (cdname.equals("AppDemoRunner")) ||
517                            (cdname.equals("FilterBankAtom")) ||
518                            (cdname.equals("Grid"))) {
519                           newRate = 16;
520                         } else if(cdname.equals("SentenceParser")) {
521                           newRate = 4;
522                         }
523                         //do {
524                         //    tint = r.nextInt()%100;
525                         //   } while(tint <= 0);
526                         //   int probability = tint;
527                         int probability = 100;
528                         pfe.addNewObjInfo(cd, newRate, probability);
529                       }
530                       fev = null;
531                     }
532                   }
533                 }
534               }
535
536               Iterator it_flags = ta.getFlagStates(cd).iterator();
537               while(it_flags.hasNext()) {
538                 FlagState fs = (FlagState)it_flags.next();
539                 Iterator it_edges = fs.edges();
540                 int total = 100;
541                 while(it_edges.hasNext()) {
542                   //do {
543                   //    tint = r.nextInt()%10;
544                   //   } while(tint <= 0);
545                   tint = 3;
546                   FEdge edge = (FEdge)it_edges.next();
547                   edge.setExeTime(tint);
548                   if((fs.getClassDescriptor().getSymbol().equals("MD")) && (edge.getTask().getSymbol().equals("t6"))) {
549                     if(edge.isbackedge()) {
550                       if(edge.getTarget().equals(edge.getSource())) {
551                         edge.setProbability(93.75);
552                       } else {
553                         edge.setProbability(3.125);
554                       }
555                     } else {
556                       edge.setProbability(3.125);
557                     }
558                     continue;
559                   }
560                   if(!it_edges.hasNext()) {
561                     edge.setProbability(total);
562                   } else {
563                     if((total != 0) && (total != 1)) {
564                       do {
565                         tint = r.nextInt()%total;
566                       } while(tint <= 0);
567                     }
568                     edge.setProbability(tint);
569                     total -= tint;
570                   }
571                 }
572               }
573             }
574           }
575         }
576
577         // Use ownership analysis to get alias information
578         CallGraph callGraph = new CallGraph(state);
579         OwnershipAnalysis oa = new OwnershipAnalysis(state,
580                                                      tu,
581                                                      callGraph,
582                                                      state.OWNERSHIPALLOCDEPTH,
583                                                      state.OWNERSHIPWRITEDOTS,
584                                                      state.OWNERSHIPWRITEALL,
585                                                      state.OWNERSHIPALIASFILE);
586
587         // Save the current standard input, output, and error streams
588         // for later restoration.
589         PrintStream origOut = System.out;
590
591         // Create a new output stream for the standard output.
592         PrintStream stdout  = null;
593         try {
594           stdout = new PrintStream(new FileOutputStream("/scratch/SimulatorResult.out"));
595         } catch (Exception e) {
596           // Sigh.  Couldn't open the file.
597           System.out.println("Redirect:  Unable to open output file!");
598           System.exit(1);
599         }
600
601         // Print stuff to the original output and error streams.
602         // On most systems all of this will end up on your console when you
603         // run this application.
604         //origOut.println ("\nRedirect:  Round #1");
605         //System.out.println ("Test output via 'System.out'.");
606         //origOut.println ("Test output via 'origOut' reference.");
607
608         // Set the System out and err streams to use our replacements.
609         System.setOut(stdout);
610
611         // Print stuff to the original output and error streams.
612         // The stuff printed through the 'origOut' and 'origErr' references
613         // should go to the console on most systems while the messages
614         // printed through the 'System.out' and 'System.err' will end up in
615         // the files we created for them.
616         //origOut.println ("\nRedirect:  Round #2");
617         //System.out.println ("Test output via 'SimulatorResult.out'.");
618         //origOut.println ("Test output via 'origOut' reference.");
619
620         // generate multiple schedulings
621         ScheduleAnalysis scheduleAnalysis = new ScheduleAnalysis(state, ta);
622         scheduleAnalysis.preSchedule();
623         scheduleAnalysis.scheduleAnalysis();
624         //scheduleAnalysis.setCoreNum(scheduleAnalysis.getSEdges4Test().size());
625         scheduleAnalysis.setCoreNum(state.CORENUM);
626         scheduleAnalysis.schedule();
627
628         //simulate these schedulings
629         ScheduleSimulator scheduleSimulator = new ScheduleSimulator(scheduleAnalysis.getCoreNum(), state, ta);
630         Vector<Vector<Schedule>> schedulings = scheduleAnalysis.getSchedulings();
631         Vector<Integer> selectedScheduling = new Vector<Integer>();
632         int processTime = Integer.MAX_VALUE;
633         if(schedulings.size() > 1500) {
634           int index = 0;
635           int upperbound = schedulings.size();
636           long seed = 0;
637           java.util.Random r = new java.util.Random(seed);
638           for(int ii = 0; ii < 1500; ii++) {
639             index = (int)((Math.abs((double)r.nextInt() / (double)Integer.MAX_VALUE)) * upperbound);
640             System.out.println("Scheduling index:" + index);
641             //System.err.println("Scheduling index:" + index);
642             Vector<Schedule> scheduling = schedulings.elementAt(index);
643             scheduleSimulator.setScheduling(scheduling);
644             int tmpTime = scheduleSimulator.process();
645             if(tmpTime < processTime) {
646               selectedScheduling.clear();
647               selectedScheduling.add(index);
648               processTime = tmpTime;
649             } else if(tmpTime == processTime) {
650               selectedScheduling.add(index);
651             }
652             scheduling = null;
653           }
654         } else {
655           Iterator it_scheduling = scheduleAnalysis.getSchedulingsIter();
656           int index = 0;
657           while(it_scheduling.hasNext()) {
658             Vector<Schedule> scheduling = (Vector<Schedule>)it_scheduling.next();
659             scheduleSimulator.setScheduling(scheduling);
660             int tmpTime = scheduleSimulator.process();
661             if(tmpTime < processTime) {
662               selectedScheduling.clear();
663               selectedScheduling.add(index);
664               processTime = tmpTime;
665             } else if(tmpTime == processTime) {
666               selectedScheduling.add(index);
667             }
668             scheduling = null;
669             index++;
670           }
671         }
672
673         System.out.print("Selected schedulings with least exectution time " + processTime + ": \n\t");
674         for(int i = 0; i < selectedScheduling.size(); i++) {
675           System.out.print((selectedScheduling.elementAt(i) + 1) + ", ");
676         }
677         System.out.println();
678
679         // Close the streams.
680         try {
681           stdout.close();
682           System.setOut(origOut);
683         } catch (Exception e) {
684           origOut.println("Redirect:  Unable to close files!");
685         }
686
687         if(state.MULTICORE) {
688           //it_scheduling = scheduleAnalysis.getSchedulingsIter();
689           //Vector<Schedule> scheduling = (Vector<Schedule>)it_scheduling.next();
690           Vector<Schedule> scheduling = scheduleAnalysis.getSchedulings().elementAt(selectedScheduling.firstElement());
691           BuildCodeMultiCore bcm=new BuildCodeMultiCore(state, bf.getMap(), tu, sa, scheduling, scheduleAnalysis.getCoreNum(), pa);
692           bcm.setOwnershipAnalysis(oa);
693           bcm.buildCode();
694           scheduling = null;
695         }
696         selectedScheduling = null;
697       }
698
699     }
700
701     if(!state.MULTICORE) {
702       if (state.DSM) {
703         CallGraph callgraph=new CallGraph(state);
704         if (state.PREFETCH) {
705           //speed up prefetch generation using locality analysis results
706           LocalityAnalysis la=new LocalityAnalysis(state, callgraph, tu);
707           pa=new PrefetchAnalysis(state, callgraph, tu, la);
708         }
709
710         LocalityAnalysis la=new LocalityAnalysis(state, callgraph, tu);
711         GenerateConversions gc=new GenerateConversions(la, state);
712         BuildCode bc=new BuildCode(state, bf.getMap(), tu, la, pa);
713         bc.buildCode();
714       } else {
715         BuildCode bc=new BuildCode(state, bf.getMap(), tu, sa, pa);
716         bc.buildCode();
717       }
718     }
719
720     if (state.FLATIRGRAPH) {
721       FlatIRGraph firg = new FlatIRGraph(state,
722                                          state.FLATIRGRAPHTASKS,
723                                          state.FLATIRGRAPHUSERMETHODS,
724                                          state.FLATIRGRAPHLIBMETHODS);
725     }
726
727     if (state.OWNERSHIP) {
728       CallGraph callGraph = new CallGraph(state);
729       OwnershipAnalysis oa = new OwnershipAnalysis(state,
730                                                    tu,
731                                                    callGraph,
732                                                    state.OWNERSHIPALLOCDEPTH,
733                                                    state.OWNERSHIPWRITEDOTS,
734                                                    state.OWNERSHIPWRITEALL,
735                                                    state.OWNERSHIPALIASFILE);
736     }
737
738     System.exit(0);
739   }
740
741   /** Reads in a source file and adds the parse tree to the state object. */
742
743   private static void readSourceFile(State state, String sourcefile) throws Exception {
744     Reader fr = new BufferedReader(new FileReader(sourcefile));
745     Lex.Lexer l = new Lex.Lexer(fr);
746     java_cup.runtime.lr_parser g;
747     g = new Parse.Parser(l);
748     ParseNode p=null;
749     try {
750       p=(ParseNode) g./*debug_*/ parse().value;
751     } catch (Exception e) {
752       System.err.println("Error parsing file:"+sourcefile);
753       e.printStackTrace();
754       System.exit(-1);
755     }
756     state.addParseNode(p);
757     if (l.numErrors()!=0) {
758       System.out.println("Error parsing "+sourcefile);
759       System.exit(l.numErrors());
760     }
761   }
762
763   static class TaskInfo {
764     public int m_numofexits;
765     public int[] m_exetime;
766     public double[] m_probability;
767     public Vector<Hashtable<String, Integer>> m_newobjinfo;
768     public int m_byObj;
769
770     public TaskInfo(int numofexits) {
771       this.m_numofexits = numofexits;
772       this.m_exetime = new int[this.m_numofexits];
773       this.m_probability = new double[this.m_numofexits];
774       this.m_newobjinfo = new Vector<Hashtable<String, Integer>>();
775       for(int i = 0; i < this.m_numofexits; i++) {
776         this.m_newobjinfo.add(null);
777       }
778       this.m_byObj = -1;
779     }
780   }
781 }