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/Analysis/TargetLibraryInfo.h"
24 #include "llvm/Analysis/TargetTransformInfo.h"
25 #include "llvm/Bitcode/BitcodeWriterPass.h"
26 #include "llvm/CodeGen/CommandFlags.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/IRPrintingPasses.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/LegacyPassNameParser.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/Verifier.h"
34 #include "llvm/IRReader/IRReader.h"
35 #include "llvm/InitializePasses.h"
36 #include "llvm/LinkAllIR.h"
37 #include "llvm/LinkAllPasses.h"
38 #include "llvm/MC/SubtargetFeature.h"
39 #include "llvm/IR/LegacyPassManager.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/FileSystem.h"
42 #include "llvm/Support/ManagedStatic.h"
43 #include "llvm/Support/PluginLoader.h"
44 #include "llvm/Support/PrettyStackTrace.h"
45 #include "llvm/Support/Signals.h"
46 #include "llvm/Support/SourceMgr.h"
47 #include "llvm/Support/SystemUtils.h"
48 #include "llvm/Support/TargetRegistry.h"
49 #include "llvm/Support/TargetSelect.h"
50 #include "llvm/Support/ToolOutputFile.h"
51 #include "llvm/Target/TargetMachine.h"
52 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
56 using namespace opt_tool;
58 // The OptimizationList is automatically populated with registered Passes by the
61 static cl::list<const PassInfo*, bool, PassNameParser>
62 PassList(cl::desc("Optimizations available:"));
64 // This flag specifies a textual description of the optimization pass pipeline
65 // to run over the module. This flag switches opt to use the new pass manager
66 // infrastructure, completely disabling all of the flags specific to the old
68 static cl::opt<std::string> PassPipeline(
70 cl::desc("A textual description of the pass pipeline for optimizing"),
73 // Other command line options...
75 static cl::opt<std::string>
76 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
77 cl::init("-"), cl::value_desc("filename"));
79 static cl::opt<std::string>
80 OutputFilename("o", cl::desc("Override output filename"),
81 cl::value_desc("filename"));
84 Force("f", cl::desc("Enable binary output on terminals"));
87 PrintEachXForm("p", cl::desc("Print module after each transformation"));
90 NoOutput("disable-output",
91 cl::desc("Do not write result bitcode file"), cl::Hidden);
94 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
97 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
100 VerifyEach("verify-each", cl::desc("Verify after each transform"));
103 StripDebug("strip-debug",
104 cl::desc("Strip debugger symbol info from translation unit"));
107 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
110 DisableOptimizations("disable-opt",
111 cl::desc("Do not run any optimization passes"));
114 StandardLinkOpts("std-link-opts",
115 cl::desc("Include the standard link time optimizations"));
119 cl::desc("Optimization level 1. Similar to clang -O1"));
123 cl::desc("Optimization level 2. Similar to clang -O2"));
127 cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
131 cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
135 cl::desc("Optimization level 3. Similar to clang -O3"));
137 static cl::opt<std::string>
138 TargetTriple("mtriple", cl::desc("Override target triple for module"));
141 UnitAtATime("funit-at-a-time",
142 cl::desc("Enable IPO. This corresponds to gcc's -funit-at-a-time"),
146 DisableLoopUnrolling("disable-loop-unrolling",
147 cl::desc("Disable loop unrolling in all relevant passes"),
150 DisableLoopVectorization("disable-loop-vectorization",
151 cl::desc("Disable the loop vectorization pass"),
155 DisableSLPVectorization("disable-slp-vectorization",
156 cl::desc("Disable the slp vectorization pass"),
161 DisableSimplifyLibCalls("disable-simplify-libcalls",
162 cl::desc("Disable simplify-libcalls"));
165 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
168 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
171 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
174 PrintBreakpoints("print-breakpoints-for-testing",
175 cl::desc("Print select breakpoints location for testing"));
177 static cl::opt<std::string>
178 DefaultDataLayout("default-data-layout",
179 cl::desc("data layout string to use if not specified by module"),
180 cl::value_desc("layout-string"), cl::init(""));
184 static inline void addPass(legacy::PassManagerBase &PM, Pass *P) {
185 // Add the pass to the pass manager...
188 // If we are verifying all of the intermediate steps, add the verifier...
190 PM.add(createVerifierPass());
193 /// This routine adds optimization passes based on selected optimization level,
196 /// OptLevel - Optimization Level
197 static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
198 legacy::FunctionPassManager &FPM,
199 unsigned OptLevel, unsigned SizeLevel) {
200 FPM.add(createVerifierPass()); // Verify that input is correct
202 PassManagerBuilder Builder;
203 Builder.OptLevel = OptLevel;
204 Builder.SizeLevel = SizeLevel;
208 } else if (OptLevel > 1) {
209 Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel);
211 Builder.Inliner = createAlwaysInlinerPass();
213 Builder.DisableUnitAtATime = !UnitAtATime;
214 Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
215 DisableLoopUnrolling : OptLevel == 0;
217 // This is final, unless there is a #pragma vectorize enable
218 if (DisableLoopVectorization)
219 Builder.LoopVectorize = false;
220 // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
221 else if (!Builder.LoopVectorize)
222 Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
224 // When #pragma vectorize is on for SLP, do the same as above
225 Builder.SLPVectorize =
226 DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
228 Builder.populateFunctionPassManager(FPM);
229 Builder.populateModulePassManager(MPM);
232 static void AddStandardLinkPasses(legacy::PassManagerBase &PM) {
233 PassManagerBuilder Builder;
234 Builder.VerifyInput = true;
235 if (DisableOptimizations)
236 Builder.OptLevel = 0;
239 Builder.Inliner = createFunctionInliningPass();
240 Builder.populateLTOPassManager(PM);
243 //===----------------------------------------------------------------------===//
244 // CodeGen-related helper functions.
247 static CodeGenOpt::Level GetCodeGenOptLevel() {
249 return CodeGenOpt::Less;
251 return CodeGenOpt::Default;
253 return CodeGenOpt::Aggressive;
254 return CodeGenOpt::None;
257 // Returns the TargetMachine instance or zero if no triple is provided.
258 static TargetMachine* GetTargetMachine(Triple TheTriple) {
260 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
262 // Some modules don't specify a triple, and this is okay.
267 // Package up features to be passed to target/subtarget
268 std::string FeaturesStr;
270 SubtargetFeatures Features;
271 for (unsigned i = 0; i != MAttrs.size(); ++i)
272 Features.AddFeature(MAttrs[i]);
273 FeaturesStr = Features.getString();
276 return TheTarget->createTargetMachine(TheTriple.getTriple(),
278 InitTargetOptionsFromCodeGenFlags(),
280 GetCodeGenOptLevel());
283 #ifdef LINK_POLLY_INTO_TOOLS
285 void initializePollyPasses(llvm::PassRegistry &Registry);
289 //===----------------------------------------------------------------------===//
292 int main(int argc, char **argv) {
293 sys::PrintStackTraceOnErrorSignal();
294 llvm::PrettyStackTraceProgram X(argc, argv);
296 // Enable debug stream buffering.
297 EnableDebugBuffering = true;
299 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
300 LLVMContext &Context = getGlobalContext();
302 InitializeAllTargets();
303 InitializeAllTargetMCs();
304 InitializeAllAsmPrinters();
307 PassRegistry &Registry = *PassRegistry::getPassRegistry();
308 initializeCore(Registry);
309 initializeScalarOpts(Registry);
310 initializeObjCARCOpts(Registry);
311 initializeVectorization(Registry);
312 initializeIPO(Registry);
313 initializeAnalysis(Registry);
314 initializeIPA(Registry);
315 initializeTransformUtils(Registry);
316 initializeInstCombine(Registry);
317 initializeInstrumentation(Registry);
318 initializeTarget(Registry);
319 // For codegen passes, only passes that do IR to IR transformation are
321 initializeCodeGenPreparePass(Registry);
322 initializeAtomicExpandPass(Registry);
323 initializeRewriteSymbolsPass(Registry);
324 initializeWinEHPreparePass(Registry);
325 initializeDwarfEHPreparePass(Registry);
327 #ifdef LINK_POLLY_INTO_TOOLS
328 polly::initializePollyPasses(Registry);
331 cl::ParseCommandLineOptions(argc, argv,
332 "llvm .bc -> .bc modular optimizer and analysis printer\n");
334 if (AnalyzeOnly && NoOutput) {
335 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
341 // Load the input module...
342 std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context);
345 Err.print(argv[0], errs());
349 // Strip debug info before running the verifier.
353 // Immediately run the verifier to catch any problems before starting up the
354 // pass pipelines. Otherwise we can crash on broken code during
355 // doInitialization().
356 if (!NoVerify && verifyModule(*M, &errs())) {
357 errs() << argv[0] << ": " << InputFilename << ": error: does not verify\n";
361 // If we are supposed to override the target triple, do so now.
362 if (!TargetTriple.empty())
363 M->setTargetTriple(Triple::normalize(TargetTriple));
365 // Figure out what stream we are supposed to write to...
366 std::unique_ptr<tool_output_file> Out;
368 if (!OutputFilename.empty())
369 errs() << "WARNING: The -o (output filename) option is ignored when\n"
370 "the --disable-output option is used.\n";
372 // Default to standard output.
373 if (OutputFilename.empty())
374 OutputFilename = "-";
377 Out.reset(new tool_output_file(OutputFilename, EC, sys::fs::F_None));
379 errs() << EC.message() << '\n';
384 Triple ModuleTriple(M->getTargetTriple());
385 TargetMachine *Machine = nullptr;
386 if (ModuleTriple.getArch())
387 Machine = GetTargetMachine(ModuleTriple);
388 std::unique_ptr<TargetMachine> TM(Machine);
390 // If the output is set to be emitted to standard out, and standard out is a
391 // console, print out a warning message and refuse to do it. We don't
392 // impress anyone by spewing tons of binary goo to a terminal.
393 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
394 if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
397 if (PassPipeline.getNumOccurrences() > 0) {
398 OutputKind OK = OK_NoOutput;
400 OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
402 VerifierKind VK = VK_VerifyInAndOut;
406 VK = VK_VerifyEachPass;
408 // The user has asked to use the new pass manager and provided a pipeline
409 // string. Hand off the rest of the functionality to the new code for that
411 return runPassPipeline(argv[0], Context, *M, TM.get(), Out.get(),
412 PassPipeline, OK, VK)
417 // Create a PassManager to hold and optimize the collection of passes we are
420 legacy::PassManager Passes;
422 // Add an appropriate TargetLibraryInfo pass for the module's triple.
423 TargetLibraryInfoImpl TLII(ModuleTriple);
425 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
426 if (DisableSimplifyLibCalls)
427 TLII.disableAllFunctions();
428 Passes.add(new TargetLibraryInfoWrapperPass(TLII));
430 // Add an appropriate DataLayout instance for this module.
431 const DataLayout &DL = M->getDataLayout();
432 if (DL.isDefault() && !DefaultDataLayout.empty()) {
433 M->setDataLayout(DefaultDataLayout);
436 // Add internal analysis passes from the target machine.
437 Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
438 : TargetIRAnalysis()));
440 std::unique_ptr<legacy::FunctionPassManager> FPasses;
441 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
442 FPasses.reset(new legacy::FunctionPassManager(M.get()));
443 FPasses->add(createTargetTransformInfoWrapperPass(
444 TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
447 if (PrintBreakpoints) {
448 // Default to standard output.
450 if (OutputFilename.empty())
451 OutputFilename = "-";
454 Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
457 errs() << EC.message() << '\n';
461 Passes.add(createBreakpointPrinter(Out->os()));
465 // Create a new optimization pass for each one specified on the command line
466 for (unsigned i = 0; i < PassList.size(); ++i) {
467 if (StandardLinkOpts &&
468 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
469 AddStandardLinkPasses(Passes);
470 StandardLinkOpts = false;
473 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
474 AddOptimizationPasses(Passes, *FPasses, 1, 0);
478 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
479 AddOptimizationPasses(Passes, *FPasses, 2, 0);
483 if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
484 AddOptimizationPasses(Passes, *FPasses, 2, 1);
488 if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
489 AddOptimizationPasses(Passes, *FPasses, 2, 2);
493 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
494 AddOptimizationPasses(Passes, *FPasses, 3, 0);
498 const PassInfo *PassInf = PassList[i];
500 if (PassInf->getTargetMachineCtor())
501 P = PassInf->getTargetMachineCtor()(TM.get());
502 else if (PassInf->getNormalCtor())
503 P = PassInf->getNormalCtor()();
505 errs() << argv[0] << ": cannot create pass: "
506 << PassInf->getPassName() << "\n";
508 PassKind Kind = P->getPassKind();
514 Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
517 Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
520 Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
523 Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
525 case PT_CallGraphSCC:
526 Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
529 Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
536 Passes.add(createPrintModulePass(errs()));
539 if (StandardLinkOpts) {
540 AddStandardLinkPasses(Passes);
541 StandardLinkOpts = false;
545 AddOptimizationPasses(Passes, *FPasses, 1, 0);
548 AddOptimizationPasses(Passes, *FPasses, 2, 0);
551 AddOptimizationPasses(Passes, *FPasses, 2, 1);
554 AddOptimizationPasses(Passes, *FPasses, 2, 2);
557 AddOptimizationPasses(Passes, *FPasses, 3, 0);
559 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
560 FPasses->doInitialization();
561 for (Function &F : *M)
563 FPasses->doFinalization();
566 // Check that the module is well formed on completion of optimization
567 if (!NoVerify && !VerifyEach)
568 Passes.add(createVerifierPass());
570 // Write bitcode or assembly to the output as the last step...
571 if (!NoOutput && !AnalyzeOnly) {
573 Passes.add(createPrintModulePass(Out->os()));
575 Passes.add(createBitcodeWriterPass(Out->os()));
578 // Before executing passes, print the final values of the LLVM options.
579 cl::PrintOptionValues();
581 // Now that we have all of the passes ready, run them.
585 if (!NoOutput || PrintBreakpoints)