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 "BreakpointPrinter.h"
16 #include "NewPMDriver.h"
17 #include "PassPrinters.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Analysis/CallGraph.h"
20 #include "llvm/Analysis/CallGraphSCCPass.h"
21 #include "llvm/Analysis/LoopPass.h"
22 #include "llvm/Analysis/RegionPass.h"
23 #include "llvm/Bitcode/BitcodeWriterPass.h"
24 #include "llvm/CodeGen/CommandFlags.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/IRPrintingPasses.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/Verifier.h"
30 #include "llvm/IRReader/IRReader.h"
31 #include "llvm/LinkAllIR.h"
32 #include "llvm/LinkAllPasses.h"
33 #include "llvm/MC/SubtargetFeature.h"
34 #include "llvm/PassManager.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ManagedStatic.h"
37 #include "llvm/Support/PassNameParser.h"
38 #include "llvm/Support/PluginLoader.h"
39 #include "llvm/Support/PrettyStackTrace.h"
40 #include "llvm/Support/Signals.h"
41 #include "llvm/Support/SourceMgr.h"
42 #include "llvm/Support/SystemUtils.h"
43 #include "llvm/Support/TargetRegistry.h"
44 #include "llvm/Support/TargetSelect.h"
45 #include "llvm/Support/ToolOutputFile.h"
46 #include "llvm/Target/TargetLibraryInfo.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
52 using namespace opt_tool;
54 // The OptimizationList is automatically populated with registered Passes by the
57 static cl::list<const PassInfo*, bool, PassNameParser>
58 PassList(cl::desc("Optimizations available:"));
60 // This flag specifies a textual description of the optimization pass pipeline
61 // to run over the module. This flag switches opt to use the new pass manager
62 // infrastructure, completely disabling all of the flags specific to the old
64 static cl::opt<std::string> PassPipeline(
66 cl::desc("A textual description of the pass pipeline for optimizing"),
69 // Other command line options...
71 static cl::opt<std::string>
72 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
73 cl::init("-"), cl::value_desc("filename"));
75 static cl::opt<std::string>
76 OutputFilename("o", cl::desc("Override output filename"),
77 cl::value_desc("filename"));
80 Force("f", cl::desc("Enable binary output on terminals"));
83 PrintEachXForm("p", cl::desc("Print module after each transformation"));
86 NoOutput("disable-output",
87 cl::desc("Do not write result bitcode file"), cl::Hidden);
90 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
93 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
96 VerifyEach("verify-each", cl::desc("Verify after each transform"));
99 StripDebug("strip-debug",
100 cl::desc("Strip debugger symbol info from translation unit"));
103 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
106 DisableOptimizations("disable-opt",
107 cl::desc("Do not run any optimization passes"));
110 DisableInternalize("disable-internalize",
111 cl::desc("Do not mark all symbols as internal"));
114 StandardCompileOpts("std-compile-opts",
115 cl::desc("Include the standard compile time optimizations"));
118 StandardLinkOpts("std-link-opts",
119 cl::desc("Include the standard link time optimizations"));
123 cl::desc("Optimization level 1. Similar to clang -O1"));
127 cl::desc("Optimization level 2. Similar to clang -O2"));
131 cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
135 cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
139 cl::desc("Optimization level 3. Similar to clang -O3"));
141 static cl::opt<std::string>
142 TargetTriple("mtriple", cl::desc("Override target triple for module"));
145 UnitAtATime("funit-at-a-time",
146 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
150 DisableLoopUnrolling("disable-loop-unrolling",
151 cl::desc("Disable loop unrolling in all relevant passes"),
154 DisableLoopVectorization("disable-loop-vectorization",
155 cl::desc("Disable the loop vectorization pass"),
159 DisableSLPVectorization("disable-slp-vectorization",
160 cl::desc("Disable the slp vectorization pass"),
165 DisableSimplifyLibCalls("disable-simplify-libcalls",
166 cl::desc("Disable simplify-libcalls"));
169 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
172 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
175 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
178 PrintBreakpoints("print-breakpoints-for-testing",
179 cl::desc("Print select breakpoints location for testing"));
181 static cl::opt<std::string>
182 DefaultDataLayout("default-data-layout",
183 cl::desc("data layout string to use if not specified by module"),
184 cl::value_desc("layout-string"), cl::init(""));
188 static inline void addPass(PassManagerBase &PM, Pass *P) {
189 // Add the pass to the pass manager...
192 // If we are verifying all of the intermediate steps, add the verifier...
193 if (VerifyEach) PM.add(createVerifierPass());
196 /// AddOptimizationPasses - This routine adds optimization passes
197 /// based on selected optimization level, OptLevel. This routine
198 /// duplicates llvm-gcc behaviour.
200 /// OptLevel - Optimization Level
201 static void AddOptimizationPasses(PassManagerBase &MPM,FunctionPassManager &FPM,
202 unsigned OptLevel, unsigned SizeLevel) {
203 FPM.add(createVerifierPass()); // Verify that input is correct
205 PassManagerBuilder Builder;
206 Builder.OptLevel = OptLevel;
207 Builder.SizeLevel = SizeLevel;
211 } else if (OptLevel > 1) {
212 unsigned Threshold = 225;
213 if (SizeLevel == 1) // -Os
215 else if (SizeLevel == 2) // -Oz
219 Builder.Inliner = createFunctionInliningPass(Threshold);
221 Builder.Inliner = createAlwaysInlinerPass();
223 Builder.DisableUnitAtATime = !UnitAtATime;
224 Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
225 DisableLoopUnrolling : OptLevel == 0;
227 // This is final, unless there is a #pragma vectorize enable
228 if (DisableLoopVectorization)
229 Builder.LoopVectorize = false;
230 // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
231 else if (!Builder.LoopVectorize)
232 Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
234 // When #pragma vectorize is on for SLP, do the same as above
235 Builder.SLPVectorize =
236 DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
238 Builder.populateFunctionPassManager(FPM);
239 Builder.populateModulePassManager(MPM);
242 static void AddStandardCompilePasses(PassManagerBase &PM) {
243 PM.add(createVerifierPass()); // Verify that input is correct
245 // If the -strip-debug command line option was specified, do it.
247 addPass(PM, createStripSymbolsPass(true));
249 if (DisableOptimizations) return;
251 // -std-compile-opts adds the same module passes as -O3.
252 PassManagerBuilder Builder;
254 Builder.Inliner = createFunctionInliningPass();
255 Builder.OptLevel = 3;
256 Builder.populateModulePassManager(PM);
259 static void AddStandardLinkPasses(PassManagerBase &PM) {
260 PM.add(createVerifierPass()); // Verify that input is correct
262 // If the -strip-debug command line option was specified, do it.
264 addPass(PM, createStripSymbolsPass(true));
266 if (DisableOptimizations) return;
268 PassManagerBuilder Builder;
269 Builder.populateLTOPassManager(PM, /*Internalize=*/ !DisableInternalize,
270 /*RunInliner=*/ !DisableInline);
273 //===----------------------------------------------------------------------===//
274 // CodeGen-related helper functions.
277 CodeGenOpt::Level GetCodeGenOptLevel() {
279 return CodeGenOpt::Less;
281 return CodeGenOpt::Default;
283 return CodeGenOpt::Aggressive;
284 return CodeGenOpt::None;
287 // Returns the TargetMachine instance or zero if no triple is provided.
288 static TargetMachine* GetTargetMachine(Triple TheTriple) {
290 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
292 // Some modules don't specify a triple, and this is okay.
297 // Package up features to be passed to target/subtarget
298 std::string FeaturesStr;
300 SubtargetFeatures Features;
301 for (unsigned i = 0; i != MAttrs.size(); ++i)
302 Features.AddFeature(MAttrs[i]);
303 FeaturesStr = Features.getString();
306 return TheTarget->createTargetMachine(TheTriple.getTriple(),
308 InitTargetOptionsFromCodeGenFlags(),
310 GetCodeGenOptLevel());
313 //===----------------------------------------------------------------------===//
316 int main(int argc, char **argv) {
317 sys::PrintStackTraceOnErrorSignal();
318 llvm::PrettyStackTraceProgram X(argc, argv);
320 // Enable debug stream buffering.
321 EnableDebugBuffering = true;
323 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
324 LLVMContext &Context = getGlobalContext();
326 InitializeAllTargets();
327 InitializeAllTargetMCs();
330 PassRegistry &Registry = *PassRegistry::getPassRegistry();
331 initializeCore(Registry);
332 initializeDebugIRPass(Registry);
333 initializeScalarOpts(Registry);
334 initializeObjCARCOpts(Registry);
335 initializeVectorization(Registry);
336 initializeIPO(Registry);
337 initializeAnalysis(Registry);
338 initializeIPA(Registry);
339 initializeTransformUtils(Registry);
340 initializeInstCombine(Registry);
341 initializeInstrumentation(Registry);
342 initializeTarget(Registry);
344 cl::ParseCommandLineOptions(argc, argv,
345 "llvm .bc -> .bc modular optimizer and analysis printer\n");
347 if (AnalyzeOnly && NoOutput) {
348 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
354 // Load the input module...
356 M.reset(ParseIRFile(InputFilename, Err, Context));
359 Err.print(argv[0], errs());
363 // If we are supposed to override the target triple, do so now.
364 if (!TargetTriple.empty())
365 M->setTargetTriple(Triple::normalize(TargetTriple));
367 // Figure out what stream we are supposed to write to...
368 OwningPtr<tool_output_file> Out;
370 if (!OutputFilename.empty())
371 errs() << "WARNING: The -o (output filename) option is ignored when\n"
372 "the --disable-output option is used.\n";
374 // Default to standard output.
375 if (OutputFilename.empty())
376 OutputFilename = "-";
378 std::string ErrorInfo;
379 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
381 if (!ErrorInfo.empty()) {
382 errs() << ErrorInfo << '\n';
387 // If the output is set to be emitted to standard out, and standard out is a
388 // console, print out a warning message and refuse to do it. We don't
389 // impress anyone by spewing tons of binary goo to a terminal.
390 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
391 if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
394 if (PassPipeline.getNumOccurrences() > 0) {
395 OutputKind OK = OK_NoOutput;
397 OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
399 VerifierKind VK = VK_VerifyInAndOut;
403 VK = VK_VerifyEachPass;
405 // The user has asked to use the new pass manager and provided a pipeline
406 // string. Hand off the rest of the functionality to the new code for that
408 return runPassPipeline(argv[0], Context, *M.get(), Out.get(), PassPipeline,
414 // Create a PassManager to hold and optimize the collection of passes we are
419 // Add an appropriate TargetLibraryInfo pass for the module's triple.
420 TargetLibraryInfo *TLI = new TargetLibraryInfo(Triple(M->getTargetTriple()));
422 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
423 if (DisableSimplifyLibCalls)
424 TLI->disableAllFunctions();
427 // Add an appropriate DataLayout instance for this module.
429 const std::string &ModuleDataLayout = M.get()->getDataLayout();
430 if (!ModuleDataLayout.empty())
431 DL = new DataLayout(ModuleDataLayout);
432 else if (!DefaultDataLayout.empty())
433 DL = new DataLayout(DefaultDataLayout);
438 Triple ModuleTriple(M->getTargetTriple());
439 TargetMachine *Machine = 0;
440 if (ModuleTriple.getArch())
441 Machine = GetTargetMachine(Triple(ModuleTriple));
442 OwningPtr<TargetMachine> TM(Machine);
444 // Add internal analysis passes from the target machine.
446 TM->addAnalysisPasses(Passes);
448 OwningPtr<FunctionPassManager> FPasses;
449 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
450 FPasses.reset(new FunctionPassManager(M.get()));
452 FPasses->add(new DataLayout(*DL));
454 TM->addAnalysisPasses(*FPasses);
458 if (PrintBreakpoints) {
459 // Default to standard output.
461 if (OutputFilename.empty())
462 OutputFilename = "-";
464 std::string ErrorInfo;
465 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
467 if (!ErrorInfo.empty()) {
468 errs() << ErrorInfo << '\n';
472 Passes.add(createBreakpointPrinter(Out->os()));
476 // If the -strip-debug command line option was specified, add it. If
477 // -std-compile-opts was also specified, it will handle StripDebug.
478 if (StripDebug && !StandardCompileOpts)
479 addPass(Passes, createStripSymbolsPass(true));
481 // Create a new optimization pass for each one specified on the command line
482 for (unsigned i = 0; i < PassList.size(); ++i) {
483 // Check to see if -std-compile-opts was specified before this option. If
485 if (StandardCompileOpts &&
486 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
487 AddStandardCompilePasses(Passes);
488 StandardCompileOpts = false;
491 if (StandardLinkOpts &&
492 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
493 AddStandardLinkPasses(Passes);
494 StandardLinkOpts = false;
497 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
498 AddOptimizationPasses(Passes, *FPasses, 1, 0);
502 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
503 AddOptimizationPasses(Passes, *FPasses, 2, 0);
507 if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
508 AddOptimizationPasses(Passes, *FPasses, 2, 1);
512 if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
513 AddOptimizationPasses(Passes, *FPasses, 2, 2);
517 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
518 AddOptimizationPasses(Passes, *FPasses, 3, 0);
522 const PassInfo *PassInf = PassList[i];
524 if (PassInf->getTargetMachineCtor())
525 P = PassInf->getTargetMachineCtor()(TM.get());
526 else if (PassInf->getNormalCtor())
527 P = PassInf->getNormalCtor()();
529 errs() << argv[0] << ": cannot create pass: "
530 << PassInf->getPassName() << "\n";
532 PassKind Kind = P->getPassKind();
538 Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
541 Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
544 Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
547 Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
549 case PT_CallGraphSCC:
550 Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
553 Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
560 Passes.add(createPrintModulePass(errs()));
563 // If -std-compile-opts was specified at the end of the pass list, add them.
564 if (StandardCompileOpts) {
565 AddStandardCompilePasses(Passes);
566 StandardCompileOpts = false;
569 if (StandardLinkOpts) {
570 AddStandardLinkPasses(Passes);
571 StandardLinkOpts = false;
575 AddOptimizationPasses(Passes, *FPasses, 1, 0);
578 AddOptimizationPasses(Passes, *FPasses, 2, 0);
581 AddOptimizationPasses(Passes, *FPasses, 2, 1);
584 AddOptimizationPasses(Passes, *FPasses, 2, 2);
587 AddOptimizationPasses(Passes, *FPasses, 3, 0);
589 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
590 FPasses->doInitialization();
591 for (Module::iterator F = M->begin(), E = M->end(); F != E; ++F)
593 FPasses->doFinalization();
596 // Check that the module is well formed on completion of optimization
597 if (!NoVerify && !VerifyEach)
598 Passes.add(createVerifierPass());
600 // Write bitcode or assembly to the output as the last step...
601 if (!NoOutput && !AnalyzeOnly) {
603 Passes.add(createPrintModulePass(Out->os()));
605 Passes.add(createBitcodeWriterPass(Out->os()));
608 // Before executing passes, print the final values of the LLVM options.
609 cl::PrintOptionValues();
611 // Now that we have all of the passes ready, run them.
612 Passes.run(*M.get());
615 if (!NoOutput || PrintBreakpoints)