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