1 //===-- TargetPassConfig.cpp - Target independent code generation passes --===// 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 // This file defines interfaces to access the target independent code 11 // generation passes provided by the LLVM backend. 12 // 13 //===---------------------------------------------------------------------===// 14 15 #include "llvm/CodeGen/TargetPassConfig.h" 16 17 #include "llvm/Analysis/BasicAliasAnalysis.h" 18 #include "llvm/Analysis/CFLAndersAliasAnalysis.h" 19 #include "llvm/Analysis/CFLSteensAliasAnalysis.h" 20 #include "llvm/Analysis/CallGraphSCCPass.h" 21 #include "llvm/Analysis/Passes.h" 22 #include "llvm/Analysis/ScopedNoAliasAA.h" 23 #include "llvm/Analysis/TypeBasedAliasAnalysis.h" 24 #include "llvm/CodeGen/MachineFunctionPass.h" 25 #include "llvm/CodeGen/RegAllocRegistry.h" 26 #include "llvm/CodeGen/RegisterUsageInfo.h" 27 #include "llvm/IR/IRPrintingPasses.h" 28 #include "llvm/IR/LegacyPassManager.h" 29 #include "llvm/IR/Verifier.h" 30 #include "llvm/MC/MCAsmInfo.h" 31 #include "llvm/Support/Debug.h" 32 #include "llvm/Support/ErrorHandling.h" 33 #include "llvm/Support/raw_ostream.h" 34 #include "llvm/Target/TargetMachine.h" 35 #include "llvm/Transforms/Instrumentation.h" 36 #include "llvm/Transforms/Scalar.h" 37 #include "llvm/Transforms/Utils/SymbolRewriter.h" 38 39 using namespace llvm; 40 41 static cl::opt<bool> DisablePostRASched("disable-post-ra", cl::Hidden, 42 cl::desc("Disable Post Regalloc Scheduler")); 43 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden, 44 cl::desc("Disable branch folding")); 45 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden, 46 cl::desc("Disable tail duplication")); 47 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden, 48 cl::desc("Disable pre-register allocation tail duplication")); 49 static cl::opt<bool> DisableBlockPlacement("disable-block-placement", 50 cl::Hidden, cl::desc("Disable probability-driven block placement")); 51 static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-stats", 52 cl::Hidden, cl::desc("Collect probability-driven block placement stats")); 53 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden, 54 cl::desc("Disable Stack Slot Coloring")); 55 static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden, 56 cl::desc("Disable Machine Dead Code Elimination")); 57 static cl::opt<bool> DisableEarlyIfConversion("disable-early-ifcvt", cl::Hidden, 58 cl::desc("Disable Early If-conversion")); 59 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden, 60 cl::desc("Disable Machine LICM")); 61 static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden, 62 cl::desc("Disable Machine Common Subexpression Elimination")); 63 static cl::opt<cl::boolOrDefault> OptimizeRegAlloc( 64 "optimize-regalloc", cl::Hidden, 65 cl::desc("Enable optimized register allocation compilation path.")); 66 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm", 67 cl::Hidden, 68 cl::desc("Disable Machine LICM")); 69 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden, 70 cl::desc("Disable Machine Sinking")); 71 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden, 72 cl::desc("Disable Loop Strength Reduction Pass")); 73 static cl::opt<bool> DisableConstantHoisting("disable-constant-hoisting", 74 cl::Hidden, cl::desc("Disable ConstantHoisting")); 75 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden, 76 cl::desc("Disable Codegen Prepare")); 77 static cl::opt<bool> DisableCopyProp("disable-copyprop", cl::Hidden, 78 cl::desc("Disable Copy Propagation pass")); 79 static cl::opt<bool> DisablePartialLibcallInlining("disable-partial-libcall-inlining", 80 cl::Hidden, cl::desc("Disable Partial Libcall Inlining")); 81 static cl::opt<bool> EnableImplicitNullChecks( 82 "enable-implicit-null-checks", 83 cl::desc("Fold null checks into faulting memory operations"), 84 cl::init(false)); 85 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden, 86 cl::desc("Print LLVM IR produced by the loop-reduce pass")); 87 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden, 88 cl::desc("Print LLVM IR input to isel pass")); 89 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden, 90 cl::desc("Dump garbage collector data")); 91 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden, 92 cl::desc("Verify generated machine code"), 93 cl::init(false), 94 cl::ZeroOrMore); 95 96 static cl::opt<std::string> 97 PrintMachineInstrs("print-machineinstrs", cl::ValueOptional, 98 cl::desc("Print machine instrs"), 99 cl::value_desc("pass-name"), cl::init("option-unspecified")); 100 101 static cl::opt<int> EnableGlobalISelAbort( 102 "global-isel-abort", cl::Hidden, 103 cl::desc("Enable abort calls when \"global\" instruction selection " 104 "fails to lower/select an instruction: 0 disable the abort, " 105 "1 enable the abort, and " 106 "2 disable the abort but emit a diagnostic on failure"), 107 cl::init(1)); 108 109 // Temporary option to allow experimenting with MachineScheduler as a post-RA 110 // scheduler. Targets can "properly" enable this with 111 // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID). 112 // Targets can return true in targetSchedulesPostRAScheduling() and 113 // insert a PostRA scheduling pass wherever it wants. 114 cl::opt<bool> MISchedPostRA("misched-postra", cl::Hidden, 115 cl::desc("Run MachineScheduler post regalloc (independent of preRA sched)")); 116 117 // Experimental option to run live interval analysis early. 118 static cl::opt<bool> EarlyLiveIntervals("early-live-intervals", cl::Hidden, 119 cl::desc("Run live interval analysis earlier in the pipeline")); 120 121 // Experimental option to use CFL-AA in codegen 122 enum class CFLAAType { None, Steensgaard, Andersen, Both }; 123 static cl::opt<CFLAAType> UseCFLAA( 124 "use-cfl-aa-in-codegen", cl::init(CFLAAType::None), cl::Hidden, 125 cl::desc("Enable the new, experimental CFL alias analysis in CodeGen"), 126 cl::values(clEnumValN(CFLAAType::None, "none", "Disable CFL-AA"), 127 clEnumValN(CFLAAType::Steensgaard, "steens", 128 "Enable unification-based CFL-AA"), 129 clEnumValN(CFLAAType::Andersen, "anders", 130 "Enable inclusion-based CFL-AA"), 131 clEnumValN(CFLAAType::Both, "both", 132 "Enable both variants of CFL-AA"))); 133 134 /// Allow standard passes to be disabled by command line options. This supports 135 /// simple binary flags that either suppress the pass or do nothing. 136 /// i.e. -disable-mypass=false has no effect. 137 /// These should be converted to boolOrDefault in order to use applyOverride. 138 static IdentifyingPassPtr applyDisable(IdentifyingPassPtr PassID, 139 bool Override) { 140 if (Override) 141 return IdentifyingPassPtr(); 142 return PassID; 143 } 144 145 /// Allow standard passes to be disabled by the command line, regardless of who 146 /// is adding the pass. 147 /// 148 /// StandardID is the pass identified in the standard pass pipeline and provided 149 /// to addPass(). It may be a target-specific ID in the case that the target 150 /// directly adds its own pass, but in that case we harmlessly fall through. 151 /// 152 /// TargetID is the pass that the target has configured to override StandardID. 153 /// 154 /// StandardID may be a pseudo ID. In that case TargetID is the name of the real 155 /// pass to run. This allows multiple options to control a single pass depending 156 /// on where in the pipeline that pass is added. 157 static IdentifyingPassPtr overridePass(AnalysisID StandardID, 158 IdentifyingPassPtr TargetID) { 159 if (StandardID == &PostRASchedulerID) 160 return applyDisable(TargetID, DisablePostRASched); 161 162 if (StandardID == &BranchFolderPassID) 163 return applyDisable(TargetID, DisableBranchFold); 164 165 if (StandardID == &TailDuplicateID) 166 return applyDisable(TargetID, DisableTailDuplicate); 167 168 if (StandardID == &TargetPassConfig::EarlyTailDuplicateID) 169 return applyDisable(TargetID, DisableEarlyTailDup); 170 171 if (StandardID == &MachineBlockPlacementID) 172 return applyDisable(TargetID, DisableBlockPlacement); 173 174 if (StandardID == &StackSlotColoringID) 175 return applyDisable(TargetID, DisableSSC); 176 177 if (StandardID == &DeadMachineInstructionElimID) 178 return applyDisable(TargetID, DisableMachineDCE); 179 180 if (StandardID == &EarlyIfConverterID) 181 return applyDisable(TargetID, DisableEarlyIfConversion); 182 183 if (StandardID == &MachineLICMID) 184 return applyDisable(TargetID, DisableMachineLICM); 185 186 if (StandardID == &MachineCSEID) 187 return applyDisable(TargetID, DisableMachineCSE); 188 189 if (StandardID == &TargetPassConfig::PostRAMachineLICMID) 190 return applyDisable(TargetID, DisablePostRAMachineLICM); 191 192 if (StandardID == &MachineSinkingID) 193 return applyDisable(TargetID, DisableMachineSink); 194 195 if (StandardID == &MachineCopyPropagationID) 196 return applyDisable(TargetID, DisableCopyProp); 197 198 return TargetID; 199 } 200 201 //===---------------------------------------------------------------------===// 202 /// TargetPassConfig 203 //===---------------------------------------------------------------------===// 204 205 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig", 206 "Target Pass Configuration", false, false) 207 char TargetPassConfig::ID = 0; 208 209 // Pseudo Pass IDs. 210 char TargetPassConfig::EarlyTailDuplicateID = 0; 211 char TargetPassConfig::PostRAMachineLICMID = 0; 212 213 namespace { 214 struct InsertedPass { 215 AnalysisID TargetPassID; 216 IdentifyingPassPtr InsertedPassID; 217 bool VerifyAfter; 218 bool PrintAfter; 219 220 InsertedPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID, 221 bool VerifyAfter, bool PrintAfter) 222 : TargetPassID(TargetPassID), InsertedPassID(InsertedPassID), 223 VerifyAfter(VerifyAfter), PrintAfter(PrintAfter) {} 224 225 Pass *getInsertedPass() const { 226 assert(InsertedPassID.isValid() && "Illegal Pass ID!"); 227 if (InsertedPassID.isInstance()) 228 return InsertedPassID.getInstance(); 229 Pass *NP = Pass::createPass(InsertedPassID.getID()); 230 assert(NP && "Pass ID not registered"); 231 return NP; 232 } 233 }; 234 } 235 236 namespace llvm { 237 class PassConfigImpl { 238 public: 239 // List of passes explicitly substituted by this target. Normally this is 240 // empty, but it is a convenient way to suppress or replace specific passes 241 // that are part of a standard pass pipeline without overridding the entire 242 // pipeline. This mechanism allows target options to inherit a standard pass's 243 // user interface. For example, a target may disable a standard pass by 244 // default by substituting a pass ID of zero, and the user may still enable 245 // that standard pass with an explicit command line option. 246 DenseMap<AnalysisID,IdentifyingPassPtr> TargetPasses; 247 248 /// Store the pairs of <AnalysisID, AnalysisID> of which the second pass 249 /// is inserted after each instance of the first one. 250 SmallVector<InsertedPass, 4> InsertedPasses; 251 }; 252 } // namespace llvm 253 254 // Out of line virtual method. 255 TargetPassConfig::~TargetPassConfig() { 256 delete Impl; 257 } 258 259 // Out of line constructor provides default values for pass options and 260 // registers all common codegen passes. 261 TargetPassConfig::TargetPassConfig(TargetMachine *tm, PassManagerBase &pm) 262 : ImmutablePass(ID), PM(&pm), Started(true), Stopped(false), 263 AddingMachinePasses(false), TM(tm), Impl(nullptr), Initialized(false), 264 DisableVerify(false), EnableTailMerge(true) { 265 266 Impl = new PassConfigImpl(); 267 268 // Register all target independent codegen passes to activate their PassIDs, 269 // including this pass itself. 270 initializeCodeGen(*PassRegistry::getPassRegistry()); 271 272 // Also register alias analysis passes required by codegen passes. 273 initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry()); 274 initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry()); 275 276 // Substitute Pseudo Pass IDs for real ones. 277 substitutePass(&EarlyTailDuplicateID, &TailDuplicateID); 278 substitutePass(&PostRAMachineLICMID, &MachineLICMID); 279 280 if (StringRef(PrintMachineInstrs.getValue()).equals("")) 281 TM->Options.PrintMachineCode = true; 282 } 283 284 CodeGenOpt::Level TargetPassConfig::getOptLevel() const { 285 return TM->getOptLevel(); 286 } 287 288 /// Insert InsertedPassID pass after TargetPassID. 289 void TargetPassConfig::insertPass(AnalysisID TargetPassID, 290 IdentifyingPassPtr InsertedPassID, 291 bool VerifyAfter, bool PrintAfter) { 292 assert(((!InsertedPassID.isInstance() && 293 TargetPassID != InsertedPassID.getID()) || 294 (InsertedPassID.isInstance() && 295 TargetPassID != InsertedPassID.getInstance()->getPassID())) && 296 "Insert a pass after itself!"); 297 Impl->InsertedPasses.emplace_back(TargetPassID, InsertedPassID, VerifyAfter, 298 PrintAfter); 299 } 300 301 /// createPassConfig - Create a pass configuration object to be used by 302 /// addPassToEmitX methods for generating a pipeline of CodeGen passes. 303 /// 304 /// Targets may override this to extend TargetPassConfig. 305 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) { 306 return new TargetPassConfig(this, PM); 307 } 308 309 TargetPassConfig::TargetPassConfig() 310 : ImmutablePass(ID), PM(nullptr) { 311 llvm_unreachable("TargetPassConfig should not be constructed on-the-fly"); 312 } 313 314 // Helper to verify the analysis is really immutable. 315 void TargetPassConfig::setOpt(bool &Opt, bool Val) { 316 assert(!Initialized && "PassConfig is immutable"); 317 Opt = Val; 318 } 319 320 void TargetPassConfig::substitutePass(AnalysisID StandardID, 321 IdentifyingPassPtr TargetID) { 322 Impl->TargetPasses[StandardID] = TargetID; 323 } 324 325 IdentifyingPassPtr TargetPassConfig::getPassSubstitution(AnalysisID ID) const { 326 DenseMap<AnalysisID, IdentifyingPassPtr>::const_iterator 327 I = Impl->TargetPasses.find(ID); 328 if (I == Impl->TargetPasses.end()) 329 return ID; 330 return I->second; 331 } 332 333 bool TargetPassConfig::isPassSubstitutedOrOverridden(AnalysisID ID) const { 334 IdentifyingPassPtr TargetID = getPassSubstitution(ID); 335 IdentifyingPassPtr FinalPtr = overridePass(ID, TargetID); 336 return !FinalPtr.isValid() || FinalPtr.isInstance() || 337 FinalPtr.getID() != ID; 338 } 339 340 /// Add a pass to the PassManager if that pass is supposed to be run. If the 341 /// Started/Stopped flags indicate either that the compilation should start at 342 /// a later pass or that it should stop after an earlier pass, then do not add 343 /// the pass. Finally, compare the current pass against the StartAfter 344 /// and StopAfter options and change the Started/Stopped flags accordingly. 345 void TargetPassConfig::addPass(Pass *P, bool verifyAfter, bool printAfter) { 346 assert(!Initialized && "PassConfig is immutable"); 347 348 // Cache the Pass ID here in case the pass manager finds this pass is 349 // redundant with ones already scheduled / available, and deletes it. 350 // Fundamentally, once we add the pass to the manager, we no longer own it 351 // and shouldn't reference it. 352 AnalysisID PassID = P->getPassID(); 353 354 if (StartBefore == PassID) 355 Started = true; 356 if (StopBefore == PassID) 357 Stopped = true; 358 if (Started && !Stopped) { 359 std::string Banner; 360 // Construct banner message before PM->add() as that may delete the pass. 361 if (AddingMachinePasses && (printAfter || verifyAfter)) 362 Banner = std::string("After ") + std::string(P->getPassName()); 363 PM->add(P); 364 if (AddingMachinePasses) { 365 if (printAfter) 366 addPrintPass(Banner); 367 if (verifyAfter) 368 addVerifyPass(Banner); 369 } 370 371 // Add the passes after the pass P if there is any. 372 for (auto IP : Impl->InsertedPasses) { 373 if (IP.TargetPassID == PassID) 374 addPass(IP.getInsertedPass(), IP.VerifyAfter, IP.PrintAfter); 375 } 376 } else { 377 delete P; 378 } 379 if (StopAfter == PassID) 380 Stopped = true; 381 if (StartAfter == PassID) 382 Started = true; 383 if (Stopped && !Started) 384 report_fatal_error("Cannot stop compilation after pass that is not run"); 385 } 386 387 /// Add a CodeGen pass at this point in the pipeline after checking for target 388 /// and command line overrides. 389 /// 390 /// addPass cannot return a pointer to the pass instance because is internal the 391 /// PassManager and the instance we create here may already be freed. 392 AnalysisID TargetPassConfig::addPass(AnalysisID PassID, bool verifyAfter, 393 bool printAfter) { 394 IdentifyingPassPtr TargetID = getPassSubstitution(PassID); 395 IdentifyingPassPtr FinalPtr = overridePass(PassID, TargetID); 396 if (!FinalPtr.isValid()) 397 return nullptr; 398 399 Pass *P; 400 if (FinalPtr.isInstance()) 401 P = FinalPtr.getInstance(); 402 else { 403 P = Pass::createPass(FinalPtr.getID()); 404 if (!P) 405 llvm_unreachable("Pass ID not registered"); 406 } 407 AnalysisID FinalID = P->getPassID(); 408 addPass(P, verifyAfter, printAfter); // Ends the lifetime of P. 409 410 return FinalID; 411 } 412 413 void TargetPassConfig::printAndVerify(const std::string &Banner) { 414 addPrintPass(Banner); 415 addVerifyPass(Banner); 416 } 417 418 void TargetPassConfig::addPrintPass(const std::string &Banner) { 419 if (TM->shouldPrintMachineCode()) 420 PM->add(createMachineFunctionPrinterPass(dbgs(), Banner)); 421 } 422 423 void TargetPassConfig::addVerifyPass(const std::string &Banner) { 424 if (VerifyMachineCode) 425 PM->add(createMachineVerifierPass(Banner)); 426 } 427 428 /// Add common target configurable passes that perform LLVM IR to IR transforms 429 /// following machine independent optimization. 430 void TargetPassConfig::addIRPasses() { 431 switch (UseCFLAA) { 432 case CFLAAType::Steensgaard: 433 addPass(createCFLSteensAAWrapperPass()); 434 break; 435 case CFLAAType::Andersen: 436 addPass(createCFLAndersAAWrapperPass()); 437 break; 438 case CFLAAType::Both: 439 addPass(createCFLAndersAAWrapperPass()); 440 addPass(createCFLSteensAAWrapperPass()); 441 break; 442 default: 443 break; 444 } 445 446 // Basic AliasAnalysis support. 447 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that 448 // BasicAliasAnalysis wins if they disagree. This is intended to help 449 // support "obvious" type-punning idioms. 450 addPass(createTypeBasedAAWrapperPass()); 451 addPass(createScopedNoAliasAAWrapperPass()); 452 addPass(createBasicAAWrapperPass()); 453 454 // Before running any passes, run the verifier to determine if the input 455 // coming from the front-end and/or optimizer is valid. 456 if (!DisableVerify) 457 addPass(createVerifierPass()); 458 459 // Run loop strength reduction before anything else. 460 if (getOptLevel() != CodeGenOpt::None && !DisableLSR) { 461 addPass(createLoopStrengthReducePass()); 462 if (PrintLSR) 463 addPass(createPrintFunctionPass(dbgs(), "\n\n*** Code after LSR ***\n")); 464 } 465 466 // Run GC lowering passes for builtin collectors 467 // TODO: add a pass insertion point here 468 addPass(createGCLoweringPass()); 469 addPass(createShadowStackGCLoweringPass()); 470 471 // Make sure that no unreachable blocks are instruction selected. 472 addPass(createUnreachableBlockEliminationPass()); 473 474 // Prepare expensive constants for SelectionDAG. 475 if (getOptLevel() != CodeGenOpt::None && !DisableConstantHoisting) 476 addPass(createConstantHoistingPass()); 477 478 if (getOptLevel() != CodeGenOpt::None && !DisablePartialLibcallInlining) 479 addPass(createPartiallyInlineLibCallsPass()); 480 481 // Insert calls to mcount-like functions. 482 addPass(createCountingFunctionInserterPass()); 483 } 484 485 /// Turn exception handling constructs into something the code generators can 486 /// handle. 487 void TargetPassConfig::addPassesToHandleExceptions() { 488 const MCAsmInfo *MCAI = TM->getMCAsmInfo(); 489 assert(MCAI && "No MCAsmInfo"); 490 switch (MCAI->getExceptionHandlingType()) { 491 case ExceptionHandling::SjLj: 492 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both 493 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise, 494 // catch info can get misplaced when a selector ends up more than one block 495 // removed from the parent invoke(s). This could happen when a landing 496 // pad is shared by multiple invokes and is also a target of a normal 497 // edge from elsewhere. 498 addPass(createSjLjEHPreparePass()); 499 LLVM_FALLTHROUGH; 500 case ExceptionHandling::DwarfCFI: 501 case ExceptionHandling::ARM: 502 addPass(createDwarfEHPass(TM)); 503 break; 504 case ExceptionHandling::WinEH: 505 // We support using both GCC-style and MSVC-style exceptions on Windows, so 506 // add both preparation passes. Each pass will only actually run if it 507 // recognizes the personality function. 508 addPass(createWinEHPass(TM)); 509 addPass(createDwarfEHPass(TM)); 510 break; 511 case ExceptionHandling::None: 512 addPass(createLowerInvokePass()); 513 514 // The lower invoke pass may create unreachable code. Remove it. 515 addPass(createUnreachableBlockEliminationPass()); 516 break; 517 } 518 } 519 520 /// Add pass to prepare the LLVM IR for code generation. This should be done 521 /// before exception handling preparation passes. 522 void TargetPassConfig::addCodeGenPrepare() { 523 if (getOptLevel() != CodeGenOpt::None && !DisableCGP) 524 addPass(createCodeGenPreparePass(TM)); 525 addPass(createRewriteSymbolsPass()); 526 } 527 528 /// Add common passes that perform LLVM IR to IR transforms in preparation for 529 /// instruction selection. 530 void TargetPassConfig::addISelPrepare() { 531 addPreISel(); 532 533 // Force codegen to run according to the callgraph. 534 if (TM->Options.EnableIPRA) 535 addPass(new DummyCGSCCPass); 536 537 // Add both the safe stack and the stack protection passes: each of them will 538 // only protect functions that have corresponding attributes. 539 addPass(createSafeStackPass(TM)); 540 addPass(createStackProtectorPass(TM)); 541 542 if (PrintISelInput) 543 addPass(createPrintFunctionPass( 544 dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n")); 545 546 // All passes which modify the LLVM IR are now complete; run the verifier 547 // to ensure that the IR is valid. 548 if (!DisableVerify) 549 addPass(createVerifierPass()); 550 } 551 552 /// Add the complete set of target-independent postISel code generator passes. 553 /// 554 /// This can be read as the standard order of major LLVM CodeGen stages. Stages 555 /// with nontrivial configuration or multiple passes are broken out below in 556 /// add%Stage routines. 557 /// 558 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The 559 /// addPre/Post methods with empty header implementations allow injecting 560 /// target-specific fixups just before or after major stages. Additionally, 561 /// targets have the flexibility to change pass order within a stage by 562 /// overriding default implementation of add%Stage routines below. Each 563 /// technique has maintainability tradeoffs because alternate pass orders are 564 /// not well supported. addPre/Post works better if the target pass is easily 565 /// tied to a common pass. But if it has subtle dependencies on multiple passes, 566 /// the target should override the stage instead. 567 /// 568 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection 569 /// before/after any target-independent pass. But it's currently overkill. 570 void TargetPassConfig::addMachinePasses() { 571 AddingMachinePasses = true; 572 573 // Insert a machine instr printer pass after the specified pass. 574 if (!StringRef(PrintMachineInstrs.getValue()).equals("") && 575 !StringRef(PrintMachineInstrs.getValue()).equals("option-unspecified")) { 576 const PassRegistry *PR = PassRegistry::getPassRegistry(); 577 const PassInfo *TPI = PR->getPassInfo(PrintMachineInstrs.getValue()); 578 const PassInfo *IPI = PR->getPassInfo(StringRef("machineinstr-printer")); 579 assert (TPI && IPI && "Pass ID not registered!"); 580 const char *TID = (const char *)(TPI->getTypeInfo()); 581 const char *IID = (const char *)(IPI->getTypeInfo()); 582 insertPass(TID, IID); 583 } 584 585 // Print the instruction selected machine code... 586 printAndVerify("After Instruction Selection"); 587 588 if (TM->Options.EnableIPRA) 589 addPass(createRegUsageInfoPropPass()); 590 591 // Expand pseudo-instructions emitted by ISel. 592 addPass(&ExpandISelPseudosID); 593 594 // Add passes that optimize machine instructions in SSA form. 595 if (getOptLevel() != CodeGenOpt::None) { 596 addMachineSSAOptimization(); 597 } else { 598 // If the target requests it, assign local variables to stack slots relative 599 // to one another and simplify frame index references where possible. 600 addPass(&LocalStackSlotAllocationID, false); 601 } 602 603 // Run pre-ra passes. 604 addPreRegAlloc(); 605 606 // Run register allocation and passes that are tightly coupled with it, 607 // including phi elimination and scheduling. 608 if (getOptimizeRegAlloc()) 609 addOptimizedRegAlloc(createRegAllocPass(true)); 610 else 611 addFastRegAlloc(createRegAllocPass(false)); 612 613 // Run post-ra passes. 614 addPostRegAlloc(); 615 616 // Insert prolog/epilog code. Eliminate abstract frame index references... 617 if (getOptLevel() != CodeGenOpt::None) 618 addPass(&ShrinkWrapID); 619 620 // Prolog/Epilog inserter needs a TargetMachine to instantiate. But only 621 // do so if it hasn't been disabled, substituted, or overridden. 622 if (!isPassSubstitutedOrOverridden(&PrologEpilogCodeInserterID)) 623 addPass(createPrologEpilogInserterPass(TM)); 624 625 /// Add passes that optimize machine instructions after register allocation. 626 if (getOptLevel() != CodeGenOpt::None) 627 addMachineLateOptimization(); 628 629 // Expand pseudo instructions before second scheduling pass. 630 addPass(&ExpandPostRAPseudosID); 631 632 // Run pre-sched2 passes. 633 addPreSched2(); 634 635 if (EnableImplicitNullChecks) 636 addPass(&ImplicitNullChecksID); 637 638 // Second pass scheduler. 639 // Let Target optionally insert this pass by itself at some other 640 // point. 641 if (getOptLevel() != CodeGenOpt::None && 642 !TM->targetSchedulesPostRAScheduling()) { 643 if (MISchedPostRA) 644 addPass(&PostMachineSchedulerID); 645 else 646 addPass(&PostRASchedulerID); 647 } 648 649 // GC 650 if (addGCPasses()) { 651 if (PrintGCInfo) 652 addPass(createGCInfoPrinter(dbgs()), false, false); 653 } 654 655 // Basic block placement. 656 if (getOptLevel() != CodeGenOpt::None) 657 addBlockPlacement(); 658 659 addPreEmitPass(); 660 661 if (TM->Options.EnableIPRA) 662 // Collect register usage information and produce a register mask of 663 // clobbered registers, to be used to optimize call sites. 664 addPass(createRegUsageInfoCollector()); 665 666 addPass(&FuncletLayoutID, false); 667 668 addPass(&StackMapLivenessID, false); 669 addPass(&LiveDebugValuesID, false); 670 671 // Insert before XRay Instrumentation. 672 addPass(&FEntryInserterID, false); 673 674 addPass(&XRayInstrumentationID, false); 675 addPass(&PatchableFunctionID, false); 676 677 AddingMachinePasses = false; 678 } 679 680 /// Add passes that optimize machine instructions in SSA form. 681 void TargetPassConfig::addMachineSSAOptimization() { 682 // Pre-ra tail duplication. 683 addPass(&EarlyTailDuplicateID); 684 685 // Optimize PHIs before DCE: removing dead PHI cycles may make more 686 // instructions dead. 687 addPass(&OptimizePHIsID, false); 688 689 // This pass merges large allocas. StackSlotColoring is a different pass 690 // which merges spill slots. 691 addPass(&StackColoringID, false); 692 693 // If the target requests it, assign local variables to stack slots relative 694 // to one another and simplify frame index references where possible. 695 addPass(&LocalStackSlotAllocationID, false); 696 697 // With optimization, dead code should already be eliminated. However 698 // there is one known exception: lowered code for arguments that are only 699 // used by tail calls, where the tail calls reuse the incoming stack 700 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll). 701 addPass(&DeadMachineInstructionElimID); 702 703 // Allow targets to insert passes that improve instruction level parallelism, 704 // like if-conversion. Such passes will typically need dominator trees and 705 // loop info, just like LICM and CSE below. 706 addILPOpts(); 707 708 addPass(&MachineLICMID, false); 709 addPass(&MachineCSEID, false); 710 711 // Coalesce basic blocks with the same branch condition 712 addPass(&BranchCoalescingID); 713 714 addPass(&MachineSinkingID); 715 716 addPass(&PeepholeOptimizerID); 717 // Clean-up the dead code that may have been generated by peephole 718 // rewriting. 719 addPass(&DeadMachineInstructionElimID); 720 } 721 722 //===---------------------------------------------------------------------===// 723 /// Register Allocation Pass Configuration 724 //===---------------------------------------------------------------------===// 725 726 bool TargetPassConfig::getOptimizeRegAlloc() const { 727 switch (OptimizeRegAlloc) { 728 case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None; 729 case cl::BOU_TRUE: return true; 730 case cl::BOU_FALSE: return false; 731 } 732 llvm_unreachable("Invalid optimize-regalloc state"); 733 } 734 735 /// RegisterRegAlloc's global Registry tracks allocator registration. 736 MachinePassRegistry RegisterRegAlloc::Registry; 737 738 /// A dummy default pass factory indicates whether the register allocator is 739 /// overridden on the command line. 740 static llvm::once_flag InitializeDefaultRegisterAllocatorFlag; 741 static FunctionPass *useDefaultRegisterAllocator() { return nullptr; } 742 static RegisterRegAlloc 743 defaultRegAlloc("default", 744 "pick register allocator based on -O option", 745 useDefaultRegisterAllocator); 746 747 /// -regalloc=... command line option. 748 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false, 749 RegisterPassParser<RegisterRegAlloc> > 750 RegAlloc("regalloc", 751 cl::init(&useDefaultRegisterAllocator), 752 cl::desc("Register allocator to use")); 753 754 static void initializeDefaultRegisterAllocatorOnce() { 755 RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault(); 756 757 if (!Ctor) { 758 Ctor = RegAlloc; 759 RegisterRegAlloc::setDefault(RegAlloc); 760 } 761 } 762 763 764 /// Instantiate the default register allocator pass for this target for either 765 /// the optimized or unoptimized allocation path. This will be added to the pass 766 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc 767 /// in the optimized case. 768 /// 769 /// A target that uses the standard regalloc pass order for fast or optimized 770 /// allocation may still override this for per-target regalloc 771 /// selection. But -regalloc=... always takes precedence. 772 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) { 773 if (Optimized) 774 return createGreedyRegisterAllocator(); 775 else 776 return createFastRegisterAllocator(); 777 } 778 779 /// Find and instantiate the register allocation pass requested by this target 780 /// at the current optimization level. Different register allocators are 781 /// defined as separate passes because they may require different analysis. 782 /// 783 /// This helper ensures that the regalloc= option is always available, 784 /// even for targets that override the default allocator. 785 /// 786 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs, 787 /// this can be folded into addPass. 788 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) { 789 // Initialize the global default. 790 llvm::call_once(InitializeDefaultRegisterAllocatorFlag, 791 initializeDefaultRegisterAllocatorOnce); 792 793 RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault(); 794 if (Ctor != useDefaultRegisterAllocator) 795 return Ctor(); 796 797 // With no -regalloc= override, ask the target for a regalloc pass. 798 return createTargetRegisterAllocator(Optimized); 799 } 800 801 /// Return true if the default global register allocator is in use and 802 /// has not be overriden on the command line with '-regalloc=...' 803 bool TargetPassConfig::usingDefaultRegAlloc() const { 804 return RegAlloc.getNumOccurrences() == 0; 805 } 806 807 /// Add the minimum set of target-independent passes that are required for 808 /// register allocation. No coalescing or scheduling. 809 void TargetPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) { 810 addPass(&PHIEliminationID, false); 811 addPass(&TwoAddressInstructionPassID, false); 812 813 if (RegAllocPass) 814 addPass(RegAllocPass); 815 } 816 817 /// Add standard target-independent passes that are tightly coupled with 818 /// optimized register allocation, including coalescing, machine instruction 819 /// scheduling, and register allocation itself. 820 void TargetPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) { 821 addPass(&DetectDeadLanesID, false); 822 823 addPass(&ProcessImplicitDefsID, false); 824 825 // LiveVariables currently requires pure SSA form. 826 // 827 // FIXME: Once TwoAddressInstruction pass no longer uses kill flags, 828 // LiveVariables can be removed completely, and LiveIntervals can be directly 829 // computed. (We still either need to regenerate kill flags after regalloc, or 830 // preferably fix the scavenger to not depend on them). 831 addPass(&LiveVariablesID, false); 832 833 // Edge splitting is smarter with machine loop info. 834 addPass(&MachineLoopInfoID, false); 835 addPass(&PHIEliminationID, false); 836 837 // Eventually, we want to run LiveIntervals before PHI elimination. 838 if (EarlyLiveIntervals) 839 addPass(&LiveIntervalsID, false); 840 841 addPass(&TwoAddressInstructionPassID, false); 842 addPass(&RegisterCoalescerID); 843 844 // The machine scheduler may accidentally create disconnected components 845 // when moving subregister definitions around, avoid this by splitting them to 846 // separate vregs before. Splitting can also improve reg. allocation quality. 847 addPass(&RenameIndependentSubregsID); 848 849 // PreRA instruction scheduling. 850 addPass(&MachineSchedulerID); 851 852 if (RegAllocPass) { 853 // Add the selected register allocation pass. 854 addPass(RegAllocPass); 855 856 // Allow targets to change the register assignments before rewriting. 857 addPreRewrite(); 858 859 // Finally rewrite virtual registers. 860 addPass(&VirtRegRewriterID); 861 862 // Perform stack slot coloring and post-ra machine LICM. 863 // 864 // FIXME: Re-enable coloring with register when it's capable of adding 865 // kill markers. 866 addPass(&StackSlotColoringID); 867 868 // Run post-ra machine LICM to hoist reloads / remats. 869 // 870 // FIXME: can this move into MachineLateOptimization? 871 addPass(&PostRAMachineLICMID); 872 } 873 } 874 875 //===---------------------------------------------------------------------===// 876 /// Post RegAlloc Pass Configuration 877 //===---------------------------------------------------------------------===// 878 879 /// Add passes that optimize machine instructions after register allocation. 880 void TargetPassConfig::addMachineLateOptimization() { 881 // Branch folding must be run after regalloc and prolog/epilog insertion. 882 addPass(&BranchFolderPassID); 883 884 // Tail duplication. 885 // Note that duplicating tail just increases code size and degrades 886 // performance for targets that require Structured Control Flow. 887 // In addition it can also make CFG irreducible. Thus we disable it. 888 if (!TM->requiresStructuredCFG()) 889 addPass(&TailDuplicateID); 890 891 // Copy propagation. 892 addPass(&MachineCopyPropagationID); 893 } 894 895 /// Add standard GC passes. 896 bool TargetPassConfig::addGCPasses() { 897 addPass(&GCMachineCodeAnalysisID, false); 898 return true; 899 } 900 901 /// Add standard basic block placement passes. 902 void TargetPassConfig::addBlockPlacement() { 903 if (addPass(&MachineBlockPlacementID)) { 904 // Run a separate pass to collect block placement statistics. 905 if (EnableBlockPlacementStats) 906 addPass(&MachineBlockPlacementStatsID); 907 } 908 } 909 910 //===---------------------------------------------------------------------===// 911 /// GlobalISel Configuration 912 //===---------------------------------------------------------------------===// 913 bool TargetPassConfig::isGlobalISelAbortEnabled() const { 914 return EnableGlobalISelAbort == 1; 915 } 916 917 bool TargetPassConfig::reportDiagnosticWhenGlobalISelFallback() const { 918 return EnableGlobalISelAbort == 2; 919 } 920