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/Module.h"
29 #include "llvm/IR/Verifier.h"
30 #include "llvm/IRReader/IRReader.h"
31 #include "llvm/LinkAllIR.h"
32 #include "llvm/LinkAllPasses.h"
33 #include "llvm/MC/SubtargetFeature.h"
34 #include "llvm/PassManager.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ManagedStatic.h"
37 #include "llvm/Support/PassNameParser.h"
38 #include "llvm/Support/PluginLoader.h"
39 #include "llvm/Support/PrettyStackTrace.h"
40 #include "llvm/Support/Signals.h"
41 #include "llvm/Support/SourceMgr.h"
42 #include "llvm/Support/SystemUtils.h"
43 #include "llvm/Support/TargetRegistry.h"
44 #include "llvm/Support/TargetSelect.h"
45 #include "llvm/Support/ToolOutputFile.h"
46 #include "llvm/Target/TargetLibraryInfo.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
52 using namespace opt_tool;
54 // The OptimizationList is automatically populated with registered Passes by the
57 static cl::list<const PassInfo*, bool, PassNameParser>
58 PassList(cl::desc("Optimizations available:"));
60 // This flag specifies a textual description of the optimization pass pipeline
61 // to run over the module. This flag switches opt to use the new pass manager
62 // infrastructure, completely disabling all of the flags specific to the old
64 static cl::opt<std::string> PassPipeline(
66 cl::desc("A textual description of the pass pipeline for optimizing"),
69 // Other command line options...
71 static cl::opt<std::string>
72 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
73 cl::init("-"), cl::value_desc("filename"));
75 static cl::opt<std::string>
76 OutputFilename("o", cl::desc("Override output filename"),
77 cl::value_desc("filename"));
80 Force("f", cl::desc("Enable binary output on terminals"));
83 PrintEachXForm("p", cl::desc("Print module after each transformation"));
86 NoOutput("disable-output",
87 cl::desc("Do not write result bitcode file"), cl::Hidden);
90 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
93 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
96 VerifyEach("verify-each", cl::desc("Verify after each transform"));
99 StripDebug("strip-debug",
100 cl::desc("Strip debugger symbol info from translation unit"));
103 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
106 DisableOptimizations("disable-opt",
107 cl::desc("Do not run any optimization passes"));
110 DisableInternalize("disable-internalize",
111 cl::desc("Do not mark all symbols as internal"));
114 StandardCompileOpts("std-compile-opts",
115 cl::desc("Include the standard compile time optimizations"));
118 StandardLinkOpts("std-link-opts",
119 cl::desc("Include the standard link time optimizations"));
123 cl::desc("Optimization level 1. Similar to clang -O1"));
127 cl::desc("Optimization level 2. Similar to clang -O2"));
131 cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
135 cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
139 cl::desc("Optimization level 3. Similar to clang -O3"));
141 static cl::opt<std::string>
142 TargetTriple("mtriple", cl::desc("Override target triple for module"));
145 UnitAtATime("funit-at-a-time",
146 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
150 DisableLoopUnrolling("disable-loop-unrolling",
151 cl::desc("Disable loop unrolling in all relevant passes"),
154 DisableLoopVectorization("disable-loop-vectorization",
155 cl::desc("Disable the loop vectorization pass"),
159 DisableSLPVectorization("disable-slp-vectorization",
160 cl::desc("Disable the slp vectorization pass"),
165 DisableSimplifyLibCalls("disable-simplify-libcalls",
166 cl::desc("Disable simplify-libcalls"));
169 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
172 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
175 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
178 PrintBreakpoints("print-breakpoints-for-testing",
179 cl::desc("Print select breakpoints location for testing"));
181 static cl::opt<std::string>
182 DefaultDataLayout("default-data-layout",
183 cl::desc("data layout string to use if not specified by module"),
184 cl::value_desc("layout-string"), cl::init(""));
188 static inline void addPass(PassManagerBase &PM, Pass *P) {
189 // Add the pass to the pass manager...
192 // If we are verifying all of the intermediate steps, add the verifier...
193 if (VerifyEach) PM.add(createVerifierPass());
196 /// AddOptimizationPasses - This routine adds optimization passes
197 /// based on selected optimization level, OptLevel. This routine
198 /// duplicates llvm-gcc behaviour.
200 /// OptLevel - Optimization Level
201 static void AddOptimizationPasses(PassManagerBase &MPM,FunctionPassManager &FPM,
202 unsigned OptLevel, unsigned SizeLevel) {
203 FPM.add(createVerifierPass()); // Verify that input is correct
205 PassManagerBuilder Builder;
206 Builder.OptLevel = OptLevel;
207 Builder.SizeLevel = SizeLevel;
211 } else if (OptLevel > 1) {
212 unsigned Threshold = 225;
213 if (SizeLevel == 1) // -Os
215 else if (SizeLevel == 2) // -Oz
219 Builder.Inliner = createFunctionInliningPass(Threshold);
221 Builder.Inliner = createAlwaysInlinerPass();
223 Builder.DisableUnitAtATime = !UnitAtATime;
224 Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
225 DisableLoopUnrolling : OptLevel == 0;
227 // This is final, unless there is a #pragma vectorize enable
228 if (DisableLoopVectorization)
229 Builder.LoopVectorize = false;
230 // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
231 else if (!Builder.LoopVectorize)
232 Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
234 // When #pragma vectorize is on for SLP, do the same as above
235 Builder.SLPVectorize =
236 DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
238 Builder.populateFunctionPassManager(FPM);
239 Builder.populateModulePassManager(MPM);
242 static void AddStandardCompilePasses(PassManagerBase &PM) {
243 PM.add(createVerifierPass()); // Verify that input is correct
245 // If the -strip-debug command line option was specified, do it.
247 addPass(PM, createStripSymbolsPass(true));
249 if (DisableOptimizations) return;
251 // -std-compile-opts adds the same module passes as -O3.
252 PassManagerBuilder Builder;
254 Builder.Inliner = createFunctionInliningPass();
255 Builder.OptLevel = 3;
256 Builder.populateModulePassManager(PM);
259 static void AddStandardLinkPasses(PassManagerBase &PM) {
260 PM.add(createVerifierPass()); // Verify that input is correct
262 // If the -strip-debug command line option was specified, do it.
264 addPass(PM, createStripSymbolsPass(true));
266 if (DisableOptimizations) return;
268 PassManagerBuilder Builder;
269 Builder.populateLTOPassManager(PM, /*Internalize=*/ !DisableInternalize,
270 /*RunInliner=*/ !DisableInline);
273 //===----------------------------------------------------------------------===//
274 // CodeGen-related helper functions.
276 static TargetOptions GetTargetOptions() {
277 TargetOptions Options;
278 Options.LessPreciseFPMADOption = EnableFPMAD;
279 Options.NoFramePointerElim = DisableFPElim;
280 Options.AllowFPOpFusion = FuseFPOps;
281 Options.UnsafeFPMath = EnableUnsafeFPMath;
282 Options.NoInfsFPMath = EnableNoInfsFPMath;
283 Options.NoNaNsFPMath = EnableNoNaNsFPMath;
284 Options.HonorSignDependentRoundingFPMathOption =
285 EnableHonorSignDependentRoundingFPMath;
286 Options.UseSoftFloat = GenerateSoftFloatCalls;
287 if (FloatABIForCalls != FloatABI::Default)
288 Options.FloatABIType = FloatABIForCalls;
289 Options.NoZerosInBSS = DontPlaceZerosInBSS;
290 Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
291 Options.DisableTailCalls = DisableTailCalls;
292 Options.StackAlignmentOverride = OverrideStackAlignment;
293 Options.TrapFuncName = TrapFuncName;
294 Options.PositionIndependentExecutable = EnablePIE;
295 Options.EnableSegmentedStacks = SegmentedStacks;
296 Options.UseInitArray = UseInitArray;
300 CodeGenOpt::Level GetCodeGenOptLevel() {
302 return CodeGenOpt::Less;
304 return CodeGenOpt::Default;
306 return CodeGenOpt::Aggressive;
307 return CodeGenOpt::None;
310 // Returns the TargetMachine instance or zero if no triple is provided.
311 static TargetMachine* GetTargetMachine(Triple TheTriple) {
313 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
315 // Some modules don't specify a triple, and this is okay.
320 // Package up features to be passed to target/subtarget
321 std::string FeaturesStr;
323 SubtargetFeatures Features;
324 for (unsigned i = 0; i != MAttrs.size(); ++i)
325 Features.AddFeature(MAttrs[i]);
326 FeaturesStr = Features.getString();
329 return TheTarget->createTargetMachine(TheTriple.getTriple(),
330 MCPU, FeaturesStr, GetTargetOptions(),
332 GetCodeGenOptLevel());
335 //===----------------------------------------------------------------------===//
338 int main(int argc, char **argv) {
339 sys::PrintStackTraceOnErrorSignal();
340 llvm::PrettyStackTraceProgram X(argc, argv);
342 // Enable debug stream buffering.
343 EnableDebugBuffering = true;
345 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
346 LLVMContext &Context = getGlobalContext();
348 InitializeAllTargets();
349 InitializeAllTargetMCs();
352 PassRegistry &Registry = *PassRegistry::getPassRegistry();
353 initializeCore(Registry);
354 initializeDebugIRPass(Registry);
355 initializeScalarOpts(Registry);
356 initializeObjCARCOpts(Registry);
357 initializeVectorization(Registry);
358 initializeIPO(Registry);
359 initializeAnalysis(Registry);
360 initializeIPA(Registry);
361 initializeTransformUtils(Registry);
362 initializeInstCombine(Registry);
363 initializeInstrumentation(Registry);
364 initializeTarget(Registry);
366 cl::ParseCommandLineOptions(argc, argv,
367 "llvm .bc -> .bc modular optimizer and analysis printer\n");
369 if (AnalyzeOnly && NoOutput) {
370 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
376 // Load the input module...
378 M.reset(ParseIRFile(InputFilename, Err, Context));
381 Err.print(argv[0], errs());
385 // If we are supposed to override the target triple, do so now.
386 if (!TargetTriple.empty())
387 M->setTargetTriple(Triple::normalize(TargetTriple));
389 // Figure out what stream we are supposed to write to...
390 OwningPtr<tool_output_file> Out;
392 if (!OutputFilename.empty())
393 errs() << "WARNING: The -o (output filename) option is ignored when\n"
394 "the --disable-output option is used.\n";
396 // Default to standard output.
397 if (OutputFilename.empty())
398 OutputFilename = "-";
400 std::string ErrorInfo;
401 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
403 if (!ErrorInfo.empty()) {
404 errs() << ErrorInfo << '\n';
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.get(), Out.get(), PassPipeline,
436 // Create a PassManager to hold and optimize the collection of passes we are
441 // Add an appropriate TargetLibraryInfo pass for the module's triple.
442 TargetLibraryInfo *TLI = new TargetLibraryInfo(Triple(M->getTargetTriple()));
444 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
445 if (DisableSimplifyLibCalls)
446 TLI->disableAllFunctions();
449 // Add an appropriate DataLayout instance for this module.
451 const std::string &ModuleDataLayout = M.get()->getDataLayout();
452 if (!ModuleDataLayout.empty())
453 TD = new DataLayout(ModuleDataLayout);
454 else if (!DefaultDataLayout.empty())
455 TD = new DataLayout(DefaultDataLayout);
460 Triple ModuleTriple(M->getTargetTriple());
461 TargetMachine *Machine = 0;
462 if (ModuleTriple.getArch())
463 Machine = GetTargetMachine(Triple(ModuleTriple));
464 OwningPtr<TargetMachine> TM(Machine);
466 // Add internal analysis passes from the target machine.
468 TM->addAnalysisPasses(Passes);
470 OwningPtr<FunctionPassManager> FPasses;
471 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
472 FPasses.reset(new FunctionPassManager(M.get()));
474 FPasses->add(new DataLayout(*TD));
476 TM->addAnalysisPasses(*FPasses);
480 if (PrintBreakpoints) {
481 // Default to standard output.
483 if (OutputFilename.empty())
484 OutputFilename = "-";
486 std::string ErrorInfo;
487 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
489 if (!ErrorInfo.empty()) {
490 errs() << ErrorInfo << '\n';
494 Passes.add(createBreakpointPrinter(Out->os()));
498 // If the -strip-debug command line option was specified, add it. If
499 // -std-compile-opts was also specified, it will handle StripDebug.
500 if (StripDebug && !StandardCompileOpts)
501 addPass(Passes, createStripSymbolsPass(true));
503 // Create a new optimization pass for each one specified on the command line
504 for (unsigned i = 0; i < PassList.size(); ++i) {
505 // Check to see if -std-compile-opts was specified before this option. If
507 if (StandardCompileOpts &&
508 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
509 AddStandardCompilePasses(Passes);
510 StandardCompileOpts = false;
513 if (StandardLinkOpts &&
514 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
515 AddStandardLinkPasses(Passes);
516 StandardLinkOpts = false;
519 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
520 AddOptimizationPasses(Passes, *FPasses, 1, 0);
524 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
525 AddOptimizationPasses(Passes, *FPasses, 2, 0);
529 if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
530 AddOptimizationPasses(Passes, *FPasses, 2, 1);
534 if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
535 AddOptimizationPasses(Passes, *FPasses, 2, 2);
539 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
540 AddOptimizationPasses(Passes, *FPasses, 3, 0);
544 const PassInfo *PassInf = PassList[i];
546 if (PassInf->getTargetMachineCtor())
547 P = PassInf->getTargetMachineCtor()(TM.get());
548 else if (PassInf->getNormalCtor())
549 P = PassInf->getNormalCtor()();
551 errs() << argv[0] << ": cannot create pass: "
552 << PassInf->getPassName() << "\n";
554 PassKind Kind = P->getPassKind();
560 Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
563 Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
566 Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
569 Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
571 case PT_CallGraphSCC:
572 Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
575 Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
582 Passes.add(createPrintModulePass(errs()));
585 // If -std-compile-opts was specified at the end of the pass list, add them.
586 if (StandardCompileOpts) {
587 AddStandardCompilePasses(Passes);
588 StandardCompileOpts = false;
591 if (StandardLinkOpts) {
592 AddStandardLinkPasses(Passes);
593 StandardLinkOpts = false;
597 AddOptimizationPasses(Passes, *FPasses, 1, 0);
600 AddOptimizationPasses(Passes, *FPasses, 2, 0);
603 AddOptimizationPasses(Passes, *FPasses, 2, 1);
606 AddOptimizationPasses(Passes, *FPasses, 2, 2);
609 AddOptimizationPasses(Passes, *FPasses, 3, 0);
611 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
612 FPasses->doInitialization();
613 for (Module::iterator F = M->begin(), E = M->end(); F != E; ++F)
615 FPasses->doFinalization();
618 // Check that the module is well formed on completion of optimization
619 if (!NoVerify && !VerifyEach)
620 Passes.add(createVerifierPass());
622 // Write bitcode or assembly to the output as the last step...
623 if (!NoOutput && !AnalyzeOnly) {
625 Passes.add(createPrintModulePass(Out->os()));
627 Passes.add(createBitcodeWriterPass(Out->os()));
630 // Before executing passes, print the final values of the LLVM options.
631 cl::PrintOptionValues();
633 // Now that we have all of the passes ready, run them.
634 Passes.run(*M.get());
637 if (!NoOutput || PrintBreakpoints)