LLVM 24.0.0git
SPIRVLegalizeResourceBinding.cpp
Go to the documentation of this file.
1//===- SPIRVLegalizeResourceBinding.cpp - Legalize resource bindings ----*- C++
2//-*-===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass legalizes the @llvm.spv.resource.handlefromimplicitbinding.mdname
11// and @llvm.spv.resource.handlefromheap intrinsics by replacing them with a
12// call to @llvm.spv.resource.handlefrombinding.mdname.
13// It also replaces any @llvm.spv.resource.counterhandlefromimplicitbinding and
14// @llvm.spv.resource.counterhandlefromheap intrinsics with calls to
15// @llvm.spv.resource.counterhandlefrombinding.
16//
17//===----------------------------------------------------------------------===//
18
19#include "SPIRV.h"
20#include "llvm/ADT/BitVector.h"
21#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/Twine.h"
24#include "llvm/IR/IRBuilder.h"
25#include "llvm/IR/InstVisitor.h"
26#include "llvm/IR/Intrinsics.h"
27#include "llvm/IR/IntrinsicsSPIRV.h"
28#include "llvm/IR/Module.h"
29#include "llvm/Pass.h"
31#include <vector>
32
33using namespace llvm;
34
35namespace {
36class SPIRVLegalizeResourceBindingImpl {
37public:
38 bool runOnModule(Module &M);
39
40private:
41 void collectBindingInfo(Module &M);
42 uint32_t getAndReserveFirstUnusedBinding(uint32_t DescSet);
43 bool replaceImplicitBindingCalls(Module &M);
44 bool replaceHeapBindingCalls(Module &M);
45
46 // A map from descriptor set to a bit vector of used binding numbers.
47 std::vector<BitVector> UsedBindings;
48
49 // Set to true by collectBindingInfo() if there are possibly any implicit
50 // binding or heap binding calls in the module (if the module contains a
51 // declaration of implicit binding or heap intrinsic).
52 bool MayHaveImplicitBindings = false;
53 bool MayHaveHeapBindings = false;
54};
55
56class SPIRVLegalizeResourceBindingLegacy : public ModulePass {
57public:
58 static char ID;
59 SPIRVLegalizeResourceBindingLegacy() : ModulePass(ID) {}
60 StringRef getPassName() const override {
61 return "SPIRV Legalize Resource Binding";
62 }
63 bool runOnModule(Module &M) override {
64 return SPIRVLegalizeResourceBindingImpl().runOnModule(M);
65 }
66};
67
68static uint32_t getDescSet(const CallInst *CI) {
69 uint32_t DescSetArgIdx;
70 switch (CI->getIntrinsicID()) {
71 case Intrinsic::spv_resource_handlefromimplicitbinding_mdname:
72 DescSetArgIdx = 1;
73 break;
74 case Intrinsic::spv_resource_counterhandlefromimplicitbinding:
75 DescSetArgIdx = 2;
76 break;
77 default:
78 llvm_unreachable("CallInst is not an implicit binding intrinsic");
79 }
80 return cast<ConstantInt>(CI->getArgOperand(DescSetArgIdx))->getZExtValue();
81}
82
83// Collect all of the bindings used by llvm.spv.resource.handlefrombinding
84// and llvm.spv.resource.counterhandlefrombinding calls. Also check if there
85// are any implicit binding calls.
86void SPIRVLegalizeResourceBindingImpl::collectBindingInfo(Module &M) {
87
88 auto addBinding = [&](uint32_t DescSet, uint32_t Binding) {
89 if (UsedBindings.size() <= DescSet) {
90 UsedBindings.resize(DescSet + 1);
91 UsedBindings[DescSet].resize(64);
92 }
93 if (UsedBindings[DescSet].size() <= Binding) {
94 UsedBindings[DescSet].resize(2 * Binding + 1);
95 }
96 UsedBindings[DescSet].set(Binding);
97 };
98
99 auto collectBinding = [&](Function &F, uint32_t ArgDescSetIdx,
100 uint32_t ArgBindingIdx) {
101 for (User *U : F.users()) {
102 if (CallInst *CI = dyn_cast<CallInst>(U)) {
103 const uint32_t DescSet =
104 cast<ConstantInt>(CI->getArgOperand(ArgDescSetIdx))->getZExtValue();
105 const uint32_t Binding =
106 cast<ConstantInt>(CI->getArgOperand(ArgBindingIdx))->getZExtValue();
107 addBinding(DescSet, Binding);
108 }
109 }
110 };
111
112 for (Function &F : M) {
113 if (!F.isDeclaration())
114 continue;
115
116 switch (F.getIntrinsicID()) {
117 case Intrinsic::spv_resource_handlefrombinding_mdname:
118 collectBinding(F, /*ArgDescSetIdx*/ 0, /*ArgBindingIdx*/ 1);
119 break;
120 case Intrinsic::spv_resource_counterhandlefrombinding:
121 collectBinding(F, /*ArgDescSetIdx*/ 1, /*ArgBindingIdx*/ 2);
122 break;
123 case Intrinsic::spv_resource_handlefromimplicitbinding_mdname:
124 case Intrinsic::spv_resource_counterhandlefromimplicitbinding:
125 MayHaveImplicitBindings = true;
126 break;
127 case Intrinsic::spv_resource_handlefromheap:
128 case Intrinsic::spv_resource_counterhandlefromheap:
129 MayHaveHeapBindings = true;
130 break;
131 default:
132 break;
133 }
134 }
135}
136
137uint32_t SPIRVLegalizeResourceBindingImpl::getAndReserveFirstUnusedBinding(
138 uint32_t DescSet) {
139 if (UsedBindings.size() <= DescSet) {
140 UsedBindings.resize(DescSet + 1);
141 UsedBindings[DescSet].resize(64);
142 }
143
144 int NewBinding = UsedBindings[DescSet].find_first_unset();
145 if (NewBinding == -1) {
146 NewBinding = UsedBindings[DescSet].size();
147 UsedBindings[DescSet].resize(2 * NewBinding + 1);
148 }
149
150 UsedBindings[DescSet].set(NewBinding);
151 return NewBinding;
152}
153
154// Replace the implicit binding call with a new call using explicit binding.
155static void replaceWithHandleFromBinding(Module &M, CallInst *CI,
156 uint32_t DescSet, uint32_t Binding,
157 Value *RangeOp, Value *IndexOp,
158 Value *Name) {
159 assert((CI->getIntrinsicID() ==
160 Intrinsic::spv_resource_handlefromimplicitbinding_mdname ||
161 CI->getIntrinsicID() == Intrinsic::spv_resource_handlefromheap) &&
162 "unexpected binding intrinsic");
163 IRBuilder<> Builder(CI);
164 Value *DescSetOp = Builder.getInt32(DescSet);
165 Value *BindingOp = Builder.getInt32(Binding);
167 &M, Intrinsic::spv_resource_handlefrombinding_mdname, {CI->getType()});
168 CallInst *NewCI = Builder.CreateCall(
169 NewFunc, {DescSetOp, BindingOp, RangeOp, IndexOp, Name});
170 NewCI->setCallingConv(CI->getCallingConv());
171 CI->replaceAllUsesWith(NewCI);
172 CI->eraseFromParent();
173}
174
175// Replace the implicit counter binding call with a new call using explicit
176// binding.
177static void replaceWithCounterHandleFromBinding(Module &M, CallInst *CI,
178 uint32_t DescSet,
179 uint32_t Binding) {
180 assert(
181 (CI->getIntrinsicID() ==
182 Intrinsic::spv_resource_counterhandlefromimplicitbinding ||
183 CI->getIntrinsicID() == Intrinsic::spv_resource_counterhandlefromheap) &&
184 "unexpected binding intrinsic");
185 IRBuilder<> Builder(CI);
186 Value *DescSetOp = Builder.getInt32(DescSet);
187 Value *BindingOp = Builder.getInt32(Binding);
188 Value *MainHandle = CI->getArgOperand(0);
189 Type *OverloadTys[] = {CI->getType(), MainHandle->getType()};
191 &M, Intrinsic::spv_resource_counterhandlefrombinding, OverloadTys);
192 CallInst *NewCI =
193 Builder.CreateCall(NewFunc, {MainHandle, DescSetOp, BindingOp});
194 NewCI->setCallingConv(CI->getCallingConv());
195 CI->replaceAllUsesWith(NewCI);
196 CI->eraseFromParent();
197}
198
199bool SPIRVLegalizeResourceBindingImpl::replaceImplicitBindingCalls(Module &M) {
200 // Collect all implicit binding calls.
202 bool Changed = false;
203 for (Function &F : M) {
204 if (!F.isDeclaration())
205 continue;
206
207 uint32_t OrderIdIdx;
208 if (F.getIntrinsicID() ==
209 Intrinsic::spv_resource_handlefromimplicitbinding_mdname)
210 OrderIdIdx = 0;
211 else if (F.getIntrinsicID() ==
212 Intrinsic::spv_resource_counterhandlefromimplicitbinding)
213 OrderIdIdx = 1;
214 else
215 continue;
216
217 for (User *U : F.users()) {
218 if (CallInst *CI = dyn_cast<CallInst>(U)) {
219 ConstantInt *OrderId = cast<ConstantInt>(CI->getArgOperand(OrderIdIdx));
220 IBCalls.emplace_back(OrderId->getZExtValue(), CI);
221 }
222 }
223 }
224
225 if (IBCalls.empty())
226 return false;
227
228 // Sort the collected calls by their order ID.
229 llvm::sort(IBCalls, llvm::less_first());
230
231 // Assign bindings based on the order ID. Same order ID gets the same binding.
232 // Also make sure that calls with the same order ID have the same descriptor
233 // set.
234 uint32_t LastOrderId = -1;
235 uint32_t LastBinding = -1;
236 uint32_t LastDescSet = -1;
237 for (auto &[OrderId, CI] : IBCalls) {
238 uint32_t Binding;
239 uint32_t DescSet = getDescSet(CI);
240 if (OrderId == LastOrderId) {
241 if (DescSet != LastDescSet)
242 report_fatal_error("Implicit binding calls with the same order ID must "
243 "have the same descriptor set");
244 Binding = LastBinding;
245 } else {
246 Binding = getAndReserveFirstUnusedBinding(DescSet);
247 }
248
249 // Replace the implicit binding call with an explicit binding call.
250 if (CI->getIntrinsicID() ==
251 Intrinsic::spv_resource_handlefromimplicitbinding_mdname)
252 replaceWithHandleFromBinding(M, CI, DescSet, Binding,
253 CI->getArgOperand(2), CI->getArgOperand(3),
254 CI->getArgOperand(4));
255 else
256 replaceWithCounterHandleFromBinding(M, CI, DescSet, Binding);
257 Changed = true;
258
259 LastOrderId = OrderId;
260 LastBinding = Binding;
261 LastDescSet = DescSet;
262 }
263 return Changed;
264}
265
266static Value *createHeapNameMetadata(LLVMContext &Ctx, StringRef Name,
267 unsigned ID) {
268 std::string HeapName = (Twine(".") + Name + "." + Twine(ID)).str();
269 return MetadataAsValue::get(Ctx,
270 MDNode::get(Ctx, MDString::get(Ctx, HeapName)));
271}
272
273// The SPIR-V backend represents dynamic resources as unbounded resource arrays.
274// This function scans the module for calls to
275// `llvm.spv.resource.handlefromheap` and groups them according to whether they
276// create CBV/SRV/UAV resources or samplers. It also collects calls to
277// `llvm.spv.resource.counterhandlefromheap` intrinsics that form a third group.
278//
279// The function assigns the first available binding to each non-empty heap group
280// in this order: CBV/SRV/UAV resources, samplers, and counters. For each group,
281// it will replace the heap intrinsic calls with their explicit
282// `handlefrombinding` equivalents using the assigned binding.
283//
284// The function does not actually create the unbounded resource-array globals
285// itself. It only assigns a unique name that is shared by all resources
286// belonging to the same heap type; the existing `SPIRVInstructionSelector` will
287// create the globals.
288//
289// Because the CBV/SRV/UAV group can contain resources of different types, these
290// resources must be represented by separate arrays, one for each unique
291// resource type. All of these arrays will use the same binding and therefore
292// overlap.
293bool SPIRVLegalizeResourceBindingImpl::replaceHeapBindingCalls(Module &M) {
294 // First we collect all used heap binding declarations and group them based on
295 // their kind.
299 bool Changed = false;
300
301 for (Function &F : M) {
302 if (!F.isDeclaration() || F.user_empty())
303 continue;
304
305 if (F.getIntrinsicID() == Intrinsic::spv_resource_handlefromheap) {
306 TargetExtType *ResType = cast<TargetExtType>(F.getReturnType());
307 if (ResType->getName() == "spirv.Sampler")
308 Samplers.emplace_back(&F);
309 else
310 CbvSrvUavs.emplace_back(&F);
311 } else if (F.getIntrinsicID() ==
312 Intrinsic::spv_resource_counterhandlefromheap) {
313 Counters.emplace_back(&F);
314 } else
315 continue;
316 }
317
318 if (CbvSrvUavs.empty() && Samplers.empty() && Counters.empty())
319 return false;
320
321 // Heap resources are always mapped to descriptor set 0 as an unbounded
322 // runtime array.
323 constexpr uint32_t DescSet = 0;
324 Value *Zero =
325 llvm::ConstantInt::get(llvm::Type::getInt32Ty(M.getContext()), 0);
326
327 if (!CbvSrvUavs.empty()) {
328 // For CBV/UAV/SRV resources we need to create a different
329 // ResourceDescriptorHeap name for each unique resource type. They will all
330 // share the same binding and will overlap.
331 uint32_t Binding = getAndReserveFirstUnusedBinding(DescSet);
332 unsigned HeapID = 0;
333 for (Function *F : CbvSrvUavs) {
334 Value *HeapName = createHeapNameMetadata(
335 M.getContext(), "ResourceDescriptorHeap", HeapID++);
336
337 for (User *U : make_early_inc_range(F->users())) {
338 if (CallInst *CI = dyn_cast<CallInst>(U)) {
339 Value *HeapIdx = CI->getArgOperand(0);
340 replaceWithHandleFromBinding(M, CI, DescSet, Binding, Zero, HeapIdx,
341 HeapName);
342 Changed = true;
343 }
344 }
345 F->eraseFromParent();
346 }
347 }
348
349 if (!Samplers.empty()) {
350 uint32_t Binding = getAndReserveFirstUnusedBinding(DescSet);
351 // The Sampler handle type should be the same for all samplers
352 // (target("spirv.Sampler")).
353 [[maybe_unused]] TargetExtType *SamplerHandleType =
354 cast<TargetExtType>(Samplers.front()->getReturnType());
355
356 Value *HeapName =
357 createHeapNameMetadata(M.getContext(), "SamplerDescriptorHeap", 0);
358 for (Function *F : Samplers) {
359 assert(F->getReturnType() == SamplerHandleType &&
360 "sampler handle type mismatch");
361 for (User *U : make_early_inc_range(F->users())) {
362 if (CallInst *CI = dyn_cast<CallInst>(U)) {
363 Value *HeapIdx = CI->getArgOperand(0);
364 replaceWithHandleFromBinding(M, CI, DescSet, Binding, Zero, HeapIdx,
365 HeapName);
366 Changed = true;
367 }
368 }
369 F->eraseFromParent();
370 }
371 }
372
373 if (!Counters.empty()) {
374 uint32_t Binding = getAndReserveFirstUnusedBinding(DescSet);
375 [[maybe_unused]] Type *CounterHandleTy = Counters.front()->getReturnType();
376 for (Function *F : Counters) {
377 // The counter handle type should be the same for all resource types
378 // that have a counter (target("spirv.VulkanBuffer", i32, 12, 1)).
379 assert(F->getReturnType() == CounterHandleTy &&
380 "counter handle type mismatch");
381 for (User *U : make_early_inc_range(F->users())) {
382 if (CallInst *CI = dyn_cast<CallInst>(U)) {
383 replaceWithCounterHandleFromBinding(M, CI, DescSet, Binding);
384 Changed = true;
385 }
386 }
387 F->eraseFromParent();
388 }
389 }
390
391 return Changed;
392}
393
394bool SPIRVLegalizeResourceBindingImpl::runOnModule(Module &M) {
395 collectBindingInfo(M);
396
397 bool Changed = false;
398 if (MayHaveImplicitBindings)
399 Changed |= replaceImplicitBindingCalls(M);
400 if (MayHaveHeapBindings)
401 Changed |= replaceHeapBindingCalls(M);
402
403 return Changed;
404}
405} // namespace
406
407PreservedAnalyses
409 return SPIRVLegalizeResourceBindingImpl().runOnModule(M)
412}
413
414char SPIRVLegalizeResourceBindingLegacy::ID = 0;
415
416INITIALIZE_PASS(SPIRVLegalizeResourceBindingLegacy,
417 "legalize-spirv-resource-binding",
418 "Legalize SPIR-V resource bindings", false, false)
419
421 return new SPIRVLegalizeResourceBindingLegacy();
422}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements the BitVector class.
DXIL Resource Implicit Binding
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
Machine Check Debug Module
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
void setCallingConv(CallingConv::ID CC)
CallingConv::ID getCallingConv() const
Value * getArgOperand(unsigned i) const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
This class represents a function call, abstracting a target machine's calling convention.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
void setCallingConv(CallingConv::ID CC)
Definition Function.h:277
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:595
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:105
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:253
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
reference emplace_back(ArgTypes &&... Args)
StringRef getName() const
Return the name for this target extension type.
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
This is an optimization pass for GlobalISel generic memory operations.
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
ModulePass * createSPIRVLegalizeResourceBindingPass()
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39