Comment out code that is breaking compile....please check in the code this needs...
[IRC.git] / Robust / src / Main / Main.java
1 package Main;
2
3 import java.io.FileOutputStream;
4 import java.io.InputStream;
5 import java.io.PrintStream;
6 import java.io.Reader;
7 import java.io.BufferedReader;
8 import java.io.FileReader;
9 import java.io.FileInputStream;
10 import java.util.Iterator;
11 import java.util.Vector;
12
13 import IR.Tree.ParseNode;
14 import IR.Tree.BuildIR;
15 import IR.Tree.SemanticCheck;
16 import IR.Flat.BuildCodeMultiCore;
17 import IR.Flat.BuildFlat;
18 import IR.Flat.BuildCode;
19 import IR.ClassDescriptor;
20 import IR.State;
21 import IR.TaskDescriptor;
22 import IR.TypeUtil;
23 import Analysis.Scheduling.Schedule;
24 import Analysis.Scheduling.ScheduleAnalysis;
25 import Analysis.Scheduling.ScheduleEdge;
26 import Analysis.Scheduling.ScheduleNode;
27 import Analysis.Scheduling.ScheduleSimulator;
28 import Analysis.TaskStateAnalysis.TaskAnalysis;
29 import Analysis.TaskStateAnalysis.TaskTagAnalysis;
30 import Analysis.TaskStateAnalysis.TaskGraph;
31 import Analysis.CallGraph.CallGraph;
32 import Analysis.TaskStateAnalysis.FEdge;
33 import Analysis.TaskStateAnalysis.FlagState;
34 import Analysis.TaskStateAnalysis.TagAnalysis;
35 import Analysis.TaskStateAnalysis.GarbageAnalysis;
36 import Analysis.TaskStateAnalysis.ExecutionGraph;
37 import Analysis.TaskStateAnalysis.SafetyAnalysis;
38 import Analysis.Locality.LocalityAnalysis;
39 import Analysis.Locality.GenerateConversions;
40 import Analysis.Prefetch.PrefetchAnalysis;
41 import Analysis.FlatIRGraph.FlatIRGraph;
42 import Analysis.OwnershipAnalysis.OwnershipAnalysis;
43 import Interface.*;
44
45 public class Main {
46
47     /** Main method for the compiler.  */
48
49   public static void main(String args[]) throws Exception {
50       String ClassLibraryPrefix="./ClassLibrary/";
51       State state=new State();
52
53       for(int i=0;i<args.length;i++) {
54           String option=args[i];
55           if (option.equals("-precise"))
56               IR.Flat.BuildCode.GENERATEPRECISEGC=true;
57           else if (option.equals("-prefetch"))
58               state.PREFETCH=true;
59           else if (option.equals("-dir"))
60               IR.Flat.BuildCode.PREFIX=args[++i]+"/";
61           else if (option.equals("-selfloop"))
62               state.selfloops.add(args[++i]);
63           else if (option.equals("-excprefetch"))
64               state.excprefetch.add(args[++i]);
65           else if (option.equals("-classlibrary"))
66               ClassLibraryPrefix=args[++i]+"/";
67           else if (option.equals("-mainclass"))
68               state.main=args[++i];
69           else if (option.equals("-trueprob")) {
70               state.TRUEPROB=Double.parseDouble(args[++i]);
71           } else if (option.equals("-printflat"))
72               State.PRINTFLAT=true;
73           else if (option.equals("-struct"))
74               state.structfile=args[++i];
75           else if (option.equals("-conscheck"))
76               state.CONSCHECK=true;
77           else if (option.equals("-task"))
78               state.TASK=true;
79           else if (option.equals("-taskstate"))
80               state.TASKSTATE=true;
81           else if (option.equals("-tagstate"))
82               state.TAGSTATE=true;
83           else if (option.equals("-flatirtasks")) {
84               state.FLATIRGRAPH=true;
85               state.FLATIRGRAPHTASKS=true;
86           }
87           else if (option.equals("-flatirusermethods")) {
88               state.FLATIRGRAPH=true;
89               state.FLATIRGRAPHUSERMETHODS=true;
90           }
91           else if (option.equals("-flatirlibmethods")) {
92               state.FLATIRGRAPH=true;
93               state.FLATIRGRAPHLIBMETHODS=true;
94           }
95           else if (option.equals("-multicore"))
96                   state.MULTICORE=true;
97           else if (option.equals("-ownership"))
98               state.OWNERSHIP=true;
99           else if (option.equals("-optional"))
100               state.OPTIONAL=true;
101           /*else if (option.equals("-raw"))
102                   state.RAW=true;*/
103           else if (option.equals("-scheduling"))
104                   state.SCHEDULING=true; 
105           else if (option.equals("-thread"))
106               state.THREAD=true;
107           else if (option.equals("-dsm"))
108               state.DSM=true;
109           else if (option.equals("-webinterface"))
110               state.WEBINTERFACE=true;
111           else if (option.equals("-instructionfailures"))
112               state.INSTRUCTIONFAILURE=true;
113           else if (option.equals("-help")) {
114               System.out.println("-classlibrary classlibrarydirectory -- directory where classlibrary is located");
115               System.out.println("-selfloop task -- this task doesn't self loop its parameters forever");
116               System.out.println("-dir outputdirectory -- output code in outputdirectory");
117               System.out.println("-struct structfile -- output structure declarations for repair tool");
118               System.out.println("-mainclass -- main function to call");
119               System.out.println("-dsm -- distributed shared memory support");
120               System.out.println("-precise -- use precise garbage collection");
121               System.out.println("-conscheck -- turn on consistency checking");
122               System.out.println("-task -- compiler for tasks");
123               System.out.println("-thread -- threads");
124               System.out.println("-trueprob <d> -- probability of true branch");
125               System.out.println("-printflat -- print out flat representation");
126               System.out.println("-instructionfailures -- insert code for instruction level failures");
127               System.out.println("-taskstate -- do task state analysis");
128               System.out.println("-flatirtasks -- create dot files for flat IR graphs of tasks");
129               System.out.println("-flatirusermethods -- create dot files for flat IR graphs of user methods");
130               System.out.println("-flatirlibmethods -- create dot files for flat IR graphs of library class methods");
131               System.out.println("  note: -flatirusermethods or -flatirlibmethods currently generate all class method flat IR graphs");
132               System.out.println("-ownership -- do ownership analysis");
133               System.out.println("-optional -- enable optional arguments");
134               System.out.println("-webinterface -- enable web interface");
135               System.out.println("-help -- print out help");
136               System.exit(0);
137           } else {
138               readSourceFile(state, args[i]);
139           }
140       }
141       
142
143       readSourceFile(state, ClassLibraryPrefix+"System.java");
144       readSourceFile(state, ClassLibraryPrefix+"String.java");
145       readSourceFile(state, ClassLibraryPrefix+"HashSet.java");
146       readSourceFile(state, ClassLibraryPrefix+"HashMap.java");
147       readSourceFile(state, ClassLibraryPrefix+"HashMapIterator.java");
148       readSourceFile(state, ClassLibraryPrefix+"HashEntry.java");
149       readSourceFile(state, ClassLibraryPrefix+"Integer.java");
150       readSourceFile(state, ClassLibraryPrefix+"StringBuffer.java");
151       readSourceFile(state, ClassLibraryPrefix+"FileInputStream.java");
152       readSourceFile(state, ClassLibraryPrefix+"InputStream.java");
153       readSourceFile(state, ClassLibraryPrefix+"OutputStream.java");
154       readSourceFile(state, ClassLibraryPrefix+"FileOutputStream.java");
155       readSourceFile(state, ClassLibraryPrefix+"File.java");
156       readSourceFile(state, ClassLibraryPrefix+"Math.java");
157       readSourceFile(state, ClassLibraryPrefix+"InetAddress.java");
158       readSourceFile(state, ClassLibraryPrefix+"SocketInputStream.java");
159       readSourceFile(state, ClassLibraryPrefix+"SocketOutputStream.java");
160       readSourceFile(state, ClassLibraryPrefix+"gnu/Random.java");
161           readSourceFile(state, ClassLibraryPrefix+"Vector.java");
162           readSourceFile(state, ClassLibraryPrefix+"Enumeration.java");
163
164
165       if (state.TASK) {
166           readSourceFile(state, ClassLibraryPrefix+"Object.java");
167           readSourceFile(state, ClassLibraryPrefix+"TagDescriptor.java");
168       } else if (state.DSM) {
169           readSourceFile(state, ClassLibraryPrefix+"ThreadDSM.java");
170           readSourceFile(state, ClassLibraryPrefix+"ObjectJavaDSM.java");
171       } else {
172           if (state.THREAD) {
173               readSourceFile(state, ClassLibraryPrefix+"Thread.java");
174               readSourceFile(state, ClassLibraryPrefix+"ObjectJava.java");
175           } else
176               readSourceFile(state, ClassLibraryPrefix+"ObjectJavaNT.java");
177       }
178
179       if (state.TASK) {
180           readSourceFile(state, ClassLibraryPrefix+"StartupObject.java");
181           readSourceFile(state, ClassLibraryPrefix+"Socket.java");
182           readSourceFile(state, ClassLibraryPrefix+"ServerSocket.java");
183       } else {
184           readSourceFile(state, ClassLibraryPrefix+"SocketJava.java");
185           readSourceFile(state, ClassLibraryPrefix+"ServerSocketJava.java");
186       }
187
188       BuildIR bir=new BuildIR(state);
189       bir.buildtree();
190       
191       TypeUtil tu=new TypeUtil(state);
192       
193       SemanticCheck sc=new SemanticCheck(state,tu);
194       sc.semanticCheck();
195       tu.createFullTable();
196
197       BuildFlat bf=new BuildFlat(state,tu);
198       bf.buildFlat();
199       SafetyAnalysis sa=null;
200
201       if (state.TAGSTATE) {
202           CallGraph callgraph=new CallGraph(state);
203           TagAnalysis taganalysis=new TagAnalysis(state, callgraph);
204           TaskTagAnalysis tta=new TaskTagAnalysis(state, taganalysis);
205       }
206
207       if (state.TASKSTATE) {
208           CallGraph callgraph=new CallGraph(state);
209           TagAnalysis taganalysis=new TagAnalysis(state, callgraph);
210           TaskAnalysis ta=new TaskAnalysis(state, taganalysis);
211           ta.taskAnalysis();
212           TaskGraph tg=new TaskGraph(state, ta);
213           tg.createDOTfiles();
214           
215           if (state.OPTIONAL) {
216               ExecutionGraph et=new ExecutionGraph(state, ta);
217               et.createExecutionGraph();
218               sa = new SafetyAnalysis(et.getExecutionGraph(), state, ta);
219               sa.doAnalysis();
220               state.storeAnalysisResult(sa.getResult());
221               state.storeOptionalTaskDescriptors(sa.getOptionalTaskDescriptors());
222           }
223           
224           if (state.WEBINTERFACE) {
225               GarbageAnalysis ga=new GarbageAnalysis(state, ta);
226               WebInterface wi=new WebInterface(state, ta, tg, ga, taganalysis);
227               JhttpServer serve=new JhttpServer(8000,wi);
228               serve.run();
229           }
230           
231           if (state.SCHEDULING) {
232               // Save the current standard input, output, and error streams
233               // for later restoration.
234               PrintStream       origOut = System.out;
235
236               // Create a new output stream for the standard output.
237               PrintStream       stdout  = null;
238               try {
239                   stdout = new PrintStream (new FileOutputStream("SimulatorResult.out"));
240               } catch (Exception e) {
241                   // Sigh.  Couldn't open the file.
242                   System.out.println ("Redirect:  Unable to open output file!");
243                   System.exit (1);
244               }
245
246               // Print stuff to the original output and error streams.
247               // On most systems all of this will end up on your console when you
248               // run this application.
249               //origOut.println ("\nRedirect:  Round #1");
250               //System.out.println ("Test output via 'System.out'.");
251               //origOut.println ("Test output via 'origOut' reference.");
252
253               // Set the System out and err streams to use our replacements.
254               System.setOut(stdout);
255
256               // Print stuff to the original output and error streams.
257               // The stuff printed through the 'origOut' and 'origErr' references
258               // should go to the console on most systems while the messages
259               // printed through the 'System.out' and 'System.err' will end up in
260               // the files we created for them.
261               //origOut.println ("\nRedirect:  Round #2");
262               //System.out.println ("Test output via 'SimulatorResult.out'.");
263               //origOut.println ("Test output via 'origOut' reference.");
264               
265               // for test
266               // Randomly set the newRate and probability of FEdges
267               java.util.Random r=new java.util.Random();
268               int tint = 0;
269               for(Iterator it_classes=state.getClassSymbolTable().getDescriptorsIterator();it_classes.hasNext();) {
270                   ClassDescriptor cd=(ClassDescriptor) it_classes.next();
271                   if(cd.hasFlags()){
272                       Vector rootnodes=ta.getRootNodes(cd);
273                       if(rootnodes!=null)
274                           for(Iterator it_rootnodes=rootnodes.iterator();it_rootnodes.hasNext();){
275                               FlagState root=(FlagState)it_rootnodes.next();
276                               Vector allocatingTasks = root.getAllocatingTasks();
277                               if(allocatingTasks != null) {
278                                   for(int k = 0; k < allocatingTasks.size(); k++) {
279                                       TaskDescriptor td = (TaskDescriptor)allocatingTasks.elementAt(k);
280                                       Vector<FEdge> fev = (Vector<FEdge>)ta.getFEdgesFromTD(td);
281                                       int numEdges = fev.size();
282                                       int total = 100;
283                                       for(int j = 0; j < numEdges; j++) {
284                                           FEdge pfe = fev.elementAt(j);
285                                           if(numEdges - j == 1) {
286                                               pfe.setProbability(total);
287                                           } else {
288                                               if((total != 0) && (total != 1)){
289                                                   do {
290                                                       tint = r.nextInt()%total;
291                                                   } while(tint <= 0);
292                                               }
293                                               pfe.setProbability(tint);
294                                               total -= tint;
295                                           }
296                                           /*do {
297                                               tint = r.nextInt()%10;
298                                           } while(tint <= 0);*/
299                                           //int newRate = tint;
300                                           //int newRate = (j+1)%2+1;
301                                           int newRate = 1;
302                                           /*do {
303                                               tint = r.nextInt()%100;
304                                           } while(tint <= 0);
305                                           int probability = tint;*/
306                                           int probability = 100;
307                                           pfe.addNewObjInfo(cd, newRate, probability);
308                                       }
309                                   }
310                               }
311                           }
312                       
313                       Iterator it_flags = ta.getFlagStates(cd).iterator();
314                       while(it_flags.hasNext()) {
315                           FlagState fs = (FlagState)it_flags.next();
316                           Iterator it_edges = fs.edges();
317                           while(it_edges.hasNext()) {
318                               /*do {
319                                   tint = r.nextInt()%10;
320                               } while(tint <= 0);*/
321                               tint = 1;
322                               ((FEdge)it_edges.next()).setExeTime(tint);
323                           }
324                       }
325                   }
326               }
327               
328               // generate multiple schedulings
329               ScheduleAnalysis scheduleAnalysis = new ScheduleAnalysis(state, ta);
330               scheduleAnalysis.preSchedule();
331               scheduleAnalysis.scheduleAnalysis();
332               //scheduleAnalysis.setCoreNum(scheduleAnalysis.getSEdges4Test().size());
333               scheduleAnalysis.setCoreNum(1);
334               //scheduleAnalysis.setCoreNum(2);
335               scheduleAnalysis.schedule();
336               
337               //simulate these schedulings
338               ScheduleSimulator scheduleSimulator = new ScheduleSimulator(scheduleAnalysis.getCoreNum(), state, ta);
339               Iterator it_scheduling = scheduleAnalysis.getSchedulingsIter();
340               int index = 0;
341               Vector<Integer> selectedScheduling = new Vector<Integer>();
342               int processTime = Integer.MAX_VALUE;
343               while(it_scheduling.hasNext()) {
344                   Vector<Schedule> scheduling = (Vector<Schedule>)it_scheduling.next();
345                   scheduleSimulator.setScheduling(scheduling);
346                   int tmpTime = scheduleSimulator.process();
347                   if(tmpTime < processTime) {
348                       selectedScheduling.clear();
349                       selectedScheduling.add(index);
350                       processTime = tmpTime;
351                   } else if(tmpTime == processTime) {
352                       selectedScheduling.add(index);
353                   }
354                   index++;
355               }
356               System.out.print("Selected schedulings with least exectution time " + processTime + ": \n\t");
357               for(int i = 0; i < selectedScheduling.size(); i++) {
358                   System.out.print(selectedScheduling.elementAt(i) + ", ");
359               }
360               System.out.println();
361               
362               /*ScheduleSimulator scheduleSimulator = new ScheduleSimulator(4, state, ta);
363               Vector<Schedule> scheduling = new Vector<Schedule>();
364               for(int i = 0; i < 4; i++) {
365                   Schedule schedule = new Schedule(i);
366                   scheduling.add(schedule);
367               }
368               Iterator it_tasks = state.getTaskSymbolTable().getAllDescriptorsIterator();
369               while(it_tasks.hasNext()) {
370                   TaskDescriptor td = (TaskDescriptor)it_tasks.next();
371                   if(td.getSymbol().equals("t10")) {
372                       scheduling.elementAt(1).addTask(td);
373                   } else {
374                       scheduling.elementAt(0).addTask(td);
375                   }
376               }
377               ClassDescriptor cd = (ClassDescriptor)state.getClassSymbolTable().get("E");
378               scheduling.elementAt(0).addTargetCore(cd, 1);
379               scheduleSimulator.setScheduling(scheduling);
380               scheduleSimulator.process();
381               
382               Vector<Schedule> scheduling1 = new Vector<Schedule>();
383               for(int i = 0; i < 4; i++) {
384                   Schedule schedule = new Schedule(i);
385                   scheduling1.add(schedule);
386               }
387               Iterator it_tasks1 = state.getTaskSymbolTable().getAllDescriptorsIterator();
388               while(it_tasks1.hasNext()) {
389                   TaskDescriptor td = (TaskDescriptor)it_tasks1.next();
390                   scheduling1.elementAt(0).addTask(td);
391               }
392               scheduleSimulator.setScheduling(scheduling1);
393               scheduleSimulator.process();*/
394               
395               // Close the streams.
396               try {
397                   stdout.close ();
398                   System.setOut(origOut);
399               } catch (Exception e) {
400                   origOut.println ("Redirect:  Unable to close files!");
401               }
402               
403               if(state.MULTICORE) {
404                   it_scheduling = scheduleAnalysis.getSchedulingsIter();
405                   Vector<Schedule> scheduling = (Vector<Schedule>)it_scheduling.next();
406                   BuildCodeMultiCore bcm=new BuildCodeMultiCore(state, bf.getMap(), tu, sa, scheduling, scheduleAnalysis.getCoreNum());
407                   bcm.buildCode();
408               }
409           }
410           
411       }
412
413       if(!state.MULTICORE) {
414           if (state.DSM) {
415               CallGraph callgraph=new CallGraph(state);
416               if (state.PREFETCH) {
417                   PrefetchAnalysis pa=new PrefetchAnalysis(state, callgraph, tu);
418               }
419               LocalityAnalysis la=new LocalityAnalysis(state, callgraph, tu);
420               GenerateConversions gc=new GenerateConversions(la, state);
421               BuildCode bc=new BuildCode(state, bf.getMap(), tu, la);
422               bc.buildCode();
423           } else {
424               BuildCode bc=new BuildCode(state, bf.getMap(), tu, sa);
425               bc.buildCode();
426           }
427       }
428
429       if (state.FLATIRGRAPH) {
430           FlatIRGraph firg = new FlatIRGraph(state,
431                                              state.FLATIRGRAPHTASKS,
432                                              state.FLATIRGRAPHUSERMETHODS,
433                                              state.FLATIRGRAPHLIBMETHODS);
434       }
435
436       if (state.OWNERSHIP) {
437           CallGraph callGraph  = new CallGraph( state );
438           int allocationDepth  = 3;
439           OwnershipAnalysis oa =
440               new OwnershipAnalysis( state, callGraph, allocationDepth );
441           //This was breaking the compile
442           //      oa.writeAllAliases( "identifiedAliases.txt" );
443       }
444
445       System.exit(0);
446   }
447     
448     /** Reads in a source file and adds the parse tree to the state object. */
449     
450     private static void readSourceFile(State state, String sourcefile) throws Exception {
451         Reader fr = new BufferedReader(new FileReader(sourcefile));
452         Lex.Lexer l = new Lex.Lexer(fr);
453         java_cup.runtime.lr_parser g;
454         g = new Parse.Parser(l);
455         ParseNode p=null;
456         try {
457             p=(ParseNode) g./*debug_*/parse().value;
458         } catch (Exception e) {
459             System.err.println("Error parsing file:"+sourcefile);
460             e.printStackTrace();
461             System.exit(-1);
462         }
463         state.addParseNode(p);
464         if (l.numErrors()!=0) {
465             System.out.println("Error parsing "+sourcefile);
466             System.exit(l.numErrors());
467         }
468     }
469 }