Merge System into Support.
[oota-llvm.git] / tools / opt / opt.cpp
1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Optimizations may be specified an arbitrary number of times on the command
11 // line, They are run in the order specified.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/LLVMContext.h"
16 #include "llvm/Module.h"
17 #include "llvm/PassManager.h"
18 #include "llvm/CallGraphSCCPass.h"
19 #include "llvm/Bitcode/ReaderWriter.h"
20 #include "llvm/Assembly/PrintModulePass.h"
21 #include "llvm/Analysis/Verifier.h"
22 #include "llvm/Analysis/LoopPass.h"
23 #include "llvm/Analysis/RegionPass.h"
24 #include "llvm/Analysis/CallGraph.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/PassNameParser.h"
28 #include "llvm/Support/Signals.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/IRReader.h"
31 #include "llvm/Support/ManagedStatic.h"
32 #include "llvm/Support/PluginLoader.h"
33 #include "llvm/Support/PrettyStackTrace.h"
34 #include "llvm/Support/StandardPasses.h"
35 #include "llvm/Support/SystemUtils.h"
36 #include "llvm/Support/ToolOutputFile.h"
37 #include "llvm/LinkAllPasses.h"
38 #include "llvm/LinkAllVMCore.h"
39 #include <memory>
40 #include <algorithm>
41 using namespace llvm;
42
43 // The OptimizationList is automatically populated with registered Passes by the
44 // PassNameParser.
45 //
46 static cl::list<const PassInfo*, bool, PassNameParser>
47 PassList(cl::desc("Optimizations available:"));
48
49 // Other command line options...
50 //
51 static cl::opt<std::string>
52 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
53     cl::init("-"), cl::value_desc("filename"));
54
55 static cl::opt<std::string>
56 OutputFilename("o", cl::desc("Override output filename"),
57                cl::value_desc("filename"));
58
59 static cl::opt<bool>
60 Force("f", cl::desc("Enable binary output on terminals"));
61
62 static cl::opt<bool>
63 PrintEachXForm("p", cl::desc("Print module after each transformation"));
64
65 static cl::opt<bool>
66 NoOutput("disable-output",
67          cl::desc("Do not write result bitcode file"), cl::Hidden);
68
69 static cl::opt<bool>
70 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
71
72 static cl::opt<bool>
73 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
74
75 static cl::opt<bool>
76 VerifyEach("verify-each", cl::desc("Verify after each transform"));
77
78 static cl::opt<bool>
79 StripDebug("strip-debug",
80            cl::desc("Strip debugger symbol info from translation unit"));
81
82 static cl::opt<bool>
83 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
84
85 static cl::opt<bool>
86 DisableOptimizations("disable-opt",
87                      cl::desc("Do not run any optimization passes"));
88
89 static cl::opt<bool>
90 DisableInternalize("disable-internalize",
91                    cl::desc("Do not mark all symbols as internal"));
92
93 static cl::opt<bool>
94 StandardCompileOpts("std-compile-opts",
95                    cl::desc("Include the standard compile time optimizations"));
96
97 static cl::opt<bool>
98 StandardLinkOpts("std-link-opts",
99                  cl::desc("Include the standard link time optimizations"));
100
101 static cl::opt<bool>
102 OptLevelO1("O1",
103            cl::desc("Optimization level 1. Similar to llvm-gcc -O1"));
104
105 static cl::opt<bool>
106 OptLevelO2("O2",
107            cl::desc("Optimization level 2. Similar to llvm-gcc -O2"));
108
109 static cl::opt<bool>
110 OptLevelO3("O3",
111            cl::desc("Optimization level 3. Similar to llvm-gcc -O3"));
112
113 static cl::opt<bool>
114 UnitAtATime("funit-at-a-time",
115             cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
116             cl::init(true));
117
118 static cl::opt<bool>
119 DisableSimplifyLibCalls("disable-simplify-libcalls",
120                         cl::desc("Disable simplify-libcalls"));
121
122 static cl::opt<bool>
123 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
124
125 static cl::alias
126 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
127
128 static cl::opt<bool>
129 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
130
131 static cl::opt<std::string>
132 DefaultDataLayout("default-data-layout", 
133           cl::desc("data layout string to use if not specified by module"),
134           cl::value_desc("layout-string"), cl::init(""));
135
136 // ---------- Define Printers for module and function passes ------------
137 namespace {
138
139 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
140   static char ID;
141   const PassInfo *PassToPrint;
142   raw_ostream &Out;
143   std::string PassName;
144
145   CallGraphSCCPassPrinter(const PassInfo *PI, raw_ostream &out) :
146     CallGraphSCCPass(ID), PassToPrint(PI), Out(out) {
147       std::string PassToPrintName =  PassToPrint->getPassName();
148       PassName = "CallGraphSCCPass Printer: " + PassToPrintName;
149     }
150
151   virtual bool runOnSCC(CallGraphSCC &SCC) {
152     if (!Quiet)
153       Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
154
155     // Get and print pass...
156     for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
157       Function *F = (*I)->getFunction();
158       if (F)
159         getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
160                                                               F->getParent());
161     }
162     return false;
163   }
164
165   virtual const char *getPassName() const { return PassName.c_str(); }
166
167   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
168     AU.addRequiredID(PassToPrint->getTypeInfo());
169     AU.setPreservesAll();
170   }
171 };
172
173 char CallGraphSCCPassPrinter::ID = 0;
174
175 struct ModulePassPrinter : public ModulePass {
176   static char ID;
177   const PassInfo *PassToPrint;
178   raw_ostream &Out;
179   std::string PassName;
180
181   ModulePassPrinter(const PassInfo *PI, raw_ostream &out)
182     : ModulePass(ID), PassToPrint(PI), Out(out) {
183       std::string PassToPrintName =  PassToPrint->getPassName();
184       PassName = "ModulePass Printer: " + PassToPrintName;
185     }
186
187   virtual bool runOnModule(Module &M) {
188     if (!Quiet)
189       Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
190
191     // Get and print pass...
192     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, &M);
193     return false;
194   }
195
196   virtual const char *getPassName() const { return PassName.c_str(); }
197
198   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
199     AU.addRequiredID(PassToPrint->getTypeInfo());
200     AU.setPreservesAll();
201   }
202 };
203
204 char ModulePassPrinter::ID = 0;
205 struct FunctionPassPrinter : public FunctionPass {
206   const PassInfo *PassToPrint;
207   raw_ostream &Out;
208   static char ID;
209   std::string PassName;
210
211   FunctionPassPrinter(const PassInfo *PI, raw_ostream &out)
212     : FunctionPass(ID), PassToPrint(PI), Out(out) {
213       std::string PassToPrintName =  PassToPrint->getPassName();
214       PassName = "FunctionPass Printer: " + PassToPrintName;
215     }
216
217   virtual bool runOnFunction(Function &F) {
218     if (!Quiet)
219       Out << "Printing analysis '" << PassToPrint->getPassName()
220           << "' for function '" << F.getName() << "':\n";
221
222     // Get and print pass...
223     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
224             F.getParent());
225     return false;
226   }
227
228   virtual const char *getPassName() const { return PassName.c_str(); }
229
230   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
231     AU.addRequiredID(PassToPrint->getTypeInfo());
232     AU.setPreservesAll();
233   }
234 };
235
236 char FunctionPassPrinter::ID = 0;
237
238 struct LoopPassPrinter : public LoopPass {
239   static char ID;
240   const PassInfo *PassToPrint;
241   raw_ostream &Out;
242   std::string PassName;
243
244   LoopPassPrinter(const PassInfo *PI, raw_ostream &out) :
245     LoopPass(ID), PassToPrint(PI), Out(out) {
246       std::string PassToPrintName =  PassToPrint->getPassName();
247       PassName = "LoopPass Printer: " + PassToPrintName;
248     }
249
250
251   virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
252     if (!Quiet)
253       Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
254
255     // Get and print pass...
256     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
257                         L->getHeader()->getParent()->getParent());
258     return false;
259   }
260
261   virtual const char *getPassName() const { return PassName.c_str(); }
262
263   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
264     AU.addRequiredID(PassToPrint->getTypeInfo());
265     AU.setPreservesAll();
266   }
267 };
268
269 char LoopPassPrinter::ID = 0;
270
271 struct RegionPassPrinter : public RegionPass {
272   static char ID;
273   const PassInfo *PassToPrint;
274   raw_ostream &Out;
275   std::string PassName;
276
277   RegionPassPrinter(const PassInfo *PI, raw_ostream &out) : RegionPass(ID),
278     PassToPrint(PI), Out(out) {
279     std::string PassToPrintName =  PassToPrint->getPassName();
280     PassName = "LoopPass Printer: " + PassToPrintName;
281   }
282
283   virtual bool runOnRegion(Region *R, RGPassManager &RGM) {
284     if (!Quiet) {
285       Out << "Printing analysis '" << PassToPrint->getPassName() << "' for "
286         << "region: '" << R->getNameStr() << "' in function '"
287         << R->getEntry()->getParent()->getNameStr() << "':\n";
288     }
289     // Get and print pass...
290    getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
291                        R->getEntry()->getParent()->getParent());
292     return false;
293   }
294
295   virtual const char *getPassName() const { return "'Pass' Printer"; }
296
297   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
298     AU.addRequiredID(PassToPrint->getTypeInfo());
299     AU.setPreservesAll();
300   }
301 };
302
303 char RegionPassPrinter::ID = 0;
304
305 struct BasicBlockPassPrinter : public BasicBlockPass {
306   const PassInfo *PassToPrint;
307   raw_ostream &Out;
308   static char ID;
309   std::string PassName;
310
311   BasicBlockPassPrinter(const PassInfo *PI, raw_ostream &out)
312     : BasicBlockPass(ID), PassToPrint(PI), Out(out) {
313       std::string PassToPrintName =  PassToPrint->getPassName();
314       PassName = "BasicBlockPass Printer: " + PassToPrintName;
315     }
316
317   virtual bool runOnBasicBlock(BasicBlock &BB) {
318     if (!Quiet)
319       Out << "Printing Analysis info for BasicBlock '" << BB.getName()
320           << "': Pass " << PassToPrint->getPassName() << ":\n";
321
322     // Get and print pass...
323     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, 
324             BB.getParent()->getParent());
325     return false;
326   }
327
328   virtual const char *getPassName() const { return PassName.c_str(); }
329
330   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
331     AU.addRequiredID(PassToPrint->getTypeInfo());
332     AU.setPreservesAll();
333   }
334 };
335
336 char BasicBlockPassPrinter::ID = 0;
337 inline void addPass(PassManagerBase &PM, Pass *P) {
338   // Add the pass to the pass manager...
339   PM.add(P);
340
341   // If we are verifying all of the intermediate steps, add the verifier...
342   if (VerifyEach) PM.add(createVerifierPass());
343 }
344
345 /// AddOptimizationPasses - This routine adds optimization passes
346 /// based on selected optimization level, OptLevel. This routine
347 /// duplicates llvm-gcc behaviour.
348 ///
349 /// OptLevel - Optimization Level
350 void AddOptimizationPasses(PassManagerBase &MPM, PassManagerBase &FPM,
351                            unsigned OptLevel) {
352   createStandardFunctionPasses(&FPM, OptLevel);
353
354   llvm::Pass *InliningPass = 0;
355   if (DisableInline) {
356     // No inlining pass
357   } else if (OptLevel) {
358     unsigned Threshold = 225;
359     if (OptLevel > 2)
360       Threshold = 275;
361     InliningPass = createFunctionInliningPass(Threshold);
362   } else {
363     InliningPass = createAlwaysInlinerPass();
364   }
365   createStandardModulePasses(&MPM, OptLevel,
366                              /*OptimizeSize=*/ false,
367                              UnitAtATime,
368                              /*UnrollLoops=*/ OptLevel > 1,
369                              !DisableSimplifyLibCalls,
370                              /*HaveExceptions=*/ true,
371                              InliningPass);
372 }
373
374 void AddStandardCompilePasses(PassManagerBase &PM) {
375   PM.add(createVerifierPass());                  // Verify that input is correct
376
377   addPass(PM, createLowerSetJmpPass());          // Lower llvm.setjmp/.longjmp
378
379   // If the -strip-debug command line option was specified, do it.
380   if (StripDebug)
381     addPass(PM, createStripSymbolsPass(true));
382
383   if (DisableOptimizations) return;
384
385   llvm::Pass *InliningPass = !DisableInline ? createFunctionInliningPass() : 0;
386
387   // -std-compile-opts adds the same module passes as -O3.
388   createStandardModulePasses(&PM, 3,
389                              /*OptimizeSize=*/ false,
390                              /*UnitAtATime=*/ true,
391                              /*UnrollLoops=*/ true,
392                              /*SimplifyLibCalls=*/ true,
393                              /*HaveExceptions=*/ true,
394                              InliningPass);
395 }
396
397 void AddStandardLinkPasses(PassManagerBase &PM) {
398   PM.add(createVerifierPass());                  // Verify that input is correct
399
400   // If the -strip-debug command line option was specified, do it.
401   if (StripDebug)
402     addPass(PM, createStripSymbolsPass(true));
403
404   if (DisableOptimizations) return;
405
406   createStandardLTOPasses(&PM, /*Internalize=*/ !DisableInternalize,
407                           /*RunInliner=*/ !DisableInline,
408                           /*VerifyEach=*/ VerifyEach);
409 }
410
411 } // anonymous namespace
412
413
414 //===----------------------------------------------------------------------===//
415 // main for opt
416 //
417 int main(int argc, char **argv) {
418   sys::PrintStackTraceOnErrorSignal();
419   llvm::PrettyStackTraceProgram X(argc, argv);
420
421   if (AnalyzeOnly && NoOutput) {
422     errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
423     return 1;
424   }
425   
426   // Enable debug stream buffering.
427   EnableDebugBuffering = true;
428
429   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
430   LLVMContext &Context = getGlobalContext();
431   
432   // Initialize passes
433   PassRegistry &Registry = *PassRegistry::getPassRegistry();
434   initializeCore(Registry);
435   initializeScalarOpts(Registry);
436   initializeIPO(Registry);
437   initializeAnalysis(Registry);
438   initializeIPA(Registry);
439   initializeTransformUtils(Registry);
440   initializeInstCombine(Registry);
441   initializeInstrumentation(Registry);
442   initializeTarget(Registry);
443   
444   cl::ParseCommandLineOptions(argc, argv,
445     "llvm .bc -> .bc modular optimizer and analysis printer\n");
446
447   // Allocate a full target machine description only if necessary.
448   // FIXME: The choice of target should be controllable on the command line.
449   std::auto_ptr<TargetMachine> target;
450
451   SMDiagnostic Err;
452
453   // Load the input module...
454   std::auto_ptr<Module> M;
455   M.reset(ParseIRFile(InputFilename, Err, Context));
456
457   if (M.get() == 0) {
458     Err.Print(argv[0], errs());
459     return 1;
460   }
461
462   // Figure out what stream we are supposed to write to...
463   OwningPtr<tool_output_file> Out;
464   if (NoOutput) {
465     if (!OutputFilename.empty())
466       errs() << "WARNING: The -o (output filename) option is ignored when\n"
467                 "the --disable-output option is used.\n";
468   } else {
469     // Default to standard output.
470     if (OutputFilename.empty())
471       OutputFilename = "-";
472
473     std::string ErrorInfo;
474     Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
475                                    raw_fd_ostream::F_Binary));
476     if (!ErrorInfo.empty()) {
477       errs() << ErrorInfo << '\n';
478       return 1;
479     }
480   }
481
482   // If the output is set to be emitted to standard out, and standard out is a
483   // console, print out a warning message and refuse to do it.  We don't
484   // impress anyone by spewing tons of binary goo to a terminal.
485   if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
486     if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
487       NoOutput = true;
488
489   // Create a PassManager to hold and optimize the collection of passes we are
490   // about to build...
491   //
492   PassManager Passes;
493
494   // Add an appropriate TargetData instance for this module...
495   TargetData *TD = 0;
496   const std::string &ModuleDataLayout = M.get()->getDataLayout();
497   if (!ModuleDataLayout.empty())
498     TD = new TargetData(ModuleDataLayout);
499   else if (!DefaultDataLayout.empty())
500     TD = new TargetData(DefaultDataLayout);
501
502   if (TD)
503     Passes.add(TD);
504
505   OwningPtr<PassManager> FPasses;
506   if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
507     FPasses.reset(new PassManager());
508     if (TD)
509       FPasses->add(new TargetData(*TD));
510   }
511
512   // If the -strip-debug command line option was specified, add it.  If
513   // -std-compile-opts was also specified, it will handle StripDebug.
514   if (StripDebug && !StandardCompileOpts)
515     addPass(Passes, createStripSymbolsPass(true));
516
517   // Create a new optimization pass for each one specified on the command line
518   for (unsigned i = 0; i < PassList.size(); ++i) {
519     // Check to see if -std-compile-opts was specified before this option.  If
520     // so, handle it.
521     if (StandardCompileOpts &&
522         StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
523       AddStandardCompilePasses(Passes);
524       StandardCompileOpts = false;
525     }
526
527     if (StandardLinkOpts &&
528         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
529       AddStandardLinkPasses(Passes);
530       StandardLinkOpts = false;
531     }
532
533     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
534       AddOptimizationPasses(Passes, *FPasses, 1);
535       OptLevelO1 = false;
536     }
537
538     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
539       AddOptimizationPasses(Passes, *FPasses, 2);
540       OptLevelO2 = false;
541     }
542
543     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
544       AddOptimizationPasses(Passes, *FPasses, 3);
545       OptLevelO3 = false;
546     }
547
548     const PassInfo *PassInf = PassList[i];
549     Pass *P = 0;
550     if (PassInf->getNormalCtor())
551       P = PassInf->getNormalCtor()();
552     else
553       errs() << argv[0] << ": cannot create pass: "
554              << PassInf->getPassName() << "\n";
555     if (P) {
556       PassKind Kind = P->getPassKind();
557       addPass(Passes, P);
558
559       if (AnalyzeOnly) {
560         switch (Kind) {
561         case PT_BasicBlock:
562           Passes.add(new BasicBlockPassPrinter(PassInf, Out->os()));
563           break;
564         case PT_Region:
565           Passes.add(new RegionPassPrinter(PassInf, Out->os()));
566           break;
567         case PT_Loop:
568           Passes.add(new LoopPassPrinter(PassInf, Out->os()));
569           break;
570         case PT_Function:
571           Passes.add(new FunctionPassPrinter(PassInf, Out->os()));
572           break;
573         case PT_CallGraphSCC:
574           Passes.add(new CallGraphSCCPassPrinter(PassInf, Out->os()));
575           break;
576         default:
577           Passes.add(new ModulePassPrinter(PassInf, Out->os()));
578           break;
579         }
580       }
581     }
582
583     if (PrintEachXForm)
584       Passes.add(createPrintModulePass(&errs()));
585   }
586
587   // If -std-compile-opts was specified at the end of the pass list, add them.
588   if (StandardCompileOpts) {
589     AddStandardCompilePasses(Passes);
590     StandardCompileOpts = false;
591   }
592
593   if (StandardLinkOpts) {
594     AddStandardLinkPasses(Passes);
595     StandardLinkOpts = false;
596   }
597
598   if (OptLevelO1)
599     AddOptimizationPasses(Passes, *FPasses, 1);
600
601   if (OptLevelO2)
602     AddOptimizationPasses(Passes, *FPasses, 2);
603
604   if (OptLevelO3)
605     AddOptimizationPasses(Passes, *FPasses, 3);
606
607   if (OptLevelO1 || OptLevelO2 || OptLevelO3)
608     FPasses->run(*M.get());
609
610   // Check that the module is well formed on completion of optimization
611   if (!NoVerify && !VerifyEach)
612     Passes.add(createVerifierPass());
613
614   // Write bitcode or assembly to the output as the last step...
615   if (!NoOutput && !AnalyzeOnly) {
616     if (OutputAssembly)
617       Passes.add(createPrintModulePass(&Out->os()));
618     else
619       Passes.add(createBitcodeWriterPass(Out->os()));
620   }
621
622   // Now that we have all of the passes ready, run them.
623   Passes.run(*M.get());
624
625   // Declare success.
626   if (!NoOutput)
627     Out->keep();
628
629   return 0;
630 }