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