1 //===- TargetPassConfig.cpp - Target independent code generation passes ---===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines interfaces to access the target independent code 10 // generation passes provided by the LLVM backend. 11 // 12 //===---------------------------------------------------------------------===// 13 14 #include "llvm/CodeGen/TargetPassConfig.h" 15 #include "llvm/ADT/DenseMap.h" 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/ADT/StringRef.h" 18 #include "llvm/Analysis/BasicAliasAnalysis.h" 19 #include "llvm/Analysis/CFLAndersAliasAnalysis.h" 20 #include "llvm/Analysis/CFLSteensAliasAnalysis.h" 21 #include "llvm/Analysis/CallGraphSCCPass.h" 22 #include "llvm/Analysis/ScopedNoAliasAA.h" 23 #include "llvm/Analysis/TargetTransformInfo.h" 24 #include "llvm/Analysis/TypeBasedAliasAnalysis.h" 25 #include "llvm/CodeGen/CSEConfigBase.h" 26 #include "llvm/CodeGen/MachineFunctionPass.h" 27 #include "llvm/CodeGen/MachinePassRegistry.h" 28 #include "llvm/CodeGen/Passes.h" 29 #include "llvm/CodeGen/RegAllocRegistry.h" 30 #include "llvm/IR/IRPrintingPasses.h" 31 #include "llvm/IR/LegacyPassManager.h" 32 #include "llvm/IR/Verifier.h" 33 #include "llvm/InitializePasses.h" 34 #include "llvm/MC/MCAsmInfo.h" 35 #include "llvm/MC/MCTargetOptions.h" 36 #include "llvm/Pass.h" 37 #include "llvm/Support/CodeGen.h" 38 #include "llvm/Support/CommandLine.h" 39 #include "llvm/Support/Compiler.h" 40 #include "llvm/Support/Debug.h" 41 #include "llvm/Support/ErrorHandling.h" 42 #include "llvm/Support/SaveAndRestore.h" 43 #include "llvm/Support/Threading.h" 44 #include "llvm/Target/TargetMachine.h" 45 #include "llvm/Transforms/Scalar.h" 46 #include "llvm/Transforms/Utils.h" 47 #include "llvm/Transforms/Utils/SymbolRewriter.h" 48 #include <cassert> 49 #include <string> 50 51 using namespace llvm; 52 53 static cl::opt<bool> 54 EnableIPRA("enable-ipra", cl::init(false), cl::Hidden, 55 cl::desc("Enable interprocedural register allocation " 56 "to reduce load/store at procedure calls.")); 57 static cl::opt<bool> DisablePostRASched("disable-post-ra", cl::Hidden, 58 cl::desc("Disable Post Regalloc Scheduler")); 59 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden, 60 cl::desc("Disable branch folding")); 61 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden, 62 cl::desc("Disable tail duplication")); 63 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden, 64 cl::desc("Disable pre-register allocation tail duplication")); 65 static cl::opt<bool> DisableBlockPlacement("disable-block-placement", 66 cl::Hidden, cl::desc("Disable probability-driven block placement")); 67 static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-stats", 68 cl::Hidden, cl::desc("Collect probability-driven block placement stats")); 69 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden, 70 cl::desc("Disable Stack Slot Coloring")); 71 static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden, 72 cl::desc("Disable Machine Dead Code Elimination")); 73 static cl::opt<bool> DisableEarlyIfConversion("disable-early-ifcvt", cl::Hidden, 74 cl::desc("Disable Early If-conversion")); 75 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden, 76 cl::desc("Disable Machine LICM")); 77 static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden, 78 cl::desc("Disable Machine Common Subexpression Elimination")); 79 static cl::opt<cl::boolOrDefault> OptimizeRegAlloc( 80 "optimize-regalloc", cl::Hidden, 81 cl::desc("Enable optimized register allocation compilation path.")); 82 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm", 83 cl::Hidden, 84 cl::desc("Disable Machine LICM")); 85 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden, 86 cl::desc("Disable Machine Sinking")); 87 static cl::opt<bool> DisablePostRAMachineSink("disable-postra-machine-sink", 88 cl::Hidden, 89 cl::desc("Disable PostRA Machine Sinking")); 90 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden, 91 cl::desc("Disable Loop Strength Reduction Pass")); 92 static cl::opt<bool> DisableConstantHoisting("disable-constant-hoisting", 93 cl::Hidden, cl::desc("Disable ConstantHoisting")); 94 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden, 95 cl::desc("Disable Codegen Prepare")); 96 static cl::opt<bool> DisableCopyProp("disable-copyprop", cl::Hidden, 97 cl::desc("Disable Copy Propagation pass")); 98 static cl::opt<bool> DisablePartialLibcallInlining("disable-partial-libcall-inlining", 99 cl::Hidden, cl::desc("Disable Partial Libcall Inlining")); 100 static cl::opt<bool> EnableImplicitNullChecks( 101 "enable-implicit-null-checks", 102 cl::desc("Fold null checks into faulting memory operations"), 103 cl::init(false), cl::Hidden); 104 static cl::opt<bool> DisableMergeICmps("disable-mergeicmps", 105 cl::desc("Disable MergeICmps Pass"), 106 cl::init(false), cl::Hidden); 107 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden, 108 cl::desc("Print LLVM IR produced by the loop-reduce pass")); 109 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden, 110 cl::desc("Print LLVM IR input to isel pass")); 111 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden, 112 cl::desc("Dump garbage collector data")); 113 static cl::opt<cl::boolOrDefault> 114 VerifyMachineCode("verify-machineinstrs", cl::Hidden, 115 cl::desc("Verify generated machine code"), 116 cl::ZeroOrMore); 117 static cl::opt<cl::boolOrDefault> DebugifyAndStripAll( 118 "debugify-and-strip-all-safe", cl::Hidden, 119 cl::desc( 120 "Debugify MIR before and Strip debug after " 121 "each pass except those known to be unsafe when debug info is present"), 122 cl::ZeroOrMore); 123 enum RunOutliner { AlwaysOutline, NeverOutline, TargetDefault }; 124 // Enable or disable the MachineOutliner. 125 static cl::opt<RunOutliner> EnableMachineOutliner( 126 "enable-machine-outliner", cl::desc("Enable the machine outliner"), 127 cl::Hidden, cl::ValueOptional, cl::init(TargetDefault), 128 cl::values(clEnumValN(AlwaysOutline, "always", 129 "Run on all functions guaranteed to be beneficial"), 130 clEnumValN(NeverOutline, "never", "Disable all outlining"), 131 // Sentinel value for unspecified option. 132 clEnumValN(AlwaysOutline, "", ""))); 133 // Enable or disable FastISel. Both options are needed, because 134 // FastISel is enabled by default with -fast, and we wish to be 135 // able to enable or disable fast-isel independently from -O0. 136 static cl::opt<cl::boolOrDefault> 137 EnableFastISelOption("fast-isel", cl::Hidden, 138 cl::desc("Enable the \"fast\" instruction selector")); 139 140 static cl::opt<cl::boolOrDefault> EnableGlobalISelOption( 141 "global-isel", cl::Hidden, 142 cl::desc("Enable the \"global\" instruction selector")); 143 144 // FIXME: remove this after switching to NPM or GlobalISel, whichever gets there 145 // first... 146 static cl::opt<bool> 147 PrintAfterISel("print-after-isel", cl::init(false), cl::Hidden, 148 cl::desc("Print machine instrs after ISel")); 149 150 static cl::opt<GlobalISelAbortMode> EnableGlobalISelAbort( 151 "global-isel-abort", cl::Hidden, 152 cl::desc("Enable abort calls when \"global\" instruction selection " 153 "fails to lower/select an instruction"), 154 cl::values( 155 clEnumValN(GlobalISelAbortMode::Disable, "0", "Disable the abort"), 156 clEnumValN(GlobalISelAbortMode::Enable, "1", "Enable the abort"), 157 clEnumValN(GlobalISelAbortMode::DisableWithDiag, "2", 158 "Disable the abort but emit a diagnostic on failure"))); 159 160 // Temporary option to allow experimenting with MachineScheduler as a post-RA 161 // scheduler. Targets can "properly" enable this with 162 // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID). 163 // Targets can return true in targetSchedulesPostRAScheduling() and 164 // insert a PostRA scheduling pass wherever it wants. 165 static cl::opt<bool> MISchedPostRA( 166 "misched-postra", cl::Hidden, 167 cl::desc( 168 "Run MachineScheduler post regalloc (independent of preRA sched)")); 169 170 // Experimental option to run live interval analysis early. 171 static cl::opt<bool> EarlyLiveIntervals("early-live-intervals", cl::Hidden, 172 cl::desc("Run live interval analysis earlier in the pipeline")); 173 174 // Experimental option to use CFL-AA in codegen 175 enum class CFLAAType { None, Steensgaard, Andersen, Both }; 176 static cl::opt<CFLAAType> UseCFLAA( 177 "use-cfl-aa-in-codegen", cl::init(CFLAAType::None), cl::Hidden, 178 cl::desc("Enable the new, experimental CFL alias analysis in CodeGen"), 179 cl::values(clEnumValN(CFLAAType::None, "none", "Disable CFL-AA"), 180 clEnumValN(CFLAAType::Steensgaard, "steens", 181 "Enable unification-based CFL-AA"), 182 clEnumValN(CFLAAType::Andersen, "anders", 183 "Enable inclusion-based CFL-AA"), 184 clEnumValN(CFLAAType::Both, "both", 185 "Enable both variants of CFL-AA"))); 186 187 /// Option names for limiting the codegen pipeline. 188 /// Those are used in error reporting and we didn't want 189 /// to duplicate their names all over the place. 190 static const char StartAfterOptName[] = "start-after"; 191 static const char StartBeforeOptName[] = "start-before"; 192 static const char StopAfterOptName[] = "stop-after"; 193 static const char StopBeforeOptName[] = "stop-before"; 194 195 static cl::opt<std::string> 196 StartAfterOpt(StringRef(StartAfterOptName), 197 cl::desc("Resume compilation after a specific pass"), 198 cl::value_desc("pass-name"), cl::init(""), cl::Hidden); 199 200 static cl::opt<std::string> 201 StartBeforeOpt(StringRef(StartBeforeOptName), 202 cl::desc("Resume compilation before a specific pass"), 203 cl::value_desc("pass-name"), cl::init(""), cl::Hidden); 204 205 static cl::opt<std::string> 206 StopAfterOpt(StringRef(StopAfterOptName), 207 cl::desc("Stop compilation after a specific pass"), 208 cl::value_desc("pass-name"), cl::init(""), cl::Hidden); 209 210 static cl::opt<std::string> 211 StopBeforeOpt(StringRef(StopBeforeOptName), 212 cl::desc("Stop compilation before a specific pass"), 213 cl::value_desc("pass-name"), cl::init(""), cl::Hidden); 214 215 /// Allow standard passes to be disabled by command line options. This supports 216 /// simple binary flags that either suppress the pass or do nothing. 217 /// i.e. -disable-mypass=false has no effect. 218 /// These should be converted to boolOrDefault in order to use applyOverride. 219 static IdentifyingPassPtr applyDisable(IdentifyingPassPtr PassID, 220 bool Override) { 221 if (Override) 222 return IdentifyingPassPtr(); 223 return PassID; 224 } 225 226 /// Allow standard passes to be disabled by the command line, regardless of who 227 /// is adding the pass. 228 /// 229 /// StandardID is the pass identified in the standard pass pipeline and provided 230 /// to addPass(). It may be a target-specific ID in the case that the target 231 /// directly adds its own pass, but in that case we harmlessly fall through. 232 /// 233 /// TargetID is the pass that the target has configured to override StandardID. 234 /// 235 /// StandardID may be a pseudo ID. In that case TargetID is the name of the real 236 /// pass to run. This allows multiple options to control a single pass depending 237 /// on where in the pipeline that pass is added. 238 static IdentifyingPassPtr overridePass(AnalysisID StandardID, 239 IdentifyingPassPtr TargetID) { 240 if (StandardID == &PostRASchedulerID) 241 return applyDisable(TargetID, DisablePostRASched); 242 243 if (StandardID == &BranchFolderPassID) 244 return applyDisable(TargetID, DisableBranchFold); 245 246 if (StandardID == &TailDuplicateID) 247 return applyDisable(TargetID, DisableTailDuplicate); 248 249 if (StandardID == &EarlyTailDuplicateID) 250 return applyDisable(TargetID, DisableEarlyTailDup); 251 252 if (StandardID == &MachineBlockPlacementID) 253 return applyDisable(TargetID, DisableBlockPlacement); 254 255 if (StandardID == &StackSlotColoringID) 256 return applyDisable(TargetID, DisableSSC); 257 258 if (StandardID == &DeadMachineInstructionElimID) 259 return applyDisable(TargetID, DisableMachineDCE); 260 261 if (StandardID == &EarlyIfConverterID) 262 return applyDisable(TargetID, DisableEarlyIfConversion); 263 264 if (StandardID == &EarlyMachineLICMID) 265 return applyDisable(TargetID, DisableMachineLICM); 266 267 if (StandardID == &MachineCSEID) 268 return applyDisable(TargetID, DisableMachineCSE); 269 270 if (StandardID == &MachineLICMID) 271 return applyDisable(TargetID, DisablePostRAMachineLICM); 272 273 if (StandardID == &MachineSinkingID) 274 return applyDisable(TargetID, DisableMachineSink); 275 276 if (StandardID == &PostRAMachineSinkingID) 277 return applyDisable(TargetID, DisablePostRAMachineSink); 278 279 if (StandardID == &MachineCopyPropagationID) 280 return applyDisable(TargetID, DisableCopyProp); 281 282 return TargetID; 283 } 284 285 //===---------------------------------------------------------------------===// 286 /// TargetPassConfig 287 //===---------------------------------------------------------------------===// 288 289 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig", 290 "Target Pass Configuration", false, false) 291 char TargetPassConfig::ID = 0; 292 293 namespace { 294 295 struct InsertedPass { 296 AnalysisID TargetPassID; 297 IdentifyingPassPtr InsertedPassID; 298 bool VerifyAfter; 299 300 InsertedPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID, 301 bool VerifyAfter) 302 : TargetPassID(TargetPassID), InsertedPassID(InsertedPassID), 303 VerifyAfter(VerifyAfter) {} 304 305 Pass *getInsertedPass() const { 306 assert(InsertedPassID.isValid() && "Illegal Pass ID!"); 307 if (InsertedPassID.isInstance()) 308 return InsertedPassID.getInstance(); 309 Pass *NP = Pass::createPass(InsertedPassID.getID()); 310 assert(NP && "Pass ID not registered"); 311 return NP; 312 } 313 }; 314 315 } // end anonymous namespace 316 317 namespace llvm { 318 319 class PassConfigImpl { 320 public: 321 // List of passes explicitly substituted by this target. Normally this is 322 // empty, but it is a convenient way to suppress or replace specific passes 323 // that are part of a standard pass pipeline without overridding the entire 324 // pipeline. This mechanism allows target options to inherit a standard pass's 325 // user interface. For example, a target may disable a standard pass by 326 // default by substituting a pass ID of zero, and the user may still enable 327 // that standard pass with an explicit command line option. 328 DenseMap<AnalysisID,IdentifyingPassPtr> TargetPasses; 329 330 /// Store the pairs of <AnalysisID, AnalysisID> of which the second pass 331 /// is inserted after each instance of the first one. 332 SmallVector<InsertedPass, 4> InsertedPasses; 333 }; 334 335 } // end namespace llvm 336 337 // Out of line virtual method. 338 TargetPassConfig::~TargetPassConfig() { 339 delete Impl; 340 } 341 342 static const PassInfo *getPassInfo(StringRef PassName) { 343 if (PassName.empty()) 344 return nullptr; 345 346 const PassRegistry &PR = *PassRegistry::getPassRegistry(); 347 const PassInfo *PI = PR.getPassInfo(PassName); 348 if (!PI) 349 report_fatal_error(Twine('\"') + Twine(PassName) + 350 Twine("\" pass is not registered.")); 351 return PI; 352 } 353 354 static AnalysisID getPassIDFromName(StringRef PassName) { 355 const PassInfo *PI = getPassInfo(PassName); 356 return PI ? PI->getTypeInfo() : nullptr; 357 } 358 359 static std::pair<StringRef, unsigned> 360 getPassNameAndInstanceNum(StringRef PassName) { 361 StringRef Name, InstanceNumStr; 362 std::tie(Name, InstanceNumStr) = PassName.split(','); 363 364 unsigned InstanceNum = 0; 365 if (!InstanceNumStr.empty() && InstanceNumStr.getAsInteger(10, InstanceNum)) 366 report_fatal_error("invalid pass instance specifier " + PassName); 367 368 return std::make_pair(Name, InstanceNum); 369 } 370 371 void TargetPassConfig::setStartStopPasses() { 372 StringRef StartBeforeName; 373 std::tie(StartBeforeName, StartBeforeInstanceNum) = 374 getPassNameAndInstanceNum(StartBeforeOpt); 375 376 StringRef StartAfterName; 377 std::tie(StartAfterName, StartAfterInstanceNum) = 378 getPassNameAndInstanceNum(StartAfterOpt); 379 380 StringRef StopBeforeName; 381 std::tie(StopBeforeName, StopBeforeInstanceNum) 382 = getPassNameAndInstanceNum(StopBeforeOpt); 383 384 StringRef StopAfterName; 385 std::tie(StopAfterName, StopAfterInstanceNum) 386 = getPassNameAndInstanceNum(StopAfterOpt); 387 388 StartBefore = getPassIDFromName(StartBeforeName); 389 StartAfter = getPassIDFromName(StartAfterName); 390 StopBefore = getPassIDFromName(StopBeforeName); 391 StopAfter = getPassIDFromName(StopAfterName); 392 if (StartBefore && StartAfter) 393 report_fatal_error(Twine(StartBeforeOptName) + Twine(" and ") + 394 Twine(StartAfterOptName) + Twine(" specified!")); 395 if (StopBefore && StopAfter) 396 report_fatal_error(Twine(StopBeforeOptName) + Twine(" and ") + 397 Twine(StopAfterOptName) + Twine(" specified!")); 398 Started = (StartAfter == nullptr) && (StartBefore == nullptr); 399 } 400 401 // Out of line constructor provides default values for pass options and 402 // registers all common codegen passes. 403 TargetPassConfig::TargetPassConfig(LLVMTargetMachine &TM, PassManagerBase &pm) 404 : ImmutablePass(ID), PM(&pm), TM(&TM) { 405 Impl = new PassConfigImpl(); 406 407 // Register all target independent codegen passes to activate their PassIDs, 408 // including this pass itself. 409 initializeCodeGen(*PassRegistry::getPassRegistry()); 410 411 // Also register alias analysis passes required by codegen passes. 412 initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry()); 413 initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry()); 414 415 if (EnableIPRA.getNumOccurrences()) 416 TM.Options.EnableIPRA = EnableIPRA; 417 else { 418 // If not explicitly specified, use target default. 419 TM.Options.EnableIPRA |= TM.useIPRA(); 420 } 421 422 if (TM.Options.EnableIPRA) 423 setRequiresCodeGenSCCOrder(); 424 425 if (EnableGlobalISelAbort.getNumOccurrences()) 426 TM.Options.GlobalISelAbort = EnableGlobalISelAbort; 427 428 setStartStopPasses(); 429 } 430 431 CodeGenOpt::Level TargetPassConfig::getOptLevel() const { 432 return TM->getOptLevel(); 433 } 434 435 /// Insert InsertedPassID pass after TargetPassID. 436 void TargetPassConfig::insertPass(AnalysisID TargetPassID, 437 IdentifyingPassPtr InsertedPassID, 438 bool VerifyAfter) { 439 assert(((!InsertedPassID.isInstance() && 440 TargetPassID != InsertedPassID.getID()) || 441 (InsertedPassID.isInstance() && 442 TargetPassID != InsertedPassID.getInstance()->getPassID())) && 443 "Insert a pass after itself!"); 444 Impl->InsertedPasses.emplace_back(TargetPassID, InsertedPassID, VerifyAfter); 445 } 446 447 /// createPassConfig - Create a pass configuration object to be used by 448 /// addPassToEmitX methods for generating a pipeline of CodeGen passes. 449 /// 450 /// Targets may override this to extend TargetPassConfig. 451 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) { 452 return new TargetPassConfig(*this, PM); 453 } 454 455 TargetPassConfig::TargetPassConfig() 456 : ImmutablePass(ID) { 457 report_fatal_error("Trying to construct TargetPassConfig without a target " 458 "machine. Scheduling a CodeGen pass without a target " 459 "triple set?"); 460 } 461 462 bool TargetPassConfig::willCompleteCodeGenPipeline() { 463 return StopBeforeOpt.empty() && StopAfterOpt.empty(); 464 } 465 466 bool TargetPassConfig::hasLimitedCodeGenPipeline() { 467 return !StartBeforeOpt.empty() || !StartAfterOpt.empty() || 468 !willCompleteCodeGenPipeline(); 469 } 470 471 std::string 472 TargetPassConfig::getLimitedCodeGenPipelineReason(const char *Separator) { 473 if (!hasLimitedCodeGenPipeline()) 474 return std::string(); 475 std::string Res; 476 static cl::opt<std::string> *PassNames[] = {&StartAfterOpt, &StartBeforeOpt, 477 &StopAfterOpt, &StopBeforeOpt}; 478 static const char *OptNames[] = {StartAfterOptName, StartBeforeOptName, 479 StopAfterOptName, StopBeforeOptName}; 480 bool IsFirst = true; 481 for (int Idx = 0; Idx < 4; ++Idx) 482 if (!PassNames[Idx]->empty()) { 483 if (!IsFirst) 484 Res += Separator; 485 IsFirst = false; 486 Res += OptNames[Idx]; 487 } 488 return Res; 489 } 490 491 // Helper to verify the analysis is really immutable. 492 void TargetPassConfig::setOpt(bool &Opt, bool Val) { 493 assert(!Initialized && "PassConfig is immutable"); 494 Opt = Val; 495 } 496 497 void TargetPassConfig::substitutePass(AnalysisID StandardID, 498 IdentifyingPassPtr TargetID) { 499 Impl->TargetPasses[StandardID] = TargetID; 500 } 501 502 IdentifyingPassPtr TargetPassConfig::getPassSubstitution(AnalysisID ID) const { 503 DenseMap<AnalysisID, IdentifyingPassPtr>::const_iterator 504 I = Impl->TargetPasses.find(ID); 505 if (I == Impl->TargetPasses.end()) 506 return ID; 507 return I->second; 508 } 509 510 bool TargetPassConfig::isPassSubstitutedOrOverridden(AnalysisID ID) const { 511 IdentifyingPassPtr TargetID = getPassSubstitution(ID); 512 IdentifyingPassPtr FinalPtr = overridePass(ID, TargetID); 513 return !FinalPtr.isValid() || FinalPtr.isInstance() || 514 FinalPtr.getID() != ID; 515 } 516 517 /// Add a pass to the PassManager if that pass is supposed to be run. If the 518 /// Started/Stopped flags indicate either that the compilation should start at 519 /// a later pass or that it should stop after an earlier pass, then do not add 520 /// the pass. Finally, compare the current pass against the StartAfter 521 /// and StopAfter options and change the Started/Stopped flags accordingly. 522 void TargetPassConfig::addPass(Pass *P, bool verifyAfter) { 523 assert(!Initialized && "PassConfig is immutable"); 524 525 // Cache the Pass ID here in case the pass manager finds this pass is 526 // redundant with ones already scheduled / available, and deletes it. 527 // Fundamentally, once we add the pass to the manager, we no longer own it 528 // and shouldn't reference it. 529 AnalysisID PassID = P->getPassID(); 530 531 if (StartBefore == PassID && StartBeforeCount++ == StartBeforeInstanceNum) 532 Started = true; 533 if (StopBefore == PassID && StopBeforeCount++ == StopBeforeInstanceNum) 534 Stopped = true; 535 if (Started && !Stopped) { 536 if (AddingMachinePasses) 537 addMachinePrePasses(); 538 std::string Banner; 539 // Construct banner message before PM->add() as that may delete the pass. 540 if (AddingMachinePasses && verifyAfter) 541 Banner = std::string("After ") + std::string(P->getPassName()); 542 PM->add(P); 543 if (AddingMachinePasses) 544 addMachinePostPasses(Banner, /*AllowVerify*/ verifyAfter); 545 546 // Add the passes after the pass P if there is any. 547 for (auto IP : Impl->InsertedPasses) { 548 if (IP.TargetPassID == PassID) 549 addPass(IP.getInsertedPass(), IP.VerifyAfter); 550 } 551 } else { 552 delete P; 553 } 554 555 if (StopAfter == PassID && StopAfterCount++ == StopAfterInstanceNum) 556 Stopped = true; 557 558 if (StartAfter == PassID && StartAfterCount++ == StartAfterInstanceNum) 559 Started = true; 560 if (Stopped && !Started) 561 report_fatal_error("Cannot stop compilation after pass that is not run"); 562 } 563 564 /// Add a CodeGen pass at this point in the pipeline after checking for target 565 /// and command line overrides. 566 /// 567 /// addPass cannot return a pointer to the pass instance because is internal the 568 /// PassManager and the instance we create here may already be freed. 569 AnalysisID TargetPassConfig::addPass(AnalysisID PassID, bool verifyAfter) { 570 IdentifyingPassPtr TargetID = getPassSubstitution(PassID); 571 IdentifyingPassPtr FinalPtr = overridePass(PassID, TargetID); 572 if (!FinalPtr.isValid()) 573 return nullptr; 574 575 Pass *P; 576 if (FinalPtr.isInstance()) 577 P = FinalPtr.getInstance(); 578 else { 579 P = Pass::createPass(FinalPtr.getID()); 580 if (!P) 581 llvm_unreachable("Pass ID not registered"); 582 } 583 AnalysisID FinalID = P->getPassID(); 584 addPass(P, verifyAfter); // Ends the lifetime of P. 585 586 return FinalID; 587 } 588 589 void TargetPassConfig::printAndVerify(const std::string &Banner) { 590 addPrintPass(Banner); 591 addVerifyPass(Banner); 592 } 593 594 void TargetPassConfig::addPrintPass(const std::string &Banner) { 595 if (PrintAfterISel) 596 PM->add(createMachineFunctionPrinterPass(dbgs(), Banner)); 597 } 598 599 void TargetPassConfig::addVerifyPass(const std::string &Banner) { 600 bool Verify = VerifyMachineCode == cl::BOU_TRUE; 601 #ifdef EXPENSIVE_CHECKS 602 if (VerifyMachineCode == cl::BOU_UNSET) 603 Verify = TM->isMachineVerifierClean(); 604 #endif 605 if (Verify) 606 PM->add(createMachineVerifierPass(Banner)); 607 } 608 609 void TargetPassConfig::addDebugifyPass() { 610 PM->add(createDebugifyMachineModulePass()); 611 } 612 613 void TargetPassConfig::addStripDebugPass() { 614 PM->add(createStripDebugMachineModulePass(/*OnlyDebugified=*/true)); 615 } 616 617 void TargetPassConfig::addMachinePrePasses(bool AllowDebugify) { 618 if (AllowDebugify && DebugifyAndStripAll == cl::BOU_TRUE && DebugifyIsSafe) 619 addDebugifyPass(); 620 } 621 622 void TargetPassConfig::addMachinePostPasses(const std::string &Banner, 623 bool AllowVerify, bool AllowStrip) { 624 if (DebugifyAndStripAll == cl::BOU_TRUE && DebugifyIsSafe) 625 addStripDebugPass(); 626 if (AllowVerify) 627 addVerifyPass(Banner); 628 } 629 630 /// Add common target configurable passes that perform LLVM IR to IR transforms 631 /// following machine independent optimization. 632 void TargetPassConfig::addIRPasses() { 633 // Before running any passes, run the verifier to determine if the input 634 // coming from the front-end and/or optimizer is valid. 635 if (!DisableVerify) 636 addPass(createVerifierPass()); 637 638 if (getOptLevel() != CodeGenOpt::None) { 639 switch (UseCFLAA) { 640 case CFLAAType::Steensgaard: 641 addPass(createCFLSteensAAWrapperPass()); 642 break; 643 case CFLAAType::Andersen: 644 addPass(createCFLAndersAAWrapperPass()); 645 break; 646 case CFLAAType::Both: 647 addPass(createCFLAndersAAWrapperPass()); 648 addPass(createCFLSteensAAWrapperPass()); 649 break; 650 default: 651 break; 652 } 653 654 // Basic AliasAnalysis support. 655 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that 656 // BasicAliasAnalysis wins if they disagree. This is intended to help 657 // support "obvious" type-punning idioms. 658 addPass(createTypeBasedAAWrapperPass()); 659 addPass(createScopedNoAliasAAWrapperPass()); 660 addPass(createBasicAAWrapperPass()); 661 662 // Run loop strength reduction before anything else. 663 if (!DisableLSR) { 664 addPass(createCanonicalizeFreezeInLoopsPass()); 665 addPass(createLoopStrengthReducePass()); 666 if (PrintLSR) 667 addPass(createPrintFunctionPass(dbgs(), 668 "\n\n*** Code after LSR ***\n")); 669 } 670 671 // The MergeICmpsPass tries to create memcmp calls by grouping sequences of 672 // loads and compares. ExpandMemCmpPass then tries to expand those calls 673 // into optimally-sized loads and compares. The transforms are enabled by a 674 // target lowering hook. 675 if (!DisableMergeICmps) 676 addPass(createMergeICmpsLegacyPass()); 677 addPass(createExpandMemCmpPass()); 678 } 679 680 // Run GC lowering passes for builtin collectors 681 // TODO: add a pass insertion point here 682 addPass(createGCLoweringPass()); 683 addPass(createShadowStackGCLoweringPass()); 684 addPass(createLowerConstantIntrinsicsPass()); 685 686 // Make sure that no unreachable blocks are instruction selected. 687 addPass(createUnreachableBlockEliminationPass()); 688 689 // Prepare expensive constants for SelectionDAG. 690 if (getOptLevel() != CodeGenOpt::None && !DisableConstantHoisting) 691 addPass(createConstantHoistingPass()); 692 693 if (getOptLevel() != CodeGenOpt::None && !DisablePartialLibcallInlining) 694 addPass(createPartiallyInlineLibCallsPass()); 695 696 // Instrument function entry and exit, e.g. with calls to mcount(). 697 addPass(createPostInlineEntryExitInstrumenterPass()); 698 699 // Add scalarization of target's unsupported masked memory intrinsics pass. 700 // the unsupported intrinsic will be replaced with a chain of basic blocks, 701 // that stores/loads element one-by-one if the appropriate mask bit is set. 702 addPass(createScalarizeMaskedMemIntrinPass()); 703 704 // Expand reduction intrinsics into shuffle sequences if the target wants to. 705 addPass(createExpandReductionsPass()); 706 } 707 708 /// Turn exception handling constructs into something the code generators can 709 /// handle. 710 void TargetPassConfig::addPassesToHandleExceptions() { 711 const MCAsmInfo *MCAI = TM->getMCAsmInfo(); 712 assert(MCAI && "No MCAsmInfo"); 713 switch (MCAI->getExceptionHandlingType()) { 714 case ExceptionHandling::SjLj: 715 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both 716 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise, 717 // catch info can get misplaced when a selector ends up more than one block 718 // removed from the parent invoke(s). This could happen when a landing 719 // pad is shared by multiple invokes and is also a target of a normal 720 // edge from elsewhere. 721 addPass(createSjLjEHPreparePass(TM)); 722 LLVM_FALLTHROUGH; 723 case ExceptionHandling::DwarfCFI: 724 case ExceptionHandling::ARM: 725 addPass(createDwarfEHPass(getOptLevel())); 726 break; 727 case ExceptionHandling::WinEH: 728 // We support using both GCC-style and MSVC-style exceptions on Windows, so 729 // add both preparation passes. Each pass will only actually run if it 730 // recognizes the personality function. 731 addPass(createWinEHPass()); 732 addPass(createDwarfEHPass(getOptLevel())); 733 break; 734 case ExceptionHandling::Wasm: 735 // Wasm EH uses Windows EH instructions, but it does not need to demote PHIs 736 // on catchpads and cleanuppads because it does not outline them into 737 // funclets. Catchswitch blocks are not lowered in SelectionDAG, so we 738 // should remove PHIs there. 739 addPass(createWinEHPass(/*DemoteCatchSwitchPHIOnly=*/false)); 740 addPass(createWasmEHPass()); 741 break; 742 case ExceptionHandling::None: 743 addPass(createLowerInvokePass()); 744 745 // The lower invoke pass may create unreachable code. Remove it. 746 addPass(createUnreachableBlockEliminationPass()); 747 break; 748 } 749 } 750 751 /// Add pass to prepare the LLVM IR for code generation. This should be done 752 /// before exception handling preparation passes. 753 void TargetPassConfig::addCodeGenPrepare() { 754 if (getOptLevel() != CodeGenOpt::None && !DisableCGP) 755 addPass(createCodeGenPreparePass()); 756 addPass(createRewriteSymbolsPass()); 757 } 758 759 /// Add common passes that perform LLVM IR to IR transforms in preparation for 760 /// instruction selection. 761 void TargetPassConfig::addISelPrepare() { 762 addPreISel(); 763 764 // Force codegen to run according to the callgraph. 765 if (requiresCodeGenSCCOrder()) 766 addPass(new DummyCGSCCPass); 767 768 // Add both the safe stack and the stack protection passes: each of them will 769 // only protect functions that have corresponding attributes. 770 addPass(createSafeStackPass()); 771 addPass(createStackProtectorPass()); 772 773 if (PrintISelInput) 774 addPass(createPrintFunctionPass( 775 dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n")); 776 777 // All passes which modify the LLVM IR are now complete; run the verifier 778 // to ensure that the IR is valid. 779 if (!DisableVerify) 780 addPass(createVerifierPass()); 781 } 782 783 bool TargetPassConfig::addCoreISelPasses() { 784 // Enable FastISel with -fast-isel, but allow that to be overridden. 785 TM->setO0WantsFastISel(EnableFastISelOption != cl::BOU_FALSE); 786 787 // Determine an instruction selector. 788 enum class SelectorType { SelectionDAG, FastISel, GlobalISel }; 789 SelectorType Selector; 790 791 if (EnableFastISelOption == cl::BOU_TRUE) 792 Selector = SelectorType::FastISel; 793 else if (EnableGlobalISelOption == cl::BOU_TRUE || 794 (TM->Options.EnableGlobalISel && 795 EnableGlobalISelOption != cl::BOU_FALSE)) 796 Selector = SelectorType::GlobalISel; 797 else if (TM->getOptLevel() == CodeGenOpt::None && TM->getO0WantsFastISel()) 798 Selector = SelectorType::FastISel; 799 else 800 Selector = SelectorType::SelectionDAG; 801 802 // Set consistently TM->Options.EnableFastISel and EnableGlobalISel. 803 if (Selector == SelectorType::FastISel) { 804 TM->setFastISel(true); 805 TM->setGlobalISel(false); 806 } else if (Selector == SelectorType::GlobalISel) { 807 TM->setFastISel(false); 808 TM->setGlobalISel(true); 809 } 810 811 // FIXME: Injecting into the DAGISel pipeline seems to cause issues with 812 // analyses needing to be re-run. This can result in being unable to 813 // schedule passes (particularly with 'Function Alias Analysis 814 // Results'). It's not entirely clear why but AFAICT this seems to be 815 // due to one FunctionPassManager not being able to use analyses from a 816 // previous one. As we're injecting a ModulePass we break the usual 817 // pass manager into two. GlobalISel with the fallback path disabled 818 // and -run-pass seem to be unaffected. The majority of GlobalISel 819 // testing uses -run-pass so this probably isn't too bad. 820 SaveAndRestore<bool> SavedDebugifyIsSafe(DebugifyIsSafe); 821 if (Selector != SelectorType::GlobalISel || !isGlobalISelAbortEnabled()) 822 DebugifyIsSafe = false; 823 824 // Add instruction selector passes. 825 if (Selector == SelectorType::GlobalISel) { 826 SaveAndRestore<bool> SavedAddingMachinePasses(AddingMachinePasses, true); 827 if (addIRTranslator()) 828 return true; 829 830 addPreLegalizeMachineIR(); 831 832 if (addLegalizeMachineIR()) 833 return true; 834 835 // Before running the register bank selector, ask the target if it 836 // wants to run some passes. 837 addPreRegBankSelect(); 838 839 if (addRegBankSelect()) 840 return true; 841 842 addPreGlobalInstructionSelect(); 843 844 if (addGlobalInstructionSelect()) 845 return true; 846 847 // Pass to reset the MachineFunction if the ISel failed. 848 addPass(createResetMachineFunctionPass( 849 reportDiagnosticWhenGlobalISelFallback(), isGlobalISelAbortEnabled())); 850 851 // Provide a fallback path when we do not want to abort on 852 // not-yet-supported input. 853 if (!isGlobalISelAbortEnabled() && addInstSelector()) 854 return true; 855 856 } else if (addInstSelector()) 857 return true; 858 859 // Expand pseudo-instructions emitted by ISel. Don't run the verifier before 860 // FinalizeISel. 861 addPass(&FinalizeISelID); 862 863 // Print the instruction selected machine code... 864 printAndVerify("After Instruction Selection"); 865 866 return false; 867 } 868 869 bool TargetPassConfig::addISelPasses() { 870 if (TM->useEmulatedTLS()) 871 addPass(createLowerEmuTLSPass()); 872 873 addPass(createPreISelIntrinsicLoweringPass()); 874 PM->add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis())); 875 addIRPasses(); 876 addCodeGenPrepare(); 877 addPassesToHandleExceptions(); 878 addISelPrepare(); 879 880 return addCoreISelPasses(); 881 } 882 883 /// -regalloc=... command line option. 884 static FunctionPass *useDefaultRegisterAllocator() { return nullptr; } 885 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false, 886 RegisterPassParser<RegisterRegAlloc>> 887 RegAlloc("regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator), 888 cl::desc("Register allocator to use")); 889 890 /// Add the complete set of target-independent postISel code generator passes. 891 /// 892 /// This can be read as the standard order of major LLVM CodeGen stages. Stages 893 /// with nontrivial configuration or multiple passes are broken out below in 894 /// add%Stage routines. 895 /// 896 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The 897 /// addPre/Post methods with empty header implementations allow injecting 898 /// target-specific fixups just before or after major stages. Additionally, 899 /// targets have the flexibility to change pass order within a stage by 900 /// overriding default implementation of add%Stage routines below. Each 901 /// technique has maintainability tradeoffs because alternate pass orders are 902 /// not well supported. addPre/Post works better if the target pass is easily 903 /// tied to a common pass. But if it has subtle dependencies on multiple passes, 904 /// the target should override the stage instead. 905 /// 906 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection 907 /// before/after any target-independent pass. But it's currently overkill. 908 void TargetPassConfig::addMachinePasses() { 909 AddingMachinePasses = true; 910 911 // Add passes that optimize machine instructions in SSA form. 912 if (getOptLevel() != CodeGenOpt::None) { 913 addMachineSSAOptimization(); 914 } else { 915 // If the target requests it, assign local variables to stack slots relative 916 // to one another and simplify frame index references where possible. 917 addPass(&LocalStackSlotAllocationID); 918 } 919 920 if (TM->Options.EnableIPRA) 921 addPass(createRegUsageInfoPropPass()); 922 923 // Run pre-ra passes. 924 addPreRegAlloc(); 925 926 // Debugifying the register allocator passes seems to provoke some 927 // non-determinism that affects CodeGen and there doesn't seem to be a point 928 // where it becomes safe again so stop debugifying here. 929 DebugifyIsSafe = false; 930 931 // Run register allocation and passes that are tightly coupled with it, 932 // including phi elimination and scheduling. 933 if (getOptimizeRegAlloc()) 934 addOptimizedRegAlloc(); 935 else 936 addFastRegAlloc(); 937 938 // Run post-ra passes. 939 addPostRegAlloc(); 940 941 addPass(&FixupStatepointCallerSavedID); 942 943 // Insert prolog/epilog code. Eliminate abstract frame index references... 944 if (getOptLevel() != CodeGenOpt::None) { 945 addPass(&PostRAMachineSinkingID); 946 addPass(&ShrinkWrapID); 947 } 948 949 // Prolog/Epilog inserter needs a TargetMachine to instantiate. But only 950 // do so if it hasn't been disabled, substituted, or overridden. 951 if (!isPassSubstitutedOrOverridden(&PrologEpilogCodeInserterID)) 952 addPass(createPrologEpilogInserterPass()); 953 954 /// Add passes that optimize machine instructions after register allocation. 955 if (getOptLevel() != CodeGenOpt::None) 956 addMachineLateOptimization(); 957 958 // Expand pseudo instructions before second scheduling pass. 959 addPass(&ExpandPostRAPseudosID); 960 961 // Run pre-sched2 passes. 962 addPreSched2(); 963 964 if (EnableImplicitNullChecks) 965 addPass(&ImplicitNullChecksID); 966 967 // Second pass scheduler. 968 // Let Target optionally insert this pass by itself at some other 969 // point. 970 if (getOptLevel() != CodeGenOpt::None && 971 !TM->targetSchedulesPostRAScheduling()) { 972 if (MISchedPostRA) 973 addPass(&PostMachineSchedulerID); 974 else 975 addPass(&PostRASchedulerID); 976 } 977 978 // GC 979 if (addGCPasses()) { 980 if (PrintGCInfo) 981 addPass(createGCInfoPrinter(dbgs()), false); 982 } 983 984 // Basic block placement. 985 if (getOptLevel() != CodeGenOpt::None) 986 addBlockPlacement(); 987 988 // Insert before XRay Instrumentation. 989 addPass(&FEntryInserterID); 990 991 addPass(&XRayInstrumentationID); 992 addPass(&PatchableFunctionID); 993 994 addPreEmitPass(); 995 996 if (TM->Options.EnableIPRA) 997 // Collect register usage information and produce a register mask of 998 // clobbered registers, to be used to optimize call sites. 999 addPass(createRegUsageInfoCollector()); 1000 1001 // FIXME: Some backends are incompatible with running the verifier after 1002 // addPreEmitPass. Maybe only pass "false" here for those targets? 1003 addPass(&FuncletLayoutID, false); 1004 1005 addPass(&StackMapLivenessID, false); 1006 addPass(&LiveDebugValuesID, false); 1007 1008 if (TM->Options.EnableMachineOutliner && getOptLevel() != CodeGenOpt::None && 1009 EnableMachineOutliner != NeverOutline) { 1010 bool RunOnAllFunctions = (EnableMachineOutliner == AlwaysOutline); 1011 bool AddOutliner = RunOnAllFunctions || 1012 TM->Options.SupportsDefaultOutlining; 1013 if (AddOutliner) 1014 addPass(createMachineOutlinerPass(RunOnAllFunctions)); 1015 } 1016 1017 if (TM->getBBSectionsType() != llvm::BasicBlockSection::None) 1018 addPass(llvm::createBasicBlockSectionsPass(TM->getBBSectionsFuncListBuf())); 1019 1020 // Add passes that directly emit MI after all other MI passes. 1021 addPreEmitPass2(); 1022 1023 AddingMachinePasses = false; 1024 } 1025 1026 /// Add passes that optimize machine instructions in SSA form. 1027 void TargetPassConfig::addMachineSSAOptimization() { 1028 // Pre-ra tail duplication. 1029 addPass(&EarlyTailDuplicateID); 1030 1031 // Optimize PHIs before DCE: removing dead PHI cycles may make more 1032 // instructions dead. 1033 addPass(&OptimizePHIsID); 1034 1035 // This pass merges large allocas. StackSlotColoring is a different pass 1036 // which merges spill slots. 1037 addPass(&StackColoringID); 1038 1039 // If the target requests it, assign local variables to stack slots relative 1040 // to one another and simplify frame index references where possible. 1041 addPass(&LocalStackSlotAllocationID); 1042 1043 // With optimization, dead code should already be eliminated. However 1044 // there is one known exception: lowered code for arguments that are only 1045 // used by tail calls, where the tail calls reuse the incoming stack 1046 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll). 1047 addPass(&DeadMachineInstructionElimID); 1048 1049 // Allow targets to insert passes that improve instruction level parallelism, 1050 // like if-conversion. Such passes will typically need dominator trees and 1051 // loop info, just like LICM and CSE below. 1052 addILPOpts(); 1053 1054 addPass(&EarlyMachineLICMID); 1055 addPass(&MachineCSEID); 1056 1057 addPass(&MachineSinkingID); 1058 1059 addPass(&PeepholeOptimizerID); 1060 // Clean-up the dead code that may have been generated by peephole 1061 // rewriting. 1062 addPass(&DeadMachineInstructionElimID); 1063 } 1064 1065 //===---------------------------------------------------------------------===// 1066 /// Register Allocation Pass Configuration 1067 //===---------------------------------------------------------------------===// 1068 1069 bool TargetPassConfig::getOptimizeRegAlloc() const { 1070 switch (OptimizeRegAlloc) { 1071 case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None; 1072 case cl::BOU_TRUE: return true; 1073 case cl::BOU_FALSE: return false; 1074 } 1075 llvm_unreachable("Invalid optimize-regalloc state"); 1076 } 1077 1078 /// A dummy default pass factory indicates whether the register allocator is 1079 /// overridden on the command line. 1080 static llvm::once_flag InitializeDefaultRegisterAllocatorFlag; 1081 1082 static RegisterRegAlloc 1083 defaultRegAlloc("default", 1084 "pick register allocator based on -O option", 1085 useDefaultRegisterAllocator); 1086 1087 static void initializeDefaultRegisterAllocatorOnce() { 1088 if (!RegisterRegAlloc::getDefault()) 1089 RegisterRegAlloc::setDefault(RegAlloc); 1090 } 1091 1092 /// Instantiate the default register allocator pass for this target for either 1093 /// the optimized or unoptimized allocation path. This will be added to the pass 1094 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc 1095 /// in the optimized case. 1096 /// 1097 /// A target that uses the standard regalloc pass order for fast or optimized 1098 /// allocation may still override this for per-target regalloc 1099 /// selection. But -regalloc=... always takes precedence. 1100 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) { 1101 if (Optimized) 1102 return createGreedyRegisterAllocator(); 1103 else 1104 return createFastRegisterAllocator(); 1105 } 1106 1107 /// Find and instantiate the register allocation pass requested by this target 1108 /// at the current optimization level. Different register allocators are 1109 /// defined as separate passes because they may require different analysis. 1110 /// 1111 /// This helper ensures that the regalloc= option is always available, 1112 /// even for targets that override the default allocator. 1113 /// 1114 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs, 1115 /// this can be folded into addPass. 1116 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) { 1117 // Initialize the global default. 1118 llvm::call_once(InitializeDefaultRegisterAllocatorFlag, 1119 initializeDefaultRegisterAllocatorOnce); 1120 1121 RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault(); 1122 if (Ctor != useDefaultRegisterAllocator) 1123 return Ctor(); 1124 1125 // With no -regalloc= override, ask the target for a regalloc pass. 1126 return createTargetRegisterAllocator(Optimized); 1127 } 1128 1129 bool TargetPassConfig::addRegAssignmentFast() { 1130 if (RegAlloc != &useDefaultRegisterAllocator && 1131 RegAlloc != &createFastRegisterAllocator) 1132 report_fatal_error("Must use fast (default) register allocator for unoptimized regalloc."); 1133 1134 addPass(createRegAllocPass(false)); 1135 return true; 1136 } 1137 1138 bool TargetPassConfig::addRegAssignmentOptimized() { 1139 // Add the selected register allocation pass. 1140 addPass(createRegAllocPass(true)); 1141 1142 // Allow targets to change the register assignments before rewriting. 1143 addPreRewrite(); 1144 1145 // Finally rewrite virtual registers. 1146 addPass(&VirtRegRewriterID); 1147 1148 // Perform stack slot coloring and post-ra machine LICM. 1149 // 1150 // FIXME: Re-enable coloring with register when it's capable of adding 1151 // kill markers. 1152 addPass(&StackSlotColoringID); 1153 1154 return true; 1155 } 1156 1157 /// Return true if the default global register allocator is in use and 1158 /// has not be overriden on the command line with '-regalloc=...' 1159 bool TargetPassConfig::usingDefaultRegAlloc() const { 1160 return RegAlloc.getNumOccurrences() == 0; 1161 } 1162 1163 /// Add the minimum set of target-independent passes that are required for 1164 /// register allocation. No coalescing or scheduling. 1165 void TargetPassConfig::addFastRegAlloc() { 1166 addPass(&PHIEliminationID, false); 1167 addPass(&TwoAddressInstructionPassID, false); 1168 1169 addRegAssignmentFast(); 1170 } 1171 1172 /// Add standard target-independent passes that are tightly coupled with 1173 /// optimized register allocation, including coalescing, machine instruction 1174 /// scheduling, and register allocation itself. 1175 void TargetPassConfig::addOptimizedRegAlloc() { 1176 addPass(&DetectDeadLanesID, false); 1177 1178 addPass(&ProcessImplicitDefsID, false); 1179 1180 // LiveVariables currently requires pure SSA form. 1181 // 1182 // FIXME: Once TwoAddressInstruction pass no longer uses kill flags, 1183 // LiveVariables can be removed completely, and LiveIntervals can be directly 1184 // computed. (We still either need to regenerate kill flags after regalloc, or 1185 // preferably fix the scavenger to not depend on them). 1186 // FIXME: UnreachableMachineBlockElim is a dependant pass of LiveVariables. 1187 // When LiveVariables is removed this has to be removed/moved either. 1188 // Explicit addition of UnreachableMachineBlockElim allows stopping before or 1189 // after it with -stop-before/-stop-after. 1190 addPass(&UnreachableMachineBlockElimID, false); 1191 addPass(&LiveVariablesID, false); 1192 1193 // Edge splitting is smarter with machine loop info. 1194 addPass(&MachineLoopInfoID, false); 1195 addPass(&PHIEliminationID, false); 1196 1197 // Eventually, we want to run LiveIntervals before PHI elimination. 1198 if (EarlyLiveIntervals) 1199 addPass(&LiveIntervalsID, false); 1200 1201 addPass(&TwoAddressInstructionPassID, false); 1202 addPass(&RegisterCoalescerID); 1203 1204 // The machine scheduler may accidentally create disconnected components 1205 // when moving subregister definitions around, avoid this by splitting them to 1206 // separate vregs before. Splitting can also improve reg. allocation quality. 1207 addPass(&RenameIndependentSubregsID); 1208 1209 // PreRA instruction scheduling. 1210 addPass(&MachineSchedulerID); 1211 1212 if (addRegAssignmentOptimized()) { 1213 // Allow targets to expand pseudo instructions depending on the choice of 1214 // registers before MachineCopyPropagation. 1215 addPostRewrite(); 1216 1217 // Copy propagate to forward register uses and try to eliminate COPYs that 1218 // were not coalesced. 1219 addPass(&MachineCopyPropagationID); 1220 1221 // Run post-ra machine LICM to hoist reloads / remats. 1222 // 1223 // FIXME: can this move into MachineLateOptimization? 1224 addPass(&MachineLICMID); 1225 } 1226 } 1227 1228 //===---------------------------------------------------------------------===// 1229 /// Post RegAlloc Pass Configuration 1230 //===---------------------------------------------------------------------===// 1231 1232 /// Add passes that optimize machine instructions after register allocation. 1233 void TargetPassConfig::addMachineLateOptimization() { 1234 // Branch folding must be run after regalloc and prolog/epilog insertion. 1235 addPass(&BranchFolderPassID); 1236 1237 // Tail duplication. 1238 // Note that duplicating tail just increases code size and degrades 1239 // performance for targets that require Structured Control Flow. 1240 // In addition it can also make CFG irreducible. Thus we disable it. 1241 if (!TM->requiresStructuredCFG()) 1242 addPass(&TailDuplicateID); 1243 1244 // Copy propagation. 1245 addPass(&MachineCopyPropagationID); 1246 } 1247 1248 /// Add standard GC passes. 1249 bool TargetPassConfig::addGCPasses() { 1250 addPass(&GCMachineCodeAnalysisID, false); 1251 return true; 1252 } 1253 1254 /// Add standard basic block placement passes. 1255 void TargetPassConfig::addBlockPlacement() { 1256 if (addPass(&MachineBlockPlacementID)) { 1257 // Run a separate pass to collect block placement statistics. 1258 if (EnableBlockPlacementStats) 1259 addPass(&MachineBlockPlacementStatsID); 1260 } 1261 } 1262 1263 //===---------------------------------------------------------------------===// 1264 /// GlobalISel Configuration 1265 //===---------------------------------------------------------------------===// 1266 bool TargetPassConfig::isGlobalISelAbortEnabled() const { 1267 return TM->Options.GlobalISelAbort == GlobalISelAbortMode::Enable; 1268 } 1269 1270 bool TargetPassConfig::reportDiagnosticWhenGlobalISelFallback() const { 1271 return TM->Options.GlobalISelAbort == GlobalISelAbortMode::DisableWithDiag; 1272 } 1273 1274 bool TargetPassConfig::isGISelCSEEnabled() const { 1275 return true; 1276 } 1277 1278 std::unique_ptr<CSEConfigBase> TargetPassConfig::getCSEConfig() const { 1279 return std::make_unique<CSEConfigBase>(); 1280 } 1281