27#include "llvm/IR/IntrinsicsSPIRV.h"
36class SPIRVLegalizeResourceBindingImpl {
38 bool runOnModule(
Module &M);
41 void collectBindingInfo(
Module &M);
42 uint32_t getAndReserveFirstUnusedBinding(uint32_t DescSet);
43 bool replaceImplicitBindingCalls(
Module &M);
44 bool replaceHeapBindingCalls(
Module &M);
47 std::vector<BitVector> UsedBindings;
52 bool MayHaveImplicitBindings =
false;
53 bool MayHaveHeapBindings =
false;
56class SPIRVLegalizeResourceBindingLegacy :
public ModulePass {
59 SPIRVLegalizeResourceBindingLegacy() : ModulePass(ID) {}
60 StringRef getPassName()
const override {
61 return "SPIRV Legalize Resource Binding";
63 bool runOnModule(
Module &M)
override {
64 return SPIRVLegalizeResourceBindingImpl().runOnModule(M);
71 case Intrinsic::spv_resource_handlefromimplicitbinding_mdname:
74 case Intrinsic::spv_resource_counterhandlefromimplicitbinding:
86void SPIRVLegalizeResourceBindingImpl::collectBindingInfo(
Module &M) {
88 auto addBinding = [&](uint32_t DescSet, uint32_t
Binding) {
89 if (UsedBindings.size() <= DescSet) {
90 UsedBindings.resize(DescSet + 1);
91 UsedBindings[DescSet].resize(64);
94 UsedBindings[DescSet].resize(2 *
Binding + 1);
96 UsedBindings[DescSet].set(
Binding);
99 auto collectBinding = [&](
Function &
F, uint32_t ArgDescSetIdx,
100 uint32_t ArgBindingIdx) {
101 for (User *U :
F.users()) {
103 const uint32_t DescSet =
113 if (!
F.isDeclaration())
116 switch (
F.getIntrinsicID()) {
117 case Intrinsic::spv_resource_handlefrombinding_mdname:
118 collectBinding(
F, 0, 1);
120 case Intrinsic::spv_resource_counterhandlefrombinding:
121 collectBinding(
F, 1, 2);
123 case Intrinsic::spv_resource_handlefromimplicitbinding_mdname:
124 case Intrinsic::spv_resource_counterhandlefromimplicitbinding:
125 MayHaveImplicitBindings =
true;
127 case Intrinsic::spv_resource_handlefromheap:
128 case Intrinsic::spv_resource_counterhandlefromheap:
129 MayHaveHeapBindings =
true;
137uint32_t SPIRVLegalizeResourceBindingImpl::getAndReserveFirstUnusedBinding(
139 if (UsedBindings.size() <= DescSet) {
140 UsedBindings.resize(DescSet + 1);
141 UsedBindings[DescSet].resize(64);
144 int NewBinding = UsedBindings[DescSet].find_first_unset();
145 if (NewBinding == -1) {
146 NewBinding = UsedBindings[DescSet].size();
147 UsedBindings[DescSet].resize(2 * NewBinding + 1);
150 UsedBindings[DescSet].set(NewBinding);
155static void replaceWithHandleFromBinding(
Module &M, CallInst *CI,
156 uint32_t DescSet, uint32_t
Binding,
160 Intrinsic::spv_resource_handlefromimplicitbinding_mdname ||
161 CI->
getIntrinsicID() == Intrinsic::spv_resource_handlefromheap) &&
162 "unexpected binding intrinsic");
164 Value *DescSetOp = Builder.getInt32(DescSet);
167 &M, Intrinsic::spv_resource_handlefrombinding_mdname, {CI->
getType()});
168 CallInst *NewCI = Builder.CreateCall(
169 NewFunc, {DescSetOp, BindingOp, RangeOp, IndexOp,
Name});
177static void replaceWithCounterHandleFromBinding(
Module &M, CallInst *CI,
182 Intrinsic::spv_resource_counterhandlefromimplicitbinding ||
183 CI->
getIntrinsicID() == Intrinsic::spv_resource_counterhandlefromheap) &&
184 "unexpected binding intrinsic");
186 Value *DescSetOp = Builder.getInt32(DescSet);
191 &M, Intrinsic::spv_resource_counterhandlefrombinding, OverloadTys);
193 Builder.CreateCall(NewFunc, {MainHandle, DescSetOp, BindingOp});
199bool SPIRVLegalizeResourceBindingImpl::replaceImplicitBindingCalls(
Module &M) {
204 if (!
F.isDeclaration())
208 if (
F.getIntrinsicID() ==
209 Intrinsic::spv_resource_handlefromimplicitbinding_mdname)
211 else if (
F.getIntrinsicID() ==
212 Intrinsic::spv_resource_counterhandlefromimplicitbinding)
217 for (User *U :
F.users()) {
234 uint32_t LastOrderId = -1;
235 uint32_t LastBinding = -1;
236 uint32_t LastDescSet = -1;
237 for (
auto &[OrderId, CI] : IBCalls) {
239 uint32_t DescSet = getDescSet(CI);
240 if (OrderId == LastOrderId) {
241 if (DescSet != LastDescSet)
243 "have the same descriptor set");
246 Binding = getAndReserveFirstUnusedBinding(DescSet);
251 Intrinsic::spv_resource_handlefromimplicitbinding_mdname)
252 replaceWithHandleFromBinding(M, CI, DescSet,
Binding,
256 replaceWithCounterHandleFromBinding(M, CI, DescSet,
Binding);
259 LastOrderId = OrderId;
261 LastDescSet = DescSet;
266static Value *createHeapNameMetadata(LLVMContext &Ctx, StringRef Name,
268 std::string HeapName = (Twine(
".") +
Name +
"." + Twine(ID)).str();
293bool SPIRVLegalizeResourceBindingImpl::replaceHeapBindingCalls(
Module &M) {
302 if (!
F.isDeclaration() ||
F.user_empty())
305 if (
F.getIntrinsicID() == Intrinsic::spv_resource_handlefromheap) {
307 if (ResType->
getName() ==
"spirv.Sampler")
311 }
else if (
F.getIntrinsicID() ==
312 Intrinsic::spv_resource_counterhandlefromheap) {
323 constexpr uint32_t DescSet = 0;
327 if (!CbvSrvUavs.
empty()) {
331 uint32_t
Binding = getAndReserveFirstUnusedBinding(DescSet);
334 Value *HeapName = createHeapNameMetadata(
335 M.getContext(),
"ResourceDescriptorHeap", HeapID++);
340 replaceWithHandleFromBinding(M, CI, DescSet,
Binding,
Zero, HeapIdx,
345 F->eraseFromParent();
349 if (!Samplers.
empty()) {
350 uint32_t
Binding = getAndReserveFirstUnusedBinding(DescSet);
353 [[maybe_unused]] TargetExtType *SamplerHandleType =
357 createHeapNameMetadata(
M.getContext(),
"SamplerDescriptorHeap", 0);
359 assert(
F->getReturnType() == SamplerHandleType &&
360 "sampler handle type mismatch");
364 replaceWithHandleFromBinding(M, CI, DescSet,
Binding,
Zero, HeapIdx,
369 F->eraseFromParent();
374 uint32_t
Binding = getAndReserveFirstUnusedBinding(DescSet);
375 [[maybe_unused]]
Type *CounterHandleTy =
Counters.front()->getReturnType();
379 assert(
F->getReturnType() == CounterHandleTy &&
380 "counter handle type mismatch");
383 replaceWithCounterHandleFromBinding(M, CI, DescSet,
Binding);
387 F->eraseFromParent();
394bool SPIRVLegalizeResourceBindingImpl::runOnModule(
Module &M) {
395 collectBindingInfo(M);
398 if (MayHaveImplicitBindings)
399 Changed |= replaceImplicitBindingCalls(M);
400 if (MayHaveHeapBindings)
401 Changed |= replaceHeapBindingCalls(M);
409 return SPIRVLegalizeResourceBindingImpl().runOnModule(M)
414char SPIRVLegalizeResourceBindingLegacy::ID = 0;
417 "legalize-spirv-resource-binding",
418 "Legalize SPIR-V resource bindings",
false,
false)
421 return new SPIRVLegalizeResourceBindingLegacy();
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.
Machine Check Debug Module
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
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...
void setCallingConv(CallingConv::ID CC)
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)
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
A Module instance is used to store all the information related to an LLVM module.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
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)
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
#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.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
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...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
void sort(IteratorTy Start, IteratorTy End)
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
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.
ModulePass * createSPIRVLegalizeResourceBindingPass()
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.