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