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/IRPrintingPasses.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/LegacyPassNameParser.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Verifier.h"
33 #include "llvm/IRReader/IRReader.h"
34 #include "llvm/InitializePasses.h"
35 #include "llvm/LinkAllIR.h"
36 #include "llvm/LinkAllPasses.h"
37 #include "llvm/MC/SubtargetFeature.h"
38 #include "llvm/IR/LegacyPassManager.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/FileSystem.h"
41 #include "llvm/Support/ManagedStatic.h"
42 #include "llvm/Support/PluginLoader.h"
43 #include "llvm/Support/PrettyStackTrace.h"
44 #include "llvm/Support/Signals.h"
45 #include "llvm/Support/SourceMgr.h"
46 #include "llvm/Support/SystemUtils.h"
47 #include "llvm/Support/TargetRegistry.h"
48 #include "llvm/Support/TargetSelect.h"
49 #include "llvm/Support/ToolOutputFile.h"
50 #include "llvm/Target/TargetMachine.h"
51 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
55 using namespace opt_tool;
57 // The OptimizationList is automatically populated with registered Passes by the
60 static cl::list<const PassInfo*, bool, PassNameParser>
61 PassList(cl::desc("Optimizations available:"));
63 // This flag specifies a textual description of the optimization pass pipeline
64 // to run over the module. This flag switches opt to use the new pass manager
65 // infrastructure, completely disabling all of the flags specific to the old
67 static cl::opt<std::string> PassPipeline(
69 cl::desc("A textual description of the pass pipeline for optimizing"),
72 // Other command line options...
74 static cl::opt<std::string>
75 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
76 cl::init("-"), cl::value_desc("filename"));
78 static cl::opt<std::string>
79 OutputFilename("o", cl::desc("Override output filename"),
80 cl::value_desc("filename"));
83 Force("f", cl::desc("Enable binary output on terminals"));
86 PrintEachXForm("p", cl::desc("Print module after each transformation"));
89 NoOutput("disable-output",
90 cl::desc("Do not write result bitcode file"), cl::Hidden);
93 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
96 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
99 VerifyEach("verify-each", cl::desc("Verify after each transform"));
102 StripDebug("strip-debug",
103 cl::desc("Strip debugger symbol info from translation unit"));
106 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
109 DisableOptimizations("disable-opt",
110 cl::desc("Do not run any optimization passes"));
113 StandardLinkOpts("std-link-opts",
114 cl::desc("Include the standard link time optimizations"));
118 cl::desc("Optimization level 1. Similar to clang -O1"));
122 cl::desc("Optimization level 2. Similar to clang -O2"));
126 cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
130 cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
134 cl::desc("Optimization level 3. Similar to clang -O3"));
136 static cl::opt<std::string>
137 TargetTriple("mtriple", cl::desc("Override target triple for module"));
140 UnitAtATime("funit-at-a-time",
141 cl::desc("Enable IPO. This corresponds to gcc's -funit-at-a-time"),
145 DisableLoopUnrolling("disable-loop-unrolling",
146 cl::desc("Disable loop unrolling in all relevant passes"),
149 DisableLoopVectorization("disable-loop-vectorization",
150 cl::desc("Disable the loop vectorization pass"),
154 DisableSLPVectorization("disable-slp-vectorization",
155 cl::desc("Disable the slp vectorization pass"),
160 DisableSimplifyLibCalls("disable-simplify-libcalls",
161 cl::desc("Disable simplify-libcalls"));
164 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
167 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
170 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
173 PrintBreakpoints("print-breakpoints-for-testing",
174 cl::desc("Print select breakpoints location for testing"));
176 static cl::opt<std::string>
177 DefaultDataLayout("default-data-layout",
178 cl::desc("data layout string to use if not specified by module"),
179 cl::value_desc("layout-string"), cl::init(""));
183 static inline void addPass(legacy::PassManagerBase &PM, Pass *P) {
184 // Add the pass to the pass manager...
187 // If we are verifying all of the intermediate steps, add the verifier...
189 PM.add(createVerifierPass());
192 /// This routine adds optimization passes based on selected optimization level,
195 /// OptLevel - Optimization Level
196 static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
197 legacy::FunctionPassManager &FPM,
198 unsigned OptLevel, unsigned SizeLevel) {
199 FPM.add(createVerifierPass()); // Verify that input is correct
201 PassManagerBuilder Builder;
202 Builder.OptLevel = OptLevel;
203 Builder.SizeLevel = SizeLevel;
207 } else if (OptLevel > 1) {
208 Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel);
210 Builder.Inliner = createAlwaysInlinerPass();
212 Builder.DisableUnitAtATime = !UnitAtATime;
213 Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
214 DisableLoopUnrolling : OptLevel == 0;
216 // This is final, unless there is a #pragma vectorize enable
217 if (DisableLoopVectorization)
218 Builder.LoopVectorize = false;
219 // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
220 else if (!Builder.LoopVectorize)
221 Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
223 // When #pragma vectorize is on for SLP, do the same as above
224 Builder.SLPVectorize =
225 DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
227 Builder.populateFunctionPassManager(FPM);
228 Builder.populateModulePassManager(MPM);
231 static void AddStandardLinkPasses(legacy::PassManagerBase &PM) {
232 PassManagerBuilder Builder;
233 Builder.VerifyInput = true;
234 if (DisableOptimizations)
235 Builder.OptLevel = 0;
238 Builder.Inliner = createFunctionInliningPass();
239 Builder.populateLTOPassManager(PM);
242 //===----------------------------------------------------------------------===//
243 // CodeGen-related helper functions.
246 static CodeGenOpt::Level GetCodeGenOptLevel() {
248 return CodeGenOpt::Less;
250 return CodeGenOpt::Default;
252 return CodeGenOpt::Aggressive;
253 return CodeGenOpt::None;
256 // Returns the TargetMachine instance or zero if no triple is provided.
257 static TargetMachine* GetTargetMachine(Triple TheTriple) {
259 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
261 // Some modules don't specify a triple, and this is okay.
266 // Package up features to be passed to target/subtarget
267 std::string FeaturesStr;
269 SubtargetFeatures Features;
270 for (unsigned i = 0; i != MAttrs.size(); ++i)
271 Features.AddFeature(MAttrs[i]);
272 FeaturesStr = Features.getString();
275 return TheTarget->createTargetMachine(TheTriple.getTriple(),
277 InitTargetOptionsFromCodeGenFlags(),
279 GetCodeGenOptLevel());
282 #ifdef LINK_POLLY_INTO_TOOLS
284 void initializePollyPasses(llvm::PassRegistry &Registry);
288 //===----------------------------------------------------------------------===//
291 int main(int argc, char **argv) {
292 sys::PrintStackTraceOnErrorSignal();
293 llvm::PrettyStackTraceProgram X(argc, argv);
295 // Enable debug stream buffering.
296 EnableDebugBuffering = true;
298 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
299 LLVMContext &Context = getGlobalContext();
301 InitializeAllTargets();
302 InitializeAllTargetMCs();
303 InitializeAllAsmPrinters();
306 PassRegistry &Registry = *PassRegistry::getPassRegistry();
307 initializeCore(Registry);
308 initializeScalarOpts(Registry);
309 initializeObjCARCOpts(Registry);
310 initializeVectorization(Registry);
311 initializeIPO(Registry);
312 initializeAnalysis(Registry);
313 initializeIPA(Registry);
314 initializeTransformUtils(Registry);
315 initializeInstCombine(Registry);
316 initializeInstrumentation(Registry);
317 initializeTarget(Registry);
318 // For codegen passes, only passes that do IR to IR transformation are
320 initializeCodeGenPreparePass(Registry);
321 initializeAtomicExpandPass(Registry);
322 initializeRewriteSymbolsPass(Registry);
323 initializeWinEHPreparePass(Registry);
324 initializeDwarfEHPreparePass(Registry);
326 #ifdef LINK_POLLY_INTO_TOOLS
327 polly::initializePollyPasses(Registry);
330 cl::ParseCommandLineOptions(argc, argv,
331 "llvm .bc -> .bc modular optimizer and analysis printer\n");
333 if (AnalyzeOnly && NoOutput) {
334 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
340 // Load the input module...
341 std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context);
344 Err.print(argv[0], errs());
348 // If we are supposed to override the target triple, do so now.
349 if (!TargetTriple.empty())
350 M->setTargetTriple(Triple::normalize(TargetTriple));
352 // Figure out what stream we are supposed to write to...
353 std::unique_ptr<tool_output_file> Out;
355 if (!OutputFilename.empty())
356 errs() << "WARNING: The -o (output filename) option is ignored when\n"
357 "the --disable-output option is used.\n";
359 // Default to standard output.
360 if (OutputFilename.empty())
361 OutputFilename = "-";
364 Out.reset(new tool_output_file(OutputFilename, EC, sys::fs::F_None));
366 errs() << EC.message() << '\n';
371 Triple ModuleTriple(M->getTargetTriple());
372 TargetMachine *Machine = nullptr;
373 if (ModuleTriple.getArch())
374 Machine = GetTargetMachine(ModuleTriple);
375 std::unique_ptr<TargetMachine> TM(Machine);
377 // If the output is set to be emitted to standard out, and standard out is a
378 // console, print out a warning message and refuse to do it. We don't
379 // impress anyone by spewing tons of binary goo to a terminal.
380 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
381 if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
384 if (PassPipeline.getNumOccurrences() > 0) {
385 OutputKind OK = OK_NoOutput;
387 OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
389 VerifierKind VK = VK_VerifyInAndOut;
393 VK = VK_VerifyEachPass;
395 // The user has asked to use the new pass manager and provided a pipeline
396 // string. Hand off the rest of the functionality to the new code for that
398 return runPassPipeline(argv[0], Context, *M, TM.get(), Out.get(),
399 PassPipeline, OK, VK)
404 // Create a PassManager to hold and optimize the collection of passes we are
407 legacy::PassManager Passes;
409 // Add an appropriate TargetLibraryInfo pass for the module's triple.
410 TargetLibraryInfoImpl TLII(ModuleTriple);
412 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
413 if (DisableSimplifyLibCalls)
414 TLII.disableAllFunctions();
415 Passes.add(new TargetLibraryInfoWrapperPass(TLII));
417 // Add an appropriate DataLayout instance for this module.
418 const DataLayout &DL = M->getDataLayout();
419 if (DL.isDefault() && !DefaultDataLayout.empty()) {
420 M->setDataLayout(DefaultDataLayout);
423 // Add internal analysis passes from the target machine.
424 Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
425 : TargetIRAnalysis()));
427 std::unique_ptr<legacy::FunctionPassManager> FPasses;
428 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
429 FPasses.reset(new legacy::FunctionPassManager(M.get()));
430 FPasses->add(createTargetTransformInfoWrapperPass(
431 TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
434 if (PrintBreakpoints) {
435 // Default to standard output.
437 if (OutputFilename.empty())
438 OutputFilename = "-";
441 Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
444 errs() << EC.message() << '\n';
448 Passes.add(createBreakpointPrinter(Out->os()));
452 // If the -strip-debug command line option was specified, add it.
454 addPass(Passes, createStripSymbolsPass(true));
456 // Create a new optimization pass for each one specified on the command line
457 for (unsigned i = 0; i < PassList.size(); ++i) {
458 if (StandardLinkOpts &&
459 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
460 AddStandardLinkPasses(Passes);
461 StandardLinkOpts = false;
464 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
465 AddOptimizationPasses(Passes, *FPasses, 1, 0);
469 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
470 AddOptimizationPasses(Passes, *FPasses, 2, 0);
474 if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
475 AddOptimizationPasses(Passes, *FPasses, 2, 1);
479 if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
480 AddOptimizationPasses(Passes, *FPasses, 2, 2);
484 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
485 AddOptimizationPasses(Passes, *FPasses, 3, 0);
489 const PassInfo *PassInf = PassList[i];
491 if (PassInf->getTargetMachineCtor())
492 P = PassInf->getTargetMachineCtor()(TM.get());
493 else if (PassInf->getNormalCtor())
494 P = PassInf->getNormalCtor()();
496 errs() << argv[0] << ": cannot create pass: "
497 << PassInf->getPassName() << "\n";
499 PassKind Kind = P->getPassKind();
505 Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
508 Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
511 Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
514 Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
516 case PT_CallGraphSCC:
517 Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
520 Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
527 Passes.add(createPrintModulePass(errs()));
530 if (StandardLinkOpts) {
531 AddStandardLinkPasses(Passes);
532 StandardLinkOpts = false;
536 AddOptimizationPasses(Passes, *FPasses, 1, 0);
539 AddOptimizationPasses(Passes, *FPasses, 2, 0);
542 AddOptimizationPasses(Passes, *FPasses, 2, 1);
545 AddOptimizationPasses(Passes, *FPasses, 2, 2);
548 AddOptimizationPasses(Passes, *FPasses, 3, 0);
550 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
551 FPasses->doInitialization();
552 for (Function &F : *M)
554 FPasses->doFinalization();
557 // Check that the module is well formed on completion of optimization
558 if (!NoVerify && !VerifyEach)
559 Passes.add(createVerifierPass());
561 // Write bitcode or assembly to the output as the last step...
562 if (!NoOutput && !AnalyzeOnly) {
564 Passes.add(createPrintModulePass(Out->os()));
566 Passes.add(createBitcodeWriterPass(Out->os()));
569 // Before executing passes, print the final values of the LLVM options.
570 cl::PrintOptionValues();
572 // Now that we have all of the passes ready, run them.
576 if (!NoOutput || PrintBreakpoints)