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