1 // Copyright (c) 2016 Google Inc.
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_OPT_INSTRUCTION_H_
16 #define SOURCE_OPT_INSTRUCTION_H_
17
18 #include <cassert>
19 #include <functional>
20 #include <memory>
21 #include <string>
22 #include <utility>
23 #include <vector>
24
25 #include "source/opcode.h"
26 #include "source/operand.h"
27 #include "source/util/ilist_node.h"
28 #include "source/util/small_vector.h"
29
30 #include "source/latest_version_glsl_std_450_header.h"
31 #include "source/latest_version_spirv_header.h"
32 #include "source/opt/reflect.h"
33 #include "spirv-tools/libspirv.h"
34
35 namespace spvtools {
36 namespace opt {
37
38 class Function;
39 class IRContext;
40 class Module;
41 class InstructionList;
42
43 // Relaxed logical addressing:
44 //
45 // In the logical addressing model, pointers cannot be stored or loaded. This
46 // is a useful assumption because it simplifies the aliasing significantly.
47 // However, for the purpose of legalizing code generated from HLSL, we will have
48 // to allow storing and loading of pointers to opaque objects and runtime
49 // arrays. This relaxation of the rule still implies that function and private
50 // scope variables do not have any aliasing, so we can treat them as before.
51 // This will be call the relaxed logical addressing model.
52 //
53 // This relaxation of the rule will be allowed by |GetBaseAddress|, but it will
54 // enforce that no other pointers are stored or loaded.
55
56 // About operand:
57 //
58 // In the SPIR-V specification, the term "operand" is used to mean any single
59 // SPIR-V word following the leading wordcount-opcode word. Here, the term
60 // "operand" is used to mean a *logical* operand. A logical operand may consist
61 // of multiple SPIR-V words, which together make up the same component. For
62 // example, a logical operand of a 64-bit integer needs two words to express.
63 //
64 // Further, we categorize logical operands into *in* and *out* operands.
65 // In operands are operands actually serve as input to operations, while out
66 // operands are operands that represent ids generated from operations (result
67 // type id or result id). For example, for "OpIAdd %rtype %rid %inop1 %inop2",
68 // "%inop1" and "%inop2" are in operands, while "%rtype" and "%rid" are out
69 // operands.
70
71 // A *logical* operand to a SPIR-V instruction. It can be the type id, result
72 // id, or other additional operands carried in an instruction.
73 struct Operand {
74 using OperandData = utils::SmallVector<uint32_t, 2>;
OperandOperand75 Operand(spv_operand_type_t t, OperandData&& w)
76 : type(t), words(std::move(w)) {}
77
OperandOperand78 Operand(spv_operand_type_t t, const OperandData& w) : type(t), words(w) {}
79
80 spv_operand_type_t type; // Type of this logical operand.
81 OperandData words; // Binary segments of this logical operand.
82
83 friend bool operator==(const Operand& o1, const Operand& o2) {
84 return o1.type == o2.type && o1.words == o2.words;
85 }
86
87 // TODO(antiagainst): create fields for literal number kind, width, etc.
88 };
89
90 inline bool operator!=(const Operand& o1, const Operand& o2) {
91 return !(o1 == o2);
92 }
93
94 // A SPIR-V instruction. It contains the opcode and any additional logical
95 // operand, including the result id (if any) and result type id (if any). It
96 // may also contain line-related debug instruction (OpLine, OpNoLine) directly
97 // appearing before this instruction. Note that the result id of an instruction
98 // should never change after the instruction being built. If the result id
99 // needs to change, the user should create a new instruction instead.
100 class Instruction : public utils::IntrusiveNodeBase<Instruction> {
101 public:
102 using OperandList = std::vector<Operand>;
103 using iterator = OperandList::iterator;
104 using const_iterator = OperandList::const_iterator;
105
106 // Creates a default OpNop instruction.
107 // This exists solely for containers that can't do without. Should be removed.
Instruction()108 Instruction()
109 : utils::IntrusiveNodeBase<Instruction>(),
110 context_(nullptr),
111 opcode_(SpvOpNop),
112 has_type_id_(false),
113 has_result_id_(false),
114 unique_id_(0) {}
115
116 // Creates a default OpNop instruction.
117 Instruction(IRContext*);
118 // Creates an instruction with the given opcode |op| and no additional logical
119 // operands.
120 Instruction(IRContext*, SpvOp);
121 // Creates an instruction using the given spv_parsed_instruction_t |inst|. All
122 // the data inside |inst| will be copied and owned in this instance. And keep
123 // record of line-related debug instructions |dbg_line| ahead of this
124 // instruction, if any.
125 Instruction(IRContext* c, const spv_parsed_instruction_t& inst,
126 std::vector<Instruction>&& dbg_line = {});
127
128 // Creates an instruction with the given opcode |op|, type id: |ty_id|,
129 // result id: |res_id| and input operands: |in_operands|.
130 Instruction(IRContext* c, SpvOp op, uint32_t ty_id, uint32_t res_id,
131 const OperandList& in_operands);
132
133 // TODO: I will want to remove these, but will first have to remove the use of
134 // std::vector<Instruction>.
135 Instruction(const Instruction&) = default;
136 Instruction& operator=(const Instruction&) = default;
137
138 Instruction(Instruction&&);
139 Instruction& operator=(Instruction&&);
140
141 virtual ~Instruction() = default;
142
143 // Returns a newly allocated instruction that has the same operands, result,
144 // and type as |this|. The new instruction is not linked into any list.
145 // It is the responsibility of the caller to make sure that the storage is
146 // removed. It is the caller's responsibility to make sure that there is only
147 // one instruction for each result id.
148 Instruction* Clone(IRContext* c) const;
149
context()150 IRContext* context() const { return context_; }
151
opcode()152 SpvOp opcode() const { return opcode_; }
153 // Sets the opcode of this instruction to a specific opcode. Note this may
154 // invalidate the instruction.
155 // TODO(qining): Remove this function when instruction building and insertion
156 // is well implemented.
SetOpcode(SpvOp op)157 void SetOpcode(SpvOp op) { opcode_ = op; }
type_id()158 uint32_t type_id() const {
159 return has_type_id_ ? GetSingleWordOperand(0) : 0;
160 }
result_id()161 uint32_t result_id() const {
162 return has_result_id_ ? GetSingleWordOperand(has_type_id_ ? 1 : 0) : 0;
163 }
unique_id()164 uint32_t unique_id() const {
165 assert(unique_id_ != 0);
166 return unique_id_;
167 }
168 // Returns the vector of line-related debug instructions attached to this
169 // instruction and the caller can directly modify them.
dbg_line_insts()170 std::vector<Instruction>& dbg_line_insts() { return dbg_line_insts_; }
dbg_line_insts()171 const std::vector<Instruction>& dbg_line_insts() const {
172 return dbg_line_insts_;
173 }
174
175 // Clear line-related debug instructions attached to this instruction.
clear_dbg_line_insts()176 void clear_dbg_line_insts() { dbg_line_insts_.clear(); }
177
178 // Same semantics as in the base class except the list the InstructionList
179 // containing |pos| will now assume ownership of |this|.
180 // inline void MoveBefore(Instruction* pos);
181 // inline void InsertAfter(Instruction* pos);
182
183 // Begin and end iterators for operands.
begin()184 iterator begin() { return operands_.begin(); }
end()185 iterator end() { return operands_.end(); }
begin()186 const_iterator begin() const { return operands_.cbegin(); }
end()187 const_iterator end() const { return operands_.cend(); }
188 // Const begin and end iterators for operands.
cbegin()189 const_iterator cbegin() const { return operands_.cbegin(); }
cend()190 const_iterator cend() const { return operands_.cend(); }
191
192 // Gets the number of logical operands.
NumOperands()193 uint32_t NumOperands() const {
194 return static_cast<uint32_t>(operands_.size());
195 }
196 // Gets the number of SPIR-V words occupied by all logical operands.
NumOperandWords()197 uint32_t NumOperandWords() const {
198 return NumInOperandWords() + TypeResultIdCount();
199 }
200 // Gets the |index|-th logical operand.
201 inline Operand& GetOperand(uint32_t index);
202 inline const Operand& GetOperand(uint32_t index) const;
203 // Adds |operand| to the list of operands of this instruction.
204 // It is the responsibility of the caller to make sure
205 // that the instruction remains valid.
206 inline void AddOperand(Operand&& operand);
207 // Gets the |index|-th logical operand as a single SPIR-V word. This method is
208 // not expected to be used with logical operands consisting of multiple SPIR-V
209 // words.
210 uint32_t GetSingleWordOperand(uint32_t index) const;
211 // Sets the |index|-th in-operand's data to the given |data|.
212 inline void SetInOperand(uint32_t index, Operand::OperandData&& data);
213 // Sets the |index|-th operand's data to the given |data|.
214 // This is for in-operands modification only, but with |index| expressed in
215 // terms of operand index rather than in-operand index.
216 inline void SetOperand(uint32_t index, Operand::OperandData&& data);
217 // Replace all of the in operands with those in |new_operands|.
218 inline void SetInOperands(OperandList&& new_operands);
219 // Sets the result type id.
220 inline void SetResultType(uint32_t ty_id);
221 // Sets the result id
222 inline void SetResultId(uint32_t res_id);
HasResultId()223 inline bool HasResultId() const { return has_result_id_; }
224 // Remove the |index|-th operand
RemoveOperand(uint32_t index)225 void RemoveOperand(uint32_t index) {
226 operands_.erase(operands_.begin() + index);
227 }
228
229 // The following methods are similar to the above, but are for in operands.
NumInOperands()230 uint32_t NumInOperands() const {
231 return static_cast<uint32_t>(operands_.size() - TypeResultIdCount());
232 }
233 uint32_t NumInOperandWords() const;
GetInOperand(uint32_t index)234 Operand& GetInOperand(uint32_t index) {
235 return GetOperand(index + TypeResultIdCount());
236 }
GetInOperand(uint32_t index)237 const Operand& GetInOperand(uint32_t index) const {
238 return GetOperand(index + TypeResultIdCount());
239 }
GetSingleWordInOperand(uint32_t index)240 uint32_t GetSingleWordInOperand(uint32_t index) const {
241 return GetSingleWordOperand(index + TypeResultIdCount());
242 }
RemoveInOperand(uint32_t index)243 void RemoveInOperand(uint32_t index) {
244 operands_.erase(operands_.begin() + index + TypeResultIdCount());
245 }
246
247 // Returns true if this instruction is OpNop.
248 inline bool IsNop() const;
249 // Turns this instruction to OpNop. This does not clear out all preceding
250 // line-related debug instructions.
251 inline void ToNop();
252
253 // Runs the given function |f| on this instruction and optionally on the
254 // preceding debug line instructions. The function will always be run
255 // if this is itself a debug line instruction.
256 inline void ForEachInst(const std::function<void(Instruction*)>& f,
257 bool run_on_debug_line_insts = false);
258 inline void ForEachInst(const std::function<void(const Instruction*)>& f,
259 bool run_on_debug_line_insts = false) const;
260
261 // Runs the given function |f| on this instruction and optionally on the
262 // preceding debug line instructions. The function will always be run
263 // if this is itself a debug line instruction. If |f| returns false,
264 // iteration is terminated and this function returns false.
265 inline bool WhileEachInst(const std::function<bool(Instruction*)>& f,
266 bool run_on_debug_line_insts = false);
267 inline bool WhileEachInst(const std::function<bool(const Instruction*)>& f,
268 bool run_on_debug_line_insts = false) const;
269
270 // Runs the given function |f| on all operand ids.
271 //
272 // |f| should not transform an ID into 0, as 0 is an invalid ID.
273 inline void ForEachId(const std::function<void(uint32_t*)>& f);
274 inline void ForEachId(const std::function<void(const uint32_t*)>& f) const;
275
276 // Runs the given function |f| on all "in" operand ids.
277 inline void ForEachInId(const std::function<void(uint32_t*)>& f);
278 inline void ForEachInId(const std::function<void(const uint32_t*)>& f) const;
279
280 // Runs the given function |f| on all "in" operand ids. If |f| returns false,
281 // iteration is terminated and this function returns false.
282 inline bool WhileEachInId(const std::function<bool(uint32_t*)>& f);
283 inline bool WhileEachInId(
284 const std::function<bool(const uint32_t*)>& f) const;
285
286 // Runs the given function |f| on all "in" operands.
287 inline void ForEachInOperand(const std::function<void(uint32_t*)>& f);
288 inline void ForEachInOperand(
289 const std::function<void(const uint32_t*)>& f) const;
290
291 // Runs the given function |f| on all "in" operands. If |f| returns false,
292 // iteration is terminated and this function return false.
293 inline bool WhileEachInOperand(const std::function<bool(uint32_t*)>& f);
294 inline bool WhileEachInOperand(
295 const std::function<bool(const uint32_t*)>& f) const;
296
297 // Returns true if any operands can be labels
298 inline bool HasLabels() const;
299
300 // Pushes the binary segments for this instruction into the back of *|binary|.
301 void ToBinaryWithoutAttachedDebugInsts(std::vector<uint32_t>* binary) const;
302
303 // Replaces the operands to the instruction with |new_operands|. The caller
304 // is responsible for building a complete and valid list of operands for
305 // this instruction.
306 void ReplaceOperands(const OperandList& new_operands);
307
308 // Returns true if the instruction annotates an id with a decoration.
309 inline bool IsDecoration() const;
310
311 // Returns true if the instruction is known to be a load from read-only
312 // memory.
313 bool IsReadOnlyLoad() const;
314
315 // Returns the instruction that gives the base address of an address
316 // calculation. The instruction must be a load, as defined by |IsLoad|,
317 // store, copy, or access chain instruction. In logical addressing mode, will
318 // return an OpVariable or OpFunctionParameter instruction. For relaxed
319 // logical addressing, it would also return a load of a pointer to an opaque
320 // object. For physical addressing mode, could return other types of
321 // instructions.
322 Instruction* GetBaseAddress() const;
323
324 // Returns true if the instruction loads from memory or samples an image, and
325 // stores the result into an id. It considers only core instructions.
326 // Memory-to-memory instructions are not considered loads.
327 inline bool IsLoad() const;
328
329 // Returns true if the instruction declares a variable that is read-only.
330 bool IsReadOnlyVariable() const;
331
332 // The following functions check for the various descriptor types defined in
333 // the Vulkan specification section 13.1.
334
335 // Returns true if the instruction defines a pointer type that points to a
336 // storage image.
337 bool IsVulkanStorageImage() const;
338
339 // Returns true if the instruction defines a pointer type that points to a
340 // sampled image.
341 bool IsVulkanSampledImage() const;
342
343 // Returns true if the instruction defines a pointer type that points to a
344 // storage texel buffer.
345 bool IsVulkanStorageTexelBuffer() const;
346
347 // Returns true if the instruction defines a pointer type that points to a
348 // storage buffer.
349 bool IsVulkanStorageBuffer() const;
350
351 // Returns true if the instruction defines a pointer type that points to a
352 // uniform buffer.
353 bool IsVulkanUniformBuffer() const;
354
355 // Returns true if the instruction is an atom operation that uses original
356 // value.
357 inline bool IsAtomicWithLoad() const;
358
359 // Returns true if the instruction is an atom operation.
360 inline bool IsAtomicOp() const;
361
362 // Returns true if this instruction is a branch or switch instruction (either
363 // conditional or not).
IsBranch()364 bool IsBranch() const { return spvOpcodeIsBranch(opcode()); }
365
366 // Returns true if this instruction causes the function to finish execution
367 // and return to its caller
IsReturn()368 bool IsReturn() const { return spvOpcodeIsReturn(opcode()); }
369
370 // Returns true if this instruction exits this function or aborts execution.
IsReturnOrAbort()371 bool IsReturnOrAbort() const { return spvOpcodeIsReturnOrAbort(opcode()); }
372
373 // Returns the id for the |element|'th subtype. If the |this| is not a
374 // composite type, this function returns 0.
375 uint32_t GetTypeComponent(uint32_t element) const;
376
377 // Returns true if this instruction is a basic block terminator.
IsBlockTerminator()378 bool IsBlockTerminator() const {
379 return spvOpcodeIsBlockTerminator(opcode());
380 }
381
382 // Returns true if |this| is an instruction that define an opaque type. Since
383 // runtime array have similar characteristics they are included as opaque
384 // types.
385 bool IsOpaqueType() const;
386
387 // Returns true if |this| is an instruction which could be folded into a
388 // constant value.
389 bool IsFoldable() const;
390
391 // Returns true if |this| is an instruction which could be folded into a
392 // constant value by |FoldScalar|.
393 bool IsFoldableByFoldScalar() const;
394
395 // Returns true if we are allowed to fold or otherwise manipulate the
396 // instruction that defines |id| in the given context. This includes not
397 // handling NaN values.
398 bool IsFloatingPointFoldingAllowed() const;
399
400 inline bool operator==(const Instruction&) const;
401 inline bool operator!=(const Instruction&) const;
402 inline bool operator<(const Instruction&) const;
403
404 // Takes ownership of the instruction owned by |i| and inserts it immediately
405 // before |this|. Returns the inserted instruction.
406 Instruction* InsertBefore(std::unique_ptr<Instruction>&& i);
407 // Takes ownership of the instructions in |list| and inserts them in order
408 // immediately before |this|. Returns the first inserted instruction.
409 // Assumes the list is non-empty.
410 Instruction* InsertBefore(std::vector<std::unique_ptr<Instruction>>&& list);
411 using utils::IntrusiveNodeBase<Instruction>::InsertBefore;
412
413 // Returns true if |this| is an instruction defining a constant, but not a
414 // Spec constant.
415 inline bool IsConstant() const;
416
417 // Returns true if |this| is an instruction with an opcode safe to move
418 bool IsOpcodeCodeMotionSafe() const;
419
420 // Pretty-prints |inst|.
421 //
422 // Provides the disassembly of a specific instruction. Utilizes |inst|'s
423 // context to provide the correct interpretation of types, constants, etc.
424 //
425 // |options| are the disassembly options. SPV_BINARY_TO_TEXT_OPTION_NO_HEADER
426 // is always added to |options|.
427 std::string PrettyPrint(uint32_t options = 0u) const;
428
429 // Returns true if the result can be a vector and the result of each component
430 // depends on the corresponding component of any vector inputs.
431 bool IsScalarizable() const;
432
433 // Return true if the only effect of this instructions is the result.
434 bool IsOpcodeSafeToDelete() const;
435
436 // Returns true if it is valid to use the result of |inst| as the base
437 // pointer for a load or store. In this case, valid is defined by the relaxed
438 // logical addressing rules when using logical addressing. Normal validation
439 // rules for physical addressing.
440 bool IsValidBasePointer() const;
441
442 // Dump this instruction on stderr. Useful when running interactive
443 // debuggers.
444 void Dump() const;
445
446 private:
447 // Returns the total count of result type id and result id.
TypeResultIdCount()448 uint32_t TypeResultIdCount() const {
449 if (has_type_id_ && has_result_id_) return 2;
450 if (has_type_id_ || has_result_id_) return 1;
451 return 0;
452 }
453
454 // Returns true if the instruction declares a variable that is read-only. The
455 // first version assumes the module is a shader module. The second assumes a
456 // kernel.
457 bool IsReadOnlyVariableShaders() const;
458 bool IsReadOnlyVariableKernel() const;
459
460 // Returns true if the result of |inst| can be used as the base image for an
461 // instruction that samples a image, reads an image, or writes to an image.
462 bool IsValidBaseImage() const;
463
464 IRContext* context_; // IR Context
465 SpvOp opcode_; // Opcode
466 bool has_type_id_; // True if the instruction has a type id
467 bool has_result_id_; // True if the instruction has a result id
468 uint32_t unique_id_; // Unique instruction id
469 // All logical operands, including result type id and result id.
470 OperandList operands_;
471 // Opline and OpNoLine instructions preceding this instruction. Note that for
472 // Instructions representing OpLine or OpNonLine itself, this field should be
473 // empty.
474 std::vector<Instruction> dbg_line_insts_;
475
476 friend InstructionList;
477 };
478
479 // Pretty-prints |inst| to |str| and returns |str|.
480 //
481 // Provides the disassembly of a specific instruction. Utilizes |inst|'s context
482 // to provide the correct interpretation of types, constants, etc.
483 //
484 // Disassembly uses raw ids (not pretty printed names).
485 std::ostream& operator<<(std::ostream& str, const Instruction& inst);
486
487 inline bool Instruction::operator==(const Instruction& other) const {
488 return unique_id() == other.unique_id();
489 }
490
491 inline bool Instruction::operator!=(const Instruction& other) const {
492 return !(*this == other);
493 }
494
495 inline bool Instruction::operator<(const Instruction& other) const {
496 return unique_id() < other.unique_id();
497 }
498
GetOperand(uint32_t index)499 inline Operand& Instruction::GetOperand(uint32_t index) {
500 assert(index < operands_.size() && "operand index out of bound");
501 return operands_[index];
502 }
503
GetOperand(uint32_t index)504 inline const Operand& Instruction::GetOperand(uint32_t index) const {
505 assert(index < operands_.size() && "operand index out of bound");
506 return operands_[index];
507 }
508
AddOperand(Operand && operand)509 inline void Instruction::AddOperand(Operand&& operand) {
510 operands_.push_back(std::move(operand));
511 }
512
SetInOperand(uint32_t index,Operand::OperandData && data)513 inline void Instruction::SetInOperand(uint32_t index,
514 Operand::OperandData&& data) {
515 SetOperand(index + TypeResultIdCount(), std::move(data));
516 }
517
SetOperand(uint32_t index,Operand::OperandData && data)518 inline void Instruction::SetOperand(uint32_t index,
519 Operand::OperandData&& data) {
520 assert(index < operands_.size() && "operand index out of bound");
521 assert(index >= TypeResultIdCount() && "operand is not a in-operand");
522 operands_[index].words = std::move(data);
523 }
524
SetInOperands(OperandList && new_operands)525 inline void Instruction::SetInOperands(OperandList&& new_operands) {
526 // Remove the old in operands.
527 operands_.erase(operands_.begin() + TypeResultIdCount(), operands_.end());
528 // Add the new in operands.
529 operands_.insert(operands_.end(), new_operands.begin(), new_operands.end());
530 }
531
SetResultId(uint32_t res_id)532 inline void Instruction::SetResultId(uint32_t res_id) {
533 // TODO(dsinclair): Allow setting a result id if there wasn't one
534 // previously. Need to make room in the operands_ array to place the result,
535 // and update the has_result_id_ flag.
536 assert(has_result_id_);
537
538 // TODO(dsinclair): Allow removing the result id. This needs to make sure,
539 // if there was a result id previously to remove it from the operands_ array
540 // and reset the has_result_id_ flag.
541 assert(res_id != 0);
542
543 auto ridx = has_type_id_ ? 1 : 0;
544 operands_[ridx].words = {res_id};
545 }
546
SetResultType(uint32_t ty_id)547 inline void Instruction::SetResultType(uint32_t ty_id) {
548 // TODO(dsinclair): Allow setting a type id if there wasn't one
549 // previously. Need to make room in the operands_ array to place the result,
550 // and update the has_type_id_ flag.
551 assert(has_type_id_);
552
553 // TODO(dsinclair): Allow removing the type id. This needs to make sure,
554 // if there was a type id previously to remove it from the operands_ array
555 // and reset the has_type_id_ flag.
556 assert(ty_id != 0);
557
558 operands_.front().words = {ty_id};
559 }
560
IsNop()561 inline bool Instruction::IsNop() const {
562 return opcode_ == SpvOpNop && !has_type_id_ && !has_result_id_ &&
563 operands_.empty();
564 }
565
ToNop()566 inline void Instruction::ToNop() {
567 opcode_ = SpvOpNop;
568 has_type_id_ = false;
569 has_result_id_ = false;
570 operands_.clear();
571 }
572
WhileEachInst(const std::function<bool (Instruction *)> & f,bool run_on_debug_line_insts)573 inline bool Instruction::WhileEachInst(
574 const std::function<bool(Instruction*)>& f, bool run_on_debug_line_insts) {
575 if (run_on_debug_line_insts) {
576 for (auto& dbg_line : dbg_line_insts_) {
577 if (!f(&dbg_line)) return false;
578 }
579 }
580 return f(this);
581 }
582
WhileEachInst(const std::function<bool (const Instruction *)> & f,bool run_on_debug_line_insts)583 inline bool Instruction::WhileEachInst(
584 const std::function<bool(const Instruction*)>& f,
585 bool run_on_debug_line_insts) const {
586 if (run_on_debug_line_insts) {
587 for (auto& dbg_line : dbg_line_insts_) {
588 if (!f(&dbg_line)) return false;
589 }
590 }
591 return f(this);
592 }
593
ForEachInst(const std::function<void (Instruction *)> & f,bool run_on_debug_line_insts)594 inline void Instruction::ForEachInst(const std::function<void(Instruction*)>& f,
595 bool run_on_debug_line_insts) {
596 WhileEachInst(
597 [&f](Instruction* inst) {
598 f(inst);
599 return true;
600 },
601 run_on_debug_line_insts);
602 }
603
ForEachInst(const std::function<void (const Instruction *)> & f,bool run_on_debug_line_insts)604 inline void Instruction::ForEachInst(
605 const std::function<void(const Instruction*)>& f,
606 bool run_on_debug_line_insts) const {
607 WhileEachInst(
608 [&f](const Instruction* inst) {
609 f(inst);
610 return true;
611 },
612 run_on_debug_line_insts);
613 }
614
ForEachId(const std::function<void (uint32_t *)> & f)615 inline void Instruction::ForEachId(const std::function<void(uint32_t*)>& f) {
616 for (auto& opnd : operands_)
617 if (spvIsIdType(opnd.type)) f(&opnd.words[0]);
618 }
619
ForEachId(const std::function<void (const uint32_t *)> & f)620 inline void Instruction::ForEachId(
621 const std::function<void(const uint32_t*)>& f) const {
622 for (const auto& opnd : operands_)
623 if (spvIsIdType(opnd.type)) f(&opnd.words[0]);
624 }
625
WhileEachInId(const std::function<bool (uint32_t *)> & f)626 inline bool Instruction::WhileEachInId(
627 const std::function<bool(uint32_t*)>& f) {
628 for (auto& opnd : operands_) {
629 if (spvIsInIdType(opnd.type)) {
630 if (!f(&opnd.words[0])) return false;
631 }
632 }
633 return true;
634 }
635
WhileEachInId(const std::function<bool (const uint32_t *)> & f)636 inline bool Instruction::WhileEachInId(
637 const std::function<bool(const uint32_t*)>& f) const {
638 for (const auto& opnd : operands_) {
639 if (spvIsInIdType(opnd.type)) {
640 if (!f(&opnd.words[0])) return false;
641 }
642 }
643 return true;
644 }
645
ForEachInId(const std::function<void (uint32_t *)> & f)646 inline void Instruction::ForEachInId(const std::function<void(uint32_t*)>& f) {
647 WhileEachInId([&f](uint32_t* id) {
648 f(id);
649 return true;
650 });
651 }
652
ForEachInId(const std::function<void (const uint32_t *)> & f)653 inline void Instruction::ForEachInId(
654 const std::function<void(const uint32_t*)>& f) const {
655 WhileEachInId([&f](const uint32_t* id) {
656 f(id);
657 return true;
658 });
659 }
660
WhileEachInOperand(const std::function<bool (uint32_t *)> & f)661 inline bool Instruction::WhileEachInOperand(
662 const std::function<bool(uint32_t*)>& f) {
663 for (auto& opnd : operands_) {
664 switch (opnd.type) {
665 case SPV_OPERAND_TYPE_RESULT_ID:
666 case SPV_OPERAND_TYPE_TYPE_ID:
667 break;
668 default:
669 if (!f(&opnd.words[0])) return false;
670 break;
671 }
672 }
673 return true;
674 }
675
WhileEachInOperand(const std::function<bool (const uint32_t *)> & f)676 inline bool Instruction::WhileEachInOperand(
677 const std::function<bool(const uint32_t*)>& f) const {
678 for (const auto& opnd : operands_) {
679 switch (opnd.type) {
680 case SPV_OPERAND_TYPE_RESULT_ID:
681 case SPV_OPERAND_TYPE_TYPE_ID:
682 break;
683 default:
684 if (!f(&opnd.words[0])) return false;
685 break;
686 }
687 }
688 return true;
689 }
690
ForEachInOperand(const std::function<void (uint32_t *)> & f)691 inline void Instruction::ForEachInOperand(
692 const std::function<void(uint32_t*)>& f) {
693 WhileEachInOperand([&f](uint32_t* op) {
694 f(op);
695 return true;
696 });
697 }
698
ForEachInOperand(const std::function<void (const uint32_t *)> & f)699 inline void Instruction::ForEachInOperand(
700 const std::function<void(const uint32_t*)>& f) const {
701 WhileEachInOperand([&f](const uint32_t* op) {
702 f(op);
703 return true;
704 });
705 }
706
HasLabels()707 inline bool Instruction::HasLabels() const {
708 switch (opcode_) {
709 case SpvOpSelectionMerge:
710 case SpvOpBranch:
711 case SpvOpLoopMerge:
712 case SpvOpBranchConditional:
713 case SpvOpSwitch:
714 case SpvOpPhi:
715 return true;
716 break;
717 default:
718 break;
719 }
720 return false;
721 }
722
IsDecoration()723 bool Instruction::IsDecoration() const {
724 return spvOpcodeIsDecoration(opcode());
725 }
726
IsLoad()727 bool Instruction::IsLoad() const { return spvOpcodeIsLoad(opcode()); }
728
IsAtomicWithLoad()729 bool Instruction::IsAtomicWithLoad() const {
730 return spvOpcodeIsAtomicWithLoad(opcode());
731 }
732
IsAtomicOp()733 bool Instruction::IsAtomicOp() const { return spvOpcodeIsAtomicOp(opcode()); }
734
IsConstant()735 bool Instruction::IsConstant() const {
736 return IsCompileTimeConstantInst(opcode());
737 }
738 } // namespace opt
739 } // namespace spvtools
740
741 #endif // SOURCE_OPT_INSTRUCTION_H_
742