LLVM 24.0.0git
SPIRVTargetMachine.cpp
Go to the documentation of this file.
1//===- SPIRVTargetMachine.cpp - Define TargetMachine for SPIR-V -*- 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//
9// Implements the info about SPIR-V target spec.
10//
11//===----------------------------------------------------------------------===//
12
13#include "SPIRVTargetMachine.h"
15#include "SPIRV.h"
16#include "SPIRVCBufferAccess.h"
18#include "SPIRVEmitIntrinsics.h"
20#include "SPIRVGlobalRegistry.h"
24#include "SPIRVLegalizerInfo.h"
27#include "SPIRVPrepareGlobals.h"
29#include "SPIRVRegularizer.h"
38#include "llvm/CodeGen/Passes.h"
42#include "llvm/Pass.h"
50#include <optional>
51
52using namespace llvm;
53
82
83static Reloc::Model getEffectiveRelocModel(std::optional<Reloc::Model> RM) {
84 if (!RM)
85 return Reloc::PIC_;
86 return *RM;
87}
88
89// Pin SPIRVTargetObjectFile's vtables to this file.
91
93 StringRef CPU, StringRef FS,
95 std::optional<Reloc::Model> RM,
96 std::optional<CodeModel::Model> CM,
97 CodeGenOptLevel OL, bool JIT)
98 : CodeGenTargetMachineImpl(T, TT.computeDataLayout(), TT, CPU, FS, Options,
100 getEffectiveCodeModel(CM, CodeModel::Small), OL),
101 TLOF(std::make_unique<SPIRVTargetObjectFile>()),
102 Subtarget(TT, CPU.str(), FS.str(), *this) {
103 initAsmInfo();
104 setGlobalISel(true);
105 setFastISel(false);
106 setO0WantsFastISel(false);
108}
109
111#define GET_PASS_REGISTRY "SPIRVPassRegistry.def"
113}
114
115namespace {
116// SPIR-V Code Generator Pass Configuration Options.
117class SPIRVPassConfig : public TargetPassConfig {
118public:
119 SPIRVPassConfig(SPIRVTargetMachine &TM, PassManagerBase &PM)
120 : TargetPassConfig(TM, PM), TM(TM) {}
121
122 SPIRVTargetMachine &getSPIRVTargetMachine() const {
124 }
125 void addMachineSSAOptimization() override;
126 void addIRPasses() override;
127 void addISelPrepare() override;
128
129 bool addIRTranslator() override;
130 void addPreLegalizeMachineIR() override;
131 bool addLegalizeMachineIR() override;
132 bool addRegBankSelect() override;
133 bool addGlobalInstructionSelect() override;
134
135 FunctionPass *createTargetRegisterAllocator(bool) override;
136 void addFastRegAlloc() override {}
137 void addOptimizedRegAlloc() override {}
138
139 void addPostRegAlloc() override;
140
141private:
142 const SPIRVTargetMachine &TM;
143};
144} // namespace
145
146// We do not use physical registers, and maintain virtual registers throughout
147// the entire pipeline, so return nullptr to disable register allocation.
148FunctionPass *SPIRVPassConfig::createTargetRegisterAllocator(bool) {
149 return nullptr;
150}
151
152// A place to disable passes that may break CFG.
153void SPIRVPassConfig::addMachineSSAOptimization() {
155}
156
157// Disable passes that break from assuming no virtual registers exist.
158void SPIRVPassConfig::addPostRegAlloc() {
159 // Do not work with vregs instead of physical regs.
160 disablePass(&MachineCopyPropagationID);
161 disablePass(&PostRAMachineSinkingID);
162 disablePass(&PostRASchedulerID);
163 disablePass(&FuncletLayoutID);
164 disablePass(&StackMapLivenessID);
165 disablePass(&PatchableFunctionID);
166 disablePass(&ShrinkWrapID);
167 disablePass(&LiveDebugValuesID);
168 disablePass(&MachineLateInstrsCleanupID);
169 disablePass(&RemoveLoadsIntoFakeUsesID);
170
171 // Do not work with OpPhi.
172 disablePass(&BranchFolderPassID);
173 disablePass(&MachineBlockPlacementID);
174
176}
177
180 return TargetTransformInfo(std::make_unique<SPIRVTTIImpl>(this, F));
181}
182
184 return new SPIRVPassConfig(*this, PM);
185}
186
187void SPIRVPassConfig::addIRPasses() {
189
191
192 if (TM.getSubtargetImpl()->isShader()) {
193 if (getOptLevel() != CodeGenOptLevel::None)
195 } else {
196 // Variadic function calls aren't supported in shader code.
197 // This needs to come before SPIRVPrepareFunctions because this
198 // may introduce intrinsic calls.
200 }
201
206}
207
208void SPIRVPassConfig::addISelPrepare() {
209 if (TM.getSubtargetImpl()->isShader()) {
210 // Vulkan does not allow address space casts. This pass is run to remove
211 // address space casts that can be removed.
212 // If an address space cast is not removed while targeting Vulkan, lowering
213 // will fail during MIR lowering.
215
216 // 1. Simplify loop for subsequent transformations. After this steps, loops
217 // have the following properties:
218 // - loops have a single entry edge (pre-header to loop header).
219 // - all loop exits are dominated by the loop pre-header.
220 // - loops have a single back-edge.
221 addPass(createLoopSimplifyPass());
222
223 // 2. Removes registers whose lifetime spans across basic blocks. Also
224 // removes phi nodes. This will greatly simplify the next steps.
225 addPass(createRegToMemWrapperPass());
226
227 // 3. Merge the convergence region exit nodes into one. After this step,
228 // regions are single-entry, single-exit. This will help determine the
229 // correct merge block.
231
232 // 4. Structurize.
234
235 // 5. Reduce the amount of variables required by pushing some operations
236 // back to virtual registers.
238 } else {
239 // Canonicalize loops so they have a single latch and preheader.
240 // This enables OpLoopMerge emission for non-shader targets.
241 addPass(createLoopSimplifyPass());
242 }
253}
254
255bool SPIRVPassConfig::addIRTranslator() {
256 addPass(new IRTranslatorLegacy(getOptLevel()));
257 return false;
258}
259
260void SPIRVPassConfig::addPreLegalizeMachineIR() {
263}
264
265// Use the default legalizer.
266bool SPIRVPassConfig::addLegalizeMachineIR() {
267 addPass(new LegalizerLegacy());
269 return false;
270}
271
272// Do not add the RegBankSelect pass, as we only ever need virtual registers.
273bool SPIRVPassConfig::addRegBankSelect() {
274 disablePass(&RegBankSelectLegacy::ID);
275 return false;
276}
277
278// Deprecated flag kept for backward compatibility. NSDI emission is now handled
279// by SPIRVNonSemanticDebugHandler, registered in SPIRVAsmPrinter::
280// doInitialization() when the module contains debug info (llvm.dbg.cu).
281// TODO: Remove this option after a deprecation period. Callers that used
282// -spv-emit-nonsemantic-debug-info should switch to -g.
284 "spv-emit-nonsemantic-debug-info",
285 cl::desc("Deprecated. Use -g to emit SPIR-V NonSemantic.Shader.DebugInfo "
286 "instructions"),
287 cl::Optional, cl::init(false));
288
289// Add the custom SPIRVInstructionSelect from above.
290bool SPIRVPassConfig::addGlobalInstructionSelect() {
291 addPass(new InstructionSelectLegacy(getOptLevel(),
292 /*RequireRegBankSelection=*/false));
293 return false;
294}
static Reloc::Model getEffectiveRelocModel()
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
#define LLVM_ABI
Definition Compiler.h:215
#define LLVM_EXTERNAL_VISIBILITY
Definition Compiler.h:132
This file declares the IRTranslator pass.
#define F(x, y, z)
Definition MD5.cpp:54
#define T
PassBuilder PB(Machine, PassOpts->PTO, std::nullopt, &PIC)
This file describes the interface of the MachineFunctionPass responsible for assigning the generic vi...
const GCNTargetMachine & getTM(const GCNSubtarget *STI)
LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeSPIRVTarget()
static cl::opt< bool > SPVEnableNonSemanticDI("spv-emit-nonsemantic-debug-info", cl::desc("Deprecated. Use -g to emit SPIR-V NonSemantic.Shader.DebugInfo " "instructions"), cl::Optional, cl::init(false))
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Target-Independent Code Generator Pass Configuration Options pass.
CodeGenTargetMachineImpl(const Target &T, StringRef DataLayoutString, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOptLevel OL)
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
This pass is responsible for selecting generic machine instructions to target-specific instructions.
This class provides access to building LLVM's passes.
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
bool isLogicalSPIRV() const
void registerPassBuilderCallbacks(PassBuilder &PB) override
Allow the target to modify the pass pipeline.
SPIRVTargetMachine(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, std::optional< Reloc::Model > RM, std::optional< CodeModel::Model > CM, CodeGenOptLevel OL, bool JIT)
const SPIRVSubtarget * getSubtargetImpl() const
TargetTransformInfo getTargetTransformInfo(const Function &F) const override
Get a TargetTransformInfo implementation for the target.
TargetPassConfig * createPassConfig(PassManagerBase &PM) override
Create a pass configuration object to be used by addPassToEmitX methods for generating a pipeline of ...
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
void setFastISel(bool Enable)
void setRequiresStructuredCFG(bool Value)
void setGlobalISel(bool Enable)
TargetOptions Options
void setO0WantsFastISel(bool Enable)
Target-Independent Code Generator Pass Configuration Options.
virtual void addPostRegAlloc()
This method may be implemented by targets that want to run passes after register allocation pass pipe...
virtual void addIRPasses()
Add common target configurable passes that perform LLVM IR to IR transforms following machine indepen...
virtual void addMachineSSAOptimization()
addMachineSSAOptimization - Add standard passes that optimize machine instructions in SSA form.
virtual void addISelPrepare()
Add common passes that perform LLVM IR to IR transforms in preparation for instruction selection.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
PassManagerBase - An abstract interface to allow code to add passes to a pass manager without having ...
Interfaces for registering analysis passes, producing common pass manager configurations,...
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
ModulePass * createSPIRVPushConstantAccessLegacyPass(SPIRVTargetMachine *TM)
ModulePass * createSPIRVCtorDtorLoweringLegacyPass()
FunctionPass * createSPIRVStructurizerPass()
ModulePass * createSPIRVEmitIntrinsicsPass(const SPIRVTargetMachine &TM)
LLVM_ABI FunctionPass * createPromoteMemoryToRegisterPass()
Definition Mem2Reg.cpp:114
Target & getTheSPIRV32Target()
LLVM_ABI FunctionPass * createRegToMemWrapperPass()
Definition Reg2Mem.cpp:146
FunctionPass * createSPIRVPreLegalizerPass()
void initializeSPIRVPushConstantAccessLegacyPass(PassRegistry &)
LLVM_ABI char & PatchableFunctionID
This pass implements the "patchable-function" attribute.
LLVM_ABI char & PostRASchedulerID
PostRAScheduler - This pass performs post register allocation scheduling.
LLVM_ABI char & RemoveLoadsIntoFakeUsesID
RemoveLoadsIntoFakeUses pass.
void initializeSPIRVLegalizePointerCastLegacyPass(PassRegistry &)
void initializeSPIRVPrepareFunctionsLegacyPass(PassRegistry &)
void initializeSPIRVPreLegalizerCombinerPass(PassRegistry &)
LLVM_ABI char & LiveDebugValuesID
LiveDebugValues pass.
FunctionPass * createSPIRVPreLegalizerCombiner()
void initializeSPIRVModuleAnalysisPass(PassRegistry &)
static Reloc::Model getEffectiveRelocModel(std::optional< Reloc::Model > RM)
FunctionPass * createSPIRVPostLegalizerPass()
CodeModel::Model getEffectiveCodeModel(std::optional< CodeModel::Model > CM, CodeModel::Model Default)
Helper method for getting the code model, returning Default if CM does not have a value.
LLVM_ABI ModulePass * createExpandVariadicsPass(ExpandVariadicsMode)
LLVM_ABI char & ShrinkWrapID
ShrinkWrap pass. Look for the best place to insert save and restore.
LLVM_ABI char & MachineLateInstrsCleanupID
MachineLateInstrsCleanup - This pass removes redundant identical instructions after register allocati...
void initializeSPIRVLegalizeZeroSizeArraysLegacyPass(PassRegistry &)
ModulePass * createSPIRVFinalizeShaderLinkagePass(const SPIRVTargetMachine &TM)
ModulePass * createSPIRVPrepareGlobalsPass()
void initializeSPIRVEmitIntrinsicsLegacyPass(PassRegistry &)
LLVM_ABI char & StackMapLivenessID
StackMapLiveness - This pass analyses the register live-out set of stackmap/patchpoint intrinsics and...
LLVM_ABI char & FuncletLayoutID
This pass lays out funclets contiguously.
LLVM_ABI char & PostRAMachineSinkingID
This pass perform post-ra machine sink for COPY instructions.
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:149
Target & getTheSPIRV64Target()
ModulePass * createSPIRVLegalizeZeroSizeArraysPass(const SPIRVTargetMachine &TM)
LLVM_ABI FunctionPass * createStripConvergenceIntrinsicsPass()
void initializeSPIRVPostLegalizerPass(PassRegistry &)
void initializeSPIRVCBufferAccessLegacyPass(PassRegistry &)
ModulePass * createSPIRVCBufferAccessLegacyPass()
LLVM_ABI void initializeGlobalISel(PassRegistry &)
Initialize all passes linked into the GlobalISel library.
void initializeSPIRVPrepareGlobalsLegacyPass(PassRegistry &)
Target & getTheSPIRVLogicalTarget()
void initializeSPIRVAsmPrinterPass(PassRegistry &)
void initializeSPIRVRegularizerLegacyPass(PassRegistry &)
FunctionPass * createSPIRVRegularizerPass()
void initializeSPIRVStructurizerPass(PassRegistry &)
FunctionPass * createSPIRVMergeRegionExitTargetsPass()
LLVM_ABI FunctionPass * createInferAddressSpacesPass(unsigned AddressSpace=~0u)
void initializeSPIRVPreLegalizerPass(PassRegistry &)
void initializeSPIRVConvergenceRegionAnalysisWrapperPassPass(PassRegistry &)
LLVM_ABI char & MachineBlockPlacementID
MachineBlockPlacement - This pass places basic blocks based on branch probabilities.
LLVM_ABI FunctionPass * createAtomicExpandLegacyPass()
AtomicExpandPass - At IR level this pass replace atomic instructions with __atomic_* library calls,...
LLVM_ABI char & BranchFolderPassID
BranchFolding - This pass performs machine code CFG based optimizations to delete branches to branche...
ModulePass * createSPIRVPrepareFunctionsPass(const SPIRVTargetMachine &TM)
FunctionPass * createSPIRVLegalizePointerCastPass(SPIRVTargetMachine *TM)
LLVM_ABI Pass * createLoopSimplifyPass()
void initializeSPIRVLegalizeImplicitBindingLegacyPass(PassRegistry &)
void initializeSPIRVCtorDtorLoweringLegacyPass(PassRegistry &)
LLVM_ABI char & MachineCopyPropagationID
MachineCopyPropagation - This pass performs copy propagation on machine instructions.
void initializeSPIRVMergeRegionExitTargetsLegacyPass(PassRegistry &)
void initializeSPIRVFinalizeShaderLinkageLegacyPass(PassRegistry &)
ModulePass * createSPIRVLegalizeImplicitBindingPass()
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
RegisterTargetMachine - Helper template for registering a target machine implementation,...