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