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/DebugInfo.h"
17 #include "llvm/Module.h"
18 #include "llvm/PassManager.h"
19 #include "llvm/CallGraphSCCPass.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/Assembly/PrintModulePass.h"
22 #include "llvm/Analysis/Verifier.h"
23 #include "llvm/Analysis/LoopPass.h"
24 #include "llvm/Analysis/RegionPass.h"
25 #include "llvm/Analysis/CallGraph.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetLibraryInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/ADT/StringSet.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/Support/PassNameParser.h"
32 #include "llvm/Support/Signals.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/IRReader.h"
35 #include "llvm/Support/ManagedStatic.h"
36 #include "llvm/Support/PluginLoader.h"
37 #include "llvm/Support/PrettyStackTrace.h"
38 #include "llvm/Support/SystemUtils.h"
39 #include "llvm/Support/ToolOutputFile.h"
40 #include "llvm/LinkAllPasses.h"
41 #include "llvm/LinkAllVMCore.h"
42 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
47 // The OptimizationList is automatically populated with registered Passes by the
50 static cl::list<const PassInfo*, bool, PassNameParser>
51 PassList(cl::desc("Optimizations available:"));
53 // Other command line options...
55 static cl::opt<std::string>
56 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
57 cl::init("-"), cl::value_desc("filename"));
59 static cl::opt<std::string>
60 OutputFilename("o", cl::desc("Override output filename"),
61 cl::value_desc("filename"));
64 Force("f", cl::desc("Enable binary output on terminals"));
67 PrintEachXForm("p", cl::desc("Print module after each transformation"));
70 NoOutput("disable-output",
71 cl::desc("Do not write result bitcode file"), cl::Hidden);
74 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
77 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
80 VerifyEach("verify-each", cl::desc("Verify after each transform"));
83 StripDebug("strip-debug",
84 cl::desc("Strip debugger symbol info from translation unit"));
87 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
90 DisableOptimizations("disable-opt",
91 cl::desc("Do not run any optimization passes"));
94 DisableInternalize("disable-internalize",
95 cl::desc("Do not mark all symbols as internal"));
98 StandardCompileOpts("std-compile-opts",
99 cl::desc("Include the standard compile time optimizations"));
102 StandardLinkOpts("std-link-opts",
103 cl::desc("Include the standard link time optimizations"));
107 cl::desc("Optimization level 1. Similar to clang -O1"));
111 cl::desc("Optimization level 2. Similar to clang -O2"));
115 cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
119 cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
123 cl::desc("Optimization level 3. Similar to clang -O3"));
125 static cl::opt<std::string>
126 TargetTriple("mtriple", cl::desc("Override target triple for module"));
129 UnitAtATime("funit-at-a-time",
130 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
134 DisableSimplifyLibCalls("disable-simplify-libcalls",
135 cl::desc("Disable simplify-libcalls"));
138 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
141 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
144 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
147 PrintBreakpoints("print-breakpoints-for-testing",
148 cl::desc("Print select breakpoints location for testing"));
150 static cl::opt<std::string>
151 DefaultDataLayout("default-data-layout",
152 cl::desc("data layout string to use if not specified by module"),
153 cl::value_desc("layout-string"), cl::init(""));
155 // ---------- Define Printers for module and function passes ------------
158 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
160 const PassInfo *PassToPrint;
162 std::string PassName;
164 CallGraphSCCPassPrinter(const PassInfo *PI, raw_ostream &out) :
165 CallGraphSCCPass(ID), PassToPrint(PI), Out(out) {
166 std::string PassToPrintName = PassToPrint->getPassName();
167 PassName = "CallGraphSCCPass Printer: " + PassToPrintName;
170 virtual bool runOnSCC(CallGraphSCC &SCC) {
172 Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
174 // Get and print pass...
175 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
176 Function *F = (*I)->getFunction();
178 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
184 virtual const char *getPassName() const { return PassName.c_str(); }
186 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
187 AU.addRequiredID(PassToPrint->getTypeInfo());
188 AU.setPreservesAll();
192 char CallGraphSCCPassPrinter::ID = 0;
194 struct ModulePassPrinter : public ModulePass {
196 const PassInfo *PassToPrint;
198 std::string PassName;
200 ModulePassPrinter(const PassInfo *PI, raw_ostream &out)
201 : ModulePass(ID), PassToPrint(PI), Out(out) {
202 std::string PassToPrintName = PassToPrint->getPassName();
203 PassName = "ModulePass Printer: " + PassToPrintName;
206 virtual bool runOnModule(Module &M) {
208 Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
210 // Get and print pass...
211 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, &M);
215 virtual const char *getPassName() const { return PassName.c_str(); }
217 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
218 AU.addRequiredID(PassToPrint->getTypeInfo());
219 AU.setPreservesAll();
223 char ModulePassPrinter::ID = 0;
224 struct FunctionPassPrinter : public FunctionPass {
225 const PassInfo *PassToPrint;
228 std::string PassName;
230 FunctionPassPrinter(const PassInfo *PI, raw_ostream &out)
231 : FunctionPass(ID), PassToPrint(PI), Out(out) {
232 std::string PassToPrintName = PassToPrint->getPassName();
233 PassName = "FunctionPass Printer: " + PassToPrintName;
236 virtual bool runOnFunction(Function &F) {
238 Out << "Printing analysis '" << PassToPrint->getPassName()
239 << "' for function '" << F.getName() << "':\n";
241 // Get and print pass...
242 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
247 virtual const char *getPassName() const { return PassName.c_str(); }
249 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
250 AU.addRequiredID(PassToPrint->getTypeInfo());
251 AU.setPreservesAll();
255 char FunctionPassPrinter::ID = 0;
257 struct LoopPassPrinter : public LoopPass {
259 const PassInfo *PassToPrint;
261 std::string PassName;
263 LoopPassPrinter(const PassInfo *PI, raw_ostream &out) :
264 LoopPass(ID), PassToPrint(PI), Out(out) {
265 std::string PassToPrintName = PassToPrint->getPassName();
266 PassName = "LoopPass Printer: " + PassToPrintName;
270 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
272 Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
274 // Get and print pass...
275 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
276 L->getHeader()->getParent()->getParent());
280 virtual const char *getPassName() const { return PassName.c_str(); }
282 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
283 AU.addRequiredID(PassToPrint->getTypeInfo());
284 AU.setPreservesAll();
288 char LoopPassPrinter::ID = 0;
290 struct RegionPassPrinter : public RegionPass {
292 const PassInfo *PassToPrint;
294 std::string PassName;
296 RegionPassPrinter(const PassInfo *PI, raw_ostream &out) : RegionPass(ID),
297 PassToPrint(PI), Out(out) {
298 std::string PassToPrintName = PassToPrint->getPassName();
299 PassName = "RegionPass Printer: " + PassToPrintName;
302 virtual bool runOnRegion(Region *R, RGPassManager &RGM) {
304 Out << "Printing analysis '" << PassToPrint->getPassName() << "' for "
305 << "region: '" << R->getNameStr() << "' in function '"
306 << R->getEntry()->getParent()->getName() << "':\n";
308 // Get and print pass...
309 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
310 R->getEntry()->getParent()->getParent());
314 virtual const char *getPassName() const { return PassName.c_str(); }
316 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
317 AU.addRequiredID(PassToPrint->getTypeInfo());
318 AU.setPreservesAll();
322 char RegionPassPrinter::ID = 0;
324 struct BasicBlockPassPrinter : public BasicBlockPass {
325 const PassInfo *PassToPrint;
328 std::string PassName;
330 BasicBlockPassPrinter(const PassInfo *PI, raw_ostream &out)
331 : BasicBlockPass(ID), PassToPrint(PI), Out(out) {
332 std::string PassToPrintName = PassToPrint->getPassName();
333 PassName = "BasicBlockPass Printer: " + PassToPrintName;
336 virtual bool runOnBasicBlock(BasicBlock &BB) {
338 Out << "Printing Analysis info for BasicBlock '" << BB.getName()
339 << "': Pass " << PassToPrint->getPassName() << ":\n";
341 // Get and print pass...
342 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
343 BB.getParent()->getParent());
347 virtual const char *getPassName() const { return PassName.c_str(); }
349 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
350 AU.addRequiredID(PassToPrint->getTypeInfo());
351 AU.setPreservesAll();
355 char BasicBlockPassPrinter::ID = 0;
357 struct BreakpointPrinter : public ModulePass {
361 BreakpointPrinter(raw_ostream &out)
362 : ModulePass(ID), Out(out) {
365 void getContextName(DIDescriptor Context, std::string &N) {
366 if (Context.isNameSpace()) {
367 DINameSpace NS(Context);
368 if (!NS.getName().empty()) {
369 getContextName(NS.getContext(), N);
370 N = N + NS.getName().str() + "::";
372 } else if (Context.isType()) {
374 if (!TY.getName().empty()) {
375 getContextName(TY.getContext(), N);
376 N = N + TY.getName().str() + "::";
381 virtual bool runOnModule(Module &M) {
382 StringSet<> Processed;
383 if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.sp"))
384 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
386 DISubprogram SP(NMD->getOperand(i));
388 getContextName(SP.getContext(), Name);
389 Name = Name + SP.getDisplayName().str();
390 if (!Name.empty() && Processed.insert(Name)) {
397 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
398 AU.setPreservesAll();
402 } // anonymous namespace
404 char BreakpointPrinter::ID = 0;
406 static inline void addPass(PassManagerBase &PM, Pass *P) {
407 // Add the pass to the pass manager...
410 // If we are verifying all of the intermediate steps, add the verifier...
411 if (VerifyEach) PM.add(createVerifierPass());
414 /// AddOptimizationPasses - This routine adds optimization passes
415 /// based on selected optimization level, OptLevel. This routine
416 /// duplicates llvm-gcc behaviour.
418 /// OptLevel - Optimization Level
419 static void AddOptimizationPasses(PassManagerBase &MPM,FunctionPassManager &FPM,
420 unsigned OptLevel, unsigned SizeLevel) {
421 FPM.add(createVerifierPass()); // Verify that input is correct
423 PassManagerBuilder Builder;
424 Builder.OptLevel = OptLevel;
425 Builder.SizeLevel = SizeLevel;
429 } else if (OptLevel > 1) {
430 unsigned Threshold = 225;
431 if (SizeLevel == 1) // -Os
433 else if (SizeLevel == 2) // -Oz
437 Builder.Inliner = createFunctionInliningPass(Threshold);
439 Builder.Inliner = createAlwaysInlinerPass();
441 Builder.DisableUnitAtATime = !UnitAtATime;
442 Builder.DisableUnrollLoops = OptLevel == 0;
443 Builder.DisableSimplifyLibCalls = DisableSimplifyLibCalls;
445 Builder.populateFunctionPassManager(FPM);
446 Builder.populateModulePassManager(MPM);
449 static void AddStandardCompilePasses(PassManagerBase &PM) {
450 PM.add(createVerifierPass()); // Verify that input is correct
452 // If the -strip-debug command line option was specified, do it.
454 addPass(PM, createStripSymbolsPass(true));
456 if (DisableOptimizations) return;
458 // -std-compile-opts adds the same module passes as -O3.
459 PassManagerBuilder Builder;
461 Builder.Inliner = createFunctionInliningPass();
462 Builder.OptLevel = 3;
463 Builder.DisableSimplifyLibCalls = DisableSimplifyLibCalls;
464 Builder.populateModulePassManager(PM);
467 static void AddStandardLinkPasses(PassManagerBase &PM) {
468 PM.add(createVerifierPass()); // Verify that input is correct
470 // If the -strip-debug command line option was specified, do it.
472 addPass(PM, createStripSymbolsPass(true));
474 if (DisableOptimizations) return;
476 PassManagerBuilder Builder;
477 Builder.populateLTOPassManager(PM, /*Internalize=*/ !DisableInternalize,
478 /*RunInliner=*/ !DisableInline);
482 //===----------------------------------------------------------------------===//
485 int main(int argc, char **argv) {
486 sys::PrintStackTraceOnErrorSignal();
487 llvm::PrettyStackTraceProgram X(argc, argv);
489 // Enable debug stream buffering.
490 EnableDebugBuffering = true;
492 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
493 LLVMContext &Context = getGlobalContext();
496 PassRegistry &Registry = *PassRegistry::getPassRegistry();
497 initializeCore(Registry);
498 initializeScalarOpts(Registry);
499 initializeVectorization(Registry);
500 initializeIPO(Registry);
501 initializeAnalysis(Registry);
502 initializeIPA(Registry);
503 initializeTransformUtils(Registry);
504 initializeInstCombine(Registry);
505 initializeInstrumentation(Registry);
506 initializeTarget(Registry);
508 cl::ParseCommandLineOptions(argc, argv,
509 "llvm .bc -> .bc modular optimizer and analysis printer\n");
511 if (AnalyzeOnly && NoOutput) {
512 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
516 // Allocate a full target machine description only if necessary.
517 // FIXME: The choice of target should be controllable on the command line.
518 std::auto_ptr<TargetMachine> target;
522 // Load the input module...
523 std::auto_ptr<Module> M;
524 M.reset(ParseIRFile(InputFilename, Err, Context));
527 Err.print(argv[0], errs());
531 // If we are supposed to override the target triple, do so now.
532 if (!TargetTriple.empty())
533 M->setTargetTriple(Triple::normalize(TargetTriple));
535 // Figure out what stream we are supposed to write to...
536 OwningPtr<tool_output_file> Out;
538 if (!OutputFilename.empty())
539 errs() << "WARNING: The -o (output filename) option is ignored when\n"
540 "the --disable-output option is used.\n";
542 // Default to standard output.
543 if (OutputFilename.empty())
544 OutputFilename = "-";
546 std::string ErrorInfo;
547 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
548 raw_fd_ostream::F_Binary));
549 if (!ErrorInfo.empty()) {
550 errs() << ErrorInfo << '\n';
555 // If the output is set to be emitted to standard out, and standard out is a
556 // console, print out a warning message and refuse to do it. We don't
557 // impress anyone by spewing tons of binary goo to a terminal.
558 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
559 if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
562 // Create a PassManager to hold and optimize the collection of passes we are
567 // Add an appropriate TargetLibraryInfo pass for the module's triple.
568 TargetLibraryInfo *TLI = new TargetLibraryInfo(Triple(M->getTargetTriple()));
570 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
571 if (DisableSimplifyLibCalls)
572 TLI->disableAllFunctions();
575 // Add an appropriate TargetData instance for this module.
577 const std::string &ModuleDataLayout = M.get()->getDataLayout();
578 if (!ModuleDataLayout.empty())
579 TD = new TargetData(ModuleDataLayout);
580 else if (!DefaultDataLayout.empty())
581 TD = new TargetData(DefaultDataLayout);
586 OwningPtr<FunctionPassManager> FPasses;
587 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
588 FPasses.reset(new FunctionPassManager(M.get()));
590 FPasses->add(new TargetData(*TD));
593 if (PrintBreakpoints) {
594 // Default to standard output.
596 if (OutputFilename.empty())
597 OutputFilename = "-";
599 std::string ErrorInfo;
600 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
601 raw_fd_ostream::F_Binary));
602 if (!ErrorInfo.empty()) {
603 errs() << ErrorInfo << '\n';
607 Passes.add(new BreakpointPrinter(Out->os()));
611 // If the -strip-debug command line option was specified, add it. If
612 // -std-compile-opts was also specified, it will handle StripDebug.
613 if (StripDebug && !StandardCompileOpts)
614 addPass(Passes, createStripSymbolsPass(true));
616 // Create a new optimization pass for each one specified on the command line
617 for (unsigned i = 0; i < PassList.size(); ++i) {
618 // Check to see if -std-compile-opts was specified before this option. If
620 if (StandardCompileOpts &&
621 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
622 AddStandardCompilePasses(Passes);
623 StandardCompileOpts = false;
626 if (StandardLinkOpts &&
627 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
628 AddStandardLinkPasses(Passes);
629 StandardLinkOpts = false;
632 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
633 AddOptimizationPasses(Passes, *FPasses, 1, 0);
637 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
638 AddOptimizationPasses(Passes, *FPasses, 2, 0);
642 if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
643 AddOptimizationPasses(Passes, *FPasses, 2, 1);
647 if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
648 AddOptimizationPasses(Passes, *FPasses, 2, 2);
652 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
653 AddOptimizationPasses(Passes, *FPasses, 3, 0);
657 const PassInfo *PassInf = PassList[i];
659 if (PassInf->getNormalCtor())
660 P = PassInf->getNormalCtor()();
662 errs() << argv[0] << ": cannot create pass: "
663 << PassInf->getPassName() << "\n";
665 PassKind Kind = P->getPassKind();
671 Passes.add(new BasicBlockPassPrinter(PassInf, Out->os()));
674 Passes.add(new RegionPassPrinter(PassInf, Out->os()));
677 Passes.add(new LoopPassPrinter(PassInf, Out->os()));
680 Passes.add(new FunctionPassPrinter(PassInf, Out->os()));
682 case PT_CallGraphSCC:
683 Passes.add(new CallGraphSCCPassPrinter(PassInf, Out->os()));
686 Passes.add(new ModulePassPrinter(PassInf, Out->os()));
693 Passes.add(createPrintModulePass(&errs()));
696 // If -std-compile-opts was specified at the end of the pass list, add them.
697 if (StandardCompileOpts) {
698 AddStandardCompilePasses(Passes);
699 StandardCompileOpts = false;
702 if (StandardLinkOpts) {
703 AddStandardLinkPasses(Passes);
704 StandardLinkOpts = false;
708 AddOptimizationPasses(Passes, *FPasses, 1, 0);
711 AddOptimizationPasses(Passes, *FPasses, 2, 0);
714 AddOptimizationPasses(Passes, *FPasses, 2, 1);
717 AddOptimizationPasses(Passes, *FPasses, 2, 2);
720 AddOptimizationPasses(Passes, *FPasses, 3, 0);
722 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
723 FPasses->doInitialization();
724 for (Module::iterator F = M->begin(), E = M->end(); F != E; ++F)
726 FPasses->doFinalization();
729 // Check that the module is well formed on completion of optimization
730 if (!NoVerify && !VerifyEach)
731 Passes.add(createVerifierPass());
733 // Write bitcode or assembly to the output as the last step...
734 if (!NoOutput && !AnalyzeOnly) {
736 Passes.add(createPrintModulePass(&Out->os()));
738 Passes.add(createBitcodeWriterPass(Out->os()));
741 // Before executing passes, print the final values of the LLVM options.
742 cl::PrintOptionValues();
744 // Now that we have all of the passes ready, run them.
745 Passes.run(*M.get());
748 if (!NoOutput || PrintBreakpoints)