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 == &TailDuplicateLegacyID) 294 return applyDisable(TargetID, DisableTailDuplicate); 295 296 if (StandardID == &EarlyTailDuplicateLegacyID) 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 == &EarlyIfConverterLegacyID) 309 return applyDisable(TargetID, DisableEarlyIfConversion); 310 311 if (StandardID == &EarlyMachineLICMID) 312 return applyDisable(TargetID, DisableMachineLICM); 313 314 if (StandardID == &MachineCSELegacyID) 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, EarlyIfConverterLegacyPass) 525 DISABLE_PASS(DisableEarlyTailDup, EarlyTailDuplicatePass) 526 DISABLE_PASS(DisableMachineCSE, MachineCSELegacyPass) 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 (EnableLoopTermFold) 832 addPass(createLoopTermFoldPass()); 833 if (PrintLSR) 834 addPass(createPrintFunctionPass(dbgs(), 835 "\n\n*** Code after LSR ***\n")); 836 } 837 838 // The MergeICmpsPass tries to create memcmp calls by grouping sequences of 839 // loads and compares. ExpandMemCmpPass then tries to expand those calls 840 // into optimally-sized loads and compares. The transforms are enabled by a 841 // target lowering hook. 842 if (!DisableMergeICmps) 843 addPass(createMergeICmpsLegacyPass()); 844 addPass(createExpandMemCmpLegacyPass()); 845 } 846 847 // Run GC lowering passes for builtin collectors 848 // TODO: add a pass insertion point here 849 addPass(&GCLoweringID); 850 addPass(&ShadowStackGCLoweringID); 851 852 // For MachO, lower @llvm.global_dtors into @llvm.global_ctors with 853 // __cxa_atexit() calls to avoid emitting the deprecated __mod_term_func. 854 if (TM->getTargetTriple().isOSBinFormatMachO() && 855 !DisableAtExitBasedGlobalDtorLowering) 856 addPass(createLowerGlobalDtorsLegacyPass()); 857 858 // Make sure that no unreachable blocks are instruction selected. 859 addPass(createUnreachableBlockEliminationPass()); 860 861 // Prepare expensive constants for SelectionDAG. 862 if (getOptLevel() != CodeGenOptLevel::None && !DisableConstantHoisting) 863 addPass(createConstantHoistingPass()); 864 865 if (getOptLevel() != CodeGenOptLevel::None && !DisableReplaceWithVecLib) 866 addPass(createReplaceWithVeclibLegacyPass()); 867 868 if (getOptLevel() != CodeGenOptLevel::None && !DisablePartialLibcallInlining) 869 addPass(createPartiallyInlineLibCallsPass()); 870 871 // Instrument function entry after all inlining. 872 addPass(createPostInlineEntryExitInstrumenterPass()); 873 874 // Add scalarization of target's unsupported masked memory intrinsics pass. 875 // the unsupported intrinsic will be replaced with a chain of basic blocks, 876 // that stores/loads element one-by-one if the appropriate mask bit is set. 877 addPass(createScalarizeMaskedMemIntrinLegacyPass()); 878 879 // Expand reduction intrinsics into shuffle sequences if the target wants to. 880 // Allow disabling it for testing purposes. 881 if (!DisableExpandReductions) 882 addPass(createExpandReductionsPass()); 883 884 if (getOptLevel() != CodeGenOptLevel::None) 885 addPass(createTLSVariableHoistPass()); 886 887 // Convert conditional moves to conditional jumps when profitable. 888 if (getOptLevel() != CodeGenOptLevel::None && !DisableSelectOptimize) 889 addPass(createSelectOptimizePass()); 890 } 891 892 /// Turn exception handling constructs into something the code generators can 893 /// handle. 894 void TargetPassConfig::addPassesToHandleExceptions() { 895 const MCAsmInfo *MCAI = TM->getMCAsmInfo(); 896 assert(MCAI && "No MCAsmInfo"); 897 switch (MCAI->getExceptionHandlingType()) { 898 case ExceptionHandling::SjLj: 899 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both 900 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise, 901 // catch info can get misplaced when a selector ends up more than one block 902 // removed from the parent invoke(s). This could happen when a landing 903 // pad is shared by multiple invokes and is also a target of a normal 904 // edge from elsewhere. 905 addPass(createSjLjEHPreparePass(TM)); 906 [[fallthrough]]; 907 case ExceptionHandling::DwarfCFI: 908 case ExceptionHandling::ARM: 909 case ExceptionHandling::AIX: 910 case ExceptionHandling::ZOS: 911 addPass(createDwarfEHPass(getOptLevel())); 912 break; 913 case ExceptionHandling::WinEH: 914 // We support using both GCC-style and MSVC-style exceptions on Windows, so 915 // add both preparation passes. Each pass will only actually run if it 916 // recognizes the personality function. 917 addPass(createWinEHPass()); 918 addPass(createDwarfEHPass(getOptLevel())); 919 break; 920 case ExceptionHandling::Wasm: 921 // Wasm EH uses Windows EH instructions, but it does not need to demote PHIs 922 // on catchpads and cleanuppads because it does not outline them into 923 // funclets. Catchswitch blocks are not lowered in SelectionDAG, so we 924 // should remove PHIs there. 925 addPass(createWinEHPass(/*DemoteCatchSwitchPHIOnly=*/true)); 926 addPass(createWasmEHPass()); 927 break; 928 case ExceptionHandling::None: 929 addPass(createLowerInvokePass()); 930 931 // The lower invoke pass may create unreachable code. Remove it. 932 addPass(createUnreachableBlockEliminationPass()); 933 break; 934 } 935 } 936 937 /// Add pass to prepare the LLVM IR for code generation. This should be done 938 /// before exception handling preparation passes. 939 void TargetPassConfig::addCodeGenPrepare() { 940 if (getOptLevel() != CodeGenOptLevel::None && !DisableCGP) 941 addPass(createCodeGenPrepareLegacyPass()); 942 } 943 944 /// Add common passes that perform LLVM IR to IR transforms in preparation for 945 /// instruction selection. 946 void TargetPassConfig::addISelPrepare() { 947 addPreISel(); 948 949 // Force codegen to run according to the callgraph. 950 if (requiresCodeGenSCCOrder()) 951 addPass(new DummyCGSCCPass); 952 953 if (getOptLevel() != CodeGenOptLevel::None) 954 addPass(createObjCARCContractPass()); 955 956 addPass(createCallBrPass()); 957 958 // Add both the safe stack and the stack protection passes: each of them will 959 // only protect functions that have corresponding attributes. 960 addPass(createSafeStackPass()); 961 addPass(createStackProtectorPass()); 962 963 if (PrintISelInput) 964 addPass(createPrintFunctionPass( 965 dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n")); 966 967 // All passes which modify the LLVM IR are now complete; run the verifier 968 // to ensure that the IR is valid. 969 if (!DisableVerify) 970 addPass(createVerifierPass()); 971 } 972 973 bool TargetPassConfig::addCoreISelPasses() { 974 // Enable FastISel with -fast-isel, but allow that to be overridden. 975 TM->setO0WantsFastISel(EnableFastISelOption != cl::BOU_FALSE); 976 977 // Determine an instruction selector. 978 enum class SelectorType { SelectionDAG, FastISel, GlobalISel }; 979 SelectorType Selector; 980 981 if (EnableFastISelOption == cl::BOU_TRUE) 982 Selector = SelectorType::FastISel; 983 else if (EnableGlobalISelOption == cl::BOU_TRUE || 984 (TM->Options.EnableGlobalISel && 985 EnableGlobalISelOption != cl::BOU_FALSE)) 986 Selector = SelectorType::GlobalISel; 987 else if (TM->getOptLevel() == CodeGenOptLevel::None && 988 TM->getO0WantsFastISel()) 989 Selector = SelectorType::FastISel; 990 else 991 Selector = SelectorType::SelectionDAG; 992 993 // Set consistently TM->Options.EnableFastISel and EnableGlobalISel. 994 if (Selector == SelectorType::FastISel) { 995 TM->setFastISel(true); 996 TM->setGlobalISel(false); 997 } else if (Selector == SelectorType::GlobalISel) { 998 TM->setFastISel(false); 999 TM->setGlobalISel(true); 1000 } 1001 1002 // FIXME: Injecting into the DAGISel pipeline seems to cause issues with 1003 // analyses needing to be re-run. This can result in being unable to 1004 // schedule passes (particularly with 'Function Alias Analysis 1005 // Results'). It's not entirely clear why but AFAICT this seems to be 1006 // due to one FunctionPassManager not being able to use analyses from a 1007 // previous one. As we're injecting a ModulePass we break the usual 1008 // pass manager into two. GlobalISel with the fallback path disabled 1009 // and -run-pass seem to be unaffected. The majority of GlobalISel 1010 // testing uses -run-pass so this probably isn't too bad. 1011 SaveAndRestore SavedDebugifyIsSafe(DebugifyIsSafe); 1012 if (Selector != SelectorType::GlobalISel || !isGlobalISelAbortEnabled()) 1013 DebugifyIsSafe = false; 1014 1015 // Add instruction selector passes. 1016 if (Selector == SelectorType::GlobalISel) { 1017 SaveAndRestore SavedAddingMachinePasses(AddingMachinePasses, true); 1018 if (addIRTranslator()) 1019 return true; 1020 1021 addPreLegalizeMachineIR(); 1022 1023 if (addLegalizeMachineIR()) 1024 return true; 1025 1026 // Before running the register bank selector, ask the target if it 1027 // wants to run some passes. 1028 addPreRegBankSelect(); 1029 1030 if (addRegBankSelect()) 1031 return true; 1032 1033 addPreGlobalInstructionSelect(); 1034 1035 if (addGlobalInstructionSelect()) 1036 return true; 1037 1038 // Pass to reset the MachineFunction if the ISel failed. 1039 addPass(createResetMachineFunctionPass( 1040 reportDiagnosticWhenGlobalISelFallback(), isGlobalISelAbortEnabled())); 1041 1042 // Provide a fallback path when we do not want to abort on 1043 // not-yet-supported input. 1044 if (!isGlobalISelAbortEnabled() && addInstSelector()) 1045 return true; 1046 1047 } else if (addInstSelector()) 1048 return true; 1049 1050 // Expand pseudo-instructions emitted by ISel. Don't run the verifier before 1051 // FinalizeISel. 1052 addPass(&FinalizeISelID); 1053 1054 // Print the instruction selected machine code... 1055 printAndVerify("After Instruction Selection"); 1056 1057 return false; 1058 } 1059 1060 bool TargetPassConfig::addISelPasses() { 1061 if (TM->useEmulatedTLS()) 1062 addPass(createLowerEmuTLSPass()); 1063 1064 PM->add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis())); 1065 addPass(createPreISelIntrinsicLoweringPass()); 1066 addPass(createExpandLargeDivRemPass()); 1067 addPass(createExpandLargeFpConvertPass()); 1068 addIRPasses(); 1069 addCodeGenPrepare(); 1070 addPassesToHandleExceptions(); 1071 addISelPrepare(); 1072 1073 return addCoreISelPasses(); 1074 } 1075 1076 /// -regalloc=... command line option. 1077 static FunctionPass *useDefaultRegisterAllocator() { return nullptr; } 1078 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false, 1079 RegisterPassParser<RegisterRegAlloc>> 1080 RegAlloc("regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator), 1081 cl::desc("Register allocator to use")); 1082 1083 /// Add the complete set of target-independent postISel code generator passes. 1084 /// 1085 /// This can be read as the standard order of major LLVM CodeGen stages. Stages 1086 /// with nontrivial configuration or multiple passes are broken out below in 1087 /// add%Stage routines. 1088 /// 1089 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The 1090 /// addPre/Post methods with empty header implementations allow injecting 1091 /// target-specific fixups just before or after major stages. Additionally, 1092 /// targets have the flexibility to change pass order within a stage by 1093 /// overriding default implementation of add%Stage routines below. Each 1094 /// technique has maintainability tradeoffs because alternate pass orders are 1095 /// not well supported. addPre/Post works better if the target pass is easily 1096 /// tied to a common pass. But if it has subtle dependencies on multiple passes, 1097 /// the target should override the stage instead. 1098 /// 1099 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection 1100 /// before/after any target-independent pass. But it's currently overkill. 1101 void TargetPassConfig::addMachinePasses() { 1102 AddingMachinePasses = true; 1103 1104 // Add passes that optimize machine instructions in SSA form. 1105 if (getOptLevel() != CodeGenOptLevel::None) { 1106 addMachineSSAOptimization(); 1107 } else { 1108 // If the target requests it, assign local variables to stack slots relative 1109 // to one another and simplify frame index references where possible. 1110 addPass(&LocalStackSlotAllocationID); 1111 } 1112 1113 if (TM->Options.EnableIPRA) 1114 addPass(createRegUsageInfoPropPass()); 1115 1116 // Run pre-ra passes. 1117 addPreRegAlloc(); 1118 1119 // Debugifying the register allocator passes seems to provoke some 1120 // non-determinism that affects CodeGen and there doesn't seem to be a point 1121 // where it becomes safe again so stop debugifying here. 1122 DebugifyIsSafe = false; 1123 1124 // Add a FSDiscriminator pass right before RA, so that we could get 1125 // more precise SampleFDO profile for RA. 1126 if (EnableFSDiscriminator) { 1127 addPass(createMIRAddFSDiscriminatorsPass( 1128 sampleprof::FSDiscriminatorPass::Pass1)); 1129 const std::string ProfileFile = getFSProfileFile(TM); 1130 if (!ProfileFile.empty() && !DisableRAFSProfileLoader) 1131 addPass(createMIRProfileLoaderPass(ProfileFile, getFSRemappingFile(TM), 1132 sampleprof::FSDiscriminatorPass::Pass1, 1133 nullptr)); 1134 } 1135 1136 // Run register allocation and passes that are tightly coupled with it, 1137 // including phi elimination and scheduling. 1138 if (getOptimizeRegAlloc()) 1139 addOptimizedRegAlloc(); 1140 else 1141 addFastRegAlloc(); 1142 1143 // Run post-ra passes. 1144 addPostRegAlloc(); 1145 1146 addPass(&RemoveRedundantDebugValuesID); 1147 1148 addPass(&FixupStatepointCallerSavedID); 1149 1150 // Insert prolog/epilog code. Eliminate abstract frame index references... 1151 if (getOptLevel() != CodeGenOptLevel::None) { 1152 addPass(&PostRAMachineSinkingID); 1153 addPass(&ShrinkWrapID); 1154 } 1155 1156 // Prolog/Epilog inserter needs a TargetMachine to instantiate. But only 1157 // do so if it hasn't been disabled, substituted, or overridden. 1158 if (!isPassSubstitutedOrOverridden(&PrologEpilogCodeInserterID)) 1159 addPass(createPrologEpilogInserterPass()); 1160 1161 /// Add passes that optimize machine instructions after register allocation. 1162 if (getOptLevel() != CodeGenOptLevel::None) 1163 addMachineLateOptimization(); 1164 1165 // Expand pseudo instructions before second scheduling pass. 1166 addPass(&ExpandPostRAPseudosID); 1167 1168 // Run pre-sched2 passes. 1169 addPreSched2(); 1170 1171 if (EnableImplicitNullChecks) 1172 addPass(&ImplicitNullChecksID); 1173 1174 // Second pass scheduler. 1175 // Let Target optionally insert this pass by itself at some other 1176 // point. 1177 if (getOptLevel() != CodeGenOptLevel::None && 1178 !TM->targetSchedulesPostRAScheduling()) { 1179 if (MISchedPostRA) 1180 addPass(&PostMachineSchedulerID); 1181 else 1182 addPass(&PostRASchedulerID); 1183 } 1184 1185 // GC 1186 addGCPasses(); 1187 1188 // Basic block placement. 1189 if (getOptLevel() != CodeGenOptLevel::None) 1190 addBlockPlacement(); 1191 1192 // Insert before XRay Instrumentation. 1193 addPass(&FEntryInserterID); 1194 1195 addPass(&XRayInstrumentationID); 1196 addPass(&PatchableFunctionID); 1197 1198 addPreEmitPass(); 1199 1200 if (TM->Options.EnableIPRA) 1201 // Collect register usage information and produce a register mask of 1202 // clobbered registers, to be used to optimize call sites. 1203 addPass(createRegUsageInfoCollector()); 1204 1205 // FIXME: Some backends are incompatible with running the verifier after 1206 // addPreEmitPass. Maybe only pass "false" here for those targets? 1207 addPass(&FuncletLayoutID); 1208 1209 addPass(&RemoveLoadsIntoFakeUsesID); 1210 addPass(&StackMapLivenessID); 1211 addPass(&LiveDebugValuesID); 1212 addPass(&MachineSanitizerBinaryMetadataID); 1213 1214 if (TM->Options.EnableMachineOutliner && 1215 getOptLevel() != CodeGenOptLevel::None && 1216 EnableMachineOutliner != RunOutliner::NeverOutline) { 1217 bool RunOnAllFunctions = 1218 (EnableMachineOutliner == RunOutliner::AlwaysOutline); 1219 bool AddOutliner = 1220 RunOnAllFunctions || TM->Options.SupportsDefaultOutlining; 1221 if (AddOutliner) 1222 addPass(createMachineOutlinerPass(RunOnAllFunctions)); 1223 } 1224 1225 if (GCEmptyBlocks) 1226 addPass(llvm::createGCEmptyBasicBlocksPass()); 1227 1228 if (EnableFSDiscriminator) 1229 addPass(createMIRAddFSDiscriminatorsPass( 1230 sampleprof::FSDiscriminatorPass::PassLast)); 1231 1232 bool NeedsBBSections = 1233 TM->getBBSectionsType() != llvm::BasicBlockSection::None; 1234 // Machine function splitter uses the basic block sections feature. Both 1235 // cannot be enabled at the same time. We do not apply machine function 1236 // splitter if -basic-block-sections is requested. 1237 if (!NeedsBBSections && (TM->Options.EnableMachineFunctionSplitter || 1238 EnableMachineFunctionSplitter)) { 1239 const std::string ProfileFile = getFSProfileFile(TM); 1240 if (!ProfileFile.empty()) { 1241 if (EnableFSDiscriminator) { 1242 addPass(createMIRProfileLoaderPass( 1243 ProfileFile, getFSRemappingFile(TM), 1244 sampleprof::FSDiscriminatorPass::PassLast, nullptr)); 1245 } else { 1246 // Sample profile is given, but FSDiscriminator is not 1247 // enabled, this may result in performance regression. 1248 WithColor::warning() 1249 << "Using AutoFDO without FSDiscriminator for MFS may regress " 1250 "performance.\n"; 1251 } 1252 } 1253 addPass(createMachineFunctionSplitterPass()); 1254 } 1255 // We run the BasicBlockSections pass if either we need BB sections or BB 1256 // address map (or both). 1257 if (NeedsBBSections || TM->Options.BBAddrMap) { 1258 if (TM->getBBSectionsType() == llvm::BasicBlockSection::List) { 1259 addPass(llvm::createBasicBlockSectionsProfileReaderWrapperPass( 1260 TM->getBBSectionsFuncListBuf())); 1261 addPass(llvm::createBasicBlockPathCloningPass()); 1262 } 1263 addPass(llvm::createBasicBlockSectionsPass()); 1264 } 1265 1266 addPostBBSections(); 1267 1268 if (!DisableCFIFixup && TM->Options.EnableCFIFixup) 1269 addPass(createCFIFixup()); 1270 1271 PM->add(createStackFrameLayoutAnalysisPass()); 1272 1273 // Add passes that directly emit MI after all other MI passes. 1274 addPreEmitPass2(); 1275 1276 AddingMachinePasses = false; 1277 } 1278 1279 /// Add passes that optimize machine instructions in SSA form. 1280 void TargetPassConfig::addMachineSSAOptimization() { 1281 // Pre-ra tail duplication. 1282 addPass(&EarlyTailDuplicateLegacyID); 1283 1284 // Optimize PHIs before DCE: removing dead PHI cycles may make more 1285 // instructions dead. 1286 addPass(&OptimizePHIsLegacyID); 1287 1288 // This pass merges large allocas. StackSlotColoring is a different pass 1289 // which merges spill slots. 1290 addPass(&StackColoringLegacyID); 1291 1292 // If the target requests it, assign local variables to stack slots relative 1293 // to one another and simplify frame index references where possible. 1294 addPass(&LocalStackSlotAllocationID); 1295 1296 // With optimization, dead code should already be eliminated. However 1297 // there is one known exception: lowered code for arguments that are only 1298 // used by tail calls, where the tail calls reuse the incoming stack 1299 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll). 1300 addPass(&DeadMachineInstructionElimID); 1301 1302 // Allow targets to insert passes that improve instruction level parallelism, 1303 // like if-conversion. Such passes will typically need dominator trees and 1304 // loop info, just like LICM and CSE below. 1305 addILPOpts(); 1306 1307 addPass(&EarlyMachineLICMID); 1308 addPass(&MachineCSELegacyID); 1309 1310 addPass(&MachineSinkingID); 1311 1312 addPass(&PeepholeOptimizerID); 1313 // Clean-up the dead code that may have been generated by peephole 1314 // rewriting. 1315 addPass(&DeadMachineInstructionElimID); 1316 } 1317 1318 //===---------------------------------------------------------------------===// 1319 /// Register Allocation Pass Configuration 1320 //===---------------------------------------------------------------------===// 1321 1322 bool TargetPassConfig::getOptimizeRegAlloc() const { 1323 switch (OptimizeRegAlloc) { 1324 case cl::BOU_UNSET: 1325 return getOptLevel() != CodeGenOptLevel::None; 1326 case cl::BOU_TRUE: return true; 1327 case cl::BOU_FALSE: return false; 1328 } 1329 llvm_unreachable("Invalid optimize-regalloc state"); 1330 } 1331 1332 /// A dummy default pass factory indicates whether the register allocator is 1333 /// overridden on the command line. 1334 static llvm::once_flag InitializeDefaultRegisterAllocatorFlag; 1335 1336 static RegisterRegAlloc 1337 defaultRegAlloc("default", 1338 "pick register allocator based on -O option", 1339 useDefaultRegisterAllocator); 1340 1341 static void initializeDefaultRegisterAllocatorOnce() { 1342 if (!RegisterRegAlloc::getDefault()) 1343 RegisterRegAlloc::setDefault(RegAlloc); 1344 } 1345 1346 /// Instantiate the default register allocator pass for this target for either 1347 /// the optimized or unoptimized allocation path. This will be added to the pass 1348 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc 1349 /// in the optimized case. 1350 /// 1351 /// A target that uses the standard regalloc pass order for fast or optimized 1352 /// allocation may still override this for per-target regalloc 1353 /// selection. But -regalloc=... always takes precedence. 1354 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) { 1355 if (Optimized) 1356 return createGreedyRegisterAllocator(); 1357 else 1358 return createFastRegisterAllocator(); 1359 } 1360 1361 /// Find and instantiate the register allocation pass requested by this target 1362 /// at the current optimization level. Different register allocators are 1363 /// defined as separate passes because they may require different analysis. 1364 /// 1365 /// This helper ensures that the regalloc= option is always available, 1366 /// even for targets that override the default allocator. 1367 /// 1368 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs, 1369 /// this can be folded into addPass. 1370 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) { 1371 // Initialize the global default. 1372 llvm::call_once(InitializeDefaultRegisterAllocatorFlag, 1373 initializeDefaultRegisterAllocatorOnce); 1374 1375 RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault(); 1376 if (Ctor != useDefaultRegisterAllocator) 1377 return Ctor(); 1378 1379 // With no -regalloc= override, ask the target for a regalloc pass. 1380 return createTargetRegisterAllocator(Optimized); 1381 } 1382 1383 bool TargetPassConfig::isCustomizedRegAlloc() { 1384 return RegAlloc != 1385 (RegisterRegAlloc::FunctionPassCtor)&useDefaultRegisterAllocator; 1386 } 1387 1388 bool TargetPassConfig::addRegAssignAndRewriteFast() { 1389 if (RegAlloc != (RegisterRegAlloc::FunctionPassCtor)&useDefaultRegisterAllocator && 1390 RegAlloc != (RegisterRegAlloc::FunctionPassCtor)&createFastRegisterAllocator) 1391 report_fatal_error("Must use fast (default) register allocator for unoptimized regalloc."); 1392 1393 addPass(createRegAllocPass(false)); 1394 1395 // Allow targets to change the register assignments after 1396 // fast register allocation. 1397 addPostFastRegAllocRewrite(); 1398 return true; 1399 } 1400 1401 bool TargetPassConfig::addRegAssignAndRewriteOptimized() { 1402 // Add the selected register allocation pass. 1403 addPass(createRegAllocPass(true)); 1404 1405 // Allow targets to change the register assignments before rewriting. 1406 addPreRewrite(); 1407 1408 // Finally rewrite virtual registers. 1409 addPass(&VirtRegRewriterID); 1410 1411 // Regalloc scoring for ML-driven eviction - noop except when learning a new 1412 // eviction policy. 1413 addPass(createRegAllocScoringPass()); 1414 return true; 1415 } 1416 1417 /// Return true if the default global register allocator is in use and 1418 /// has not be overriden on the command line with '-regalloc=...' 1419 bool TargetPassConfig::usingDefaultRegAlloc() const { 1420 return RegAlloc.getNumOccurrences() == 0; 1421 } 1422 1423 /// Add the minimum set of target-independent passes that are required for 1424 /// register allocation. No coalescing or scheduling. 1425 void TargetPassConfig::addFastRegAlloc() { 1426 addPass(&PHIEliminationID); 1427 addPass(&TwoAddressInstructionPassID); 1428 1429 addRegAssignAndRewriteFast(); 1430 } 1431 1432 /// Add standard target-independent passes that are tightly coupled with 1433 /// optimized register allocation, including coalescing, machine instruction 1434 /// scheduling, and register allocation itself. 1435 void TargetPassConfig::addOptimizedRegAlloc() { 1436 addPass(&DetectDeadLanesID); 1437 1438 addPass(&InitUndefID); 1439 1440 addPass(&ProcessImplicitDefsID); 1441 1442 // LiveVariables currently requires pure SSA form. 1443 // 1444 // FIXME: Once TwoAddressInstruction pass no longer uses kill flags, 1445 // LiveVariables can be removed completely, and LiveIntervals can be directly 1446 // computed. (We still either need to regenerate kill flags after regalloc, or 1447 // preferably fix the scavenger to not depend on them). 1448 // FIXME: UnreachableMachineBlockElim is a dependant pass of LiveVariables. 1449 // When LiveVariables is removed this has to be removed/moved either. 1450 // Explicit addition of UnreachableMachineBlockElim allows stopping before or 1451 // after it with -stop-before/-stop-after. 1452 addPass(&UnreachableMachineBlockElimID); 1453 addPass(&LiveVariablesID); 1454 1455 // Edge splitting is smarter with machine loop info. 1456 addPass(&MachineLoopInfoID); 1457 addPass(&PHIEliminationID); 1458 1459 // Eventually, we want to run LiveIntervals before PHI elimination. 1460 if (EarlyLiveIntervals) 1461 addPass(&LiveIntervalsID); 1462 1463 addPass(&TwoAddressInstructionPassID); 1464 addPass(&RegisterCoalescerID); 1465 1466 // The machine scheduler may accidentally create disconnected components 1467 // when moving subregister definitions around, avoid this by splitting them to 1468 // separate vregs before. Splitting can also improve reg. allocation quality. 1469 addPass(&RenameIndependentSubregsID); 1470 1471 // PreRA instruction scheduling. 1472 addPass(&MachineSchedulerID); 1473 1474 if (addRegAssignAndRewriteOptimized()) { 1475 // Perform stack slot coloring and post-ra machine LICM. 1476 addPass(&StackSlotColoringID); 1477 1478 // Allow targets to expand pseudo instructions depending on the choice of 1479 // registers before MachineCopyPropagation. 1480 addPostRewrite(); 1481 1482 // Copy propagate to forward register uses and try to eliminate COPYs that 1483 // were not coalesced. 1484 addPass(&MachineCopyPropagationID); 1485 1486 // Run post-ra machine LICM to hoist reloads / remats. 1487 // 1488 // FIXME: can this move into MachineLateOptimization? 1489 addPass(&MachineLICMID); 1490 } 1491 } 1492 1493 //===---------------------------------------------------------------------===// 1494 /// Post RegAlloc Pass Configuration 1495 //===---------------------------------------------------------------------===// 1496 1497 /// Add passes that optimize machine instructions after register allocation. 1498 void TargetPassConfig::addMachineLateOptimization() { 1499 // Cleanup of redundant immediate/address loads. 1500 addPass(&MachineLateInstrsCleanupID); 1501 1502 // Branch folding must be run after regalloc and prolog/epilog insertion. 1503 addPass(&BranchFolderPassID); 1504 1505 // Tail duplication. 1506 // Note that duplicating tail just increases code size and degrades 1507 // performance for targets that require Structured Control Flow. 1508 // In addition it can also make CFG irreducible. Thus we disable it. 1509 if (!TM->requiresStructuredCFG()) 1510 addPass(&TailDuplicateLegacyID); 1511 1512 // Copy propagation. 1513 addPass(&MachineCopyPropagationID); 1514 } 1515 1516 /// Add standard GC passes. 1517 bool TargetPassConfig::addGCPasses() { 1518 addPass(&GCMachineCodeAnalysisID); 1519 return true; 1520 } 1521 1522 /// Add standard basic block placement passes. 1523 void TargetPassConfig::addBlockPlacement() { 1524 if (EnableFSDiscriminator) { 1525 addPass(createMIRAddFSDiscriminatorsPass( 1526 sampleprof::FSDiscriminatorPass::Pass2)); 1527 const std::string ProfileFile = getFSProfileFile(TM); 1528 if (!ProfileFile.empty() && !DisableLayoutFSProfileLoader) 1529 addPass(createMIRProfileLoaderPass(ProfileFile, getFSRemappingFile(TM), 1530 sampleprof::FSDiscriminatorPass::Pass2, 1531 nullptr)); 1532 } 1533 if (addPass(&MachineBlockPlacementID)) { 1534 // Run a separate pass to collect block placement statistics. 1535 if (EnableBlockPlacementStats) 1536 addPass(&MachineBlockPlacementStatsID); 1537 } 1538 } 1539 1540 //===---------------------------------------------------------------------===// 1541 /// GlobalISel Configuration 1542 //===---------------------------------------------------------------------===// 1543 bool TargetPassConfig::isGlobalISelAbortEnabled() const { 1544 return TM->Options.GlobalISelAbort == GlobalISelAbortMode::Enable; 1545 } 1546 1547 bool TargetPassConfig::reportDiagnosticWhenGlobalISelFallback() const { 1548 return TM->Options.GlobalISelAbort == GlobalISelAbortMode::DisableWithDiag; 1549 } 1550 1551 bool TargetPassConfig::isGISelCSEEnabled() const { 1552 return true; 1553 } 1554 1555 std::unique_ptr<CSEConfigBase> TargetPassConfig::getCSEConfig() const { 1556 return std::make_unique<CSEConfigBase>(); 1557 } 1558