1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // Optimizations may be specified an arbitrary number of times on the command 11 // line, They are run in the order specified. 12 // 13 //===----------------------------------------------------------------------===// 14 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/InitializePasses.h" 26 #include "llvm/IR/DataLayout.h" 27 #include "llvm/IR/IRPrintingPasses.h" 28 #include "llvm/IR/LLVMContext.h" 29 #include "llvm/IR/Module.h" 30 #include "llvm/IR/Verifier.h" 31 #include "llvm/IRReader/IRReader.h" 32 #include "llvm/LinkAllIR.h" 33 #include "llvm/LinkAllPasses.h" 34 #include "llvm/MC/SubtargetFeature.h" 35 #include "llvm/PassManager.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/ManagedStatic.h" 38 #include "llvm/Support/PassNameParser.h" 39 #include "llvm/Support/PluginLoader.h" 40 #include "llvm/Support/PrettyStackTrace.h" 41 #include "llvm/Support/Signals.h" 42 #include "llvm/Support/SourceMgr.h" 43 #include "llvm/Support/SystemUtils.h" 44 #include "llvm/Support/TargetRegistry.h" 45 #include "llvm/Support/TargetSelect.h" 46 #include "llvm/Support/ToolOutputFile.h" 47 #include "llvm/Target/TargetLibraryInfo.h" 48 #include "llvm/Target/TargetMachine.h" 49 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 50 #include <algorithm> 51 #include <memory> 52 using namespace llvm; 53 using namespace opt_tool; 54 55 // The OptimizationList is automatically populated with registered Passes by the 56 // PassNameParser. 57 // 58 static cl::list<const PassInfo*, bool, PassNameParser> 59 PassList(cl::desc("Optimizations available:")); 60 61 // This flag specifies a textual description of the optimization pass pipeline 62 // to run over the module. This flag switches opt to use the new pass manager 63 // infrastructure, completely disabling all of the flags specific to the old 64 // pass management. 65 static cl::opt<std::string> PassPipeline( 66 "passes", 67 cl::desc("A textual description of the pass pipeline for optimizing"), 68 cl::Hidden); 69 70 // Other command line options... 71 // 72 static cl::opt<std::string> 73 InputFilename(cl::Positional, cl::desc("<input bitcode file>"), 74 cl::init("-"), cl::value_desc("filename")); 75 76 static cl::opt<std::string> 77 OutputFilename("o", cl::desc("Override output filename"), 78 cl::value_desc("filename")); 79 80 static cl::opt<bool> 81 Force("f", cl::desc("Enable binary output on terminals")); 82 83 static cl::opt<bool> 84 PrintEachXForm("p", cl::desc("Print module after each transformation")); 85 86 static cl::opt<bool> 87 NoOutput("disable-output", 88 cl::desc("Do not write result bitcode file"), cl::Hidden); 89 90 static cl::opt<bool> 91 OutputAssembly("S", cl::desc("Write output as LLVM assembly")); 92 93 static cl::opt<bool> 94 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden); 95 96 static cl::opt<bool> 97 VerifyEach("verify-each", cl::desc("Verify after each transform")); 98 99 static cl::opt<bool> 100 StripDebug("strip-debug", 101 cl::desc("Strip debugger symbol info from translation unit")); 102 103 static cl::opt<bool> 104 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass")); 105 106 static cl::opt<bool> 107 DisableOptimizations("disable-opt", 108 cl::desc("Do not run any optimization passes")); 109 110 static cl::opt<bool> 111 DisableInternalize("disable-internalize", 112 cl::desc("Do not mark all symbols as internal")); 113 114 static cl::opt<bool> 115 StandardCompileOpts("std-compile-opts", 116 cl::desc("Include the standard compile time optimizations")); 117 118 static cl::opt<bool> 119 StandardLinkOpts("std-link-opts", 120 cl::desc("Include the standard link time optimizations")); 121 122 static cl::opt<bool> 123 OptLevelO1("O1", 124 cl::desc("Optimization level 1. Similar to clang -O1")); 125 126 static cl::opt<bool> 127 OptLevelO2("O2", 128 cl::desc("Optimization level 2. Similar to clang -O2")); 129 130 static cl::opt<bool> 131 OptLevelOs("Os", 132 cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os")); 133 134 static cl::opt<bool> 135 OptLevelOz("Oz", 136 cl::desc("Like -Os but reduces code size further. Similar to clang -Oz")); 137 138 static cl::opt<bool> 139 OptLevelO3("O3", 140 cl::desc("Optimization level 3. Similar to clang -O3")); 141 142 static cl::opt<std::string> 143 TargetTriple("mtriple", cl::desc("Override target triple for module")); 144 145 static cl::opt<bool> 146 UnitAtATime("funit-at-a-time", 147 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"), 148 cl::init(true)); 149 150 static cl::opt<bool> 151 DisableLoopUnrolling("disable-loop-unrolling", 152 cl::desc("Disable loop unrolling in all relevant passes"), 153 cl::init(false)); 154 static cl::opt<bool> 155 DisableLoopVectorization("disable-loop-vectorization", 156 cl::desc("Disable the loop vectorization pass"), 157 cl::init(false)); 158 159 static cl::opt<bool> 160 DisableSLPVectorization("disable-slp-vectorization", 161 cl::desc("Disable the slp vectorization pass"), 162 cl::init(false)); 163 164 165 static cl::opt<bool> 166 DisableSimplifyLibCalls("disable-simplify-libcalls", 167 cl::desc("Disable simplify-libcalls")); 168 169 static cl::opt<bool> 170 Quiet("q", cl::desc("Obsolete option"), cl::Hidden); 171 172 static cl::alias 173 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet)); 174 175 static cl::opt<bool> 176 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization")); 177 178 static cl::opt<bool> 179 PrintBreakpoints("print-breakpoints-for-testing", 180 cl::desc("Print select breakpoints location for testing")); 181 182 static cl::opt<std::string> 183 DefaultDataLayout("default-data-layout", 184 cl::desc("data layout string to use if not specified by module"), 185 cl::value_desc("layout-string"), cl::init("")); 186 187 188 189 static inline void addPass(PassManagerBase &PM, Pass *P) { 190 // Add the pass to the pass manager... 191 PM.add(P); 192 193 // If we are verifying all of the intermediate steps, add the verifier... 194 if (VerifyEach) PM.add(createVerifierPass()); 195 } 196 197 /// AddOptimizationPasses - This routine adds optimization passes 198 /// based on selected optimization level, OptLevel. This routine 199 /// duplicates llvm-gcc behaviour. 200 /// 201 /// OptLevel - Optimization Level 202 static void AddOptimizationPasses(PassManagerBase &MPM,FunctionPassManager &FPM, 203 unsigned OptLevel, unsigned SizeLevel) { 204 FPM.add(createVerifierPass()); // Verify that input is correct 205 206 PassManagerBuilder Builder; 207 Builder.OptLevel = OptLevel; 208 Builder.SizeLevel = SizeLevel; 209 210 if (DisableInline) { 211 // No inlining pass 212 } else if (OptLevel > 1) { 213 unsigned Threshold = 225; 214 if (SizeLevel == 1) // -Os 215 Threshold = 75; 216 else if (SizeLevel == 2) // -Oz 217 Threshold = 25; 218 if (OptLevel > 2) 219 Threshold = 275; 220 Builder.Inliner = createFunctionInliningPass(Threshold); 221 } else { 222 Builder.Inliner = createAlwaysInlinerPass(); 223 } 224 Builder.DisableUnitAtATime = !UnitAtATime; 225 Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ? 226 DisableLoopUnrolling : OptLevel == 0; 227 228 // This is final, unless there is a #pragma vectorize enable 229 if (DisableLoopVectorization) 230 Builder.LoopVectorize = false; 231 // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize) 232 else if (!Builder.LoopVectorize) 233 Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2; 234 235 // When #pragma vectorize is on for SLP, do the same as above 236 Builder.SLPVectorize = 237 DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2; 238 239 Builder.populateFunctionPassManager(FPM); 240 Builder.populateModulePassManager(MPM); 241 } 242 243 static void AddStandardCompilePasses(PassManagerBase &PM) { 244 PM.add(createVerifierPass()); // Verify that input is correct 245 246 // If the -strip-debug command line option was specified, do it. 247 if (StripDebug) 248 addPass(PM, createStripSymbolsPass(true)); 249 250 if (DisableOptimizations) return; 251 252 // -std-compile-opts adds the same module passes as -O3. 253 PassManagerBuilder Builder; 254 if (!DisableInline) 255 Builder.Inliner = createFunctionInliningPass(); 256 Builder.OptLevel = 3; 257 Builder.populateModulePassManager(PM); 258 } 259 260 static void AddStandardLinkPasses(PassManagerBase &PM) { 261 PM.add(createVerifierPass()); // Verify that input is correct 262 263 // If the -strip-debug command line option was specified, do it. 264 if (StripDebug) 265 addPass(PM, createStripSymbolsPass(true)); 266 267 if (DisableOptimizations) return; 268 269 PassManagerBuilder Builder; 270 Builder.populateLTOPassManager(PM, /*Internalize=*/ !DisableInternalize, 271 /*RunInliner=*/ !DisableInline); 272 } 273 274 //===----------------------------------------------------------------------===// 275 // CodeGen-related helper functions. 276 // 277 278 CodeGenOpt::Level GetCodeGenOptLevel() { 279 if (OptLevelO1) 280 return CodeGenOpt::Less; 281 if (OptLevelO2) 282 return CodeGenOpt::Default; 283 if (OptLevelO3) 284 return CodeGenOpt::Aggressive; 285 return CodeGenOpt::None; 286 } 287 288 // Returns the TargetMachine instance or zero if no triple is provided. 289 static TargetMachine* GetTargetMachine(Triple TheTriple) { 290 std::string Error; 291 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple, 292 Error); 293 // Some modules don't specify a triple, and this is okay. 294 if (!TheTarget) { 295 return 0; 296 } 297 298 // Package up features to be passed to target/subtarget 299 std::string FeaturesStr; 300 if (MAttrs.size()) { 301 SubtargetFeatures Features; 302 for (unsigned i = 0; i != MAttrs.size(); ++i) 303 Features.AddFeature(MAttrs[i]); 304 FeaturesStr = Features.getString(); 305 } 306 307 return TheTarget->createTargetMachine(TheTriple.getTriple(), 308 MCPU, FeaturesStr, 309 InitTargetOptionsFromCodeGenFlags(), 310 RelocModel, CMModel, 311 GetCodeGenOptLevel()); 312 } 313 314 //===----------------------------------------------------------------------===// 315 // main for opt 316 // 317 int main(int argc, char **argv) { 318 sys::PrintStackTraceOnErrorSignal(); 319 llvm::PrettyStackTraceProgram X(argc, argv); 320 321 // Enable debug stream buffering. 322 EnableDebugBuffering = true; 323 324 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 325 LLVMContext &Context = getGlobalContext(); 326 327 InitializeAllTargets(); 328 InitializeAllTargetMCs(); 329 330 // Initialize passes 331 PassRegistry &Registry = *PassRegistry::getPassRegistry(); 332 initializeCore(Registry); 333 initializeDebugIRPass(Registry); 334 initializeScalarOpts(Registry); 335 initializeObjCARCOpts(Registry); 336 initializeVectorization(Registry); 337 initializeIPO(Registry); 338 initializeAnalysis(Registry); 339 initializeIPA(Registry); 340 initializeTransformUtils(Registry); 341 initializeInstCombine(Registry); 342 initializeInstrumentation(Registry); 343 initializeTarget(Registry); 344 // For codegen passes, only passes that do IR to IR transformation are 345 // supported. For now, just add CodeGenPrepare. 346 initializeCodeGenPreparePass(Registry); 347 348 cl::ParseCommandLineOptions(argc, argv, 349 "llvm .bc -> .bc modular optimizer and analysis printer\n"); 350 351 if (AnalyzeOnly && NoOutput) { 352 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n"; 353 return 1; 354 } 355 356 SMDiagnostic Err; 357 358 // Load the input module... 359 OwningPtr<Module> M; 360 M.reset(ParseIRFile(InputFilename, Err, Context)); 361 362 if (M.get() == 0) { 363 Err.print(argv[0], errs()); 364 return 1; 365 } 366 367 // If we are supposed to override the target triple, do so now. 368 if (!TargetTriple.empty()) 369 M->setTargetTriple(Triple::normalize(TargetTriple)); 370 371 // Figure out what stream we are supposed to write to... 372 OwningPtr<tool_output_file> Out; 373 if (NoOutput) { 374 if (!OutputFilename.empty()) 375 errs() << "WARNING: The -o (output filename) option is ignored when\n" 376 "the --disable-output option is used.\n"; 377 } else { 378 // Default to standard output. 379 if (OutputFilename.empty()) 380 OutputFilename = "-"; 381 382 std::string ErrorInfo; 383 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo, 384 sys::fs::F_None)); 385 if (!ErrorInfo.empty()) { 386 errs() << ErrorInfo << '\n'; 387 return 1; 388 } 389 } 390 391 // If the output is set to be emitted to standard out, and standard out is a 392 // console, print out a warning message and refuse to do it. We don't 393 // impress anyone by spewing tons of binary goo to a terminal. 394 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly) 395 if (CheckBitcodeOutputToConsole(Out->os(), !Quiet)) 396 NoOutput = true; 397 398 if (PassPipeline.getNumOccurrences() > 0) { 399 OutputKind OK = OK_NoOutput; 400 if (!NoOutput) 401 OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode; 402 403 VerifierKind VK = VK_VerifyInAndOut; 404 if (NoVerify) 405 VK = VK_NoVerifier; 406 else if (VerifyEach) 407 VK = VK_VerifyEachPass; 408 409 // The user has asked to use the new pass manager and provided a pipeline 410 // string. Hand off the rest of the functionality to the new code for that 411 // layer. 412 return runPassPipeline(argv[0], Context, *M.get(), Out.get(), PassPipeline, 413 OK, VK) 414 ? 0 415 : 1; 416 } 417 418 // Create a PassManager to hold and optimize the collection of passes we are 419 // about to build. 420 // 421 PassManager Passes; 422 423 // Add an appropriate TargetLibraryInfo pass for the module's triple. 424 TargetLibraryInfo *TLI = new TargetLibraryInfo(Triple(M->getTargetTriple())); 425 426 // The -disable-simplify-libcalls flag actually disables all builtin optzns. 427 if (DisableSimplifyLibCalls) 428 TLI->disableAllFunctions(); 429 Passes.add(TLI); 430 431 // Add an appropriate DataLayout instance for this module. 432 DataLayout *DL = 0; 433 const std::string &ModuleDataLayout = M.get()->getDataLayout(); 434 if (!ModuleDataLayout.empty()) 435 DL = new DataLayout(ModuleDataLayout); 436 else if (!DefaultDataLayout.empty()) 437 DL = new DataLayout(DefaultDataLayout); 438 439 if (DL) 440 Passes.add(DL); 441 442 Triple ModuleTriple(M->getTargetTriple()); 443 TargetMachine *Machine = 0; 444 if (ModuleTriple.getArch()) 445 Machine = GetTargetMachine(Triple(ModuleTriple)); 446 OwningPtr<TargetMachine> TM(Machine); 447 448 // Add internal analysis passes from the target machine. 449 if (TM.get()) 450 TM->addAnalysisPasses(Passes); 451 452 OwningPtr<FunctionPassManager> FPasses; 453 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) { 454 FPasses.reset(new FunctionPassManager(M.get())); 455 if (DL) 456 FPasses->add(new DataLayout(*DL)); 457 if (TM.get()) 458 TM->addAnalysisPasses(*FPasses); 459 460 } 461 462 if (PrintBreakpoints) { 463 // Default to standard output. 464 if (!Out) { 465 if (OutputFilename.empty()) 466 OutputFilename = "-"; 467 468 std::string ErrorInfo; 469 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo, 470 sys::fs::F_None)); 471 if (!ErrorInfo.empty()) { 472 errs() << ErrorInfo << '\n'; 473 return 1; 474 } 475 } 476 Passes.add(createBreakpointPrinter(Out->os())); 477 NoOutput = true; 478 } 479 480 // If the -strip-debug command line option was specified, add it. If 481 // -std-compile-opts was also specified, it will handle StripDebug. 482 if (StripDebug && !StandardCompileOpts) 483 addPass(Passes, createStripSymbolsPass(true)); 484 485 // Create a new optimization pass for each one specified on the command line 486 for (unsigned i = 0; i < PassList.size(); ++i) { 487 // Check to see if -std-compile-opts was specified before this option. If 488 // so, handle it. 489 if (StandardCompileOpts && 490 StandardCompileOpts.getPosition() < PassList.getPosition(i)) { 491 AddStandardCompilePasses(Passes); 492 StandardCompileOpts = false; 493 } 494 495 if (StandardLinkOpts && 496 StandardLinkOpts.getPosition() < PassList.getPosition(i)) { 497 AddStandardLinkPasses(Passes); 498 StandardLinkOpts = false; 499 } 500 501 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) { 502 AddOptimizationPasses(Passes, *FPasses, 1, 0); 503 OptLevelO1 = false; 504 } 505 506 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) { 507 AddOptimizationPasses(Passes, *FPasses, 2, 0); 508 OptLevelO2 = false; 509 } 510 511 if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) { 512 AddOptimizationPasses(Passes, *FPasses, 2, 1); 513 OptLevelOs = false; 514 } 515 516 if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) { 517 AddOptimizationPasses(Passes, *FPasses, 2, 2); 518 OptLevelOz = false; 519 } 520 521 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) { 522 AddOptimizationPasses(Passes, *FPasses, 3, 0); 523 OptLevelO3 = false; 524 } 525 526 const PassInfo *PassInf = PassList[i]; 527 Pass *P = 0; 528 if (PassInf->getTargetMachineCtor()) 529 P = PassInf->getTargetMachineCtor()(TM.get()); 530 else if (PassInf->getNormalCtor()) 531 P = PassInf->getNormalCtor()(); 532 else 533 errs() << argv[0] << ": cannot create pass: " 534 << PassInf->getPassName() << "\n"; 535 if (P) { 536 PassKind Kind = P->getPassKind(); 537 addPass(Passes, P); 538 539 if (AnalyzeOnly) { 540 switch (Kind) { 541 case PT_BasicBlock: 542 Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet)); 543 break; 544 case PT_Region: 545 Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet)); 546 break; 547 case PT_Loop: 548 Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet)); 549 break; 550 case PT_Function: 551 Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet)); 552 break; 553 case PT_CallGraphSCC: 554 Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet)); 555 break; 556 default: 557 Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet)); 558 break; 559 } 560 } 561 } 562 563 if (PrintEachXForm) 564 Passes.add(createPrintModulePass(errs())); 565 } 566 567 // If -std-compile-opts was specified at the end of the pass list, add them. 568 if (StandardCompileOpts) { 569 AddStandardCompilePasses(Passes); 570 StandardCompileOpts = false; 571 } 572 573 if (StandardLinkOpts) { 574 AddStandardLinkPasses(Passes); 575 StandardLinkOpts = false; 576 } 577 578 if (OptLevelO1) 579 AddOptimizationPasses(Passes, *FPasses, 1, 0); 580 581 if (OptLevelO2) 582 AddOptimizationPasses(Passes, *FPasses, 2, 0); 583 584 if (OptLevelOs) 585 AddOptimizationPasses(Passes, *FPasses, 2, 1); 586 587 if (OptLevelOz) 588 AddOptimizationPasses(Passes, *FPasses, 2, 2); 589 590 if (OptLevelO3) 591 AddOptimizationPasses(Passes, *FPasses, 3, 0); 592 593 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) { 594 FPasses->doInitialization(); 595 for (Module::iterator F = M->begin(), E = M->end(); F != E; ++F) 596 FPasses->run(*F); 597 FPasses->doFinalization(); 598 } 599 600 // Check that the module is well formed on completion of optimization 601 if (!NoVerify && !VerifyEach) 602 Passes.add(createVerifierPass()); 603 604 // Write bitcode or assembly to the output as the last step... 605 if (!NoOutput && !AnalyzeOnly) { 606 if (OutputAssembly) 607 Passes.add(createPrintModulePass(Out->os())); 608 else 609 Passes.add(createBitcodeWriterPass(Out->os())); 610 } 611 612 // Before executing passes, print the final values of the LLVM options. 613 cl::PrintOptionValues(); 614 615 // Now that we have all of the passes ready, run them. 616 Passes.run(*M.get()); 617 618 // Declare success. 619 if (!NoOutput || PrintBreakpoints) 620 Out->keep(); 621 622 return 0; 623 } 624