1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Optimizations may be specified an arbitrary number of times on the command
11 // line, They are run in the order specified.
13 //===----------------------------------------------------------------------===//
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/CallGraph.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/PassNameParser.h"
27 #include "llvm/System/Signals.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/IRReader.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/PluginLoader.h"
32 #include "llvm/Support/PrettyStackTrace.h"
33 #include "llvm/Support/StandardPasses.h"
34 #include "llvm/Support/SystemUtils.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/LinkAllPasses.h"
37 #include "llvm/LinkAllVMCore.h"
42 // The OptimizationList is automatically populated with registered Passes by the
45 static cl::list<const PassInfo*, bool, PassNameParser>
46 PassList(cl::desc("Optimizations available:"));
48 // Other command line options...
50 static cl::opt<std::string>
51 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
52 cl::init("-"), cl::value_desc("filename"));
54 static cl::opt<std::string>
55 OutputFilename("o", cl::desc("Override output filename"),
56 cl::value_desc("filename"), cl::init("-"));
59 Force("f", cl::desc("Enable binary output on terminals"));
62 PrintEachXForm("p", cl::desc("Print module after each transformation"));
65 NoOutput("disable-output",
66 cl::desc("Do not write result bitcode file"), cl::Hidden);
69 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
72 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
75 VerifyEach("verify-each", cl::desc("Verify after each transform"));
78 StripDebug("strip-debug",
79 cl::desc("Strip debugger symbol info from translation unit"));
82 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
85 DisableOptimizations("disable-opt",
86 cl::desc("Do not run any optimization passes"));
89 DisableInternalize("disable-internalize",
90 cl::desc("Do not mark all symbols as internal"));
93 StandardCompileOpts("std-compile-opts",
94 cl::desc("Include the standard compile time optimizations"));
97 StandardLinkOpts("std-link-opts",
98 cl::desc("Include the standard link time optimizations"));
102 cl::desc("Optimization level 1. Similar to llvm-gcc -O1"));
106 cl::desc("Optimization level 2. Similar to llvm-gcc -O2"));
110 cl::desc("Optimization level 3. Similar to llvm-gcc -O3"));
113 UnitAtATime("funit-at-a-time",
114 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
118 DisableSimplifyLibCalls("disable-simplify-libcalls",
119 cl::desc("Disable simplify-libcalls"));
122 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
125 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
128 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
130 static cl::opt<std::string>
131 DefaultDataLayout("default-data-layout",
132 cl::desc("data layout string to use if not specified by module"),
133 cl::value_desc("layout-string"), cl::init(""));
135 // ---------- Define Printers for module and function passes ------------
138 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
140 const PassInfo *PassToPrint;
141 CallGraphSCCPassPrinter(const PassInfo *PI) :
142 CallGraphSCCPass(&ID), PassToPrint(PI) {}
144 virtual bool runOnSCC(CallGraphSCC &SCC) {
146 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
148 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
149 Function *F = (*I)->getFunction();
151 getAnalysisID<Pass>(PassToPrint).print(outs(), F->getParent());
154 // Get and print pass...
158 virtual const char *getPassName() const { return "'Pass' Printer"; }
160 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
161 AU.addRequiredID(PassToPrint);
162 AU.setPreservesAll();
166 char CallGraphSCCPassPrinter::ID = 0;
168 struct ModulePassPrinter : public ModulePass {
170 const PassInfo *PassToPrint;
171 ModulePassPrinter(const PassInfo *PI) : ModulePass(&ID),
174 virtual bool runOnModule(Module &M) {
176 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
177 getAnalysisID<Pass>(PassToPrint).print(outs(), &M);
180 // Get and print pass...
184 virtual const char *getPassName() const { return "'Pass' Printer"; }
186 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
187 AU.addRequiredID(PassToPrint);
188 AU.setPreservesAll();
192 char ModulePassPrinter::ID = 0;
193 struct FunctionPassPrinter : public FunctionPass {
194 const PassInfo *PassToPrint;
196 FunctionPassPrinter(const PassInfo *PI) : FunctionPass(&ID),
199 virtual bool runOnFunction(Function &F) {
201 outs() << "Printing analysis '" << PassToPrint->getPassName()
202 << "' for function '" << F.getName() << "':\n";
204 // Get and print pass...
205 getAnalysisID<Pass>(PassToPrint).print(outs(), F.getParent());
209 virtual const char *getPassName() const { return "FunctionPass Printer"; }
211 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
212 AU.addRequiredID(PassToPrint);
213 AU.setPreservesAll();
217 char FunctionPassPrinter::ID = 0;
219 struct LoopPassPrinter : public LoopPass {
221 const PassInfo *PassToPrint;
222 LoopPassPrinter(const PassInfo *PI) :
223 LoopPass(&ID), PassToPrint(PI) {}
225 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
227 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
228 getAnalysisID<Pass>(PassToPrint).print(outs(),
229 L->getHeader()->getParent()->getParent());
231 // Get and print pass...
235 virtual const char *getPassName() const { return "'Pass' Printer"; }
237 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
238 AU.addRequiredID(PassToPrint);
239 AU.setPreservesAll();
243 char LoopPassPrinter::ID = 0;
245 struct BasicBlockPassPrinter : public BasicBlockPass {
246 const PassInfo *PassToPrint;
248 BasicBlockPassPrinter(const PassInfo *PI)
249 : BasicBlockPass(&ID), PassToPrint(PI) {}
251 virtual bool runOnBasicBlock(BasicBlock &BB) {
253 outs() << "Printing Analysis info for BasicBlock '" << BB.getName()
254 << "': Pass " << PassToPrint->getPassName() << ":\n";
257 // Get and print pass...
258 getAnalysisID<Pass>(PassToPrint).print(outs(), BB.getParent()->getParent());
262 virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
264 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
265 AU.addRequiredID(PassToPrint);
266 AU.setPreservesAll();
270 char BasicBlockPassPrinter::ID = 0;
271 inline void addPass(PassManagerBase &PM, Pass *P) {
272 // Add the pass to the pass manager...
275 // If we are verifying all of the intermediate steps, add the verifier...
276 if (VerifyEach) PM.add(createVerifierPass());
279 /// AddOptimizationPasses - This routine adds optimization passes
280 /// based on selected optimization level, OptLevel. This routine
281 /// duplicates llvm-gcc behaviour.
283 /// OptLevel - Optimization Level
284 void AddOptimizationPasses(PassManagerBase &MPM, PassManagerBase &FPM,
286 createStandardFunctionPasses(&FPM, OptLevel);
288 llvm::Pass *InliningPass = 0;
291 } else if (OptLevel) {
292 unsigned Threshold = 200;
295 InliningPass = createFunctionInliningPass(Threshold);
297 InliningPass = createAlwaysInlinerPass();
299 createStandardModulePasses(&MPM, OptLevel,
300 /*OptimizeSize=*/ false,
302 /*UnrollLoops=*/ OptLevel > 1,
303 !DisableSimplifyLibCalls,
304 /*HaveExceptions=*/ true,
308 void AddStandardCompilePasses(PassManagerBase &PM) {
309 PM.add(createVerifierPass()); // Verify that input is correct
311 addPass(PM, createLowerSetJmpPass()); // Lower llvm.setjmp/.longjmp
313 // If the -strip-debug command line option was specified, do it.
315 addPass(PM, createStripSymbolsPass(true));
317 if (DisableOptimizations) return;
319 llvm::Pass *InliningPass = !DisableInline ? createFunctionInliningPass() : 0;
321 // -std-compile-opts adds the same module passes as -O3.
322 createStandardModulePasses(&PM, 3,
323 /*OptimizeSize=*/ false,
324 /*UnitAtATime=*/ true,
325 /*UnrollLoops=*/ true,
326 /*SimplifyLibCalls=*/ true,
327 /*HaveExceptions=*/ true,
331 void AddStandardLinkPasses(PassManagerBase &PM) {
332 PM.add(createVerifierPass()); // Verify that input is correct
334 // If the -strip-debug command line option was specified, do it.
336 addPass(PM, createStripSymbolsPass(true));
338 if (DisableOptimizations) return;
340 createStandardLTOPasses(&PM, /*Internalize=*/ !DisableInternalize,
341 /*RunInliner=*/ !DisableInline,
342 /*VerifyEach=*/ VerifyEach);
345 } // anonymous namespace
348 //===----------------------------------------------------------------------===//
351 int main(int argc, char **argv) {
352 sys::PrintStackTraceOnErrorSignal();
353 llvm::PrettyStackTraceProgram X(argc, argv);
355 // Enable debug stream buffering.
356 EnableDebugBuffering = true;
358 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
359 LLVMContext &Context = getGlobalContext();
361 cl::ParseCommandLineOptions(argc, argv,
362 "llvm .bc -> .bc modular optimizer and analysis printer\n");
364 // Allocate a full target machine description only if necessary.
365 // FIXME: The choice of target should be controllable on the command line.
366 std::auto_ptr<TargetMachine> target;
370 // Load the input module...
371 std::auto_ptr<Module> M;
372 M.reset(ParseIRFile(InputFilename, Err, Context));
375 Err.Print(argv[0], errs());
379 // Figure out what stream we are supposed to write to...
380 // FIXME: outs() is not binary!
381 raw_ostream *Out = 0;
382 bool DeleteStream = true;
383 if (OutputFilename == "-") {
384 Out = &outs(); // Default to printing to stdout...
385 DeleteStream = false;
387 if (NoOutput || AnalyzeOnly) {
388 errs() << "WARNING: The -o (output filename) option is ignored when\n"
389 "the --disable-output or --analyze options are used.\n";
391 // Make sure that the Output file gets unlinked from the disk if we get a
393 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
395 std::string ErrorInfo;
396 Out = new raw_fd_ostream(OutputFilename.c_str(), ErrorInfo,
397 raw_fd_ostream::F_Binary);
398 if (!ErrorInfo.empty()) {
399 errs() << ErrorInfo << '\n';
406 // If the output is set to be emitted to standard out, and standard out is a
407 // console, print out a warning message and refuse to do it. We don't
408 // impress anyone by spewing tons of binary goo to a terminal.
409 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
410 if (CheckBitcodeOutputToConsole(*Out, !Quiet))
413 // Create a PassManager to hold and optimize the collection of passes we are
418 // Add an appropriate TargetData instance for this module...
420 const std::string &ModuleDataLayout = M.get()->getDataLayout();
421 if (!ModuleDataLayout.empty())
422 TD = new TargetData(ModuleDataLayout);
423 else if (!DefaultDataLayout.empty())
424 TD = new TargetData(DefaultDataLayout);
429 OwningPtr<PassManager> FPasses;
430 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
431 FPasses.reset(new PassManager());
433 FPasses->add(new TargetData(*TD));
436 // If the -strip-debug command line option was specified, add it. If
437 // -std-compile-opts was also specified, it will handle StripDebug.
438 if (StripDebug && !StandardCompileOpts)
439 addPass(Passes, createStripSymbolsPass(true));
441 // Create a new optimization pass for each one specified on the command line
442 for (unsigned i = 0; i < PassList.size(); ++i) {
443 // Check to see if -std-compile-opts was specified before this option. If
445 if (StandardCompileOpts &&
446 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
447 AddStandardCompilePasses(Passes);
448 StandardCompileOpts = false;
451 if (StandardLinkOpts &&
452 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
453 AddStandardLinkPasses(Passes);
454 StandardLinkOpts = false;
457 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
458 AddOptimizationPasses(Passes, *FPasses, 1);
462 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
463 AddOptimizationPasses(Passes, *FPasses, 2);
467 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
468 AddOptimizationPasses(Passes, *FPasses, 3);
472 const PassInfo *PassInf = PassList[i];
474 if (PassInf->getNormalCtor())
475 P = PassInf->getNormalCtor()();
477 errs() << argv[0] << ": cannot create pass: "
478 << PassInf->getPassName() << "\n";
480 PassKind Kind = P->getPassKind();
486 Passes.add(new BasicBlockPassPrinter(PassInf));
489 Passes.add(new LoopPassPrinter(PassInf));
492 Passes.add(new FunctionPassPrinter(PassInf));
494 case PT_CallGraphSCC:
495 Passes.add(new CallGraphSCCPassPrinter(PassInf));
498 Passes.add(new ModulePassPrinter(PassInf));
505 Passes.add(createPrintModulePass(&errs()));
508 // If -std-compile-opts was specified at the end of the pass list, add them.
509 if (StandardCompileOpts) {
510 AddStandardCompilePasses(Passes);
511 StandardCompileOpts = false;
514 if (StandardLinkOpts) {
515 AddStandardLinkPasses(Passes);
516 StandardLinkOpts = false;
520 AddOptimizationPasses(Passes, *FPasses, 1);
523 AddOptimizationPasses(Passes, *FPasses, 2);
526 AddOptimizationPasses(Passes, *FPasses, 3);
528 if (OptLevelO1 || OptLevelO2 || OptLevelO3)
529 FPasses->run(*M.get());
531 // Check that the module is well formed on completion of optimization
532 if (!NoVerify && !VerifyEach)
533 Passes.add(createVerifierPass());
535 // Write bitcode or assembly out to disk or outs() as the last step...
536 if (!NoOutput && !AnalyzeOnly) {
538 Passes.add(createPrintModulePass(Out));
540 Passes.add(createBitcodeWriterPass(*Out));
543 // Now that we have all of the passes ready, run them.
544 Passes.run(*M.get());
546 // Delete the raw_fd_ostream.