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/LegacyPassNameParser.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/Verifier.h"
31 #include "llvm/IRReader/IRReader.h"
32 #include "llvm/InitializePasses.h"
33 #include "llvm/LinkAllIR.h"
34 #include "llvm/LinkAllPasses.h"
35 #include "llvm/MC/SubtargetFeature.h"
36 #include "llvm/PassManager.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ManagedStatic.h"
39 #include "llvm/Support/PluginLoader.h"
40 #include "llvm/Support/PrettyStackTrace.h"
41 #include "llvm/Support/Signals.h"
42 #include "llvm/Support/SourceMgr.h"
43 #include "llvm/Support/SystemUtils.h"
44 #include "llvm/Support/TargetRegistry.h"
45 #include "llvm/Support/TargetSelect.h"
46 #include "llvm/Support/ToolOutputFile.h"
47 #include "llvm/Target/TargetLibraryInfo.h"
48 #include "llvm/Target/TargetMachine.h"
49 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
53 using namespace opt_tool;
55 // The OptimizationList is automatically populated with registered Passes by the
58 static cl::list<const PassInfo*, bool, PassNameParser>
59 PassList(cl::desc("Optimizations available:"));
61 // This flag specifies a textual description of the optimization pass pipeline
62 // to run over the module. This flag switches opt to use the new pass manager
63 // infrastructure, completely disabling all of the flags specific to the old
65 static cl::opt<std::string> PassPipeline(
67 cl::desc("A textual description of the pass pipeline for optimizing"),
70 // Other command line options...
72 static cl::opt<std::string>
73 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
74 cl::init("-"), cl::value_desc("filename"));
76 static cl::opt<std::string>
77 OutputFilename("o", cl::desc("Override output filename"),
78 cl::value_desc("filename"));
81 Force("f", cl::desc("Enable binary output on terminals"));
84 PrintEachXForm("p", cl::desc("Print module after each transformation"));
87 NoOutput("disable-output",
88 cl::desc("Do not write result bitcode file"), cl::Hidden);
91 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
94 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
97 VerifyEach("verify-each", cl::desc("Verify after each transform"));
100 StripDebug("strip-debug",
101 cl::desc("Strip debugger symbol info from translation unit"));
104 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
107 DisableOptimizations("disable-opt",
108 cl::desc("Do not run any optimization passes"));
111 DisableInternalize("disable-internalize",
112 cl::desc("Do not mark all symbols as internal"));
115 StandardCompileOpts("std-compile-opts",
116 cl::desc("Include the standard compile time optimizations"));
119 StandardLinkOpts("std-link-opts",
120 cl::desc("Include the standard link time optimizations"));
124 cl::desc("Optimization level 1. Similar to clang -O1"));
128 cl::desc("Optimization level 2. Similar to clang -O2"));
132 cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
136 cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
140 cl::desc("Optimization level 3. Similar to clang -O3"));
142 static cl::opt<std::string>
143 TargetTriple("mtriple", cl::desc("Override target triple for module"));
146 UnitAtATime("funit-at-a-time",
147 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
151 DisableLoopUnrolling("disable-loop-unrolling",
152 cl::desc("Disable loop unrolling in all relevant passes"),
155 DisableLoopVectorization("disable-loop-vectorization",
156 cl::desc("Disable the loop vectorization pass"),
160 DisableSLPVectorization("disable-slp-vectorization",
161 cl::desc("Disable the slp vectorization pass"),
166 DisableSimplifyLibCalls("disable-simplify-libcalls",
167 cl::desc("Disable simplify-libcalls"));
170 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
173 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
176 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
179 PrintBreakpoints("print-breakpoints-for-testing",
180 cl::desc("Print select breakpoints location for testing"));
182 static cl::opt<std::string>
183 DefaultDataLayout("default-data-layout",
184 cl::desc("data layout string to use if not specified by module"),
185 cl::value_desc("layout-string"), cl::init(""));
189 static inline void addPass(PassManagerBase &PM, Pass *P) {
190 // Add the pass to the pass manager...
193 // If we are verifying all of the intermediate steps, add the verifier...
195 PM.add(createVerifierPass());
196 PM.add(createDebugInfoVerifierPass());
200 /// AddOptimizationPasses - This routine adds optimization passes
201 /// based on selected optimization level, OptLevel. This routine
202 /// duplicates llvm-gcc behaviour.
204 /// OptLevel - Optimization Level
205 static void AddOptimizationPasses(PassManagerBase &MPM,FunctionPassManager &FPM,
206 unsigned OptLevel, unsigned SizeLevel) {
207 FPM.add(createVerifierPass()); // Verify that input is correct
208 MPM.add(createDebugInfoVerifierPass()); // Verify that debug info is correct
210 PassManagerBuilder Builder;
211 Builder.OptLevel = OptLevel;
212 Builder.SizeLevel = SizeLevel;
216 } else if (OptLevel > 1) {
217 Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel);
219 Builder.Inliner = createAlwaysInlinerPass();
221 Builder.DisableUnitAtATime = !UnitAtATime;
222 Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
223 DisableLoopUnrolling : OptLevel == 0;
225 // This is final, unless there is a #pragma vectorize enable
226 if (DisableLoopVectorization)
227 Builder.LoopVectorize = false;
228 // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
229 else if (!Builder.LoopVectorize)
230 Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
232 // When #pragma vectorize is on for SLP, do the same as above
233 Builder.SLPVectorize =
234 DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
236 Builder.populateFunctionPassManager(FPM);
237 Builder.populateModulePassManager(MPM);
240 static void AddStandardCompilePasses(PassManagerBase &PM) {
241 PM.add(createVerifierPass()); // Verify that input is correct
243 // If the -strip-debug command line option was specified, do it.
245 addPass(PM, createStripSymbolsPass(true));
247 // Verify debug info only after it's (possibly) stripped.
248 PM.add(createDebugInfoVerifierPass());
250 if (DisableOptimizations) return;
252 // -std-compile-opts adds the same module passes as -O3.
253 PassManagerBuilder Builder;
255 Builder.Inliner = createFunctionInliningPass();
256 Builder.OptLevel = 3;
257 Builder.populateModulePassManager(PM);
260 static void AddStandardLinkPasses(PassManagerBase &PM) {
261 PM.add(createVerifierPass()); // Verify that input is correct
263 // If the -strip-debug command line option was specified, do it.
265 addPass(PM, createStripSymbolsPass(true));
267 // Verify debug info only after it's (possibly) stripped.
268 PM.add(createDebugInfoVerifierPass());
270 if (DisableOptimizations) return;
272 PassManagerBuilder Builder;
273 Builder.populateLTOPassManager(PM, /*Internalize=*/ !DisableInternalize,
274 /*RunInliner=*/ !DisableInline);
277 //===----------------------------------------------------------------------===//
278 // CodeGen-related helper functions.
281 CodeGenOpt::Level GetCodeGenOptLevel() {
283 return CodeGenOpt::Less;
285 return CodeGenOpt::Default;
287 return CodeGenOpt::Aggressive;
288 return CodeGenOpt::None;
291 // Returns the TargetMachine instance or zero if no triple is provided.
292 static TargetMachine* GetTargetMachine(Triple TheTriple) {
294 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
296 // Some modules don't specify a triple, and this is okay.
301 // Package up features to be passed to target/subtarget
302 std::string FeaturesStr;
304 SubtargetFeatures Features;
305 for (unsigned i = 0; i != MAttrs.size(); ++i)
306 Features.AddFeature(MAttrs[i]);
307 FeaturesStr = Features.getString();
310 return TheTarget->createTargetMachine(TheTriple.getTriple(),
312 InitTargetOptionsFromCodeGenFlags(),
314 GetCodeGenOptLevel());
317 #ifdef LINK_POLLY_INTO_TOOLS
319 void initializePollyPasses(llvm::PassRegistry &Registry);
323 //===----------------------------------------------------------------------===//
326 int main(int argc, char **argv) {
327 sys::PrintStackTraceOnErrorSignal();
328 llvm::PrettyStackTraceProgram X(argc, argv);
330 // Enable debug stream buffering.
331 EnableDebugBuffering = true;
333 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
334 LLVMContext &Context = getGlobalContext();
336 InitializeAllTargets();
337 InitializeAllTargetMCs();
340 PassRegistry &Registry = *PassRegistry::getPassRegistry();
341 initializeCore(Registry);
342 initializeDebugIRPass(Registry);
343 initializeScalarOpts(Registry);
344 initializeObjCARCOpts(Registry);
345 initializeVectorization(Registry);
346 initializeIPO(Registry);
347 initializeAnalysis(Registry);
348 initializeIPA(Registry);
349 initializeTransformUtils(Registry);
350 initializeInstCombine(Registry);
351 initializeInstrumentation(Registry);
352 initializeTarget(Registry);
353 // For codegen passes, only passes that do IR to IR transformation are
354 // supported. For now, just add CodeGenPrepare.
355 initializeCodeGenPreparePass(Registry);
357 #ifdef LINK_POLLY_INTO_TOOLS
358 polly::initializePollyPasses(Registry);
361 cl::ParseCommandLineOptions(argc, argv,
362 "llvm .bc -> .bc modular optimizer and analysis printer\n");
364 if (AnalyzeOnly && NoOutput) {
365 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
371 // Load the input module...
372 std::unique_ptr<Module> M;
373 M.reset(ParseIRFile(InputFilename, Err, Context));
376 Err.print(argv[0], errs());
380 // If we are supposed to override the target triple, do so now.
381 if (!TargetTriple.empty())
382 M->setTargetTriple(Triple::normalize(TargetTriple));
384 // Figure out what stream we are supposed to write to...
385 std::unique_ptr<tool_output_file> Out;
387 if (!OutputFilename.empty())
388 errs() << "WARNING: The -o (output filename) option is ignored when\n"
389 "the --disable-output option is used.\n";
391 // Default to standard output.
392 if (OutputFilename.empty())
393 OutputFilename = "-";
395 std::string ErrorInfo;
396 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
398 if (!ErrorInfo.empty()) {
399 errs() << ErrorInfo << '\n';
404 // If the output is set to be emitted to standard out, and standard out is a
405 // console, print out a warning message and refuse to do it. We don't
406 // impress anyone by spewing tons of binary goo to a terminal.
407 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
408 if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
411 if (PassPipeline.getNumOccurrences() > 0) {
412 OutputKind OK = OK_NoOutput;
414 OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
416 VerifierKind VK = VK_VerifyInAndOut;
420 VK = VK_VerifyEachPass;
422 // The user has asked to use the new pass manager and provided a pipeline
423 // string. Hand off the rest of the functionality to the new code for that
425 return runPassPipeline(argv[0], Context, *M.get(), Out.get(), PassPipeline,
431 // Create a PassManager to hold and optimize the collection of passes we are
436 // Add an appropriate TargetLibraryInfo pass for the module's triple.
437 TargetLibraryInfo *TLI = new TargetLibraryInfo(Triple(M->getTargetTriple()));
439 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
440 if (DisableSimplifyLibCalls)
441 TLI->disableAllFunctions();
444 // Add an appropriate DataLayout instance for this module.
445 const DataLayout *DL = M.get()->getDataLayout();
446 if (!DL && !DefaultDataLayout.empty()) {
447 M->setDataLayout(DefaultDataLayout);
448 DL = M.get()->getDataLayout();
452 Passes.add(new DataLayoutPass(M.get()));
454 Triple ModuleTriple(M->getTargetTriple());
455 TargetMachine *Machine = 0;
456 if (ModuleTriple.getArch())
457 Machine = GetTargetMachine(Triple(ModuleTriple));
458 std::unique_ptr<TargetMachine> TM(Machine);
460 // Add internal analysis passes from the target machine.
462 TM->addAnalysisPasses(Passes);
464 std::unique_ptr<FunctionPassManager> FPasses;
465 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
466 FPasses.reset(new FunctionPassManager(M.get()));
468 FPasses->add(new DataLayoutPass(M.get()));
470 TM->addAnalysisPasses(*FPasses);
474 if (PrintBreakpoints) {
475 // Default to standard output.
477 if (OutputFilename.empty())
478 OutputFilename = "-";
480 std::string ErrorInfo;
481 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
483 if (!ErrorInfo.empty()) {
484 errs() << ErrorInfo << '\n';
488 Passes.add(createBreakpointPrinter(Out->os()));
492 // If the -strip-debug command line option was specified, add it. If
493 // -std-compile-opts was also specified, it will handle StripDebug.
494 if (StripDebug && !StandardCompileOpts)
495 addPass(Passes, createStripSymbolsPass(true));
497 // Create a new optimization pass for each one specified on the command line
498 for (unsigned i = 0; i < PassList.size(); ++i) {
499 // Check to see if -std-compile-opts was specified before this option. If
501 if (StandardCompileOpts &&
502 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
503 AddStandardCompilePasses(Passes);
504 StandardCompileOpts = false;
507 if (StandardLinkOpts &&
508 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
509 AddStandardLinkPasses(Passes);
510 StandardLinkOpts = false;
513 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
514 AddOptimizationPasses(Passes, *FPasses, 1, 0);
518 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
519 AddOptimizationPasses(Passes, *FPasses, 2, 0);
523 if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
524 AddOptimizationPasses(Passes, *FPasses, 2, 1);
528 if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
529 AddOptimizationPasses(Passes, *FPasses, 2, 2);
533 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
534 AddOptimizationPasses(Passes, *FPasses, 3, 0);
538 const PassInfo *PassInf = PassList[i];
540 if (PassInf->getTargetMachineCtor())
541 P = PassInf->getTargetMachineCtor()(TM.get());
542 else if (PassInf->getNormalCtor())
543 P = PassInf->getNormalCtor()();
545 errs() << argv[0] << ": cannot create pass: "
546 << PassInf->getPassName() << "\n";
548 PassKind Kind = P->getPassKind();
554 Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
557 Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
560 Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
563 Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
565 case PT_CallGraphSCC:
566 Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
569 Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
576 Passes.add(createPrintModulePass(errs()));
579 // If -std-compile-opts was specified at the end of the pass list, add them.
580 if (StandardCompileOpts) {
581 AddStandardCompilePasses(Passes);
582 StandardCompileOpts = false;
585 if (StandardLinkOpts) {
586 AddStandardLinkPasses(Passes);
587 StandardLinkOpts = false;
591 AddOptimizationPasses(Passes, *FPasses, 1, 0);
594 AddOptimizationPasses(Passes, *FPasses, 2, 0);
597 AddOptimizationPasses(Passes, *FPasses, 2, 1);
600 AddOptimizationPasses(Passes, *FPasses, 2, 2);
603 AddOptimizationPasses(Passes, *FPasses, 3, 0);
605 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
606 FPasses->doInitialization();
607 for (Module::iterator F = M->begin(), E = M->end(); F != E; ++F)
609 FPasses->doFinalization();
612 // Check that the module is well formed on completion of optimization
613 if (!NoVerify && !VerifyEach) {
614 Passes.add(createVerifierPass());
615 Passes.add(createDebugInfoVerifierPass());
618 // Write bitcode or assembly to the output as the last step...
619 if (!NoOutput && !AnalyzeOnly) {
621 Passes.add(createPrintModulePass(Out->os()));
623 Passes.add(createBitcodeWriterPass(Out->os()));
626 // Before executing passes, print the final values of the LLVM options.
627 cl::PrintOptionValues();
629 // Now that we have all of the passes ready, run them.
630 Passes.run(*M.get());
633 if (!NoOutput || PrintBreakpoints)