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