first version of inliner
[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.Flat.Inliner;
21 import IR.ClassDescriptor;
22 import IR.State;
23 import IR.TaskDescriptor;
24 import IR.TypeUtil;
25 import Analysis.Scheduling.MCImplSynthesis;
26 import Analysis.Scheduling.Schedule;
27 import Analysis.Scheduling.ScheduleAnalysis;
28 import Analysis.Scheduling.ScheduleSimulator;
29 import Analysis.TaskStateAnalysis.TaskAnalysis;
30 import Analysis.TaskStateAnalysis.TaskTagAnalysis;
31 import Analysis.TaskStateAnalysis.TaskGraph;
32 import Analysis.CallGraph.CallGraph;
33 import Analysis.TaskStateAnalysis.FEdge;
34 import Analysis.TaskStateAnalysis.FlagState;
35 import Analysis.TaskStateAnalysis.TagAnalysis;
36 import Analysis.TaskStateAnalysis.GarbageAnalysis;
37 import Analysis.TaskStateAnalysis.ExecutionGraph;
38 import Analysis.TaskStateAnalysis.SafetyAnalysis;
39 import Analysis.Locality.LocalityAnalysis;
40 import Analysis.Locality.GenerateConversions;
41 import Analysis.Prefetch.PrefetchAnalysis;
42 import Analysis.FlatIRGraph.FlatIRGraph;
43 import Analysis.OwnershipAnalysis.OwnershipAnalysis;
44 import Analysis.MLP.MLPAnalysis;
45 import Analysis.Loops.*;
46 import IR.MethodDescriptor;
47 import IR.Flat.FlatMethod;
48 import Interface.*;
49 import Util.GraphNode;
50 import Util.GraphNode.DFS;
51 import Util.GraphNode.SCC;
52
53 public class Main {
54
55   /** Main method for the compiler.  */
56
57   public static void main(String args[]) throws Exception {
58     String ClassLibraryPrefix="./ClassLibrary/";
59     State state=new State();
60     Vector sourcefiles=new Vector();
61     state.classpath.add(".");
62
63     String outputdir = null;
64     boolean isDistributeInfo = false;
65
66     for(int i=0; i<args.length; i++) {
67       String option=args[i];
68       if (option.equals("-precise"))
69         IR.Flat.BuildCode.GENERATEPRECISEGC=true;
70       else if (option.equals("-prefetch"))
71         state.PREFETCH=true;
72       else if (option.equals("-dir"))
73         IR.Flat.BuildCode.PREFIX=args[++i]+"/";
74       else if (option.equals("-fastcheck"))
75         state.FASTCHECK=true;
76       else if (option.equals("-selfloop"))
77         state.selfloops.add(args[++i]);
78           else if (option.equals("-outputdir"))
79         state.outputdir = args[++i];
80       else if (option.equals("-excprefetch"))
81         state.excprefetch.add(args[++i]);
82       else if (option.equals("-classlibrary"))
83         state.classpath.add(args[++i]);
84       else if (option.equals("-inlineatomic")) {
85         state.INLINEATOMIC=true;
86         state.inlineatomicdepth=Integer.parseInt(args[++i]);
87       } else if(option.equals("-numcore")) {
88         ++i;
89         state.CORENUM = Integer.parseInt(args[i]);
90       } else if (option.equals("-mainclass"))
91         state.main=args[++i];
92       else if (option.equals("-trueprob")) {
93         state.TRUEPROB=Double.parseDouble(args[++i]);
94       } else if (option.equals("-printflat"))
95         State.PRINTFLAT=true;
96       else if (option.equals("-printscheduling"))
97         State.PRINTSCHEDULING=true;
98       else if (option.equals("-printschedulesim"))
99         State.PRINTSCHEDULESIM=true;
100       else if (option.equals("-printcriticalpath"))
101           State.PRINTCRITICALPATH=true;
102       else if (option.equals("-struct"))
103         state.structfile=args[++i];
104       else if (option.equals("-conscheck"))
105         state.CONSCHECK=true;
106       else if (option.equals("-task"))
107         state.TASK=true;
108       else if (option.equals("-abortreaders"))
109         state.ABORTREADERS=true;
110       else if (option.equals("-taskstate"))
111         state.TASKSTATE=true;
112       else if (option.equals("-tagstate"))
113         state.TAGSTATE=true;
114       else if (option.equals("-flatirtasks")) {
115         state.FLATIRGRAPH=true;
116         state.FLATIRGRAPHTASKS=true;
117       } else if (option.equals("-flatirusermethods")) {
118         state.FLATIRGRAPH=true;
119         state.FLATIRGRAPHUSERMETHODS=true;
120       } else if (option.equals("-flatirlibmethods")) {
121         state.FLATIRGRAPH=true;
122         state.FLATIRGRAPHLIBMETHODS=true;
123       } else if (option.equals("-multicore"))
124         state.MULTICORE=true;
125       else if (option.equals("-ownership"))
126         state.OWNERSHIP=true;
127       else if (option.equals("-ownallocdepth")) {
128         state.OWNERSHIPALLOCDEPTH=Integer.parseInt(args[++i]);
129       } else if (option.equals("-ownwritedots")) {
130         state.OWNERSHIPWRITEDOTS=true;
131         if (args[++i].equals("all")) {
132           state.OWNERSHIPWRITEALL=true;
133         }
134       } else if (option.equals("-ownaliasfile"))
135         state.OWNERSHIPALIASFILE=args[++i];
136       else if (option.equals("-optional"))
137         state.OPTIONAL=true;
138       else if (option.equals("-optimize"))
139         state.OPTIMIZE=true;
140       else if (option.equals("-dcopts"))
141         state.DCOPTS=true;
142       else if (option.equals("-delaycomp"))
143         state.DELAYCOMP=true;
144       else if (option.equals("-raw"))
145         state.RAW=true;
146       else if (option.equals("-scheduling"))
147         state.SCHEDULING=true;
148       else if (option.equals("-distributioninfo"))
149         isDistributeInfo=true;
150       else if (option.equals("-useprofile"))
151         state.USEPROFILE=true;
152       else if (option.equals("-thread"))
153         state.THREAD=true;
154       else if (option.equals("-dsm"))
155         state.DSM=true;
156       else if (option.equals("-singleTM"))
157         state.SINGLETM=true;
158       else if (option.equals("-webinterface"))
159         state.WEBINTERFACE=true;
160       else if (option.equals("-instructionfailures"))
161         state.INSTRUCTIONFAILURE=true;
162       else if (option.equals("-abcclose"))
163         state.ARRAYBOUNDARYCHECK=false;
164       else if (option.equals("-mlp")) {
165         state.MLP=true;
166         state.OWNERSHIP=true;
167       } else if (option.equals("-mlpdebug")) {
168         state.MLP=true;
169         state.MLPDEBUG=true;
170         state.OWNERSHIP=true;
171       } else if (option.equals("-help")) {
172         System.out.println("-classlibrary classlibrarydirectory -- directory where classlibrary is located");
173         System.out.println("-selfloop task -- this task doesn't self loop its parameters forever");
174         System.out.println("-dir outputdirectory -- output code in outputdirectory");
175         System.out.println("-struct structfile -- output structure declarations for repair tool");
176         System.out.println("-mainclass -- main function to call");
177         System.out.println("-dsm -- distributed shared memory support");
178         System.out.println("-singleTM -- single machine committing transactions");
179         System.out.println("-abortreaders -- abort readers");
180         System.out.println("-precise -- use precise garbage collection");
181         System.out.println("-conscheck -- turn on consistency checking");
182         System.out.println("-task -- compiler for tasks");
183         System.out.println("-fastcheck -- fastcheckpointing for Bristlecone");
184         System.out.println("-thread -- threads");
185         System.out.println("-trueprob <d> -- probability of true branch");
186         System.out.println("-printflat -- print out flat representation");
187         System.out.println("-instructionfailures -- insert code for instruction level failures");
188         System.out.println("-taskstate -- do task state analysis");
189         System.out.println("-flatirtasks -- create dot files for flat IR graphs of tasks");
190         System.out.println("-flatirusermethods -- create dot files for flat IR graphs of user methods");
191         System.out.println("-flatirlibmethods -- create dot files for flat IR graphs of library class methods");
192         System.out.println("  note: -flatirusermethods or -flatirlibmethods currently generate all class method flat IR graphs");
193         System.out.println("-ownership -- do ownership analysis");
194         System.out.println("-ownallocdepth <d> -- set allocation depth for ownership analysis");
195         System.out.println("-ownwritedots <all/final> -- write ownership graphs; can be all results or just final results");
196         System.out.println("-ownaliasfile <filename> -- write a text file showing all detected aliases in program tasks");
197         System.out.println("-optimize -- enable optimizations");
198         System.out.println("-optional -- enable optional arguments");
199         System.out.println("-abcclose close the array boundary check");
200         System.out.println("-scheduling do task scheduling");
201         System.out.println("-mlp build mlp code");
202         System.out.println("-mlp build mlp code, report progress and interim results");
203         System.out.println("-multicore generate multi-core version binary");
204         System.out.println("-numcore set the number of cores (should be used together with -multicore), defaultly set as 1");
205         System.out.println("-interrupt generate raw version binary with interruption (should be used togethere with -raw)");
206         System.out.println("-rawconfig config raw simulator as 4xn (should be used together with -raw)");
207         System.out.println("-rawpath print out execute path information for raw version (should be used together with -raw)");
208         System.out.println("-useprofile use profiling data for scheduling (should be used together with -raw)");
209         System.out.println("-threadsimulate generate multi-thread simulate version binary");
210         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");
211         System.out.println("-printscheduling -- print out scheduling graphs");
212         System.out.println("-printschedulesim -- print out scheduling simulation result graphs");
213         System.out.println("-webinterface -- enable web interface");
214         System.out.println("-help -- print out help");
215         System.exit(0);
216       } else {
217         sourcefiles.add(args[i]);
218       }
219     }
220
221     //add default classpath
222     if (state.classpath.size()==1)
223       state.classpath.add(ClassLibraryPrefix);
224
225     BuildIR bir=new BuildIR(state);
226     TypeUtil tu=new TypeUtil(state, bir);
227     
228
229     SemanticCheck sc=new SemanticCheck(state,tu);
230
231     for(int i=0;i<sourcefiles.size();i++)
232       loadClass(state, bir,(String)sourcefiles.get(i));
233
234     //Stuff the runtime wants to see
235     sc.getClass("String");
236     sc.getClass("Math");
237     sc.getClass("File");
238     sc.getClass("Socket");
239     sc.getClass("ServerSocket");
240     sc.getClass("FileInputStream");
241     sc.getClass("FileOutputStream");
242     if (state.TASK) {
243       sc.getClass("TagDescriptor");
244     }
245     if (state.THREAD||state.DSM||state.SINGLETM) {
246       sc.getClass("Thread");
247     }
248
249     sc.semanticCheck();
250
251     tu.createFullTable();
252
253     BuildFlat bf=new BuildFlat(state,tu);
254     bf.buildFlat();
255     SafetyAnalysis sa=null;
256     PrefetchAnalysis pa=null;
257     MLPAnalysis mlpa=null;
258     if (state.INLINEATOMIC) {
259       Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
260       while(classit.hasNext()) {
261         ClassDescriptor cn=(ClassDescriptor)classit.next();
262         Iterator methodit=cn.getMethods();
263         while(methodit.hasNext()) {
264           // do inlining
265           MethodDescriptor md=(MethodDescriptor)methodit.next();
266           FlatMethod fm=state.getMethodFlat(md);
267           Inliner.inlineAtomic(state, tu, fm, state.inlineatomicdepth);
268         }
269       }
270     }
271
272
273     if (state.OPTIMIZE) {
274       CallGraph callgraph=new CallGraph(state);
275       CopyPropagation cp=new CopyPropagation();
276       DeadCode dc=new DeadCode();
277       GlobalFieldType gft=new GlobalFieldType(callgraph, state, tu.getMain());
278       CSE cse=new CSE(gft, tu);
279       localCSE lcse=new localCSE(gft, tu);
280       LoopOptimize lo=new LoopOptimize(gft, tu);
281       Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
282       while(classit.hasNext()) {
283         ClassDescriptor cn=(ClassDescriptor)classit.next();
284         Iterator methodit=cn.getMethods();
285         while(methodit.hasNext()) {
286           /* Classify parameters */
287           MethodDescriptor md=(MethodDescriptor)methodit.next();
288           FlatMethod fm=state.getMethodFlat(md);
289           cp.optimize(fm);
290           dc.optimize(fm);
291           lo.optimize(fm);
292           cp.optimize(fm);
293           dc.optimize(fm);
294           lcse.doAnalysis(fm);
295           cse.doAnalysis(fm);
296           cp.optimize(fm);
297           dc.optimize(fm);
298           cp.optimize(fm);
299           dc.optimize(fm);
300         }
301       }
302     }
303     
304     if (state.FLATIRGRAPH) {
305       FlatIRGraph firg = new FlatIRGraph(state,
306                                          state.FLATIRGRAPHTASKS,
307                                          state.FLATIRGRAPHUSERMETHODS,
308                                          state.FLATIRGRAPHLIBMETHODS);
309     }
310
311     if (state.OWNERSHIP && !state.MLP) {
312       CallGraph callGraph = new CallGraph(state);
313       OwnershipAnalysis oa = new OwnershipAnalysis(state,
314                                                    tu,
315                                                    callGraph,
316                                                    state.OWNERSHIPALLOCDEPTH,
317                                                    state.OWNERSHIPWRITEDOTS,
318                                                    state.OWNERSHIPWRITEALL,
319                                                    state.OWNERSHIPALIASFILE);
320     }
321
322     if (state.MLP) {
323       CallGraph callGraph = new CallGraph(state);
324       OwnershipAnalysis oa = new OwnershipAnalysis(state,
325                                                    tu,
326                                                    callGraph,
327                                                    state.OWNERSHIPALLOCDEPTH,
328                                                    state.OWNERSHIPWRITEDOTS,
329                                                    state.OWNERSHIPWRITEALL,
330                                                    state.OWNERSHIPALIASFILE);
331       mlpa = new MLPAnalysis(state,
332                              tu,
333                              callGraph,
334                              oa);
335     }    
336
337     if (state.TAGSTATE) {
338       CallGraph callgraph=new CallGraph(state);
339       TagAnalysis taganalysis=new TagAnalysis(state, callgraph);
340       TaskTagAnalysis tta=new TaskTagAnalysis(state, taganalysis, tu);
341     }
342
343     if (state.TASKSTATE) {
344       CallGraph callgraph=new CallGraph(state);
345       TagAnalysis taganalysis=new TagAnalysis(state, callgraph);
346       TaskAnalysis ta=new TaskAnalysis(state, taganalysis, tu);
347       ta.taskAnalysis();
348       TaskGraph tg=new TaskGraph(state, ta);
349       tg.createDOTfiles();
350
351       if (state.OPTIONAL) {
352         ExecutionGraph et=new ExecutionGraph(state, ta);
353         et.createExecutionGraph();
354         sa = new SafetyAnalysis(et.getExecutionGraph(), state, ta);
355         sa.doAnalysis();
356         state.storeAnalysisResult(sa.getResult());
357         state.storeOptionalTaskDescriptors(sa.getOptionalTaskDescriptors());
358       }
359
360       if (state.WEBINTERFACE) {
361         GarbageAnalysis ga=new GarbageAnalysis(state, ta);
362         WebInterface wi=new WebInterface(state, ta, tg, ga, taganalysis);
363         JhttpServer serve=new JhttpServer(8000,wi);
364         serve.run();
365       }
366
367       if (state.SCHEDULING) {
368         // Use ownership analysis to get alias information
369         CallGraph callGraph = new CallGraph(state);
370         OwnershipAnalysis oa = new OwnershipAnalysis(state,
371                                                      tu,
372                                                      callGraph,
373                                                      state.OWNERSHIPALLOCDEPTH,
374                                                      state.OWNERSHIPWRITEDOTS,
375                                                      state.OWNERSHIPWRITEALL,
376                                                      state.OWNERSHIPALIASFILE);
377         
378         // synthesis a layout according to target multicore processor
379         MCImplSynthesis mcImplSynthesis = new MCImplSynthesis(state,
380                                                               ta,
381                                                               oa);
382         if(isDistributeInfo) {
383             mcImplSynthesis.distribution();
384         } else {
385             //double timeStartAnalysis = (double) System.nanoTime();
386             mcImplSynthesis.setScheduleThreshold(20);
387             mcImplSynthesis.setProbThreshold(0);
388             mcImplSynthesis.setGenerateThreshold(30);
389             Vector<Schedule> scheduling = mcImplSynthesis.synthesis();
390             
391             //double timeEndAnalysis = (double) System.nanoTime();
392             //double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
393             //System.err.println("The analysis took" + dt +  "sec.");
394
395             // generate multicore codes
396             if(state.MULTICORE) {
397                 BuildCodeMultiCore bcm=new BuildCodeMultiCore(state,
398                                                               bf.getMap(),
399                                                               tu,
400                                                               sa,
401                                                               scheduling,
402                                                               mcImplSynthesis.getCoreNum(),
403                                                               pa);
404                 bcm.setOwnershipAnalysis(oa);
405                 bcm.buildCode();
406             }
407             scheduling.clear();
408             scheduling = null;
409         }
410       }
411     }
412     if(!state.MULTICORE) {
413       if (state.DSM||state.SINGLETM) {
414         CallGraph callgraph=new CallGraph(state);
415         if (state.PREFETCH) {
416           //speed up prefetch generation using locality analysis results
417           LocalityAnalysis la=new LocalityAnalysis(state, callgraph, tu);
418           pa=new PrefetchAnalysis(state, callgraph, tu, la);
419         }
420         LocalityAnalysis la=new LocalityAnalysis(state, callgraph, tu);
421         GenerateConversions gc=new GenerateConversions(la, state);
422         BuildCode bc=new BuildCode(state, bf.getMap(), tu, la, pa, mlpa);
423         bc.buildCode();
424       } else {
425         BuildCode bc=new BuildCode(state, bf.getMap(), tu, sa, pa, mlpa);
426         bc.buildCode();
427       }
428     }
429
430     System.out.println("Lines="+state.lines);
431     System.exit(0);
432   }
433
434   public static void loadClass(State state, BuildIR bir, String sourcefile) {
435     ParseNode pn=readSourceFile(state, sourcefile);
436     bir.buildtree(pn, null);
437   }
438
439   /** Reads in a source file and adds the parse tree to the state object. */
440
441   public static ParseNode readSourceFile(State state, String sourcefile) {
442     try {
443       Reader fr= new BufferedReader(new FileReader(sourcefile));
444       Lex.Lexer l = new Lex.Lexer(fr);
445       java_cup.runtime.lr_parser g;
446       g = new Parse.Parser(l);
447       ParseNode p=null;
448       try {
449         p=(ParseNode) g./*debug_*/parse().value;
450       } catch (Exception e) {
451         System.err.println("Error parsing file:"+sourcefile);
452         e.printStackTrace();
453         System.exit(-1);
454       }
455       state.addParseNode(p);
456       if (l.numErrors()!=0) {
457         System.out.println("Error parsing "+sourcefile);
458         System.exit(l.numErrors());
459       }
460       state.lines+=l.line_num;
461       return p;
462
463     } catch (Exception e) {
464       throw new Error(e);
465     }
466   }
467 }