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/LegacyPassManager.h"
32 #include "llvm/IR/LegacyPassNameParser.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/Verifier.h"
35 #include "llvm/IRReader/IRReader.h"
36 #include "llvm/InitializePasses.h"
37 #include "llvm/LinkAllIR.h"
38 #include "llvm/LinkAllPasses.h"
39 #include "llvm/MC/SubtargetFeature.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/FileSystem.h"
42 #include "llvm/Support/Host.h"
43 #include "llvm/Support/ManagedStatic.h"
44 #include "llvm/Support/PluginLoader.h"
45 #include "llvm/Support/PrettyStackTrace.h"
46 #include "llvm/Support/Signals.h"
47 #include "llvm/Support/SourceMgr.h"
48 #include "llvm/Support/SystemUtils.h"
49 #include "llvm/Support/TargetRegistry.h"
50 #include "llvm/Support/TargetSelect.h"
51 #include "llvm/Support/ToolOutputFile.h"
52 #include "llvm/Target/TargetMachine.h"
53 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
54 #include "llvm/Transforms/Utils/Cloning.h"
58 using namespace opt_tool;
60 // The OptimizationList is automatically populated with registered Passes by the
63 static cl::list<const PassInfo*, bool, PassNameParser>
64 PassList(cl::desc("Optimizations available:"));
66 // This flag specifies a textual description of the optimization pass pipeline
67 // to run over the module. This flag switches opt to use the new pass manager
68 // infrastructure, completely disabling all of the flags specific to the old
70 static cl::opt<std::string> PassPipeline(
72 cl::desc("A textual description of the pass pipeline for optimizing"),
75 // Other command line options...
77 static cl::opt<std::string>
78 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
79 cl::init("-"), cl::value_desc("filename"));
81 static cl::opt<std::string>
82 OutputFilename("o", cl::desc("Override output filename"),
83 cl::value_desc("filename"));
86 Force("f", cl::desc("Enable binary output on terminals"));
89 PrintEachXForm("p", cl::desc("Print module after each transformation"));
92 NoOutput("disable-output",
93 cl::desc("Do not write result bitcode file"), cl::Hidden);
96 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
99 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
102 VerifyEach("verify-each", cl::desc("Verify after each transform"));
105 StripDebug("strip-debug",
106 cl::desc("Strip debugger symbol info from translation unit"));
109 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
112 DisableOptimizations("disable-opt",
113 cl::desc("Do not run any optimization passes"));
116 StandardLinkOpts("std-link-opts",
117 cl::desc("Include the standard link time optimizations"));
121 cl::desc("Optimization level 1. Similar to clang -O1"));
125 cl::desc("Optimization level 2. Similar to clang -O2"));
129 cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
133 cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
137 cl::desc("Optimization level 3. Similar to clang -O3"));
139 static cl::opt<std::string>
140 TargetTriple("mtriple", cl::desc("Override target triple for module"));
143 UnitAtATime("funit-at-a-time",
144 cl::desc("Enable IPO. This corresponds to gcc's -funit-at-a-time"),
148 DisableLoopUnrolling("disable-loop-unrolling",
149 cl::desc("Disable loop unrolling in all relevant passes"),
152 DisableLoopVectorization("disable-loop-vectorization",
153 cl::desc("Disable the loop vectorization pass"),
157 DisableSLPVectorization("disable-slp-vectorization",
158 cl::desc("Disable the slp vectorization pass"),
163 DisableSimplifyLibCalls("disable-simplify-libcalls",
164 cl::desc("Disable simplify-libcalls"));
167 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
170 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
173 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
176 PrintBreakpoints("print-breakpoints-for-testing",
177 cl::desc("Print select breakpoints location for testing"));
179 static cl::opt<std::string>
180 DefaultDataLayout("default-data-layout",
181 cl::desc("data layout string to use if not specified by module"),
182 cl::value_desc("layout-string"), cl::init(""));
184 static cl::opt<bool> PreserveBitcodeUseListOrder(
185 "preserve-bc-uselistorder",
186 cl::desc("Preserve use-list order when writing LLVM bitcode."),
187 cl::init(true), cl::Hidden);
189 static cl::opt<bool> PreserveAssemblyUseListOrder(
190 "preserve-ll-uselistorder",
191 cl::desc("Preserve use-list order when writing LLVM assembly."),
192 cl::init(false), cl::Hidden);
195 RunTwice("run-twice",
196 cl::desc("Run all passes twice, re-using the same pass manager."),
197 cl::init(false), cl::Hidden);
199 static inline void addPass(legacy::PassManagerBase &PM, Pass *P) {
200 // Add the pass to the pass manager...
203 // If we are verifying all of the intermediate steps, add the verifier...
205 PM.add(createVerifierPass());
208 /// This routine adds optimization passes based on selected optimization level,
211 /// OptLevel - Optimization Level
212 static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
213 legacy::FunctionPassManager &FPM,
214 unsigned OptLevel, unsigned SizeLevel) {
215 FPM.add(createVerifierPass()); // Verify that input is correct
217 PassManagerBuilder Builder;
218 Builder.OptLevel = OptLevel;
219 Builder.SizeLevel = SizeLevel;
223 } else if (OptLevel > 1) {
224 Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel);
226 Builder.Inliner = createAlwaysInlinerPass();
228 Builder.DisableUnitAtATime = !UnitAtATime;
229 Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
230 DisableLoopUnrolling : OptLevel == 0;
232 // This is final, unless there is a #pragma vectorize enable
233 if (DisableLoopVectorization)
234 Builder.LoopVectorize = false;
235 // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
236 else if (!Builder.LoopVectorize)
237 Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
239 // When #pragma vectorize is on for SLP, do the same as above
240 Builder.SLPVectorize =
241 DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
243 Builder.populateFunctionPassManager(FPM);
244 Builder.populateModulePassManager(MPM);
247 static void AddStandardLinkPasses(legacy::PassManagerBase &PM) {
248 PassManagerBuilder Builder;
249 Builder.VerifyInput = true;
250 if (DisableOptimizations)
251 Builder.OptLevel = 0;
254 Builder.Inliner = createFunctionInliningPass();
255 Builder.populateLTOPassManager(PM);
258 //===----------------------------------------------------------------------===//
259 // CodeGen-related helper functions.
262 static CodeGenOpt::Level GetCodeGenOptLevel() {
264 return CodeGenOpt::Less;
266 return CodeGenOpt::Default;
268 return CodeGenOpt::Aggressive;
269 return CodeGenOpt::None;
272 // Returns the TargetMachine instance or zero if no triple is provided.
273 static TargetMachine* GetTargetMachine(Triple TheTriple, StringRef CPUStr,
274 StringRef FeaturesStr,
275 const TargetOptions &Options) {
277 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
279 // Some modules don't specify a triple, and this is okay.
284 return TheTarget->createTargetMachine(TheTriple.getTriple(),
285 CPUStr, FeaturesStr, Options,
287 GetCodeGenOptLevel());
290 #ifdef LINK_POLLY_INTO_TOOLS
292 void initializePollyPasses(llvm::PassRegistry &Registry);
296 //===----------------------------------------------------------------------===//
299 int main(int argc, char **argv) {
300 sys::PrintStackTraceOnErrorSignal();
301 llvm::PrettyStackTraceProgram X(argc, argv);
303 // Enable debug stream buffering.
304 EnableDebugBuffering = true;
306 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
307 LLVMContext &Context = getGlobalContext();
309 InitializeAllTargets();
310 InitializeAllTargetMCs();
311 InitializeAllAsmPrinters();
314 PassRegistry &Registry = *PassRegistry::getPassRegistry();
315 initializeCore(Registry);
316 initializeScalarOpts(Registry);
317 initializeObjCARCOpts(Registry);
318 initializeVectorization(Registry);
319 initializeIPO(Registry);
320 initializeAnalysis(Registry);
321 initializeTransformUtils(Registry);
322 initializeInstCombine(Registry);
323 initializeInstrumentation(Registry);
324 initializeTarget(Registry);
325 // For codegen passes, only passes that do IR to IR transformation are
327 initializeCodeGenPreparePass(Registry);
328 initializeAtomicExpandPass(Registry);
329 initializeRewriteSymbolsPass(Registry);
330 initializeWinEHPreparePass(Registry);
331 initializeDwarfEHPreparePass(Registry);
332 initializeSjLjEHPreparePass(Registry);
334 #ifdef LINK_POLLY_INTO_TOOLS
335 polly::initializePollyPasses(Registry);
338 cl::ParseCommandLineOptions(argc, argv,
339 "llvm .bc -> .bc modular optimizer and analysis printer\n");
341 if (AnalyzeOnly && NoOutput) {
342 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
348 // Load the input module...
349 std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context);
352 Err.print(argv[0], errs());
356 // Strip debug info before running the verifier.
360 // Immediately run the verifier to catch any problems before starting up the
361 // pass pipelines. Otherwise we can crash on broken code during
362 // doInitialization().
363 if (!NoVerify && verifyModule(*M, &errs())) {
364 errs() << argv[0] << ": " << InputFilename
365 << ": error: input module is broken!\n";
369 // If we are supposed to override the target triple, do so now.
370 if (!TargetTriple.empty())
371 M->setTargetTriple(Triple::normalize(TargetTriple));
373 // Figure out what stream we are supposed to write to...
374 std::unique_ptr<tool_output_file> Out;
376 if (!OutputFilename.empty())
377 errs() << "WARNING: The -o (output filename) option is ignored when\n"
378 "the --disable-output option is used.\n";
380 // Default to standard output.
381 if (OutputFilename.empty())
382 OutputFilename = "-";
385 Out.reset(new tool_output_file(OutputFilename, EC, sys::fs::F_None));
387 errs() << EC.message() << '\n';
392 Triple ModuleTriple(M->getTargetTriple());
393 std::string CPUStr, FeaturesStr;
394 TargetMachine *Machine = nullptr;
395 const TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
397 if (ModuleTriple.getArch()) {
398 CPUStr = getCPUStr();
399 FeaturesStr = getFeaturesStr();
400 Machine = GetTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options);
403 std::unique_ptr<TargetMachine> TM(Machine);
405 // Override function attributes based on CPUStr, FeaturesStr, and command line
407 setFunctionAttributes(CPUStr, FeaturesStr, *M);
409 // If the output is set to be emitted to standard out, and standard out is a
410 // console, print out a warning message and refuse to do it. We don't
411 // impress anyone by spewing tons of binary goo to a terminal.
412 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
413 if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
416 if (PassPipeline.getNumOccurrences() > 0) {
417 OutputKind OK = OK_NoOutput;
419 OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
421 VerifierKind VK = VK_VerifyInAndOut;
425 VK = VK_VerifyEachPass;
427 // The user has asked to use the new pass manager and provided a pipeline
428 // string. Hand off the rest of the functionality to the new code for that
430 return runPassPipeline(argv[0], Context, *M, TM.get(), Out.get(),
431 PassPipeline, OK, VK, PreserveAssemblyUseListOrder,
432 PreserveBitcodeUseListOrder)
437 // Create a PassManager to hold and optimize the collection of passes we are
440 legacy::PassManager Passes;
442 // Add an appropriate TargetLibraryInfo pass for the module's triple.
443 TargetLibraryInfoImpl TLII(ModuleTriple);
445 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
446 if (DisableSimplifyLibCalls)
447 TLII.disableAllFunctions();
448 Passes.add(new TargetLibraryInfoWrapperPass(TLII));
450 // Add an appropriate DataLayout instance for this module.
451 const DataLayout &DL = M->getDataLayout();
452 if (DL.isDefault() && !DefaultDataLayout.empty()) {
453 M->setDataLayout(DefaultDataLayout);
456 // Add internal analysis passes from the target machine.
457 Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
458 : TargetIRAnalysis()));
460 std::unique_ptr<legacy::FunctionPassManager> FPasses;
461 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
462 FPasses.reset(new legacy::FunctionPassManager(M.get()));
463 FPasses->add(createTargetTransformInfoWrapperPass(
464 TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
467 if (PrintBreakpoints) {
468 // Default to standard output.
470 if (OutputFilename.empty())
471 OutputFilename = "-";
474 Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
477 errs() << EC.message() << '\n';
481 Passes.add(createBreakpointPrinter(Out->os()));
485 // Create a new optimization pass for each one specified on the command line
486 for (unsigned i = 0; i < PassList.size(); ++i) {
487 if (StandardLinkOpts &&
488 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
489 AddStandardLinkPasses(Passes);
490 StandardLinkOpts = false;
493 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
494 AddOptimizationPasses(Passes, *FPasses, 1, 0);
498 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
499 AddOptimizationPasses(Passes, *FPasses, 2, 0);
503 if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
504 AddOptimizationPasses(Passes, *FPasses, 2, 1);
508 if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
509 AddOptimizationPasses(Passes, *FPasses, 2, 2);
513 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
514 AddOptimizationPasses(Passes, *FPasses, 3, 0);
518 const PassInfo *PassInf = PassList[i];
520 if (PassInf->getTargetMachineCtor())
521 P = PassInf->getTargetMachineCtor()(TM.get());
522 else if (PassInf->getNormalCtor())
523 P = PassInf->getNormalCtor()();
525 errs() << argv[0] << ": cannot create pass: "
526 << PassInf->getPassName() << "\n";
528 PassKind Kind = P->getPassKind();
534 Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
537 Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
540 Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
543 Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
545 case PT_CallGraphSCC:
546 Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
549 Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
557 createPrintModulePass(errs(), "", PreserveAssemblyUseListOrder));
560 if (StandardLinkOpts) {
561 AddStandardLinkPasses(Passes);
562 StandardLinkOpts = false;
566 AddOptimizationPasses(Passes, *FPasses, 1, 0);
569 AddOptimizationPasses(Passes, *FPasses, 2, 0);
572 AddOptimizationPasses(Passes, *FPasses, 2, 1);
575 AddOptimizationPasses(Passes, *FPasses, 2, 2);
578 AddOptimizationPasses(Passes, *FPasses, 3, 0);
580 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
581 FPasses->doInitialization();
582 for (Function &F : *M)
584 FPasses->doFinalization();
587 // Check that the module is well formed on completion of optimization
588 if (!NoVerify && !VerifyEach)
589 Passes.add(createVerifierPass());
591 // In run twice mode, we want to make sure the output is bit-by-bit
592 // equivalent if we run the pass manager again, so setup two buffers and
593 // a stream to write to them. Note that llc does something similar and it
594 // may be worth to abstract this out in the future.
595 SmallVector<char, 0> Buffer;
596 SmallVector<char, 0> CompileTwiceBuffer;
597 std::unique_ptr<raw_svector_ostream> BOS;
598 raw_ostream *OS = nullptr;
600 // Write bitcode or assembly to the output as the last step...
601 if (!NoOutput && !AnalyzeOnly) {
605 BOS = make_unique<raw_svector_ostream>(Buffer);
609 Passes.add(createPrintModulePass(*OS, "", PreserveAssemblyUseListOrder));
611 Passes.add(createBitcodeWriterPass(*OS, PreserveBitcodeUseListOrder));
614 // Before executing passes, print the final values of the LLVM options.
615 cl::PrintOptionValues();
617 // If requested, run all passes again with the same pass manager to catch
618 // bugs caused by persistent state in the passes
620 std::unique_ptr<Module> M2(CloneModule(M.get()));
622 CompileTwiceBuffer = Buffer;
626 // Now that we have all of the passes ready, run them.
629 // Compare the two outputs and make sure they're the same
632 if (Buffer.size() != CompileTwiceBuffer.size() ||
633 (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
635 errs() << "Running the pass manager twice changed the output.\n"
636 "Writing the result of the second run to the specified output.\n"
637 "To generate the one-run comparison binary, just run without\n"
638 "the compile-twice option\n";
639 Out->os() << BOS->str();
643 Out->os() << BOS->str();
647 if (!NoOutput || PrintBreakpoints)