LLVM 22.0.0git
SPIRVLegalizeImplicitBinding.cpp
Go to the documentation of this file.
1//===- SPIRVLegalizeImplicitBinding.cpp - Legalize implicit 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
11// intrinsic by replacing it with a call to
12// @llvm.spv.resource.handlefrombinding.
13//
14//===----------------------------------------------------------------------===//
15
16#include "SPIRV.h"
17#include "llvm/ADT/BitVector.h"
19#include "llvm/IR/IRBuilder.h"
20#include "llvm/IR/InstVisitor.h"
21#include "llvm/IR/Intrinsics.h"
22#include "llvm/IR/IntrinsicsSPIRV.h"
23#include "llvm/IR/Module.h"
24#include "llvm/Pass.h"
25#include <algorithm>
26#include <vector>
27
28using namespace llvm;
29
30namespace {
31class SPIRVLegalizeImplicitBinding : public ModulePass {
32public:
33 static char ID;
34 SPIRVLegalizeImplicitBinding() : ModulePass(ID) {}
35
36 bool runOnModule(Module &M) override;
37
38private:
39 void collectBindingInfo(Module &M);
40 uint32_t getAndReserveFirstUnusedBinding(uint32_t DescSet);
41 void replaceImplicitBindingCalls(Module &M);
42 void verifyUniqueOrderIdPerResource(SmallVectorImpl<CallInst *> &Calls);
43
44 // A map from descriptor set to a bit vector of used binding numbers.
45 std::vector<BitVector> UsedBindings;
46 // A list of all implicit binding calls, to be sorted by order ID.
47 SmallVector<CallInst *, 16> ImplicitBindingCalls;
48};
49
50struct BindingInfoCollector : public InstVisitor<BindingInfoCollector> {
51 std::vector<BitVector> &UsedBindings;
52 SmallVector<CallInst *, 16> &ImplicitBindingCalls;
53
54 BindingInfoCollector(std::vector<BitVector> &UsedBindings,
55 SmallVector<CallInst *, 16> &ImplicitBindingCalls)
56 : UsedBindings(UsedBindings), ImplicitBindingCalls(ImplicitBindingCalls) {
57 }
58
59 void visitCallInst(CallInst &CI) {
60 if (CI.getIntrinsicID() == Intrinsic::spv_resource_handlefrombinding) {
61 const uint32_t DescSet =
62 cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
63 const uint32_t Binding =
64 cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
65
66 if (UsedBindings.size() <= DescSet) {
67 UsedBindings.resize(DescSet + 1);
68 UsedBindings[DescSet].resize(64);
69 }
70 if (UsedBindings[DescSet].size() <= Binding) {
71 UsedBindings[DescSet].resize(2 * Binding + 1);
72 }
73 UsedBindings[DescSet].set(Binding);
74 } else if (CI.getIntrinsicID() ==
75 Intrinsic::spv_resource_handlefromimplicitbinding) {
76 ImplicitBindingCalls.push_back(&CI);
77 }
78 }
79};
80
81void SPIRVLegalizeImplicitBinding::collectBindingInfo(Module &M) {
82 BindingInfoCollector InfoCollector(UsedBindings, ImplicitBindingCalls);
83 InfoCollector.visit(M);
84
85 // Sort the collected calls by their order ID.
86 std::sort(
87 ImplicitBindingCalls.begin(), ImplicitBindingCalls.end(),
88 [](const CallInst *A, const CallInst *B) {
89 const uint32_t OrderIdArgIdx = 0;
90 const uint32_t OrderA =
91 cast<ConstantInt>(A->getArgOperand(OrderIdArgIdx))->getZExtValue();
92 const uint32_t OrderB =
93 cast<ConstantInt>(B->getArgOperand(OrderIdArgIdx))->getZExtValue();
94 return OrderA < OrderB;
95 });
96}
97
98void SPIRVLegalizeImplicitBinding::verifyUniqueOrderIdPerResource(
99 SmallVectorImpl<CallInst *> &Calls) {
100 // Check that the order Id is unique per resource.
101 for (uint32_t i = 1; i < Calls.size(); ++i) {
102 const uint32_t OrderIdArgIdx = 0;
103 const uint32_t DescSetArgIdx = 1;
104 const uint32_t OrderA =
105 cast<ConstantInt>(Calls[i - 1]->getArgOperand(OrderIdArgIdx))
106 ->getZExtValue();
107 const uint32_t OrderB =
108 cast<ConstantInt>(Calls[i]->getArgOperand(OrderIdArgIdx))
109 ->getZExtValue();
110 if (OrderA == OrderB) {
111 const uint32_t DescSetA =
112 cast<ConstantInt>(Calls[i - 1]->getArgOperand(DescSetArgIdx))
113 ->getZExtValue();
114 const uint32_t DescSetB =
115 cast<ConstantInt>(Calls[i]->getArgOperand(DescSetArgIdx))
116 ->getZExtValue();
117 if (DescSetA != DescSetB) {
118 report_fatal_error("Implicit binding calls with the same order ID must "
119 "have the same descriptor set");
120 }
121 }
122 }
123}
124
125uint32_t SPIRVLegalizeImplicitBinding::getAndReserveFirstUnusedBinding(
126 uint32_t DescSet) {
127 if (UsedBindings.size() <= DescSet) {
128 UsedBindings.resize(DescSet + 1);
129 UsedBindings[DescSet].resize(64);
130 }
131
132 int NewBinding = UsedBindings[DescSet].find_first_unset();
133 if (NewBinding == -1) {
134 NewBinding = UsedBindings[DescSet].size();
135 UsedBindings[DescSet].resize(2 * NewBinding + 1);
136 }
137
138 UsedBindings[DescSet].set(NewBinding);
139 return NewBinding;
140}
141
142void SPIRVLegalizeImplicitBinding::replaceImplicitBindingCalls(Module &M) {
143 uint32_t lastOrderId = -1;
144 uint32_t lastBindingNumber = -1;
145
146 for (CallInst *OldCI : ImplicitBindingCalls) {
147 IRBuilder<> Builder(OldCI);
148 const uint32_t OrderId =
149 cast<ConstantInt>(OldCI->getArgOperand(0))->getZExtValue();
150 const uint32_t DescSet =
151 cast<ConstantInt>(OldCI->getArgOperand(1))->getZExtValue();
152
153 // Reuse an existing binding for this order ID, if one was already assigned.
154 // Otherwise, assign a new binding.
155 const uint32_t NewBinding = (lastOrderId == OrderId)
156 ? lastBindingNumber
157 : getAndReserveFirstUnusedBinding(DescSet);
158 lastOrderId = OrderId;
159 lastBindingNumber = NewBinding;
160
161 SmallVector<Value *, 8> Args;
162 Args.push_back(Builder.getInt32(DescSet));
163 Args.push_back(Builder.getInt32(NewBinding));
164
165 // Copy the remaining arguments from the old call.
166 for (uint32_t i = 2; i < OldCI->arg_size(); ++i) {
167 Args.push_back(OldCI->getArgOperand(i));
168 }
169
171 &M, Intrinsic::spv_resource_handlefrombinding, OldCI->getType());
172 CallInst *NewCI = Builder.CreateCall(NewFunc, Args);
173 NewCI->setCallingConv(OldCI->getCallingConv());
174
175 OldCI->replaceAllUsesWith(NewCI);
176 OldCI->eraseFromParent();
177 }
178}
179
180bool SPIRVLegalizeImplicitBinding::runOnModule(Module &M) {
181 collectBindingInfo(M);
182 if (ImplicitBindingCalls.empty()) {
183 return false;
184 }
185 verifyUniqueOrderIdPerResource(ImplicitBindingCalls);
186
187 replaceImplicitBindingCalls(M);
188 return true;
189}
190} // namespace
191
192char SPIRVLegalizeImplicitBinding::ID = 0;
193
194INITIALIZE_PASS(SPIRVLegalizeImplicitBinding, "legalize-spirv-implicit-binding",
195 "Legalize SPIR-V implicit bindings", false, false)
196
198 return new SPIRVLegalizeImplicitBinding();
199}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
This file implements the BitVector class.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
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)
Definition PassSupport.h:56
This file defines the SmallVector class.
void setCallingConv(CallingConv::ID CC)
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...
Base class for instruction visitors.
Definition InstVisitor.h:78
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:255
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
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:1657
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:167
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:560
ModulePass * createSPIRVLegalizeImplicitBindingPass()