LLVM 20.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"
14#include "SPIRV.h"
15#include "SPIRVCallLowering.h"
16#include "SPIRVGlobalRegistry.h"
17#include "SPIRVLegalizerInfo.h"
26#include "llvm/CodeGen/Passes.h"
31#include "llvm/Pass.h"
36#include <optional>
37
38using namespace llvm;
39
41 // Register the target.
45
51}
52
53static std::string computeDataLayout(const Triple &TT) {
54 const auto Arch = TT.getArch();
55 // TODO: this probably needs to be revisited:
56 // Logical SPIR-V has no pointer size, so any fixed pointer size would be
57 // wrong. The choice to default to 32 or 64 is just motivated by another
58 // memory model used for graphics: PhysicalStorageBuffer64. But it shouldn't
59 // mean anything.
60 if (Arch == Triple::spirv32)
61 return "e-p:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128-v192:256-"
62 "v256:256-v512:512-v1024:1024-n8:16:32:64-G1";
63 if (TT.getVendor() == Triple::VendorType::AMD &&
64 TT.getOS() == Triple::OSType::AMDHSA)
65 return "e-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128-v192:256-v256:256-"
66 "v512:512-v1024:1024-n32:64-S32-G1-P4-A0";
67 return "e-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128-v192:256-v256:256-"
68 "v512:512-v1024:1024-n8:16:32:64-G1";
69}
70
71static Reloc::Model getEffectiveRelocModel(std::optional<Reloc::Model> RM) {
72 if (!RM)
73 return Reloc::PIC_;
74 return *RM;
75}
76
77// Pin SPIRVTargetObjectFile's vtables to this file.
79
81 StringRef CPU, StringRef FS,
83 std::optional<Reloc::Model> RM,
84 std::optional<CodeModel::Model> CM,
85 CodeGenOptLevel OL, bool JIT)
88 getEffectiveCodeModel(CM, CodeModel::Small), OL),
89 TLOF(std::make_unique<SPIRVTargetObjectFile>()),
90 Subtarget(TT, CPU.str(), FS.str(), *this) {
92 setGlobalISel(true);
93 setFastISel(false);
94 setO0WantsFastISel(false);
96}
97
99#define GET_PASS_REGISTRY "SPIRVPassRegistry.def"
101}
102
103namespace {
104// SPIR-V Code Generator Pass Configuration Options.
105class SPIRVPassConfig : public TargetPassConfig {
106public:
107 SPIRVPassConfig(SPIRVTargetMachine &TM, PassManagerBase &PM)
108 : TargetPassConfig(TM, PM), TM(TM) {}
109
110 SPIRVTargetMachine &getSPIRVTargetMachine() const {
111 return getTM<SPIRVTargetMachine>();
112 }
113 void addMachineSSAOptimization() override;
114 void addIRPasses() override;
115 void addISelPrepare() override;
116
117 bool addIRTranslator() override;
118 void addPreLegalizeMachineIR() override;
119 bool addLegalizeMachineIR() override;
120 bool addRegBankSelect() override;
121 bool addGlobalInstructionSelect() override;
122
123 FunctionPass *createTargetRegisterAllocator(bool) override;
124 void addFastRegAlloc() override {}
125 void addOptimizedRegAlloc() override {}
126
127 void addPostRegAlloc() override;
128 void addPreEmitPass() override;
129
130private:
131 const SPIRVTargetMachine &TM;
132};
133} // namespace
134
135// We do not use physical registers, and maintain virtual registers throughout
136// the entire pipeline, so return nullptr to disable register allocation.
137FunctionPass *SPIRVPassConfig::createTargetRegisterAllocator(bool) {
138 return nullptr;
139}
140
141// A place to disable passes that may break CFG.
142void SPIRVPassConfig::addMachineSSAOptimization() {
144}
145
146// Disable passes that break from assuming no virtual registers exist.
147void SPIRVPassConfig::addPostRegAlloc() {
148 // Do not work with vregs instead of physical regs.
149 disablePass(&MachineCopyPropagationID);
150 disablePass(&PostRAMachineSinkingID);
151 disablePass(&PostRASchedulerID);
152 disablePass(&FuncletLayoutID);
153 disablePass(&StackMapLivenessID);
154 disablePass(&PatchableFunctionID);
155 disablePass(&ShrinkWrapID);
156 disablePass(&LiveDebugValuesID);
157 disablePass(&MachineLateInstrsCleanupID);
158 disablePass(&RemoveLoadsIntoFakeUsesID);
159
160 // Do not work with OpPhi.
161 disablePass(&BranchFolderPassID);
162 disablePass(&MachineBlockPlacementID);
163
165}
166
169 return TargetTransformInfo(SPIRVTTIImpl(this, F));
170}
171
173 return new SPIRVPassConfig(*this, PM);
174}
175
176void SPIRVPassConfig::addIRPasses() {
178
179 if (TM.getSubtargetImpl()->isVulkanEnv()) {
180 // 1. Simplify loop for subsequent transformations. After this steps, loops
181 // have the following properties:
182 // - loops have a single entry edge (pre-header to loop header).
183 // - all loop exits are dominated by the loop pre-header.
184 // - loops have a single back-edge.
185 addPass(createLoopSimplifyPass());
186
187 // 2. Removes registers whose lifetime spans across basic blocks. Also
188 // removes phi nodes. This will greatly simplify the next steps.
189 addPass(createRegToMemWrapperPass());
190
191 // 3. Merge the convergence region exit nodes into one. After this step,
192 // regions are single-entry, single-exit. This will help determine the
193 // correct merge block.
195
196 // 4. Structurize.
198
199 // 5. Reduce the amount of variables required by pushing some operations
200 // back to virtual registers.
202 }
203
207}
208
209void SPIRVPassConfig::addISelPrepare() {
210 addPass(createSPIRVEmitIntrinsicsPass(&getTM<SPIRVTargetMachine>()));
212}
213
214bool SPIRVPassConfig::addIRTranslator() {
215 addPass(new IRTranslator(getOptLevel()));
216 return false;
217}
218
219void SPIRVPassConfig::addPreLegalizeMachineIR() {
221}
222
223// Use the default legalizer.
224bool SPIRVPassConfig::addLegalizeMachineIR() {
225 addPass(new Legalizer());
227 return false;
228}
229
230// Do not add the RegBankSelect pass, as we only ever need virtual registers.
231bool SPIRVPassConfig::addRegBankSelect() {
232 disablePass(&RegBankSelect::ID);
233 return false;
234}
235
237 "spv-emit-nonsemantic-debug-info",
238 cl::desc("Emit SPIR-V NonSemantic.Shader.DebugInfo.100 instructions"),
239 cl::Optional, cl::init(false));
240
241void SPIRVPassConfig::addPreEmitPass() {
243 addPass(createSPIRVEmitNonSemanticDIPass(&getTM<SPIRVTargetMachine>()));
244 }
245}
246
247namespace {
248// A custom subclass of InstructionSelect, which is mostly the same except from
249// not requiring RegBankSelect to occur previously.
250class SPIRVInstructionSelect : public InstructionSelect {
251 // We don't use register banks, so unset the requirement for them
252 MachineFunctionProperties getRequiredProperties() const override {
254 MachineFunctionProperties::Property::RegBankSelected);
255 }
256};
257} // namespace
258
259// Add the custom SPIRVInstructionSelect from above.
260bool SPIRVPassConfig::addGlobalInstructionSelect() {
261 addPass(new SPIRVInstructionSelect());
262 return false;
263}
#define LLVM_EXTERNAL_VISIBILITY
Definition: Compiler.h:128
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
This file declares the IRTranslator pass.
static LVOptions Options
Definition: LVOptions.cpp:25
static std::string computeDataLayout()
#define F(x, y, z)
Definition: MD5.cpp:55
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
PassBuilder PB(Machine, PassOpts->PTO, std::nullopt, &PIC)
This file describes the interface of the MachineFunctionPass responsible for assigning the generic vi...
static Reloc::Model getEffectiveRelocModel(std::optional< Reloc::Model > RM)
LLVM_EXTERNAL_VISIBILITY void LLVMInitializeSPIRVTarget()
static cl::opt< bool > SPVEnableNonSemanticDI("spv-emit-nonsemantic-debug-info", cl::desc("Emit SPIR-V NonSemantic.Shader.DebugInfo.100 instructions"), cl::Optional, cl::init(false))
Target-Independent Code Generator Pass Configuration Options pass.
implements a set of functionality in the TargetMachine class for targets that make use of the indepen...
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:310
This pass is responsible for selecting generic machine instructions to target-specific instructions.
MachineFunctionProperties getRequiredProperties() const override
Properties which a MachineFunction may have at a given point in time.
MachineFunctionProperties & reset(Property P)
This class provides access to building LLVM's passes.
Definition: PassBuilder.h:105
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
Definition: PassRegistry.h:37
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
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)
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 ...
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
void setFastISel(bool Enable)
void setRequiresStructuredCFG(bool Value)
void setGlobalISel(bool Enable)
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:44
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)
Definition: CommandLine.h:443
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
FunctionPass * createSPIRVStructurizerPass()
FunctionPass * createPromoteMemoryToRegisterPass()
Definition: Mem2Reg.cpp:114
MachineFunctionPass * createSPIRVEmitNonSemanticDIPass(SPIRVTargetMachine *TM)
Target & getTheSPIRV32Target()
ModulePass * createSPIRVEmitIntrinsicsPass(SPIRVTargetMachine *TM)
FunctionPass * createRegToMemWrapperPass()
Definition: Reg2Mem.cpp:148
FunctionPass * createSPIRVPreLegalizerPass()
char & PatchableFunctionID
This pass implements the "patchable-function" attribute.
char & PostRASchedulerID
PostRAScheduler - This pass performs post register allocation scheduling.
char & RemoveLoadsIntoFakeUsesID
RemoveLoadsIntoFakeUses pass.
FunctionPass * createSPIRVStripConvergenceIntrinsicsPass()
char & LiveDebugValuesID
LiveDebugValues pass.
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.
char & ShrinkWrapID
ShrinkWrap pass. Look for the best place to insert save and restore.
Definition: ShrinkWrap.cpp:287
char & MachineLateInstrsCleanupID
MachineLateInstrsCleanup - This pass removes redundant identical instructions after register allocati...
char & StackMapLivenessID
StackMapLiveness - This pass analyses the register live-out set of stackmap/patchpoint intrinsics and...
char & FuncletLayoutID
This pass lays out funclets contiguously.
char & PostRAMachineSinkingID
This pass perform post-ra machine sink for COPY instructions.
CodeGenOptLevel
Code generation optimization level.
Definition: CodeGen.h:54
Target & getTheSPIRV64Target()
void initializeGlobalISel(PassRegistry &)
Initialize all passes linked into the GlobalISel library.
Definition: GlobalISel.cpp:17
Target & getTheSPIRVLogicalTarget()
FunctionPass * createSPIRVRegularizerPass()
void initializeSPIRVStructurizerPass(PassRegistry &)
FunctionPass * createSPIRVMergeRegionExitTargetsPass()
void initializeSPIRVConvergenceRegionAnalysisWrapperPassPass(PassRegistry &)
char & MachineBlockPlacementID
MachineBlockPlacement - This pass places basic blocks based on branch probabilities.
char & BranchFolderPassID
BranchFolding - This pass performs machine code CFG based optimizations to delete branches to branche...
ModulePass * createSPIRVPrepareFunctionsPass(const SPIRVTargetMachine &TM)
Pass * createLoopSimplifyPass()
char & MachineCopyPropagationID
MachineCopyPropagation - This pass performs copy propagation on machine instructions.
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
RegisterTargetMachine - Helper template for registering a target machine implementation,...