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/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"
57 using namespace opt_tool;
59 // The OptimizationList is automatically populated with registered Passes by the
62 static cl::list<const PassInfo*, bool, PassNameParser>
63 PassList(cl::desc("Optimizations available:"));
65 // This flag specifies a textual description of the optimization pass pipeline
66 // to run over the module. This flag switches opt to use the new pass manager
67 // infrastructure, completely disabling all of the flags specific to the old
69 static cl::opt<std::string> PassPipeline(
71 cl::desc("A textual description of the pass pipeline for optimizing"),
74 // Other command line options...
76 static cl::opt<std::string>
77 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
78 cl::init("-"), cl::value_desc("filename"));
80 static cl::opt<std::string>
81 OutputFilename("o", cl::desc("Override output filename"),
82 cl::value_desc("filename"));
85 Force("f", cl::desc("Enable binary output on terminals"));
88 PrintEachXForm("p", cl::desc("Print module after each transformation"));
91 NoOutput("disable-output",
92 cl::desc("Do not write result bitcode file"), cl::Hidden);
95 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
98 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
101 VerifyEach("verify-each", cl::desc("Verify after each transform"));
104 StripDebug("strip-debug",
105 cl::desc("Strip debugger symbol info from translation unit"));
108 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
111 DisableOptimizations("disable-opt",
112 cl::desc("Do not run any optimization passes"));
115 StandardLinkOpts("std-link-opts",
116 cl::desc("Include the standard link time optimizations"));
120 cl::desc("Optimization level 1. Similar to clang -O1"));
124 cl::desc("Optimization level 2. Similar to clang -O2"));
128 cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
132 cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
136 cl::desc("Optimization level 3. Similar to clang -O3"));
138 static cl::opt<std::string>
139 TargetTriple("mtriple", cl::desc("Override target triple for module"));
142 UnitAtATime("funit-at-a-time",
143 cl::desc("Enable IPO. This corresponds to gcc's -funit-at-a-time"),
147 DisableLoopUnrolling("disable-loop-unrolling",
148 cl::desc("Disable loop unrolling in all relevant passes"),
151 DisableLoopVectorization("disable-loop-vectorization",
152 cl::desc("Disable the loop vectorization pass"),
156 DisableSLPVectorization("disable-slp-vectorization",
157 cl::desc("Disable the slp vectorization pass"),
162 DisableSimplifyLibCalls("disable-simplify-libcalls",
163 cl::desc("Disable simplify-libcalls"));
166 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
169 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
172 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
175 PrintBreakpoints("print-breakpoints-for-testing",
176 cl::desc("Print select breakpoints location for testing"));
178 static cl::opt<std::string>
179 DefaultDataLayout("default-data-layout",
180 cl::desc("data layout string to use if not specified by module"),
181 cl::value_desc("layout-string"), cl::init(""));
183 static cl::opt<bool> PreserveBitcodeUseListOrder(
184 "preserve-bc-uselistorder",
185 cl::desc("Preserve use-list order when writing LLVM bitcode."),
186 cl::init(true), cl::Hidden);
188 static cl::opt<bool> PreserveAssemblyUseListOrder(
189 "preserve-ll-uselistorder",
190 cl::desc("Preserve use-list order when writing LLVM assembly."),
191 cl::init(false), cl::Hidden);
193 static inline void addPass(legacy::PassManagerBase &PM, Pass *P) {
194 // Add the pass to the pass manager...
197 // If we are verifying all of the intermediate steps, add the verifier...
199 PM.add(createVerifierPass());
202 /// This routine adds optimization passes based on selected optimization level,
205 /// OptLevel - Optimization Level
206 static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
207 legacy::FunctionPassManager &FPM,
208 unsigned OptLevel, unsigned SizeLevel) {
209 FPM.add(createVerifierPass()); // Verify that input is correct
211 PassManagerBuilder Builder;
212 Builder.OptLevel = OptLevel;
213 Builder.SizeLevel = SizeLevel;
217 } else if (OptLevel > 1) {
218 Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel);
220 Builder.Inliner = createAlwaysInlinerPass();
222 Builder.DisableUnitAtATime = !UnitAtATime;
223 Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
224 DisableLoopUnrolling : OptLevel == 0;
226 // This is final, unless there is a #pragma vectorize enable
227 if (DisableLoopVectorization)
228 Builder.LoopVectorize = false;
229 // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
230 else if (!Builder.LoopVectorize)
231 Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
233 // When #pragma vectorize is on for SLP, do the same as above
234 Builder.SLPVectorize =
235 DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
237 Builder.populateFunctionPassManager(FPM);
238 Builder.populateModulePassManager(MPM);
241 static void AddStandardLinkPasses(legacy::PassManagerBase &PM) {
242 PassManagerBuilder Builder;
243 Builder.VerifyInput = true;
244 if (DisableOptimizations)
245 Builder.OptLevel = 0;
248 Builder.Inliner = createFunctionInliningPass();
249 Builder.populateLTOPassManager(PM);
252 //===----------------------------------------------------------------------===//
253 // CodeGen-related helper functions.
256 static CodeGenOpt::Level GetCodeGenOptLevel() {
258 return CodeGenOpt::Less;
260 return CodeGenOpt::Default;
262 return CodeGenOpt::Aggressive;
263 return CodeGenOpt::None;
266 // Returns the TargetMachine instance or zero if no triple is provided.
267 static TargetMachine* GetTargetMachine(Triple TheTriple, StringRef CPUStr,
268 StringRef FeaturesStr,
269 const TargetOptions &Options) {
271 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
273 // Some modules don't specify a triple, and this is okay.
278 return TheTarget->createTargetMachine(TheTriple.getTriple(),
279 CPUStr, FeaturesStr, Options,
281 GetCodeGenOptLevel());
284 #ifdef LINK_POLLY_INTO_TOOLS
286 void initializePollyPasses(llvm::PassRegistry &Registry);
290 //===----------------------------------------------------------------------===//
293 int main(int argc, char **argv) {
294 sys::PrintStackTraceOnErrorSignal();
295 llvm::PrettyStackTraceProgram X(argc, argv);
297 // Enable debug stream buffering.
298 EnableDebugBuffering = true;
300 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
301 LLVMContext &Context = getGlobalContext();
303 InitializeAllTargets();
304 InitializeAllTargetMCs();
305 InitializeAllAsmPrinters();
308 PassRegistry &Registry = *PassRegistry::getPassRegistry();
309 initializeCore(Registry);
310 initializeScalarOpts(Registry);
311 initializeObjCARCOpts(Registry);
312 initializeVectorization(Registry);
313 initializeIPO(Registry);
314 initializeAnalysis(Registry);
315 initializeIPA(Registry);
316 initializeTransformUtils(Registry);
317 initializeInstCombine(Registry);
318 initializeInstrumentation(Registry);
319 initializeTarget(Registry);
320 // For codegen passes, only passes that do IR to IR transformation are
322 initializeCodeGenPreparePass(Registry);
323 initializeAtomicExpandPass(Registry);
324 initializeRewriteSymbolsPass(Registry);
325 initializeWinEHPreparePass(Registry);
326 initializeDwarfEHPreparePass(Registry);
327 initializeSjLjEHPreparePass(Registry);
329 #ifdef LINK_POLLY_INTO_TOOLS
330 polly::initializePollyPasses(Registry);
333 cl::ParseCommandLineOptions(argc, argv,
334 "llvm .bc -> .bc modular optimizer and analysis printer\n");
336 if (AnalyzeOnly && NoOutput) {
337 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
343 // Load the input module...
344 std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context);
347 Err.print(argv[0], errs());
351 // Strip debug info before running the verifier.
355 // Immediately run the verifier to catch any problems before starting up the
356 // pass pipelines. Otherwise we can crash on broken code during
357 // doInitialization().
358 if (!NoVerify && verifyModule(*M, &errs())) {
359 errs() << argv[0] << ": " << InputFilename
360 << ": error: input module is broken!\n";
364 // If we are supposed to override the target triple, do so now.
365 if (!TargetTriple.empty())
366 M->setTargetTriple(Triple::normalize(TargetTriple));
368 // Figure out what stream we are supposed to write to...
369 std::unique_ptr<tool_output_file> Out;
371 if (!OutputFilename.empty())
372 errs() << "WARNING: The -o (output filename) option is ignored when\n"
373 "the --disable-output option is used.\n";
375 // Default to standard output.
376 if (OutputFilename.empty())
377 OutputFilename = "-";
380 Out.reset(new tool_output_file(OutputFilename, EC, sys::fs::F_None));
382 errs() << EC.message() << '\n';
387 Triple ModuleTriple(M->getTargetTriple());
388 std::string CPUStr, FeaturesStr;
389 TargetMachine *Machine = nullptr;
390 const TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
392 if (ModuleTriple.getArch()) {
393 CPUStr = getCPUStr();
394 FeaturesStr = getFeaturesStr();
395 Machine = GetTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options);
398 std::unique_ptr<TargetMachine> TM(Machine);
400 // Override function attributes based on CPUStr, FeaturesStr, and command line
402 setFunctionAttributes(CPUStr, FeaturesStr, *M);
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, TM.get(), Out.get(),
426 PassPipeline, OK, VK, PreserveAssemblyUseListOrder,
427 PreserveBitcodeUseListOrder)
432 // Create a PassManager to hold and optimize the collection of passes we are
435 legacy::PassManager Passes;
437 // Add an appropriate TargetLibraryInfo pass for the module's triple.
438 TargetLibraryInfoImpl TLII(ModuleTriple);
440 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
441 if (DisableSimplifyLibCalls)
442 TLII.disableAllFunctions();
443 Passes.add(new TargetLibraryInfoWrapperPass(TLII));
445 // Add an appropriate DataLayout instance for this module.
446 const DataLayout &DL = M->getDataLayout();
447 if (DL.isDefault() && !DefaultDataLayout.empty()) {
448 M->setDataLayout(DefaultDataLayout);
451 // Add internal analysis passes from the target machine.
452 Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
453 : TargetIRAnalysis()));
455 std::unique_ptr<legacy::FunctionPassManager> FPasses;
456 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
457 FPasses.reset(new legacy::FunctionPassManager(M.get()));
458 FPasses->add(createTargetTransformInfoWrapperPass(
459 TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
462 if (PrintBreakpoints) {
463 // Default to standard output.
465 if (OutputFilename.empty())
466 OutputFilename = "-";
469 Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
472 errs() << EC.message() << '\n';
476 Passes.add(createBreakpointPrinter(Out->os()));
480 // Create a new optimization pass for each one specified on the command line
481 for (unsigned i = 0; i < PassList.size(); ++i) {
482 if (StandardLinkOpts &&
483 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
484 AddStandardLinkPasses(Passes);
485 StandardLinkOpts = false;
488 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
489 AddOptimizationPasses(Passes, *FPasses, 1, 0);
493 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
494 AddOptimizationPasses(Passes, *FPasses, 2, 0);
498 if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
499 AddOptimizationPasses(Passes, *FPasses, 2, 1);
503 if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
504 AddOptimizationPasses(Passes, *FPasses, 2, 2);
508 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
509 AddOptimizationPasses(Passes, *FPasses, 3, 0);
513 const PassInfo *PassInf = PassList[i];
515 if (PassInf->getTargetMachineCtor())
516 P = PassInf->getTargetMachineCtor()(TM.get());
517 else if (PassInf->getNormalCtor())
518 P = PassInf->getNormalCtor()();
520 errs() << argv[0] << ": cannot create pass: "
521 << PassInf->getPassName() << "\n";
523 PassKind Kind = P->getPassKind();
529 Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
532 Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
535 Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
538 Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
540 case PT_CallGraphSCC:
541 Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
544 Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
552 createPrintModulePass(errs(), "", PreserveAssemblyUseListOrder));
555 if (StandardLinkOpts) {
556 AddStandardLinkPasses(Passes);
557 StandardLinkOpts = false;
561 AddOptimizationPasses(Passes, *FPasses, 1, 0);
564 AddOptimizationPasses(Passes, *FPasses, 2, 0);
567 AddOptimizationPasses(Passes, *FPasses, 2, 1);
570 AddOptimizationPasses(Passes, *FPasses, 2, 2);
573 AddOptimizationPasses(Passes, *FPasses, 3, 0);
575 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
576 FPasses->doInitialization();
577 for (Function &F : *M)
579 FPasses->doFinalization();
582 // Check that the module is well formed on completion of optimization
583 if (!NoVerify && !VerifyEach)
584 Passes.add(createVerifierPass());
586 // Write bitcode or assembly to the output as the last step...
587 if (!NoOutput && !AnalyzeOnly) {
590 createPrintModulePass(Out->os(), "", PreserveAssemblyUseListOrder));
593 createBitcodeWriterPass(Out->os(), PreserveBitcodeUseListOrder));
596 // Before executing passes, print the final values of the LLVM options.
597 cl::PrintOptionValues();
599 // Now that we have all of the passes ready, run them.
603 if (!NoOutput || PrintBreakpoints)