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/FileSystem.h"
39 #include "llvm/Support/ManagedStatic.h"
40 #include "llvm/Support/PluginLoader.h"
41 #include "llvm/Support/PrettyStackTrace.h"
42 #include "llvm/Support/Signals.h"
43 #include "llvm/Support/SourceMgr.h"
44 #include "llvm/Support/SystemUtils.h"
45 #include "llvm/Support/TargetRegistry.h"
46 #include "llvm/Support/TargetSelect.h"
47 #include "llvm/Support/ToolOutputFile.h"
48 #include "llvm/Target/TargetLibraryInfo.h"
49 #include "llvm/Target/TargetMachine.h"
50 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
54 using namespace opt_tool;
56 // The OptimizationList is automatically populated with registered Passes by the
59 static cl::list<const PassInfo*, bool, PassNameParser>
60 PassList(cl::desc("Optimizations available:"));
62 // This flag specifies a textual description of the optimization pass pipeline
63 // to run over the module. This flag switches opt to use the new pass manager
64 // infrastructure, completely disabling all of the flags specific to the old
66 static cl::opt<std::string> PassPipeline(
68 cl::desc("A textual description of the pass pipeline for optimizing"),
71 // Other command line options...
73 static cl::opt<std::string>
74 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
75 cl::init("-"), cl::value_desc("filename"));
77 static cl::opt<std::string>
78 OutputFilename("o", cl::desc("Override output filename"),
79 cl::value_desc("filename"));
82 Force("f", cl::desc("Enable binary output on terminals"));
85 PrintEachXForm("p", cl::desc("Print module after each transformation"));
88 NoOutput("disable-output",
89 cl::desc("Do not write result bitcode file"), cl::Hidden);
92 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
95 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
98 VerifyEach("verify-each", cl::desc("Verify after each transform"));
101 StripDebug("strip-debug",
102 cl::desc("Strip debugger symbol info from translation unit"));
105 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
108 DisableOptimizations("disable-opt",
109 cl::desc("Do not run any optimization passes"));
112 StandardLinkOpts("std-link-opts",
113 cl::desc("Include the standard link time optimizations"));
117 cl::desc("Optimization level 1. Similar to clang -O1"));
121 cl::desc("Optimization level 2. Similar to clang -O2"));
125 cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
129 cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
133 cl::desc("Optimization level 3. Similar to clang -O3"));
135 static cl::opt<std::string>
136 TargetTriple("mtriple", cl::desc("Override target triple for module"));
139 UnitAtATime("funit-at-a-time",
140 cl::desc("Enable IPO. This corresponds to gcc's -funit-at-a-time"),
144 DisableLoopUnrolling("disable-loop-unrolling",
145 cl::desc("Disable loop unrolling in all relevant passes"),
148 DisableLoopVectorization("disable-loop-vectorization",
149 cl::desc("Disable the loop vectorization pass"),
153 DisableSLPVectorization("disable-slp-vectorization",
154 cl::desc("Disable the slp vectorization pass"),
159 DisableSimplifyLibCalls("disable-simplify-libcalls",
160 cl::desc("Disable simplify-libcalls"));
163 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
166 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
169 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
172 PrintBreakpoints("print-breakpoints-for-testing",
173 cl::desc("Print select breakpoints location for testing"));
175 static cl::opt<std::string>
176 DefaultDataLayout("default-data-layout",
177 cl::desc("data layout string to use if not specified by module"),
178 cl::value_desc("layout-string"), cl::init(""));
182 static inline void addPass(PassManagerBase &PM, Pass *P) {
183 // Add the pass to the pass manager...
186 // If we are verifying all of the intermediate steps, add the verifier...
188 PM.add(createVerifierPass());
189 PM.add(createDebugInfoVerifierPass());
193 /// This routine adds optimization passes based on selected optimization level,
196 /// OptLevel - Optimization Level
197 static void AddOptimizationPasses(PassManagerBase &MPM,FunctionPassManager &FPM,
198 unsigned OptLevel, unsigned SizeLevel) {
199 FPM.add(createVerifierPass()); // Verify that input is correct
200 MPM.add(createDebugInfoVerifierPass()); // Verify that debug info 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(PassManagerBase &PM) {
233 PassManagerBuilder Builder;
234 Builder.VerifyInput = true;
235 Builder.StripDebug = StripDebug;
236 if (DisableOptimizations)
237 Builder.OptLevel = 0;
240 Builder.Inliner = createFunctionInliningPass();
241 Builder.populateLTOPassManager(PM);
244 //===----------------------------------------------------------------------===//
245 // CodeGen-related helper functions.
248 CodeGenOpt::Level GetCodeGenOptLevel() {
250 return CodeGenOpt::Less;
252 return CodeGenOpt::Default;
254 return CodeGenOpt::Aggressive;
255 return CodeGenOpt::None;
258 // Returns the TargetMachine instance or zero if no triple is provided.
259 static TargetMachine* GetTargetMachine(Triple TheTriple) {
261 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
263 // Some modules don't specify a triple, and this is okay.
268 // Package up features to be passed to target/subtarget
269 std::string FeaturesStr;
271 SubtargetFeatures Features;
272 for (unsigned i = 0; i != MAttrs.size(); ++i)
273 Features.AddFeature(MAttrs[i]);
274 FeaturesStr = Features.getString();
277 return TheTarget->createTargetMachine(TheTriple.getTriple(),
279 InitTargetOptionsFromCodeGenFlags(),
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);
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 // If the output is set to be emitted to standard out, and standard out is a
372 // console, print out a warning message and refuse to do it. We don't
373 // impress anyone by spewing tons of binary goo to a terminal.
374 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
375 if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
378 if (PassPipeline.getNumOccurrences() > 0) {
379 OutputKind OK = OK_NoOutput;
381 OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
383 VerifierKind VK = VK_VerifyInAndOut;
387 VK = VK_VerifyEachPass;
389 // The user has asked to use the new pass manager and provided a pipeline
390 // string. Hand off the rest of the functionality to the new code for that
392 return runPassPipeline(argv[0], Context, *M, Out.get(), PassPipeline,
398 // Create a PassManager to hold and optimize the collection of passes we are
403 // Add an appropriate TargetLibraryInfo pass for the module's triple.
404 TargetLibraryInfo *TLI = new TargetLibraryInfo(Triple(M->getTargetTriple()));
406 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
407 if (DisableSimplifyLibCalls)
408 TLI->disableAllFunctions();
411 // Add an appropriate DataLayout instance for this module.
412 const DataLayout *DL = M->getDataLayout();
413 if (!DL && !DefaultDataLayout.empty()) {
414 M->setDataLayout(DefaultDataLayout);
415 DL = M->getDataLayout();
419 Passes.add(new DataLayoutPass());
421 Triple ModuleTriple(M->getTargetTriple());
422 TargetMachine *Machine = nullptr;
423 if (ModuleTriple.getArch())
424 Machine = GetTargetMachine(Triple(ModuleTriple));
425 std::unique_ptr<TargetMachine> TM(Machine);
427 // Add internal analysis passes from the target machine.
429 TM->addAnalysisPasses(Passes);
431 std::unique_ptr<FunctionPassManager> FPasses;
432 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
433 FPasses.reset(new FunctionPassManager(M.get()));
435 FPasses->add(new DataLayoutPass());
437 TM->addAnalysisPasses(*FPasses);
441 if (PrintBreakpoints) {
442 // Default to standard output.
444 if (OutputFilename.empty())
445 OutputFilename = "-";
448 Out.reset(new tool_output_file(OutputFilename, EC, sys::fs::F_None));
450 errs() << EC.message() << '\n';
454 Passes.add(createBreakpointPrinter(Out->os()));
458 // If the -strip-debug command line option was specified, add it.
460 addPass(Passes, createStripSymbolsPass(true));
462 // Create a new optimization pass for each one specified on the command line
463 for (unsigned i = 0; i < PassList.size(); ++i) {
464 if (StandardLinkOpts &&
465 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
466 AddStandardLinkPasses(Passes);
467 StandardLinkOpts = false;
470 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
471 AddOptimizationPasses(Passes, *FPasses, 1, 0);
475 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
476 AddOptimizationPasses(Passes, *FPasses, 2, 0);
480 if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
481 AddOptimizationPasses(Passes, *FPasses, 2, 1);
485 if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
486 AddOptimizationPasses(Passes, *FPasses, 2, 2);
490 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
491 AddOptimizationPasses(Passes, *FPasses, 3, 0);
495 const PassInfo *PassInf = PassList[i];
497 if (PassInf->getTargetMachineCtor())
498 P = PassInf->getTargetMachineCtor()(TM.get());
499 else if (PassInf->getNormalCtor())
500 P = PassInf->getNormalCtor()();
502 errs() << argv[0] << ": cannot create pass: "
503 << PassInf->getPassName() << "\n";
505 PassKind Kind = P->getPassKind();
511 Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
514 Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
517 Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
520 Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
522 case PT_CallGraphSCC:
523 Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
526 Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
533 Passes.add(createPrintModulePass(errs()));
536 if (StandardLinkOpts) {
537 AddStandardLinkPasses(Passes);
538 StandardLinkOpts = false;
542 AddOptimizationPasses(Passes, *FPasses, 1, 0);
545 AddOptimizationPasses(Passes, *FPasses, 2, 0);
548 AddOptimizationPasses(Passes, *FPasses, 2, 1);
551 AddOptimizationPasses(Passes, *FPasses, 2, 2);
554 AddOptimizationPasses(Passes, *FPasses, 3, 0);
556 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
557 FPasses->doInitialization();
558 for (Function &F : *M)
560 FPasses->doFinalization();
563 // Check that the module is well formed on completion of optimization
564 if (!NoVerify && !VerifyEach) {
565 Passes.add(createVerifierPass());
566 Passes.add(createDebugInfoVerifierPass());
569 // Write bitcode or assembly to the output as the last step...
570 if (!NoOutput && !AnalyzeOnly) {
572 Passes.add(createPrintModulePass(Out->os()));
574 Passes.add(createBitcodeWriterPass(Out->os()));
577 // Before executing passes, print the final values of the LLVM options.
578 cl::PrintOptionValues();
580 // Now that we have all of the passes ready, run them.
584 if (!NoOutput || PrintBreakpoints)