1 //===- TargetPassConfig.h - Code Generation pass options --------*- C++ -*-===// 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 /// \file 9 /// Target-Independent Code Generator Pass Configuration Options pass. 10 /// 11 //===----------------------------------------------------------------------===// 12 13 #ifndef LLVM_CODEGEN_TARGETPASSCONFIG_H 14 #define LLVM_CODEGEN_TARGETPASSCONFIG_H 15 16 #include "llvm/Pass.h" 17 #include "llvm/Support/CodeGen.h" 18 #include "llvm/Support/Compiler.h" 19 #include "llvm/Support/Error.h" 20 #include <cassert> 21 #include <string> 22 23 namespace llvm { 24 25 class TargetMachine; 26 class PassConfigImpl; 27 class CSEConfigBase; 28 class PassInstrumentationCallbacks; 29 30 // The old pass manager infrastructure is hidden in a legacy namespace now. 31 namespace legacy { 32 33 class PassManagerBase; 34 35 } // end namespace legacy 36 37 using legacy::PassManagerBase; 38 39 /// Discriminated union of Pass ID types. 40 /// 41 /// The PassConfig API prefers dealing with IDs because they are safer and more 42 /// efficient. IDs decouple configuration from instantiation. This way, when a 43 /// pass is overriden, it isn't unnecessarily instantiated. It is also unsafe to 44 /// refer to a Pass pointer after adding it to a pass manager, which deletes 45 /// redundant pass instances. 46 /// 47 /// However, it is convient to directly instantiate target passes with 48 /// non-default ctors. These often don't have a registered PassInfo. Rather than 49 /// force all target passes to implement the pass registry boilerplate, allow 50 /// the PassConfig API to handle either type. 51 /// 52 /// AnalysisID is sadly char*, so PointerIntPair won't work. 53 class IdentifyingPassPtr { 54 union { 55 AnalysisID ID; 56 Pass *P; 57 }; 58 bool IsInstance = false; 59 60 public: IdentifyingPassPtr()61 IdentifyingPassPtr() : P(nullptr) {} IdentifyingPassPtr(AnalysisID IDPtr)62 IdentifyingPassPtr(AnalysisID IDPtr) : ID(IDPtr) {} IdentifyingPassPtr(Pass * InstancePtr)63 IdentifyingPassPtr(Pass *InstancePtr) : P(InstancePtr), IsInstance(true) {} 64 isValid()65 bool isValid() const { return P; } isInstance()66 bool isInstance() const { return IsInstance; } 67 getID()68 AnalysisID getID() const { 69 assert(!IsInstance && "Not a Pass ID"); 70 return ID; 71 } 72 getInstance()73 Pass *getInstance() const { 74 assert(IsInstance && "Not a Pass Instance"); 75 return P; 76 } 77 }; 78 79 80 /// Target-Independent Code Generator Pass Configuration Options. 81 /// 82 /// This is an ImmutablePass solely for the purpose of exposing CodeGen options 83 /// to the internals of other CodeGen passes. 84 class LLVM_ABI TargetPassConfig : public ImmutablePass { 85 private: 86 PassManagerBase *PM = nullptr; 87 AnalysisID StartBefore = nullptr; 88 AnalysisID StartAfter = nullptr; 89 AnalysisID StopBefore = nullptr; 90 AnalysisID StopAfter = nullptr; 91 92 unsigned StartBeforeInstanceNum = 0; 93 unsigned StartBeforeCount = 0; 94 95 unsigned StartAfterInstanceNum = 0; 96 unsigned StartAfterCount = 0; 97 98 unsigned StopBeforeInstanceNum = 0; 99 unsigned StopBeforeCount = 0; 100 101 unsigned StopAfterInstanceNum = 0; 102 unsigned StopAfterCount = 0; 103 104 bool Started = true; 105 bool Stopped = false; 106 bool AddingMachinePasses = false; 107 bool DebugifyIsSafe = true; 108 109 /// Set the StartAfter, StartBefore and StopAfter passes to allow running only 110 /// a portion of the normal code-gen pass sequence. 111 /// 112 /// If the StartAfter and StartBefore pass ID is zero, then compilation will 113 /// begin at the normal point; otherwise, clear the Started flag to indicate 114 /// that passes should not be added until the starting pass is seen. If the 115 /// Stop pass ID is zero, then compilation will continue to the end. 116 /// 117 /// This function expects that at least one of the StartAfter or the 118 /// StartBefore pass IDs is null. 119 void setStartStopPasses(); 120 121 protected: 122 TargetMachine *TM; 123 PassConfigImpl *Impl = nullptr; // Internal data structures 124 bool Initialized = false; // Flagged after all passes are configured. 125 126 // Target Pass Options 127 // Targets provide a default setting, user flags override. 128 bool DisableVerify = false; 129 130 /// Default setting for -enable-tail-merge on this target. 131 bool EnableTailMerge = true; 132 133 /// Enable sinking of instructions in MachineSink where a computation can be 134 /// folded into the addressing mode of a memory load/store instruction or 135 /// replace a copy. 136 bool EnableSinkAndFold = false; 137 138 /// Require processing of functions such that callees are generated before 139 /// callers. 140 bool RequireCodeGenSCCOrder = false; 141 142 /// Enable LoopTermFold immediately after LSR 143 bool EnableLoopTermFold = false; 144 145 /// Add the actual instruction selection passes. This does not include 146 /// preparation passes on IR. 147 bool addCoreISelPasses(); 148 149 public: 150 TargetPassConfig(TargetMachine &TM, PassManagerBase &PM); 151 // Dummy constructor. 152 TargetPassConfig(); 153 154 ~TargetPassConfig() override; 155 156 static char ID; 157 158 /// Get the right type of TargetMachine for this target. getTM()159 template<typename TMC> TMC &getTM() const { 160 return *static_cast<TMC*>(TM); 161 } 162 163 // setInitialized()164 void setInitialized() { Initialized = true; } 165 166 CodeGenOptLevel getOptLevel() const; 167 168 /// Returns true if one of the `-start-after`, `-start-before`, `-stop-after` 169 /// or `-stop-before` options is set. 170 static bool hasLimitedCodeGenPipeline(); 171 172 /// Returns true if none of the `-stop-before` and `-stop-after` options is 173 /// set. 174 static bool willCompleteCodeGenPipeline(); 175 176 /// If hasLimitedCodeGenPipeline is true, this method returns 177 /// a string with the name of the options that caused this 178 /// pipeline to be limited. 179 static std::string getLimitedCodeGenPipelineReason(); 180 181 struct StartStopInfo { 182 bool StartAfter; 183 bool StopAfter; 184 unsigned StartInstanceNum; 185 unsigned StopInstanceNum; 186 StringRef StartPass; 187 StringRef StopPass; 188 }; 189 190 /// Returns pass name in `-stop-before` or `-stop-after` 191 /// NOTE: New pass manager migration only 192 static Expected<StartStopInfo> 193 getStartStopInfo(PassInstrumentationCallbacks &PIC); 194 setDisableVerify(bool Disable)195 void setDisableVerify(bool Disable) { setOpt(DisableVerify, Disable); } 196 getEnableTailMerge()197 bool getEnableTailMerge() const { return EnableTailMerge; } setEnableTailMerge(bool Enable)198 void setEnableTailMerge(bool Enable) { setOpt(EnableTailMerge, Enable); } 199 getEnableSinkAndFold()200 bool getEnableSinkAndFold() const { return EnableSinkAndFold; } setEnableSinkAndFold(bool Enable)201 void setEnableSinkAndFold(bool Enable) { setOpt(EnableSinkAndFold, Enable); } 202 requiresCodeGenSCCOrder()203 bool requiresCodeGenSCCOrder() const { return RequireCodeGenSCCOrder; } 204 void setRequiresCodeGenSCCOrder(bool Enable = true) { 205 setOpt(RequireCodeGenSCCOrder, Enable); 206 } 207 208 /// Allow the target to override a specific pass without overriding the pass 209 /// pipeline. When passes are added to the standard pipeline at the 210 /// point where StandardID is expected, add TargetID in its place. 211 void substitutePass(AnalysisID StandardID, IdentifyingPassPtr TargetID); 212 213 /// Insert InsertedPassID pass after TargetPassID pass. 214 void insertPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID); 215 216 /// Allow the target to enable a specific standard pass by default. enablePass(AnalysisID PassID)217 void enablePass(AnalysisID PassID) { substitutePass(PassID, PassID); } 218 219 /// Allow the target to disable a specific standard pass by default. disablePass(AnalysisID PassID)220 void disablePass(AnalysisID PassID) { 221 substitutePass(PassID, IdentifyingPassPtr()); 222 } 223 224 /// Return the pass substituted for StandardID by the target. 225 /// If no substitution exists, return StandardID. 226 IdentifyingPassPtr getPassSubstitution(AnalysisID StandardID) const; 227 228 /// Return true if the pass has been substituted by the target or 229 /// overridden on the command line. 230 bool isPassSubstitutedOrOverridden(AnalysisID ID) const; 231 232 /// Return true if the optimized regalloc pipeline is enabled. 233 bool getOptimizeRegAlloc() const; 234 235 /// Return true if the default global register allocator is in use and 236 /// has not be overriden on the command line with '-regalloc=...' 237 bool usingDefaultRegAlloc() const; 238 239 /// High level function that adds all passes necessary to go from llvm IR 240 /// representation to the MI representation. 241 /// Adds IR based lowering and target specific optimization passes and finally 242 /// the core instruction selection passes. 243 /// \returns true if an error occurred, false otherwise. 244 bool addISelPasses(); 245 246 /// Add common target configurable passes that perform LLVM IR to IR 247 /// transforms following machine independent optimization. 248 virtual void addIRPasses(); 249 250 /// Add passes to lower exception handling for the code generator. 251 void addPassesToHandleExceptions(); 252 253 /// Add pass to prepare the LLVM IR for code generation. This should be done 254 /// before exception handling preparation passes. 255 virtual void addCodeGenPrepare(); 256 257 /// Add common passes that perform LLVM IR to IR transforms in preparation for 258 /// instruction selection. 259 virtual void addISelPrepare(); 260 261 /// addInstSelector - This method should install an instruction selector pass, 262 /// which converts from LLVM code to machine instructions. addInstSelector()263 virtual bool addInstSelector() { 264 return true; 265 } 266 267 /// This method should install an IR translator pass, which converts from 268 /// LLVM code to machine instructions with possibly generic opcodes. addIRTranslator()269 virtual bool addIRTranslator() { return true; } 270 271 /// This method may be implemented by targets that want to run passes 272 /// immediately before legalization. addPreLegalizeMachineIR()273 virtual void addPreLegalizeMachineIR() {} 274 275 /// This method should install a legalize pass, which converts the instruction 276 /// sequence into one that can be selected by the target. addLegalizeMachineIR()277 virtual bool addLegalizeMachineIR() { return true; } 278 279 /// This method may be implemented by targets that want to run passes 280 /// immediately before the register bank selection. addPreRegBankSelect()281 virtual void addPreRegBankSelect() {} 282 283 /// This method should install a register bank selector pass, which 284 /// assigns register banks to virtual registers without a register 285 /// class or register banks. addRegBankSelect()286 virtual bool addRegBankSelect() { return true; } 287 288 /// This method may be implemented by targets that want to run passes 289 /// immediately before the (global) instruction selection. addPreGlobalInstructionSelect()290 virtual void addPreGlobalInstructionSelect() {} 291 292 /// This method should install a (global) instruction selector pass, which 293 /// converts possibly generic instructions to fully target-specific 294 /// instructions, thereby constraining all generic virtual registers to 295 /// register classes. addGlobalInstructionSelect()296 virtual bool addGlobalInstructionSelect() { return true; } 297 298 /// Add the complete, standard set of LLVM CodeGen passes. 299 /// Fully developed targets will not generally override this. 300 virtual void addMachinePasses(); 301 302 /// printAndVerify - Add a pass to dump then verify the machine function, if 303 /// those steps are enabled. 304 void printAndVerify(const std::string &Banner); 305 306 /// Add a pass to print the machine function if printing is enabled. 307 void addPrintPass(const std::string &Banner); 308 309 /// Add a pass to perform basic verification of the machine function if 310 /// verification is enabled. 311 void addVerifyPass(const std::string &Banner); 312 313 /// Add a pass to add synthesized debug info to the MIR. 314 void addDebugifyPass(); 315 316 /// Add a pass to remove debug info from the MIR. 317 void addStripDebugPass(); 318 319 /// Add a pass to check synthesized debug info for MIR. 320 void addCheckDebugPass(); 321 322 /// Add standard passes before a pass that's about to be added. For example, 323 /// the DebugifyMachineModulePass if it is enabled. 324 void addMachinePrePasses(bool AllowDebugify = true); 325 326 /// Add standard passes after a pass that has just been added. For example, 327 /// the MachineVerifier if it is enabled. 328 void addMachinePostPasses(const std::string &Banner); 329 330 /// Check whether or not GlobalISel should abort on error. 331 /// When this is disabled, GlobalISel will fall back on SDISel instead of 332 /// erroring out. 333 bool isGlobalISelAbortEnabled() const; 334 335 /// Check whether or not a diagnostic should be emitted when GlobalISel 336 /// uses the fallback path. In other words, it will emit a diagnostic 337 /// when GlobalISel failed and isGlobalISelAbortEnabled is false. 338 virtual bool reportDiagnosticWhenGlobalISelFallback() const; 339 340 /// Check whether continuous CSE should be enabled in GISel passes. 341 /// By default, it's enabled for non O0 levels. 342 virtual bool isGISelCSEEnabled() const; 343 344 /// Returns the CSEConfig object to use for the current optimization level. 345 virtual std::unique_ptr<CSEConfigBase> getCSEConfig() const; 346 347 protected: 348 // Helper to verify the analysis is really immutable. 349 void setOpt(bool &Opt, bool Val); 350 351 /// Return true if register allocator is specified by -regalloc=override. 352 bool isCustomizedRegAlloc(); 353 354 /// Methods with trivial inline returns are convenient points in the common 355 /// codegen pass pipeline where targets may insert passes. Methods with 356 /// out-of-line standard implementations are major CodeGen stages called by 357 /// addMachinePasses. Some targets may override major stages when inserting 358 /// passes is insufficient, but maintaining overriden stages is more work. 359 /// 360 361 /// addPreISelPasses - This method should add any "last minute" LLVM->LLVM 362 /// passes (which are run just before instruction selector). addPreISel()363 virtual bool addPreISel() { 364 return true; 365 } 366 367 /// addMachineSSAOptimization - Add standard passes that optimize machine 368 /// instructions in SSA form. 369 virtual void addMachineSSAOptimization(); 370 371 /// Add passes that optimize instruction level parallelism for out-of-order 372 /// targets. These passes are run while the machine code is still in SSA 373 /// form, so they can use MachineTraceMetrics to control their heuristics. 374 /// 375 /// All passes added here should preserve the MachineDominatorTree, 376 /// MachineLoopInfo, and MachineTraceMetrics analyses. addILPOpts()377 virtual bool addILPOpts() { 378 return false; 379 } 380 381 /// This method may be implemented by targets that want to run passes 382 /// immediately before register allocation. addPreRegAlloc()383 virtual void addPreRegAlloc() { } 384 385 /// createTargetRegisterAllocator - Create the register allocator pass for 386 /// this target at the current optimization level. 387 virtual FunctionPass *createTargetRegisterAllocator(bool Optimized); 388 389 /// addFastRegAlloc - Add the minimum set of target-independent passes that 390 /// are required for fast register allocation. 391 virtual void addFastRegAlloc(); 392 393 /// addOptimizedRegAlloc - Add passes related to register allocation. 394 /// CodeGenTargetMachineImpl provides standard regalloc passes for most 395 /// targets. 396 virtual void addOptimizedRegAlloc(); 397 398 /// addPreRewrite - Add passes to the optimized register allocation pipeline 399 /// after register allocation is complete, but before virtual registers are 400 /// rewritten to physical registers. 401 /// 402 /// These passes must preserve VirtRegMap and LiveIntervals, and when running 403 /// after RABasic or RAGreedy, they should take advantage of LiveRegMatrix. 404 /// When these passes run, VirtRegMap contains legal physreg assignments for 405 /// all virtual registers. 406 /// 407 /// Note if the target overloads addRegAssignAndRewriteOptimized, this may not 408 /// be honored. This is also not generally used for the fast variant, 409 /// where the allocation and rewriting are done in one pass. addPreRewrite()410 virtual bool addPreRewrite() { 411 return false; 412 } 413 414 /// addPostFastRegAllocRewrite - Add passes to the optimized register 415 /// allocation pipeline after fast register allocation is complete. addPostFastRegAllocRewrite()416 virtual bool addPostFastRegAllocRewrite() { return false; } 417 418 /// Add passes to be run immediately after virtual registers are rewritten 419 /// to physical registers. addPostRewrite()420 virtual void addPostRewrite() { } 421 422 /// This method may be implemented by targets that want to run passes after 423 /// register allocation pass pipeline but before prolog-epilog insertion. addPostRegAlloc()424 virtual void addPostRegAlloc() { } 425 426 /// Add passes that optimize machine instructions after register allocation. 427 virtual void addMachineLateOptimization(); 428 429 /// This method may be implemented by targets that want to run passes after 430 /// prolog-epilog insertion and before the second instruction scheduling pass. addPreSched2()431 virtual void addPreSched2() { } 432 433 /// addGCPasses - Add late codegen passes that analyze code for garbage 434 /// collection. This should return true if GC info should be printed after 435 /// these passes. 436 virtual bool addGCPasses(); 437 438 /// Add standard basic block placement passes. 439 virtual void addBlockPlacement(); 440 441 /// This pass may be implemented by targets that want to run passes 442 /// immediately before machine code is emitted. addPreEmitPass()443 virtual void addPreEmitPass() { } 444 445 /// This pass may be implemented by targets that want to run passes 446 /// immediately after basic block sections are assigned. addPostBBSections()447 virtual void addPostBBSections() {} 448 449 /// Targets may add passes immediately before machine code is emitted in this 450 /// callback. This is called even later than `addPreEmitPass`. 451 // FIXME: Rename `addPreEmitPass` to something more sensible given its actual 452 // position and remove the `2` suffix here as this callback is what 453 // `addPreEmitPass` *should* be but in reality isn't. addPreEmitPass2()454 virtual void addPreEmitPass2() {} 455 456 /// Utilities for targets to add passes to the pass manager. 457 /// 458 459 /// Add a CodeGen pass at this point in the pipeline after checking overrides. 460 /// Return the pass that was added, or zero if no pass was added. 461 AnalysisID addPass(AnalysisID PassID); 462 463 /// Add a pass to the PassManager if that pass is supposed to be run, as 464 /// determined by the StartAfter and StopAfter options. Takes ownership of the 465 /// pass. 466 void addPass(Pass *P); 467 468 /// addMachinePasses helper to create the target-selected or overriden 469 /// regalloc pass. 470 virtual FunctionPass *createRegAllocPass(bool Optimized); 471 472 /// Add core register allocator passes which do the actual register assignment 473 /// and rewriting. \returns true if any passes were added. 474 virtual bool addRegAssignAndRewriteFast(); 475 virtual bool addRegAssignAndRewriteOptimized(); 476 }; 477 478 LLVM_ABI void registerCodeGenCallback(PassInstrumentationCallbacks &PIC, 479 TargetMachine &); 480 481 } // end namespace llvm 482 483 #endif // LLVM_CODEGEN_TARGETPASSCONFIG_H 484