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"
30#include <vector>
31
32using namespace llvm;
33
34namespace {
35class SPIRVLegalizeResourceBindingImpl {
36public:
37 bool runOnModule(Module &M);
38
39private:
40 void collectBindingInfo(Module &M);
41 uint32_t getAndReserveFirstUnusedBinding(uint32_t DescSet);
42 bool replaceImplicitBindingCalls(Module &M);
43 bool replaceHeapBindingCalls(Module &M);
44
45 // A map from descriptor set to a bit vector of used binding numbers.
46 std::vector<BitVector> UsedBindings;
47
48 // Set to true by collectBindingInfo() if there are possibly any implicit
49 // binding or heap binding calls in the module (if the module contains a
50 // declaration of implicit binding or heap intrinsic).
51 bool MayHaveImplicitBindings = false;
52 bool MayHaveHeapBindings = false;
53};
54
55class SPIRVLegalizeResourceBindingLegacy : public ModulePass {
56public:
57 static char ID;
58 SPIRVLegalizeResourceBindingLegacy() : ModulePass(ID) {}
59 StringRef getPassName() const override {
60 return "SPIRV Legalize Resource Binding";
61 }
62 bool runOnModule(Module &M) override {
63 return SPIRVLegalizeResourceBindingImpl().runOnModule(M);
64 }
65};
66
67static uint32_t getDescSet(const CallInst *CI) {
68 uint32_t DescSetArgIdx;
69 switch (CI->getIntrinsicID()) {
70 case Intrinsic::spv_resource_handlefromimplicitbinding_mdname:
71 DescSetArgIdx = 1;
72 break;
73 case Intrinsic::spv_resource_counterhandlefromimplicitbinding:
74 DescSetArgIdx = 2;
75 break;
76 default:
77 llvm_unreachable("CallInst is not an implicit binding intrinsic");
78 }
79 return cast<ConstantInt>(CI->getArgOperand(DescSetArgIdx))->getZExtValue();
80}
81
82// Collect all of the bindings used by llvm.spv.resource.handlefrombinding
83// and llvm.spv.resource.counterhandlefrombinding calls. Also check if there
84// are any implicit binding calls.
85void SPIRVLegalizeResourceBindingImpl::collectBindingInfo(Module &M) {
86
87 auto addBinding = [&](uint32_t DescSet, uint32_t Binding) {
88 if (UsedBindings.size() <= DescSet) {
89 UsedBindings.resize(DescSet + 1);
90 UsedBindings[DescSet].resize(64);
91 }
92 if (UsedBindings[DescSet].size() <= Binding) {
93 UsedBindings[DescSet].resize(2 * Binding + 1);
94 }
95 UsedBindings[DescSet].set(Binding);
96 };
97
98 auto collectBinding = [&](Function &F, uint32_t ArgDescSetIdx,
99 uint32_t ArgBindingIdx) {
100 for (User *U : F.users()) {
101 if (CallInst *CI = dyn_cast<CallInst>(U)) {
102 const uint32_t DescSet =
103 cast<ConstantInt>(CI->getArgOperand(ArgDescSetIdx))->getZExtValue();
104 const uint32_t Binding =
105 cast<ConstantInt>(CI->getArgOperand(ArgBindingIdx))->getZExtValue();
106 addBinding(DescSet, Binding);
107 }
108 }
109 };
110
111 for (Function &F : M) {
112 if (!F.isDeclaration())
113 continue;
114
115 switch (F.getIntrinsicID()) {
116 case Intrinsic::spv_resource_handlefrombinding_mdname:
117 collectBinding(F, /*ArgDescSetIdx*/ 0, /*ArgBindingIdx*/ 1);
118 break;
119 case Intrinsic::spv_resource_counterhandlefrombinding:
120 collectBinding(F, /*ArgDescSetIdx*/ 1, /*ArgBindingIdx*/ 2);
121 break;
122 case Intrinsic::spv_resource_handlefromimplicitbinding_mdname:
123 case Intrinsic::spv_resource_counterhandlefromimplicitbinding:
124 MayHaveImplicitBindings = true;
125 break;
126 case Intrinsic::spv_resource_handlefromheap:
127 case Intrinsic::spv_resource_counterhandlefromheap:
128 MayHaveHeapBindings = true;
129 break;
130 default:
131 break;
132 }
133 }
134}
135
136uint32_t SPIRVLegalizeResourceBindingImpl::getAndReserveFirstUnusedBinding(
137 uint32_t DescSet) {
138 if (UsedBindings.size() <= DescSet) {
139 UsedBindings.resize(DescSet + 1);
140 UsedBindings[DescSet].resize(64);
141 }
142
143 int NewBinding = UsedBindings[DescSet].find_first_unset();
144 if (NewBinding == -1) {
145 NewBinding = UsedBindings[DescSet].size();
146 UsedBindings[DescSet].resize(2 * NewBinding + 1);
147 }
148
149 UsedBindings[DescSet].set(NewBinding);
150 return NewBinding;
151}
152
153// Replace the implicit binding call with a new call using explicit binding.
154static void replaceWithHandleFromBinding(Module &M, CallInst *CI,
155 uint32_t DescSet, uint32_t Binding,
156 Value *RangeOp, Value *IndexOp,
157 Value *Name) {
158 assert((CI->getIntrinsicID() ==
159 Intrinsic::spv_resource_handlefromimplicitbinding_mdname ||
160 CI->getIntrinsicID() == Intrinsic::spv_resource_handlefromheap) &&
161 "unexpected binding intrinsic");
162 IRBuilder<> Builder(CI);
163 Value *DescSetOp = Builder.getInt32(DescSet);
164 Value *BindingOp = Builder.getInt32(Binding);
166 &M, Intrinsic::spv_resource_handlefrombinding_mdname, {CI->getType()});
167 CallInst *NewCI = Builder.CreateCall(
168 NewFunc, {DescSetOp, BindingOp, RangeOp, IndexOp, Name});
169 NewCI->setCallingConv(CI->getCallingConv());
170 CI->replaceAllUsesWith(NewCI);
171 CI->eraseFromParent();
172}
173
174// Replace the implicit counter binding call with a new call using explicit
175// binding.
176static void replaceWithCounterHandleFromBinding(Module &M, CallInst *CI,
177 uint32_t DescSet,
178 uint32_t Binding) {
179 assert(
180 (CI->getIntrinsicID() ==
181 Intrinsic::spv_resource_counterhandlefromimplicitbinding ||
182 CI->getIntrinsicID() == Intrinsic::spv_resource_counterhandlefromheap) &&
183 "unexpected binding intrinsic");
184 IRBuilder<> Builder(CI);
185 Value *DescSetOp = Builder.getInt32(DescSet);
186 Value *BindingOp = Builder.getInt32(Binding);
187 Value *MainHandle = CI->getArgOperand(0);
188 Type *OverloadTys[] = {CI->getType(), MainHandle->getType()};
190 &M, Intrinsic::spv_resource_counterhandlefrombinding, OverloadTys);
191 CallInst *NewCI =
192 Builder.CreateCall(NewFunc, {MainHandle, DescSetOp, BindingOp});
193 NewCI->setCallingConv(CI->getCallingConv());
194 CI->replaceAllUsesWith(NewCI);
195 CI->eraseFromParent();
196}
197
198bool SPIRVLegalizeResourceBindingImpl::replaceImplicitBindingCalls(Module &M) {
199 // Collect all implicit binding calls.
201 bool Changed = false;
202 for (Function &F : M) {
203 if (!F.isDeclaration())
204 continue;
205
206 uint32_t OrderIdIdx;
207 if (F.getIntrinsicID() ==
208 Intrinsic::spv_resource_handlefromimplicitbinding_mdname)
209 OrderIdIdx = 0;
210 else if (F.getIntrinsicID() ==
211 Intrinsic::spv_resource_counterhandlefromimplicitbinding)
212 OrderIdIdx = 1;
213 else
214 continue;
215
216 for (User *U : F.users()) {
217 if (CallInst *CI = dyn_cast<CallInst>(U)) {
218 ConstantInt *OrderId = cast<ConstantInt>(CI->getArgOperand(OrderIdIdx));
219 IBCalls.emplace_back(OrderId->getZExtValue(), CI);
220 }
221 }
222 }
223
224 if (IBCalls.empty())
225 return false;
226
227 // Sort the collected calls by their order ID.
228 llvm::sort(IBCalls, llvm::less_first());
229
230 // Assign bindings based on the order ID. Same order ID gets the same binding.
231 // Also make sure that calls with the same order ID have the same descriptor
232 // set.
233 uint32_t LastOrderId = -1;
234 uint32_t LastBinding = -1;
235 uint32_t LastDescSet = -1;
236 for (auto &[OrderId, CI] : IBCalls) {
237 uint32_t Binding;
238 uint32_t DescSet = getDescSet(CI);
239 if (OrderId == LastOrderId) {
240 if (DescSet != LastDescSet)
241 report_fatal_error("Implicit binding calls with the same order ID must "
242 "have the same descriptor set");
243 Binding = LastBinding;
244 } else {
245 Binding = getAndReserveFirstUnusedBinding(DescSet);
246 }
247
248 // Replace the implicit binding call with an explicit binding call.
249 if (CI->getIntrinsicID() ==
250 Intrinsic::spv_resource_handlefromimplicitbinding_mdname)
251 replaceWithHandleFromBinding(M, CI, DescSet, Binding,
252 CI->getArgOperand(2), CI->getArgOperand(3),
253 CI->getArgOperand(4));
254 else
255 replaceWithCounterHandleFromBinding(M, CI, DescSet, Binding);
256 Changed = true;
257
258 LastOrderId = OrderId;
259 LastBinding = Binding;
260 LastDescSet = DescSet;
261 }
262 return Changed;
263}
264
265static Value *createHeapNameMetadata(LLVMContext &Ctx, StringRef Name,
266 unsigned ID) {
267 std::string HeapName = (Twine(".") + Name + "." + Twine(ID)).str();
268 return MetadataAsValue::get(Ctx,
269 MDNode::get(Ctx, MDString::get(Ctx, HeapName)));
270}
271
272// The SPIR-V backend represents dynamic resources as unbounded resource arrays.
273// This function scans the module for calls to
274// `llvm.spv.resource.handlefromheap` and groups them according to whether they
275// create CBV/SRV/UAV resources or samplers. It also collects calls to
276// `llvm.spv.resource.counterhandlefromheap` intrinsics that form a third group.
277//
278// The function assigns the first available binding to each non-empty heap group
279// in this order: CBV/SRV/UAV resources, samplers, and counters. For each group,
280// it will replace the heap intrinsic calls with their explicit
281// `handlefrombinding` equivalents using the assigned binding.
282//
283// The function does not actually create the unbounded resource-array globals
284// itself. It only assigns a unique name that is shared by all resources
285// belonging to the same heap type; the existing `SPIRVInstructionSelector` will
286// create the globals.
287//
288// Because the CBV/SRV/UAV group can contain resources of different types, these
289// resources must be represented by separate arrays, one for each unique
290// resource type. All of these arrays will use the same binding and therefore
291// overlap.
292bool SPIRVLegalizeResourceBindingImpl::replaceHeapBindingCalls(Module &M) {
293 // First we collect all used heap binding declarations and group them based on
294 // their kind.
298 bool Changed = false;
299
300 for (Function &F : M) {
301 if (!F.isDeclaration() || F.user_empty())
302 continue;
303
304 if (F.getIntrinsicID() == Intrinsic::spv_resource_handlefromheap) {
305 TargetExtType *ResType = cast<TargetExtType>(F.getReturnType());
306 if (ResType->getName() == "spirv.Sampler")
307 Samplers.emplace_back(&F);
308 else
309 CbvSrvUavs.emplace_back(&F);
310 } else if (F.getIntrinsicID() ==
311 Intrinsic::spv_resource_counterhandlefromheap) {
312 Counters.emplace_back(&F);
313 } else
314 continue;
315 }
316
317 if (CbvSrvUavs.empty() && Samplers.empty() && Counters.empty())
318 return false;
319
320 // Heap resources are always mapped to descriptor set 0 as an unbounded
321 // runtime array.
322 constexpr uint32_t DescSet = 0;
323 Value *Zero =
324 llvm::ConstantInt::get(llvm::Type::getInt32Ty(M.getContext()), 0);
325
326 if (!CbvSrvUavs.empty()) {
327 // For CBV/UAV/SRV resources we need to create a different
328 // ResourceDescriptorHeap name for each unique resource type. They will all
329 // share the same binding and will overlap.
330 uint32_t Binding = getAndReserveFirstUnusedBinding(DescSet);
331 unsigned HeapID = 0;
332 for (Function *F : CbvSrvUavs) {
333 Value *HeapName = createHeapNameMetadata(
334 M.getContext(), "ResourceDescriptorHeap", HeapID++);
335
336 for (User *U : make_early_inc_range(F->users())) {
337 if (CallInst *CI = dyn_cast<CallInst>(U)) {
338 Value *HeapIdx = CI->getArgOperand(0);
339 replaceWithHandleFromBinding(M, CI, DescSet, Binding, Zero, HeapIdx,
340 HeapName);
341 Changed = true;
342 }
343 }
344 F->eraseFromParent();
345 }
346 }
347
348 if (!Samplers.empty()) {
349 uint32_t Binding = getAndReserveFirstUnusedBinding(DescSet);
350 // The Sampler handle type should be the same for all samplers
351 // (target("spirv.Sampler")).
352 [[maybe_unused]] TargetExtType *SamplerHandleType =
353 cast<TargetExtType>(Samplers.front()->getReturnType());
354
355 Value *HeapName =
356 createHeapNameMetadata(M.getContext(), "SamplerDescriptorHeap", 0);
357 for (Function *F : Samplers) {
358 assert(F->getReturnType() == SamplerHandleType &&
359 "sampler handle type mismatch");
360 for (User *U : make_early_inc_range(F->users())) {
361 if (CallInst *CI = dyn_cast<CallInst>(U)) {
362 Value *HeapIdx = CI->getArgOperand(0);
363 replaceWithHandleFromBinding(M, CI, DescSet, Binding, Zero, HeapIdx,
364 HeapName);
365 Changed = true;
366 }
367 }
368 F->eraseFromParent();
369 }
370 }
371
372 if (!Counters.empty()) {
373 uint32_t Binding = getAndReserveFirstUnusedBinding(DescSet);
374 [[maybe_unused]] Type *CounterHandleTy = Counters.front()->getReturnType();
375 for (Function *F : Counters) {
376 // The counter handle type should be the same for all resource types
377 // that have a counter (target("spirv.VulkanBuffer", i32, 12, 1)).
378 assert(F->getReturnType() == CounterHandleTy &&
379 "counter handle type mismatch");
380 for (User *U : make_early_inc_range(F->users())) {
381 if (CallInst *CI = dyn_cast<CallInst>(U)) {
382 replaceWithCounterHandleFromBinding(M, CI, DescSet, Binding);
383 Changed = true;
384 }
385 }
386 F->eraseFromParent();
387 }
388 }
389
390 return Changed;
391}
392
393bool SPIRVLegalizeResourceBindingImpl::runOnModule(Module &M) {
394 collectBindingInfo(M);
395
396 bool Changed = false;
397 if (MayHaveImplicitBindings)
398 Changed |= replaceImplicitBindingCalls(M);
399 if (MayHaveHeapBindings)
400 Changed |= replaceHeapBindingCalls(M);
401
402 return Changed;
403}
404} // namespace
405
406PreservedAnalyses
408 return SPIRVLegalizeResourceBindingImpl().runOnModule(M)
411}
412
413char SPIRVLegalizeResourceBindingLegacy::ID = 0;
414
415INITIALIZE_PASS(SPIRVLegalizeResourceBindingLegacy,
416 "legalize-spirv-resource-binding",
417 "Legalize SPIR-V resource bindings", false, false)
418
420 return new SPIRVLegalizeResourceBindingLegacy();
421}
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