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