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 "SPIRVGlobalRegistry.h"
17#include "SPIRVLegalizerInfo.h"
28#include "llvm/CodeGen/Passes.h"
33#include "llvm/Pass.h"
41#include <optional>
42
43using namespace llvm;
44
46 // Register the target.
51
76}
77
78static Reloc::Model getEffectiveRelocModel(std::optional<Reloc::Model> RM) {
79 if (!RM)
80 return Reloc::PIC_;
81 return *RM;
82}
83
84// Pin SPIRVTargetObjectFile's vtables to this file.
86
88 StringRef CPU, StringRef FS,
90 std::optional<Reloc::Model> RM,
91 std::optional<CodeModel::Model> CM,
92 CodeGenOptLevel OL, bool JIT)
93 : CodeGenTargetMachineImpl(T, TT, CPU, FS, Options,
95 getEffectiveCodeModel(CM, CodeModel::Small), OL),
96 CLOpts(cl::LibraryOptionsContext::get<SPIRVOptions>(
97 Options.MCOptions.LibraryOptions)),
98 TLOF(std::make_unique<SPIRVTargetObjectFile>()),
99 Subtarget(TT, CPU.str(), FS.str(), *this) {
100 initAsmInfo();
102 setGlobalISel(true);
103 setFastISel(false);
104 setO0WantsFastISel(false);
106}
107
108namespace {
109// SPIR-V Code Generator Pass Configuration Options.
110class SPIRVPassConfig : public TargetPassConfig {
111public:
112 SPIRVPassConfig(SPIRVTargetMachine &TM, PassManagerBase &PM)
113 : TargetPassConfig(TM, PM), TM(TM) {
114 // Logical SPIR-V cannot express the pointer induction variables that loop
115 // strength reduction creates.
117 EnableLoopStrengthReduce = false;
118 }
119
120 void addMachineSSAOptimization() override;
121 void addIRPasses() override;
122 void addISelPrepare() override;
123
124 bool addIRTranslator() override;
125 void addPreLegalizeMachineIR() override;
126 bool addLegalizeMachineIR() override;
127 bool addRegBankSelect() override;
128 bool addGlobalInstructionSelect() override;
129
130 void addFastRegAlloc() override {}
131 void addOptimizedRegAlloc() override {}
132
133 void addPostRegAlloc() override;
134 void addPreEmitPass2() override;
135
136private:
137 const SPIRVTargetMachine &TM;
138};
139} // namespace
140
141// A place to disable passes that may break CFG.
142void SPIRVPassConfig::addMachineSSAOptimization() {
144}
145
146void SPIRVPassConfig::addPostRegAlloc() {
147 // Does not work with vregs instead of physical regs.
148 disablePass(&LiveDebugValuesID);
149
150 // Do not work with OpPhi.
151 disablePass(&BranchFolderPassID);
152 disablePass(&MachineBlockPlacementID);
153
155}
156
157void SPIRVPassConfig::addPreEmitPass2() {
159}
160
163 return TargetTransformInfo(std::make_unique<SPIRVTTIImpl>(this, F));
164}
165
167 return new SPIRVPassConfig(*this, PM);
168}
169
170// CSE can merge same-LLT values with different SPIR-V types.
174
179
184
187 SMDiagnostic &Error, SMRange &SourceRange) const {
188 const auto &YamlMFI =
189 static_cast<const yaml::SPIRVMachineFunctionInfo &>(MFI);
190 MachineFunction &MF = PFS.MF;
191 // SPIRVPrepareFunctions resolves the environment, but does not run on MIR.
192 // Resolve it once, before restoring types, because it resets the registry.
193 SPIRVSubtarget &ST =
194 *const_cast<SPIRVTargetMachine *>(this)->getMutableSubtargetImpl();
195 if (ST.getEnv() == SPIRVSubtarget::Unknown)
196 ST.resolveEnvFromModule(*MF.getFunction().getParent());
197 SPIRVGlobalRegistry *GR = ST.getSPIRVGlobalRegistry();
198 const SPIRVInstrInfo &TII = *ST.getInstrInfo();
199 const MachineRegisterInfo &MRI = MF.getRegInfo();
200
201 auto ParseVReg = [&](const yaml::StringValue &RegName, VRegInfo *&Info) {
202 if (!parseVirtualRegisterReference(PFS, Info, RegName.Value, Error))
203 return false;
204 SourceRange = RegName.SourceRange;
205 return true;
206 };
207 auto Diagnose = [&](const yaml::StringValue &RegName, StringRef Msg) {
208 const MemoryBuffer &Buffer =
209 *PFS.SM->getMemoryBuffer(PFS.SM->getMainFileID());
210 Error = SMDiagnostic(*PFS.SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
211 static_cast<int>(RegName.Value.size()),
212 SourceMgr::DK_Error, Msg, RegName.Value, {}, {});
213 SourceRange = RegName.SourceRange;
214 return true;
215 };
216
217 for (const yaml::SPIRVVRegType &Entry : YamlMFI.VRegTypes) {
218 VRegInfo *RegInfo, *TypeInfo;
219 if (ParseVReg(Entry.Reg, RegInfo) || ParseVReg(Entry.Type, TypeInfo))
220 return true;
221 if (MRI.reg_empty(RegInfo->VReg))
222 return Diagnose(Entry.Reg, "virtual register is not used or defined");
223 const MachineInstr *TypeMI = MRI.getUniqueVRegDef(TypeInfo->VReg);
224 if (!TypeMI || !TII.isTypeDeclInstr(*TypeMI))
225 return Diagnose(Entry.Type, "expected a SPIR-V type register");
226 GR->assignSPIRVTypeToVReg(TypeMI, RegInfo->VReg, MF);
227 }
228 GR->restoreFromMIR(MF);
229 return false;
230}
231
232void SPIRVPassConfig::addIRPasses() {
234
236
238
239 if (TM.getSubtargetImpl()->isShader()) {
240 if (getOptLevel() != CodeGenOptLevel::None)
243 } else {
244 // Variadic function calls aren't supported in shader code.
245 // This needs to come before SPIRVPrepareFunctions because this
246 // may introduce intrinsic calls.
248 }
249
254}
255
256void SPIRVPassConfig::addISelPrepare() {
257 if (TM.getSubtargetImpl()->isShader()) {
258 // Vulkan does not allow address space casts. This pass is run to remove
259 // address space casts that can be removed.
260 // If an address space cast is not removed while targeting Vulkan, lowering
261 // will fail during MIR lowering.
263
264 // 1. Simplify loop for subsequent transformations. After this steps, loops
265 // have the following properties:
266 // - loops have a single entry edge (pre-header to loop header).
267 // - all loop exits are dominated by the loop pre-header.
268 // - loops have a single back-edge.
269 addPass(createLoopSimplifyPass());
270
271 // 2. Removes registers whose lifetime spans across basic blocks. Also
272 // removes phi nodes. This will greatly simplify the next steps.
273 addPass(createRegToMemWrapperPass());
274
275 // 3. Merge the convergence region exit nodes into one. After this step,
276 // regions are single-entry, single-exit. This will help determine the
277 // correct merge block.
279
280 // 4. Structurize.
282
283 // 5. Reduce the amount of variables required by pushing some operations
284 // back to virtual registers.
286 } else {
287 // Canonicalize loops so they have a single latch and preheader.
288 // This enables OpLoopMerge emission for non-shader targets.
289 addPass(createLoopSimplifyPass());
290 }
301}
302
303bool SPIRVPassConfig::addIRTranslator() {
304 addPass(new IRTranslatorLegacy(getOptLevel()));
305 return false;
306}
307
308void SPIRVPassConfig::addPreLegalizeMachineIR() {
311}
312
313// Use the default legalizer.
314bool SPIRVPassConfig::addLegalizeMachineIR() {
315 addPass(new LegalizerLegacy());
317 return false;
318}
319
320// Do not add the RegBankSelect pass, as we only ever need virtual registers.
321bool SPIRVPassConfig::addRegBankSelect() {
322 disablePass(&RegBankSelectLegacy::ID);
323 return false;
324}
325
326// Add the custom SPIRVInstructionSelect from above.
327bool SPIRVPassConfig::addGlobalInstructionSelect() {
328 addPass(new InstructionSelectLegacy(getOptLevel()));
329 return false;
330}
static Reloc::Model getEffectiveRelocModel()
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
#define LLVM_ABI
Definition Compiler.h:211
#define LLVM_EXTERNAL_VISIBILITY
Definition Compiler.h:132
const HexagonInstrInfo * TII
This file declares the IRTranslator pass.
#define RegName(no)
#define F(x, y, z)
Definition MD5.cpp:54
#define T
This file describes the interface of the MachineFunctionPass responsible for assigning the generic vi...
const GCNTargetMachine & getTM(const GCNSubtarget *STI)
const char * Msg
LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeSPIRVTarget()
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, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOptLevel OL)
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
Module * getParent()
Get the module that this global value is contained inside of...
This pass is responsible for selecting generic machine instructions to target-specific instructions.
static void setUseExtended(bool Enable)
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
This interface provides simple read-only access to a block of memory, and provides simple methods for...
virtual StringRef getBufferIdentifier() const
Return an identifier for this buffer, typically the filename it was read from.
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...
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition SourceMgr.h:307
Represents a location in source code.
Definition SMLoc.h:22
Represents a range in source code.
Definition SMLoc.h:47
void assignSPIRVTypeToVReg(SPIRVTypeInst Type, Register VReg, const MachineFunction &MF)
void restoreFromMIR(const MachineFunction &MF)
bool isLogicalSPIRV() const
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)
yaml::MachineFunctionInfo * convertFuncInfoToYAML(const MachineFunction &MF) const override
Allocate and initialize an instance of the YAML representation of the MachineFunctionInfo.
const SPIRVSubtarget * getSubtargetImpl() const
TargetTransformInfo getTargetTransformInfo(const Function &F) const override
Get a TargetTransformInfo implementation for the target.
bool parseMachineFunctionInfo(const yaml::MachineFunctionInfo &, PerFunctionMIParsingState &PFS, SMDiagnostic &Error, SMRange &SourceRange) const override
Parse out the target's MachineFunctionInfo from the YAML reprsentation.
yaml::MachineFunctionInfo * createDefaultFuncInfoYAML() const override
Allocate and return a default initialized instance of the YAML representation for the MachineFunction...
TargetPassConfig * createPassConfig(PassManagerBase &PM) override
Create a pass configuration object to be used by addPassToEmitX methods for generating a pipeline of ...
SPIRVSubtarget * getMutableSubtargetImpl()
CSEConfigBase * createCSEConfig() const override
GlobalISel CSEConfig for the new PM. Return NULL for the standard one.
unsigned getMainFileID() const
Definition SourceMgr.h:150
const MemoryBuffer * getMemoryBuffer(unsigned i) const
Definition SourceMgr.h:141
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)
std::unique_ptr< const MCRegisterInfo > MRI
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 ...
Registers T with cl::parseCommandLineOptions.
Interfaces for registering analysis passes, producing common pass manager configurations,...
This namespace contains all of the command line option processing machinery.
This is an optimization pass for GlobalISel generic memory operations.
ModulePass * createSPIRVPushConstantAccessLegacyPass(SPIRVTargetMachine *TM)
ModulePass * createSPIRVCtorDtorLoweringLegacyPass()
FunctionPass * createSPIRVStructurizerPass()
ModulePass * createSPIRVEmitIntrinsicsPass(const SPIRVTargetMachine &TM)
ModulePass * createSPIRVLowerResourceNamesLegacyPass()
LLVM_ABI FunctionPass * createPromoteMemoryToRegisterPass()
Definition Mem2Reg.cpp:114
Target & getTheSPIRV32Target()
LLVM_ABI FunctionPass * createRegToMemWrapperPass()
Definition Reg2Mem.cpp:140
void initializeSPIRVPushConstantAccessLegacyPass(PassRegistry &)
void initializeSPIRVLegalizePointerCastLegacyPass(PassRegistry &)
void initializeSPIRVPrepareFunctionsLegacyPass(PassRegistry &)
ModulePass * createSPIRVRemoveUnusedResourcesLegacyPass()
LLVM_ABI char & LiveDebugValuesID
LiveDebugValues pass.
static Reloc::Model getEffectiveRelocModel(std::optional< Reloc::Model > RM)
FunctionPass * createSPIRVPreLegalizerCombinerLegacyPass()
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)
FunctionPass * createSPIRVPostLegalizerLegacyPass()
void initializeSPIRVLegalizeZeroSizeArraysLegacyPass(PassRegistry &)
ModulePass * createSPIRVFinalizeShaderLinkagePass(const SPIRVTargetMachine &TM)
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
ModulePass * createSPIRVPrepareGlobalsPass()
void initializeSPIRVEmitIntrinsicsLegacyPass(PassRegistry &)
FunctionPass * createSPIRVPrepareModuleAnalysisLegacyPass()
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:280
Target & getTheSPIRV64Target()
void initializeSPIRVPrepareModuleAnalysisLegacyPass(PassRegistry &)
ModulePass * createSPIRVLegalizeZeroSizeArraysPass(const SPIRVTargetMachine &TM)
LLVM_ABI FunctionPass * createStripConvergenceIntrinsicsPass()
void initializeSPIRVCBufferAccessLegacyPass(PassRegistry &)
ModulePass * createSPIRVCBufferAccessLegacyPass()
LLVM_ABI void initializeGlobalISel(PassRegistry &)
Initialize all passes linked into the GlobalISel library.
void initializeSPIRVPostLegalizerLegacyPass(PassRegistry &)
void initializeSPIRVModuleAnalysisWrapperPassPass(PassRegistry &)
void initializeSPIRVRemoveUnusedResourcesLegacyPass(PassRegistry &)
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 initializeSPIRVPreLegalizerCombinerLegacyPass(PassRegistry &)
void initializeSPIRVPreLegalizerLegacyPass(PassRegistry &)
FunctionPass * createSPIRVPreLegalizerLegacyPass()
void initializeSPIRVConvergenceRegionAnalysisWrapperPassPass(PassRegistry &)
LLVM_ABI char & MachineBlockPlacementID
MachineBlockPlacement - This pass places basic blocks based on branch probabilities.
LLVM_ABI bool parseVirtualRegisterReference(PerFunctionMIParsingState &PFS, VRegInfo *&Info, StringRef Src, SMDiagnostic &Error)
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()
ModulePass * createSPIRVLegalizeResourceBindingPass()
void initializeSPIRVCtorDtorLoweringLegacyPass(PassRegistry &)
void initializeSPIRVLowerResourceNamesLegacyPass(PassRegistry &)
void initializeSPIRVMergeRegionExitTargetsLegacyPass(PassRegistry &)
void initializeSPIRVLegalizeResourceBindingLegacyPass(PassRegistry &)
void initializeSPIRVFinalizeShaderLinkageLegacyPass(PassRegistry &)
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
RegisterTargetMachine - Helper template for registering a target machine implementation,...
Register VReg
Definition MIParser.h:48
Targets should override this in a way that mirrors the implementation of llvm::MachineFunctionInfo.
A wrapper around std::string which contains a source range that's being set during parsing.