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/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"
43 // The OptimizationList is automatically populated with registered Passes by the
46 static cl::list<const PassInfo*, bool, PassNameParser>
47 PassList(cl::desc("Optimizations available:"));
49 // Other command line options...
51 static cl::opt<std::string>
52 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
53 cl::init("-"), cl::value_desc("filename"));
55 static cl::opt<std::string>
56 OutputFilename("o", cl::desc("Override output filename"),
57 cl::value_desc("filename"));
60 Force("f", cl::desc("Enable binary output on terminals"));
63 PrintEachXForm("p", cl::desc("Print module after each transformation"));
66 NoOutput("disable-output",
67 cl::desc("Do not write result bitcode file"), cl::Hidden);
70 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
73 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
76 VerifyEach("verify-each", cl::desc("Verify after each transform"));
79 StripDebug("strip-debug",
80 cl::desc("Strip debugger symbol info from translation unit"));
83 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
86 DisableOptimizations("disable-opt",
87 cl::desc("Do not run any optimization passes"));
90 DisableInternalize("disable-internalize",
91 cl::desc("Do not mark all symbols as internal"));
94 StandardCompileOpts("std-compile-opts",
95 cl::desc("Include the standard compile time optimizations"));
98 StandardLinkOpts("std-link-opts",
99 cl::desc("Include the standard link time optimizations"));
103 cl::desc("Optimization level 1. Similar to llvm-gcc -O1"));
107 cl::desc("Optimization level 2. Similar to llvm-gcc -O2"));
111 cl::desc("Optimization level 3. Similar to llvm-gcc -O3"));
114 UnitAtATime("funit-at-a-time",
115 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
119 DisableSimplifyLibCalls("disable-simplify-libcalls",
120 cl::desc("Disable simplify-libcalls"));
123 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
126 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
129 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
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(""));
136 // ---------- Define Printers for module and function passes ------------
139 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
141 const PassInfo *PassToPrint;
143 std::string PassName;
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;
151 virtual bool runOnSCC(CallGraphSCC &SCC) {
153 Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
155 // Get and print pass...
156 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
157 Function *F = (*I)->getFunction();
159 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
165 virtual const char *getPassName() const { return PassName.c_str(); }
167 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
168 AU.addRequiredID(PassToPrint->getTypeInfo());
169 AU.setPreservesAll();
173 char CallGraphSCCPassPrinter::ID = 0;
175 struct ModulePassPrinter : public ModulePass {
177 const PassInfo *PassToPrint;
179 std::string PassName;
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;
187 virtual bool runOnModule(Module &M) {
189 Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
191 // Get and print pass...
192 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, &M);
196 virtual const char *getPassName() const { return PassName.c_str(); }
198 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
199 AU.addRequiredID(PassToPrint->getTypeInfo());
200 AU.setPreservesAll();
204 char ModulePassPrinter::ID = 0;
205 struct FunctionPassPrinter : public FunctionPass {
206 const PassInfo *PassToPrint;
209 std::string PassName;
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;
217 virtual bool runOnFunction(Function &F) {
219 Out << "Printing analysis '" << PassToPrint->getPassName()
220 << "' for function '" << F.getName() << "':\n";
222 // Get and print pass...
223 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
228 virtual const char *getPassName() const { return PassName.c_str(); }
230 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
231 AU.addRequiredID(PassToPrint->getTypeInfo());
232 AU.setPreservesAll();
236 char FunctionPassPrinter::ID = 0;
238 struct LoopPassPrinter : public LoopPass {
240 const PassInfo *PassToPrint;
242 std::string PassName;
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;
251 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
253 Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
255 // Get and print pass...
256 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
257 L->getHeader()->getParent()->getParent());
261 virtual const char *getPassName() const { return PassName.c_str(); }
263 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
264 AU.addRequiredID(PassToPrint->getTypeInfo());
265 AU.setPreservesAll();
269 char LoopPassPrinter::ID = 0;
271 struct RegionPassPrinter : public RegionPass {
273 const PassInfo *PassToPrint;
275 std::string PassName;
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;
283 virtual bool runOnRegion(Region *R, RGPassManager &RGM) {
285 Out << "Printing analysis '" << PassToPrint->getPassName() << "' for "
286 << "region: '" << R->getNameStr() << "' in function '"
287 << R->getEntry()->getParent()->getNameStr() << "':\n";
289 // Get and print pass...
290 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
291 R->getEntry()->getParent()->getParent());
295 virtual const char *getPassName() const { return "'Pass' Printer"; }
297 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
298 AU.addRequiredID(PassToPrint->getTypeInfo());
299 AU.setPreservesAll();
303 char RegionPassPrinter::ID = 0;
305 struct BasicBlockPassPrinter : public BasicBlockPass {
306 const PassInfo *PassToPrint;
309 std::string PassName;
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;
317 virtual bool runOnBasicBlock(BasicBlock &BB) {
319 Out << "Printing Analysis info for BasicBlock '" << BB.getName()
320 << "': Pass " << PassToPrint->getPassName() << ":\n";
322 // Get and print pass...
323 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
324 BB.getParent()->getParent());
328 virtual const char *getPassName() const { return PassName.c_str(); }
330 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
331 AU.addRequiredID(PassToPrint->getTypeInfo());
332 AU.setPreservesAll();
336 char BasicBlockPassPrinter::ID = 0;
337 inline void addPass(PassManagerBase &PM, Pass *P) {
338 // Add the pass to the pass manager...
341 // If we are verifying all of the intermediate steps, add the verifier...
342 if (VerifyEach) PM.add(createVerifierPass());
345 /// AddOptimizationPasses - This routine adds optimization passes
346 /// based on selected optimization level, OptLevel. This routine
347 /// duplicates llvm-gcc behaviour.
349 /// OptLevel - Optimization Level
350 void AddOptimizationPasses(PassManagerBase &MPM, PassManagerBase &FPM,
352 createStandardFunctionPasses(&FPM, OptLevel);
354 llvm::Pass *InliningPass = 0;
357 } else if (OptLevel) {
358 unsigned Threshold = 225;
361 InliningPass = createFunctionInliningPass(Threshold);
363 InliningPass = createAlwaysInlinerPass();
365 createStandardModulePasses(&MPM, OptLevel,
366 /*OptimizeSize=*/ false,
368 /*UnrollLoops=*/ OptLevel > 1,
369 !DisableSimplifyLibCalls,
370 /*HaveExceptions=*/ true,
374 void AddStandardCompilePasses(PassManagerBase &PM) {
375 PM.add(createVerifierPass()); // Verify that input is correct
377 addPass(PM, createLowerSetJmpPass()); // Lower llvm.setjmp/.longjmp
379 // If the -strip-debug command line option was specified, do it.
381 addPass(PM, createStripSymbolsPass(true));
383 if (DisableOptimizations) return;
385 llvm::Pass *InliningPass = !DisableInline ? createFunctionInliningPass() : 0;
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,
397 void AddStandardLinkPasses(PassManagerBase &PM) {
398 PM.add(createVerifierPass()); // Verify that input is correct
400 // If the -strip-debug command line option was specified, do it.
402 addPass(PM, createStripSymbolsPass(true));
404 if (DisableOptimizations) return;
406 createStandardLTOPasses(&PM, /*Internalize=*/ !DisableInternalize,
407 /*RunInliner=*/ !DisableInline,
408 /*VerifyEach=*/ VerifyEach);
411 } // anonymous namespace
414 //===----------------------------------------------------------------------===//
417 int main(int argc, char **argv) {
418 sys::PrintStackTraceOnErrorSignal();
419 llvm::PrettyStackTraceProgram X(argc, argv);
421 if (AnalyzeOnly && NoOutput) {
422 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
426 // Enable debug stream buffering.
427 EnableDebugBuffering = true;
429 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
430 LLVMContext &Context = getGlobalContext();
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);
444 cl::ParseCommandLineOptions(argc, argv,
445 "llvm .bc -> .bc modular optimizer and analysis printer\n");
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;
453 // Load the input module...
454 std::auto_ptr<Module> M;
455 M.reset(ParseIRFile(InputFilename, Err, Context));
458 Err.Print(argv[0], errs());
462 // Figure out what stream we are supposed to write to...
463 OwningPtr<tool_output_file> Out;
465 if (!OutputFilename.empty())
466 errs() << "WARNING: The -o (output filename) option is ignored when\n"
467 "the --disable-output option is used.\n";
469 // Default to standard output.
470 if (OutputFilename.empty())
471 OutputFilename = "-";
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';
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))
489 // Create a PassManager to hold and optimize the collection of passes we are
494 // Add an appropriate TargetData instance for this module...
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);
505 OwningPtr<PassManager> FPasses;
506 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
507 FPasses.reset(new PassManager());
509 FPasses->add(new TargetData(*TD));
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));
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
521 if (StandardCompileOpts &&
522 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
523 AddStandardCompilePasses(Passes);
524 StandardCompileOpts = false;
527 if (StandardLinkOpts &&
528 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
529 AddStandardLinkPasses(Passes);
530 StandardLinkOpts = false;
533 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
534 AddOptimizationPasses(Passes, *FPasses, 1);
538 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
539 AddOptimizationPasses(Passes, *FPasses, 2);
543 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
544 AddOptimizationPasses(Passes, *FPasses, 3);
548 const PassInfo *PassInf = PassList[i];
550 if (PassInf->getNormalCtor())
551 P = PassInf->getNormalCtor()();
553 errs() << argv[0] << ": cannot create pass: "
554 << PassInf->getPassName() << "\n";
556 PassKind Kind = P->getPassKind();
562 Passes.add(new BasicBlockPassPrinter(PassInf, Out->os()));
565 Passes.add(new RegionPassPrinter(PassInf, Out->os()));
568 Passes.add(new LoopPassPrinter(PassInf, Out->os()));
571 Passes.add(new FunctionPassPrinter(PassInf, Out->os()));
573 case PT_CallGraphSCC:
574 Passes.add(new CallGraphSCCPassPrinter(PassInf, Out->os()));
577 Passes.add(new ModulePassPrinter(PassInf, Out->os()));
584 Passes.add(createPrintModulePass(&errs()));
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;
593 if (StandardLinkOpts) {
594 AddStandardLinkPasses(Passes);
595 StandardLinkOpts = false;
599 AddOptimizationPasses(Passes, *FPasses, 1);
602 AddOptimizationPasses(Passes, *FPasses, 2);
605 AddOptimizationPasses(Passes, *FPasses, 3);
607 if (OptLevelO1 || OptLevelO2 || OptLevelO3)
608 FPasses->run(*M.get());
610 // Check that the module is well formed on completion of optimization
611 if (!NoVerify && !VerifyEach)
612 Passes.add(createVerifierPass());
614 // Write bitcode or assembly to the output as the last step...
615 if (!NoOutput && !AnalyzeOnly) {
617 Passes.add(createPrintModulePass(&Out->os()));
619 Passes.add(createBitcodeWriterPass(Out->os()));
622 // Now that we have all of the passes ready, run them.
623 Passes.run(*M.get());