Debian Codegraph @

third_party/spirv-tools/source/fuzz/transformation_replace_constant_with_uniform.cpp

raw
1 // Copyright (c) 2019 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "source/fuzz/transformation_replace_constant_with_uniform.h"
16
17 #include "source/fuzz/fuzzer_util.h"
18 #include "source/fuzz/uniform_buffer_element_descriptor.h"
19
20 namespace spvtools {
21 namespace fuzz {
22
23 TransformationReplaceConstantWithUniform::
24 TransformationReplaceConstantWithUniform(
25 const spvtools::fuzz::protobufs::
26 TransformationReplaceConstantWithUniform& message)
27 : message_(message) {}
28
29 TransformationReplaceConstantWithUniform::
30 TransformationReplaceConstantWithUniform(
31 protobufs::IdUseDescriptor id_use,
32 protobufs::UniformBufferElementDescriptor uniform_descriptor,
33 uint32_t fresh_id_for_access_chain, uint32_t fresh_id_for_load) {
34 *message_.mutable_id_use_descriptor() = std::move(id_use);
35 *message_.mutable_uniform_descriptor() = std::move(uniform_descriptor);
36 message_.set_fresh_id_for_access_chain(fresh_id_for_access_chain);
37 message_.set_fresh_id_for_load(fresh_id_for_load);
38 }
39
40 std::unique_ptr<opt::Instruction>
41 TransformationReplaceConstantWithUniform::MakeAccessChainInstruction(
42 spvtools::opt::IRContext* ir_context, uint32_t constant_type_id) const {
43 // The input operands for the access chain.
44 opt::Instruction::OperandList operands_for_access_chain;
45
46 opt::Instruction* uniform_variable =
47 FindUniformVariable(message_.uniform_descriptor(), ir_context, false);
48
49 // The first input operand is the id of the uniform variable.
50 operands_for_access_chain.push_back(
51 {SPV_OPERAND_TYPE_ID, {uniform_variable->result_id()}});
52
53 // The other input operands are the ids of the constants used to index into
54 // the uniform. The uniform buffer descriptor specifies a series of literals;
55 // for each we find the id of the instruction that defines it, and add these
56 // instruction ids as operands.
57 opt::analysis::Integer int_type(32, true);
58 auto registered_int_type =
59 ir_context->get_type_mgr()->GetRegisteredType(&int_type)->AsInteger();
60 auto int_type_id = ir_context->get_type_mgr()->GetId(&int_type);
61 for (auto index : message_.uniform_descriptor().index()) {
62 opt::analysis::IntConstant int_constant(registered_int_type, {index});
63 auto constant_id = ir_context->get_constant_mgr()->FindDeclaredConstant(
64 &int_constant, int_type_id);
65 operands_for_access_chain.push_back({SPV_OPERAND_TYPE_ID, {constant_id}});
66 }
67
68 // The type id for the access chain is a uniform pointer with base type
69 // matching the given constant id type.
70 auto type_and_pointer_type =
71 ir_context->get_type_mgr()->GetTypeAndPointerType(constant_type_id,
72 SpvStorageClassUniform);
73 assert(type_and_pointer_type.first != nullptr);
74 assert(type_and_pointer_type.second != nullptr);
75 auto pointer_to_uniform_constant_type_id =
76 ir_context->get_type_mgr()->GetId(type_and_pointer_type.second.get());
77
78 return MakeUnique<opt::Instruction>(
79 ir_context, SpvOpAccessChain, pointer_to_uniform_constant_type_id,
80 message_.fresh_id_for_access_chain(), operands_for_access_chain);
81 }
82
83 std::unique_ptr<opt::Instruction>
84 TransformationReplaceConstantWithUniform::MakeLoadInstruction(
85 spvtools::opt::IRContext* ir_context, uint32_t constant_type_id) const {
86 opt::Instruction::OperandList operands_for_load = {
87 {SPV_OPERAND_TYPE_ID, {message_.fresh_id_for_access_chain()}}};
88 return MakeUnique<opt::Instruction>(ir_context, SpvOpLoad, constant_type_id,
89 message_.fresh_id_for_load(),
90 operands_for_load);
91 }
92
93 opt::Instruction*
94 TransformationReplaceConstantWithUniform::GetInsertBeforeInstruction(
95 opt::IRContext* ir_context) const {
96 auto* result =
97 FindInstructionContainingUse(message_.id_use_descriptor(), ir_context);
98 if (!result) {
99 return nullptr;
100 }
101
102 // The use might be in an OpPhi instruction.
103 if (result->opcode() == SpvOpPhi) {
104 // OpPhi instructions must be the first instructions in a block. Thus, we
105 // can't insert above the OpPhi instruction. Given the predecessor block
106 // that corresponds to the id use, get the last instruction in that block
107 // above which we can insert OpAccessChain and OpLoad.
108 return fuzzerutil::GetLastInsertBeforeInstruction(
109 ir_context,
110 result->GetSingleWordInOperand(
111 message_.id_use_descriptor().in_operand_index() + 1),
112 SpvOpLoad);
113 }
114
115 // The only operand that we could've replaced in the OpBranchConditional is
116 // the condition id. But that operand has a boolean type and uniform variables
117 // can't store booleans (see the spec on OpTypeBool). Thus, |result| can't be
118 // an OpBranchConditional.
119 assert(result->opcode() != SpvOpBranchConditional &&
120 "OpBranchConditional has no operands to replace");
121
122 assert(fuzzerutil::CanInsertOpcodeBeforeInstruction(SpvOpLoad, result) &&
123 "We should be able to insert OpLoad and OpAccessChain at this point");
124 return result;
125 }
126
127 bool TransformationReplaceConstantWithUniform::IsApplicable(
128 opt::IRContext* ir_context,
129 const TransformationContext& transformation_context) const {
130 // The following is really an invariant of the transformation rather than
131 // merely a requirement of the precondition. We check it here since we cannot
132 // check it in the message_ constructor.
133 assert(message_.fresh_id_for_access_chain() != message_.fresh_id_for_load() &&
134 "Fresh ids for access chain and load result cannot be the same.");
135
136 // The ids for the access chain and load instructions must both be fresh.
137 if (!fuzzerutil::IsFreshId(ir_context,
138 message_.fresh_id_for_access_chain())) {
139 return false;
140 }
141 if (!fuzzerutil::IsFreshId(ir_context, message_.fresh_id_for_load())) {
142 return false;
143 }
144
145 // The id specified in the id use descriptor must be that of a declared scalar
146 // constant.
147 auto declared_constant = ir_context->get_constant_mgr()->FindDeclaredConstant(
148 message_.id_use_descriptor().id_of_interest());
149 if (!declared_constant) {
150 return false;
151 }
152 if (!declared_constant->AsScalarConstant()) {
153 return false;
154 }
155
156 // The fact manager needs to believe that the uniform data element described
157 // by the uniform buffer element descriptor will hold a scalar value.
158 auto constant_id_associated_with_uniform =
159 transformation_context.GetFactManager()->GetConstantFromUniformDescriptor(
160 message_.uniform_descriptor());
161 if (!constant_id_associated_with_uniform) {
162 return false;
163 }
164 auto constant_associated_with_uniform =
165 ir_context->get_constant_mgr()->FindDeclaredConstant(
166 constant_id_associated_with_uniform);
167 assert(constant_associated_with_uniform &&
168 "The constant should be present in the module.");
169 if (!constant_associated_with_uniform->AsScalarConstant()) {
170 return false;
171 }
172
173 // The types and values of the scalar value held in the id specified by the id
174 // use descriptor and in the uniform data element specified by the uniform
175 // buffer element descriptor need to match on both type and value.
176 if (!declared_constant->type()->IsSame(
177 constant_associated_with_uniform->type())) {
178 return false;
179 }
180 if (declared_constant->AsScalarConstant()->words() !=
181 constant_associated_with_uniform->AsScalarConstant()->words()) {
182 return false;
183 }
184
185 // The id use descriptor must identify some instruction with respect to the
186 // module.
187 auto instruction_using_constant =
188 FindInstructionContainingUse(message_.id_use_descriptor(), ir_context);
189 if (!instruction_using_constant) {
190 return false;
191 }
192
193 // The use must not be a variable initializer; these are required to be
194 // constants, so it would be illegal to replace one with a uniform access.
195 if (instruction_using_constant->opcode() == SpvOpVariable) {
196 return false;
197 }
198
199 // The module needs to have a uniform pointer type suitable for indexing into
200 // the uniform variable, i.e. matching the type of the constant we wish to
201 // replace with a uniform.
202 opt::analysis::Pointer pointer_to_type_of_constant(declared_constant->type(),
203 SpvStorageClassUniform);
204 if (!ir_context->get_type_mgr()->GetId(&pointer_to_type_of_constant)) {
205 return false;
206 }
207
208 // In order to index into the uniform, the module has got to contain the int32
209 // type, plus an OpConstant for each of the indices of interest.
210 opt::analysis::Integer int_type(32, true);
211 if (!ir_context->get_type_mgr()->GetId(&int_type)) {
212 return false;
213 }
214 auto registered_int_type =
215 ir_context->get_type_mgr()->GetRegisteredType(&int_type)->AsInteger();
216 auto int_type_id = ir_context->get_type_mgr()->GetId(&int_type);
217 for (auto index : message_.uniform_descriptor().index()) {
218 opt::analysis::IntConstant int_constant(registered_int_type, {index});
219 if (!ir_context->get_constant_mgr()->FindDeclaredConstant(&int_constant,
220 int_type_id)) {
221 return false;
222 }
223 }
224
225 // Once all checks are completed, we should be able to safely insert
226 // OpAccessChain and OpLoad into the module.
227 assert(GetInsertBeforeInstruction(ir_context) &&
228 "There must exist an instruction that we can use to insert "
229 "OpAccessChain and OpLoad above");
230
231 return true;
232 }
233
234 void TransformationReplaceConstantWithUniform::Apply(
235 spvtools::opt::IRContext* ir_context,
236 TransformationContext* /*unused*/) const {
237 // Get the instruction that contains the id use we wish to replace.
238 auto* instruction_containing_constant_use =
239 FindInstructionContainingUse(message_.id_use_descriptor(), ir_context);
240 assert(instruction_containing_constant_use &&
241 "Precondition requires that the id use can be found.");
242 assert(instruction_containing_constant_use->GetSingleWordInOperand(
243 message_.id_use_descriptor().in_operand_index()) ==
244 message_.id_use_descriptor().id_of_interest() &&
245 "Does not appear to be a usage of the desired id.");
246
247 // The id of the type for the constant whose use we wish to replace.
248 auto constant_type_id =
249 ir_context->get_def_use_mgr()
250 ->GetDef(message_.id_use_descriptor().id_of_interest())
251 ->type_id();
252
253 // Get an instruction that will be used to insert OpAccessChain and OpLoad.
254 auto* insert_before_inst = GetInsertBeforeInstruction(ir_context);
255 assert(insert_before_inst &&
256 "There must exist an insertion point for OpAccessChain and OpLoad");
257
258 // Add an access chain instruction to target the uniform element.
259 insert_before_inst->InsertBefore(
260 MakeAccessChainInstruction(ir_context, constant_type_id));
261
262 // Add a load from this access chain.
263 insert_before_inst->InsertBefore(
264 MakeLoadInstruction(ir_context, constant_type_id));
265
266 // Adjust the instruction containing the usage of the constant so that this
267 // usage refers instead to the result of the load.
268 instruction_containing_constant_use->SetInOperand(
269 message_.id_use_descriptor().in_operand_index(),
270 {message_.fresh_id_for_load()});
271
272 // Update the module id bound to reflect the new instructions.
273 fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id_for_load());
274 fuzzerutil::UpdateModuleIdBound(ir_context,
275 message_.fresh_id_for_access_chain());
276
277 ir_context->InvalidateAnalysesExceptFor(
278 opt::IRContext::Analysis::kAnalysisNone);
279 }
280
281 protobufs::Transformation TransformationReplaceConstantWithUniform::ToMessage()
282 const {
283 protobufs::Transformation result;
284 *result.mutable_replace_constant_with_uniform() = message_;
285 return result;
286 }
287
288 std::unordered_set<uint32_t>
289 TransformationReplaceConstantWithUniform::GetFreshIds() const {
290 return {message_.fresh_id_for_access_chain(), message_.fresh_id_for_load()};
291 }
292
293 } // namespace fuzz
294 } // namespace spvtools