• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #ifndef SOURCE_FUZZ_FUZZER_UTIL_H_
16 #define SOURCE_FUZZ_FUZZER_UTIL_H_
17 
18 #include <iostream>
19 #include <map>
20 #include <vector>
21 
22 #include "source/fuzz/protobufs/spirvfuzz_protobufs.h"
23 #include "source/fuzz/transformation_context.h"
24 #include "source/opt/basic_block.h"
25 #include "source/opt/instruction.h"
26 #include "source/opt/ir_context.h"
27 #include "source/opt/module.h"
28 #include "spirv-tools/libspirv.hpp"
29 
30 namespace spvtools {
31 namespace fuzz {
32 
33 // Provides types and global utility methods for use by the fuzzer
34 namespace fuzzerutil {
35 
36 // A silent message consumer.
37 extern const spvtools::MessageConsumer kSilentMessageConsumer;
38 
39 // Function type that produces a SPIR-V module.
40 using ModuleSupplier = std::function<std::unique_ptr<opt::IRContext>()>;
41 
42 // Builds a new opt::IRContext object. Returns true if successful and changes
43 // the |ir_context| parameter. Otherwise (if any errors occur), returns false
44 // and |ir_context| remains unchanged.
45 bool BuildIRContext(spv_target_env target_env,
46                     const spvtools::MessageConsumer& message_consumer,
47                     const std::vector<uint32_t>& binary_in,
48                     spv_validator_options validator_options,
49                     std::unique_ptr<spvtools::opt::IRContext>* ir_context);
50 
51 // Returns true if and only if the module does not define the given id.
52 bool IsFreshId(opt::IRContext* context, uint32_t id);
53 
54 // Updates the module's id bound if needed so that it is large enough to
55 // account for the given id.
56 void UpdateModuleIdBound(opt::IRContext* context, uint32_t id);
57 
58 // Return the block with id |maybe_block_id| if it exists, and nullptr
59 // otherwise.
60 opt::BasicBlock* MaybeFindBlock(opt::IRContext* context,
61                                 uint32_t maybe_block_id);
62 
63 // When adding an edge from |bb_from| to |bb_to| (which are assumed to be blocks
64 // in the same function), it is important to supply |bb_to| with ids that can be
65 // used to augment OpPhi instructions in the case that there is not already such
66 // an edge.  This function returns true if and only if the ids provided in
67 // |phi_ids| suffice for this purpose,
68 bool PhiIdsOkForNewEdge(
69     opt::IRContext* context, opt::BasicBlock* bb_from, opt::BasicBlock* bb_to,
70     const google::protobuf::RepeatedField<google::protobuf::uint32>& phi_ids);
71 
72 // Returns an OpBranchConditional instruction that will create an unreachable
73 // branch from |bb_from_id| to |bb_to_id|. |bool_id| must be a result id of
74 // either OpConstantTrue or OpConstantFalse. Based on the opcode of |bool_id|,
75 // operands of the returned instruction will be positioned in a way that the
76 // branch from |bb_from_id| to |bb_to_id| is always unreachable.
77 opt::Instruction CreateUnreachableEdgeInstruction(opt::IRContext* ir_context,
78                                                   uint32_t bb_from_id,
79                                                   uint32_t bb_to_id,
80                                                   uint32_t bool_id);
81 
82 // Requires that |bool_id| is a valid result id of either OpConstantTrue or
83 // OpConstantFalse, that PhiIdsOkForNewEdge(context, bb_from, bb_to, phi_ids)
84 // holds, and that bb_from ends with "OpBranch %some_block".  Turns OpBranch
85 // into "OpBranchConditional |condition_value| ...", such that control will
86 // branch to %some_block, with |bb_to| being the unreachable alternative.
87 // Updates OpPhi instructions in |bb_to| using |phi_ids| so that the new edge is
88 // valid. |condition_value| above is equal to |true| if |bool_id| is a result id
89 // of an OpConstantTrue instruction.
90 void AddUnreachableEdgeAndUpdateOpPhis(
91     opt::IRContext* context, opt::BasicBlock* bb_from, opt::BasicBlock* bb_to,
92     uint32_t bool_id,
93     const google::protobuf::RepeatedField<google::protobuf::uint32>& phi_ids);
94 
95 // Returns true if and only if |loop_header_id| is a loop header and
96 // |block_id| is a reachable block branching to and dominated by
97 // |loop_header_id|.
98 bool BlockIsBackEdge(opt::IRContext* context, uint32_t block_id,
99                      uint32_t loop_header_id);
100 
101 // Returns true if and only if |maybe_loop_header_id| is a loop header and
102 // |block_id| is in the continue construct of the associated loop.
103 bool BlockIsInLoopContinueConstruct(opt::IRContext* context, uint32_t block_id,
104                                     uint32_t maybe_loop_header_id);
105 
106 // If |block| contains |inst|, an iterator for |inst| is returned.
107 // Otherwise |block|->end() is returned.
108 opt::BasicBlock::iterator GetIteratorForInstruction(
109     opt::BasicBlock* block, const opt::Instruction* inst);
110 
111 // Determines whether it is OK to insert an instruction with opcode |opcode|
112 // before |instruction_in_block|.
113 bool CanInsertOpcodeBeforeInstruction(
114     SpvOp opcode, const opt::BasicBlock::iterator& instruction_in_block);
115 
116 // Determines whether it is OK to make a synonym of |inst|.
117 // |transformation_context| is used to verify that the result id of |inst|
118 // does not participate in IdIsIrrelevant fact.
119 bool CanMakeSynonymOf(opt::IRContext* ir_context,
120                       const TransformationContext& transformation_context,
121                       opt::Instruction* inst);
122 
123 // Determines whether the given type is a composite; that is: an array, matrix,
124 // struct or vector.
125 bool IsCompositeType(const opt::analysis::Type* type);
126 
127 // Returns a vector containing the same elements as |repeated_field|.
128 std::vector<uint32_t> RepeatedFieldToVector(
129     const google::protobuf::RepeatedField<uint32_t>& repeated_field);
130 
131 // Given a type id, |base_object_type_id|, returns 0 if the type is not a
132 // composite type or if |index| is too large to be used as an index into the
133 // composite.  Otherwise returns the type id of the type associated with the
134 // composite's index.
135 //
136 // Example: if |base_object_type_id| is 10, and we have:
137 //
138 // %10 = OpTypeStruct %3 %4 %5
139 //
140 // then 3 will be returned if |index| is 0, 5 if |index| is 2, and 0 if index
141 // is 3 or larger.
142 uint32_t WalkOneCompositeTypeIndex(opt::IRContext* context,
143                                    uint32_t base_object_type_id,
144                                    uint32_t index);
145 
146 // Given a type id, |base_object_type_id|, checks that the given sequence of
147 // |indices| is suitable for indexing into this type.  Returns the id of the
148 // type of the final sub-object reached via the indices if they are valid, and
149 // 0 otherwise.
150 uint32_t WalkCompositeTypeIndices(
151     opt::IRContext* context, uint32_t base_object_type_id,
152     const google::protobuf::RepeatedField<google::protobuf::uint32>& indices);
153 
154 // Returns the number of members associated with |struct_type_instruction|,
155 // which must be an OpStructType instruction.
156 uint32_t GetNumberOfStructMembers(
157     const opt::Instruction& struct_type_instruction);
158 
159 // Returns the constant size of the array associated with
160 // |array_type_instruction|, which must be an OpArrayType instruction. Returns
161 // 0 if there is not a static size.
162 uint32_t GetArraySize(const opt::Instruction& array_type_instruction,
163                       opt::IRContext* context);
164 
165 // Returns the bound for indexing into a composite of type
166 // |composite_type_inst|, i.e. the number of fields of a struct, the size of an
167 // array, the number of components of a vector, or the number of columns of a
168 // matrix. |composite_type_inst| must be the type of a composite.
169 uint32_t GetBoundForCompositeIndex(const opt::Instruction& composite_type_inst,
170                                    opt::IRContext* ir_context);
171 
172 // Returns true if and only if |context| is valid, according to the validator
173 // instantiated with |validator_options|.  |consumer| is used for error
174 // reporting.
175 bool IsValid(const opt::IRContext* context,
176              spv_validator_options validator_options, MessageConsumer consumer);
177 
178 // Returns true if and only if IsValid(|context|, |validator_options|) holds,
179 // and furthermore every basic block in |context| has its enclosing function as
180 // its parent, and every instruction in |context| has a distinct unique id.
181 // |consumer| is used for error reporting.
182 bool IsValidAndWellFormed(const opt::IRContext* context,
183                           spv_validator_options validator_options,
184                           MessageConsumer consumer);
185 
186 // Returns a clone of |context|, by writing |context| to a binary and then
187 // parsing it again.
188 std::unique_ptr<opt::IRContext> CloneIRContext(opt::IRContext* context);
189 
190 // Returns true if and only if |id| is the id of a type that is not a function
191 // type.
192 bool IsNonFunctionTypeId(opt::IRContext* ir_context, uint32_t id);
193 
194 // Returns true if and only if |block_id| is a merge block or continue target
195 bool IsMergeOrContinue(opt::IRContext* ir_context, uint32_t block_id);
196 
197 // Returns the id of the header of the loop corresponding to the given loop
198 // merge block. Returns 0 if |merge_block_id| is not a loop merge block.
199 uint32_t GetLoopFromMergeBlock(opt::IRContext* ir_context,
200                                uint32_t merge_block_id);
201 
202 // Returns the result id of an instruction of the form:
203 //  %id = OpTypeFunction |type_ids|
204 // or 0 if no such instruction exists.
205 uint32_t FindFunctionType(opt::IRContext* ir_context,
206                           const std::vector<uint32_t>& type_ids);
207 
208 // Returns a type instruction (OpTypeFunction) for |function|.
209 // Returns |nullptr| if type is not found.
210 opt::Instruction* GetFunctionType(opt::IRContext* context,
211                                   const opt::Function* function);
212 
213 // Returns the function with result id |function_id|, or |nullptr| if no such
214 // function exists.
215 opt::Function* FindFunction(opt::IRContext* ir_context, uint32_t function_id);
216 
217 // Returns true if |function| has a block that the termination instruction is
218 // OpKill or OpUnreachable.
219 bool FunctionContainsOpKillOrUnreachable(const opt::Function& function);
220 
221 // Returns |true| if one of entry points has function id |function_id|.
222 bool FunctionIsEntryPoint(opt::IRContext* context, uint32_t function_id);
223 
224 // Checks whether |id| is available (according to dominance rules) at the use
225 // point defined by input operand |use_input_operand_index| of
226 // |use_instruction|. |use_instruction| must be a in some basic block.
227 bool IdIsAvailableAtUse(opt::IRContext* context,
228                         opt::Instruction* use_instruction,
229                         uint32_t use_input_operand_index, uint32_t id);
230 
231 // Checks whether |id| is available (according to dominance rules) at the
232 // program point directly before |instruction|. |instruction| must be in some
233 // basic block.
234 bool IdIsAvailableBeforeInstruction(opt::IRContext* context,
235                                     opt::Instruction* instruction, uint32_t id);
236 
237 // Returns true if and only if |instruction| is an OpFunctionParameter
238 // associated with |function|.
239 bool InstructionIsFunctionParameter(opt::Instruction* instruction,
240                                     opt::Function* function);
241 
242 // Returns the type id of the instruction defined by |result_id|, or 0 if there
243 // is no such result id.
244 uint32_t GetTypeId(opt::IRContext* context, uint32_t result_id);
245 
246 // Given |pointer_type_inst|, which must be an OpTypePointer instruction,
247 // returns the id of the associated pointee type.
248 uint32_t GetPointeeTypeIdFromPointerType(opt::Instruction* pointer_type_inst);
249 
250 // Given |pointer_type_id|, which must be the id of a pointer type, returns the
251 // id of the associated pointee type.
252 uint32_t GetPointeeTypeIdFromPointerType(opt::IRContext* context,
253                                          uint32_t pointer_type_id);
254 
255 // Given |pointer_type_inst|, which must be an OpTypePointer instruction,
256 // returns the associated storage class.
257 SpvStorageClass GetStorageClassFromPointerType(
258     opt::Instruction* pointer_type_inst);
259 
260 // Given |pointer_type_id|, which must be the id of a pointer type, returns the
261 // associated storage class.
262 SpvStorageClass GetStorageClassFromPointerType(opt::IRContext* context,
263                                                uint32_t pointer_type_id);
264 
265 // Returns the id of a pointer with pointee type |pointee_type_id| and storage
266 // class |storage_class|, if it exists, and 0 otherwise.
267 uint32_t MaybeGetPointerType(opt::IRContext* context, uint32_t pointee_type_id,
268                              SpvStorageClass storage_class);
269 
270 // Given an instruction |inst| and an operand absolute index |absolute_index|,
271 // returns the index of the operand restricted to the input operands.
272 uint32_t InOperandIndexFromOperandIndex(const opt::Instruction& inst,
273                                         uint32_t absolute_index);
274 
275 // Returns true if and only if |type| is one of the types for which it is legal
276 // to have an OpConstantNull value.
277 bool IsNullConstantSupported(const opt::analysis::Type& type);
278 
279 // Returns true if and only if the SPIR-V version being used requires that
280 // global variables accessed in the static call graph of an entry point need
281 // to be listed in that entry point's interface.
282 bool GlobalVariablesMustBeDeclaredInEntryPointInterfaces(
283     const opt::IRContext* context);
284 
285 // Adds |id| into the interface of every entry point of the shader.
286 // Does nothing if SPIR-V doesn't require global variables, that are accessed
287 // from an entry point function, to be listed in that function's interface.
288 void AddVariableIdToEntryPointInterfaces(opt::IRContext* context, uint32_t id);
289 
290 // Adds a global variable with storage class |storage_class| to the module, with
291 // type |type_id| and either no initializer or |initializer_id| as an
292 // initializer, depending on whether |initializer_id| is 0. The global variable
293 // has result id |result_id|. Updates module's id bound to accommodate for
294 // |result_id|.
295 //
296 // - |type_id| must be the id of a pointer type with the same storage class as
297 //   |storage_class|.
298 // - |storage_class| must be Private or Workgroup.
299 // - |initializer_id| must be 0 if |storage_class| is Workgroup, and otherwise
300 //   may either be 0 or the id of a constant whose type is the pointee type of
301 //   |type_id|.
302 //
303 // Returns a pointer to the new global variable instruction.
304 opt::Instruction* AddGlobalVariable(opt::IRContext* context, uint32_t result_id,
305                                     uint32_t type_id,
306                                     SpvStorageClass storage_class,
307                                     uint32_t initializer_id);
308 
309 // Adds an instruction to the start of |function_id|, of the form:
310 //   |result_id| = OpVariable |type_id| Function |initializer_id|.
311 // Updates module's id bound to accommodate for |result_id|.
312 //
313 // - |type_id| must be the id of a pointer type with Function storage class.
314 // - |initializer_id| must be the id of a constant with the same type as the
315 //   pointer's pointee type.
316 // - |function_id| must be the id of a function.
317 //
318 // Returns a pointer to the new local variable instruction.
319 opt::Instruction* AddLocalVariable(opt::IRContext* context, uint32_t result_id,
320                                    uint32_t type_id, uint32_t function_id,
321                                    uint32_t initializer_id);
322 
323 // Returns true if the vector |arr| has duplicates.
324 bool HasDuplicates(const std::vector<uint32_t>& arr);
325 
326 // Checks that the given vector |arr| contains a permutation of a range
327 // [lo, hi]. That being said, all elements in the range are present without
328 // duplicates. If |arr| is empty, returns true iff |lo > hi|.
329 bool IsPermutationOfRange(const std::vector<uint32_t>& arr, uint32_t lo,
330                           uint32_t hi);
331 
332 // Returns OpFunctionParameter instructions corresponding to the function
333 // with result id |function_id|.
334 std::vector<opt::Instruction*> GetParameters(opt::IRContext* ir_context,
335                                              uint32_t function_id);
336 
337 // Removes an OpFunctionParameter instruction with result id |parameter_id|
338 // from the its function. Parameter's function must not be an entry-point
339 // function. The function must have a parameter with result id |parameter_id|.
340 //
341 // Prefer using this function to opt::Function::RemoveParameter since
342 // this function also guarantees that |ir_context| has no invalid pointers
343 // to the removed parameter.
344 void RemoveParameter(opt::IRContext* ir_context, uint32_t parameter_id);
345 
346 // Returns all OpFunctionCall instructions that call a function with result id
347 // |function_id|.
348 std::vector<opt::Instruction*> GetCallers(opt::IRContext* ir_context,
349                                           uint32_t function_id);
350 
351 // Returns a function that contains OpFunctionParameter instruction with result
352 // id |param_id|. Returns nullptr if the module has no such function.
353 opt::Function* GetFunctionFromParameterId(opt::IRContext* ir_context,
354                                           uint32_t param_id);
355 
356 // Changes the type of function |function_id| so that its return type is
357 // |return_type_id| and its parameters' types are |parameter_type_ids|. If a
358 // suitable function type already exists in the module, it is used, otherwise
359 // |new_function_type_result_id| is used as the result id of a suitable new
360 // function type instruction. If the old type of the function doesn't have any
361 // more users, it is removed from the module. Returns the result id of the
362 // OpTypeFunction instruction that is used as a type of the function with
363 // |function_id|.
364 //
365 // CAUTION: When the old type of the function is removed from the module, its
366 //          memory is deallocated. Be sure not to use any pointers to the old
367 //          type when this function returns.
368 uint32_t UpdateFunctionType(opt::IRContext* ir_context, uint32_t function_id,
369                             uint32_t new_function_type_result_id,
370                             uint32_t return_type_id,
371                             const std::vector<uint32_t>& parameter_type_ids);
372 
373 // Creates new OpTypeFunction instruction in the module. |type_ids| may not be
374 // empty. It may not contain result ids of OpTypeFunction instructions.
375 // |type_ids[i]| may not be a result id of OpTypeVoid instruction for |i >= 1|.
376 // |result_id| may not equal to 0. Updates module's id bound to accommodate for
377 // |result_id|.
378 void AddFunctionType(opt::IRContext* ir_context, uint32_t result_id,
379                      const std::vector<uint32_t>& type_ids);
380 
381 // Returns a result id of an OpTypeFunction instruction in the module. Creates a
382 // new instruction if required and returns |result_id|. type_ids| may not be
383 // empty. It may not contain result ids of OpTypeFunction instructions.
384 // |type_ids[i]| may not be a result id of OpTypeVoid instruction for |i >= 1|.
385 // |result_id| must not be equal to 0. Updates module's id bound to accommodate
386 // for |result_id|.
387 uint32_t FindOrCreateFunctionType(opt::IRContext* ir_context,
388                                   uint32_t result_id,
389                                   const std::vector<uint32_t>& type_ids);
390 
391 // Returns a result id of an OpTypeInt instruction if present. Returns 0
392 // otherwise.
393 uint32_t MaybeGetIntegerType(opt::IRContext* ir_context, uint32_t width,
394                              bool is_signed);
395 
396 // Returns a result id of an OpTypeFloat instruction if present. Returns 0
397 // otherwise.
398 uint32_t MaybeGetFloatType(opt::IRContext* ir_context, uint32_t width);
399 
400 // Returns a result id of an OpTypeBool instruction if present. Returns 0
401 // otherwise.
402 uint32_t MaybeGetBoolType(opt::IRContext* ir_context);
403 
404 // Returns a result id of an OpTypeVector instruction if present. Returns 0
405 // otherwise. |component_type_id| must be a valid result id of an OpTypeInt,
406 // OpTypeFloat or OpTypeBool instruction in the module. |element_count| must be
407 // in the range [2, 4].
408 uint32_t MaybeGetVectorType(opt::IRContext* ir_context,
409                             uint32_t component_type_id, uint32_t element_count);
410 
411 // Returns a result id of an OpTypeStruct instruction whose field types exactly
412 // match |component_type_ids| if such an instruction is present. Returns 0
413 // otherwise. |component_type_ids| may not contain a result id of an
414 // OpTypeFunction.
415 uint32_t MaybeGetStructType(opt::IRContext* ir_context,
416                             const std::vector<uint32_t>& component_type_ids);
417 
418 // Returns a result id of an OpTypeVoid instruction if present. Returns 0
419 // otherwise.
420 uint32_t MaybeGetVoidType(opt::IRContext* ir_context);
421 
422 // Recursive definition is the following:
423 // - if |scalar_or_composite_type_id| is a result id of a scalar type - returns
424 //   a result id of the following constants (depending on the type): int -> 0,
425 //   float -> 0.0, bool -> false.
426 // - otherwise, returns a result id of an OpConstantComposite instruction.
427 //   Every component of the composite constant is looked up by calling this
428 //   function with the type id of that component.
429 // Returns 0 if no such instruction is present in the module.
430 // The returned id either participates in IdIsIrrelevant fact or not, depending
431 // on the |is_irrelevant| parameter.
432 uint32_t MaybeGetZeroConstant(
433     opt::IRContext* ir_context,
434     const TransformationContext& transformation_context,
435     uint32_t scalar_or_composite_type_id, bool is_irrelevant);
436 
437 // Returns true if it is possible to create an OpConstant or an
438 // OpConstantComposite instruction of type |type_id|. That is, returns true if
439 // the type associated with |type_id| and all its constituents are either scalar
440 // or composite.
441 bool CanCreateConstant(opt::IRContext* ir_context, uint32_t type_id);
442 
443 // Returns the result id of an OpConstant instruction. |scalar_type_id| must be
444 // a result id of a scalar type (i.e. int, float or bool). Returns 0 if no such
445 // instruction is present in the module. The returned id either participates in
446 // IdIsIrrelevant fact or not, depending on the |is_irrelevant| parameter.
447 uint32_t MaybeGetScalarConstant(
448     opt::IRContext* ir_context,
449     const TransformationContext& transformation_context,
450     const std::vector<uint32_t>& words, uint32_t scalar_type_id,
451     bool is_irrelevant);
452 
453 // Returns the result id of an OpConstantComposite instruction.
454 // |composite_type_id| must be a result id of a composite type (i.e. vector,
455 // matrix, struct or array). Returns 0 if no such instruction is present in the
456 // module. The returned id either participates in IdIsIrrelevant fact or not,
457 // depending on the |is_irrelevant| parameter.
458 uint32_t MaybeGetCompositeConstant(
459     opt::IRContext* ir_context,
460     const TransformationContext& transformation_context,
461     const std::vector<uint32_t>& component_ids, uint32_t composite_type_id,
462     bool is_irrelevant);
463 
464 // Returns the result id of an OpConstant instruction of integral type.
465 // Returns 0 if no such instruction or type is present in the module.
466 // The returned id either participates in IdIsIrrelevant fact or not, depending
467 // on the |is_irrelevant| parameter.
468 uint32_t MaybeGetIntegerConstant(
469     opt::IRContext* ir_context,
470     const TransformationContext& transformation_context,
471     const std::vector<uint32_t>& words, uint32_t width, bool is_signed,
472     bool is_irrelevant);
473 
474 // Returns the id of a 32-bit integer constant in the module with type
475 // |int_type_id| and value |value|, or 0 if no such constant exists in the
476 // module. |int_type_id| must exist in the module and it must correspond to a
477 // 32-bit integer type.
478 uint32_t MaybeGetIntegerConstantFromValueAndType(opt::IRContext* ir_context,
479                                                  uint32_t value,
480                                                  uint32_t int_type_id);
481 
482 // Returns the result id of an OpConstant instruction of floating-point type.
483 // Returns 0 if no such instruction or type is present in the module.
484 // The returned id either participates in IdIsIrrelevant fact or not, depending
485 // on the |is_irrelevant| parameter.
486 uint32_t MaybeGetFloatConstant(
487     opt::IRContext* ir_context,
488     const TransformationContext& transformation_context,
489     const std::vector<uint32_t>& words, uint32_t width, bool is_irrelevant);
490 
491 // Returns the id of a boolean constant with value |value| if it exists in the
492 // module, or 0 otherwise. The returned id either participates in IdIsIrrelevant
493 // fact or not, depending on the |is_irrelevant| parameter.
494 uint32_t MaybeGetBoolConstant(
495     opt::IRContext* context,
496     const TransformationContext& transformation_context, bool value,
497     bool is_irrelevant);
498 
499 // Returns a vector of words representing the integer |value|, only considering
500 // the last |width| bits. The last |width| bits are sign-extended if the value
501 // is signed, zero-extended if it is unsigned.
502 // |width| must be <= 64.
503 // If |width| <= 32, returns a vector containing one value. If |width| > 64,
504 // returns a vector containing two values, with the first one representing the
505 // lower-order word of the value and the second one representing the
506 // higher-order word.
507 std::vector<uint32_t> IntToWords(uint64_t value, uint32_t width,
508                                  bool is_signed);
509 
510 // Returns a bit pattern that represents a floating-point |value|.
FloatToWord(float value)511 inline uint32_t FloatToWord(float value) {
512   uint32_t result;
513   memcpy(&result, &value, sizeof(uint32_t));
514   return result;
515 }
516 
517 // Returns true if any of the following is true:
518 // - |type1_id| and |type2_id| are the same id
519 // - |type1_id| and |type2_id| refer to integer scalar or vector types, only
520 //   differing by their signedness.
521 bool TypesAreEqualUpToSign(opt::IRContext* ir_context, uint32_t type1_id,
522                            uint32_t type2_id);
523 
524 // Converts repeated field of UInt32Pair to a map. If two or more equal values
525 // of |UInt32Pair::first()| are available in |data|, the last value of
526 // |UInt32Pair::second()| is used.
527 std::map<uint32_t, uint32_t> RepeatedUInt32PairToMap(
528     const google::protobuf::RepeatedPtrField<protobufs::UInt32Pair>& data);
529 
530 // Converts a map into a repeated field of UInt32Pair.
531 google::protobuf::RepeatedPtrField<protobufs::UInt32Pair>
532 MapToRepeatedUInt32Pair(const std::map<uint32_t, uint32_t>& data);
533 
534 // Returns the last instruction in |block_id| before which an instruction with
535 // opcode |opcode| can be inserted, or nullptr if there is no such instruction.
536 opt::Instruction* GetLastInsertBeforeInstruction(opt::IRContext* ir_context,
537                                                  uint32_t block_id,
538                                                  SpvOp opcode);
539 
540 // Checks whether various conditions hold related to the acceptability of
541 // replacing the id use at |use_in_operand_index| of |use_instruction| with a
542 // synonym or another id of appropriate type if the original id is irrelevant.
543 // In particular, this checks that:
544 // - If id use is an index of an irrelevant id (|use_in_operand_index > 0|)
545 //   in OpAccessChain - it can't be replaced.
546 // - The id use is not an index into a struct field in an OpAccessChain - such
547 //   indices must be constants, so it is dangerous to replace them.
548 // - The id use is not a pointer function call argument, on which there are
549 //   restrictions that make replacement problematic.
550 // - The id use is not the Sample parameter of an OpImageTexelPointer
551 //   instruction, as this must satisfy particular requirements.
552 bool IdUseCanBeReplaced(opt::IRContext* ir_context,
553                         const TransformationContext& transformation_context,
554                         opt::Instruction* use_instruction,
555                         uint32_t use_in_operand_index);
556 
557 // Requires that |struct_type_id| is the id of a struct type, and (as per the
558 // SPIR-V spec) that either all or none of the members of |struct_type_id| have
559 // the BuiltIn decoration. Returns true if and only if all members have the
560 // BuiltIn decoration.
561 bool MembersHaveBuiltInDecoration(opt::IRContext* ir_context,
562                                   uint32_t struct_type_id);
563 
564 // Returns true if and only if |id| is decorated with either Block or
565 // BufferBlock.  Even though these decorations are only allowed on struct types,
566 // for convenience |id| can be any result id so that it is possible to call this
567 // method on something that *might* be a struct type.
568 bool HasBlockOrBufferBlockDecoration(opt::IRContext* ir_context, uint32_t id);
569 
570 // Returns true iff splitting block |block_to_split| just before the instruction
571 // |split_before| would separate an OpSampledImage instruction from its usage.
572 bool SplittingBeforeInstructionSeparatesOpSampledImageDefinitionFromUse(
573     opt::BasicBlock* block_to_split, opt::Instruction* split_before);
574 
575 // Returns true if the instruction given has no side effects.
576 // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/3758): Add any
577 //  missing instructions to the list. In particular, GLSL extended instructions
578 //  (called using OpExtInst) have not been considered.
579 bool InstructionHasNoSideEffects(const opt::Instruction& instruction);
580 
581 // Returns a set of the ids of all the return blocks that are reachable from
582 // the entry block of |function_id|.
583 // Assumes that the function exists in the module.
584 std::set<uint32_t> GetReachableReturnBlocks(opt::IRContext* ir_context,
585                                             uint32_t function_id);
586 
587 // Returns true if changing terminator instruction to |new_terminator| in the
588 // basic block with id |block_id| preserves domination rules and valid block
589 // order (i.e. dominator must always appear before dominated in the CFG).
590 // Returns false otherwise.
591 bool NewTerminatorPreservesDominationRules(opt::IRContext* ir_context,
592                                            uint32_t block_id,
593                                            opt::Instruction new_terminator);
594 
595 // Return the iterator that points to the function with the corresponding
596 // function id. If the function is not found, return the pointer pointing to
597 // module()->end().
598 opt::Module::iterator GetFunctionIterator(opt::IRContext* ir_context,
599                                           uint32_t function_id);
600 
601 }  // namespace fuzzerutil
602 }  // namespace fuzz
603 }  // namespace spvtools
604 
605 #endif  // SOURCE_FUZZ_FUZZER_UTIL_H_
606