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 "NonSemanticShaderDebugInfo100.h"
26 #include "OpenCLDebugInfo100.h"
27 #include "source/binary.h"
28 #include "source/common_debug_info.h"
29 #include "source/latest_version_glsl_std_450_header.h"
30 #include "source/latest_version_spirv_header.h"
31 #include "source/opcode.h"
32 #include "source/operand.h"
33 #include "source/opt/reflect.h"
34 #include "source/util/ilist_node.h"
35 #include "source/util/small_vector.h"
36 #include "source/util/string_utils.h"
37 #include "spirv-tools/libspirv.h"
38
39 const uint32_t kNoDebugScope = 0;
40 const uint32_t kNoInlinedAt = 0;
41
42 namespace spvtools {
43 namespace opt {
44
45 class Function;
46 class IRContext;
47 class Module;
48 class InstructionList;
49
50 // Relaxed logical addressing:
51 //
52 // In the logical addressing model, pointers cannot be stored or loaded. This
53 // is a useful assumption because it simplifies the aliasing significantly.
54 // However, for the purpose of legalizing code generated from HLSL, we will have
55 // to allow storing and loading of pointers to opaque objects and runtime
56 // arrays. This relaxation of the rule still implies that function and private
57 // scope variables do not have any aliasing, so we can treat them as before.
58 // This will be call the relaxed logical addressing model.
59 //
60 // This relaxation of the rule will be allowed by |GetBaseAddress|, but it will
61 // enforce that no other pointers are stored or loaded.
62
63 // About operand:
64 //
65 // In the SPIR-V specification, the term "operand" is used to mean any single
66 // SPIR-V word following the leading wordcount-opcode word. Here, the term
67 // "operand" is used to mean a *logical* operand. A logical operand may consist
68 // of multiple SPIR-V words, which together make up the same component. For
69 // example, a logical operand of a 64-bit integer needs two words to express.
70 //
71 // Further, we categorize logical operands into *in* and *out* operands.
72 // In operands are operands actually serve as input to operations, while out
73 // operands are operands that represent ids generated from operations (result
74 // type id or result id). For example, for "OpIAdd %rtype %rid %inop1 %inop2",
75 // "%inop1" and "%inop2" are in operands, while "%rtype" and "%rid" are out
76 // operands.
77
78 // A *logical* operand to a SPIR-V instruction. It can be the type id, result
79 // id, or other additional operands carried in an instruction.
80 struct Operand {
81 using OperandData = utils::SmallVector<uint32_t, 2>;
OperandOperand82 Operand(spv_operand_type_t t, OperandData&& w)
83 : type(t), words(std::move(w)) {}
84
OperandOperand85 Operand(spv_operand_type_t t, const OperandData& w) : type(t), words(w) {}
86
87 template <class InputIt>
OperandOperand88 Operand(spv_operand_type_t t, InputIt firstOperandData,
89 InputIt lastOperandData)
90 : type(t), words(firstOperandData, lastOperandData) {}
91
92 spv_operand_type_t type; // Type of this logical operand.
93 OperandData words; // Binary segments of this logical operand.
94
AsIdOperand95 uint32_t AsId() const {
96 assert(spvIsIdType(type));
97 assert(words.size() == 1);
98 return words[0];
99 }
100
101 // Returns a string operand as a std::string.
AsStringOperand102 std::string AsString() const {
103 assert(type == SPV_OPERAND_TYPE_LITERAL_STRING);
104 return spvtools::utils::MakeString(words);
105 }
106
107 // Returns a literal integer operand as a uint64_t
AsLiteralUint64Operand108 uint64_t AsLiteralUint64() const {
109 assert(type == SPV_OPERAND_TYPE_LITERAL_INTEGER ||
110 type == SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER ||
111 type == SPV_OPERAND_TYPE_OPTIONAL_LITERAL_INTEGER ||
112 type == SPV_OPERAND_TYPE_OPTIONAL_TYPED_LITERAL_INTEGER);
113 assert(1 <= words.size());
114 assert(words.size() <= 2);
115 uint64_t result = 0;
116 if (words.size() > 0) { // Needed to avoid maybe-uninitialized GCC warning
117 uint32_t low = words[0];
118 result = uint64_t(low);
119 }
120 if (words.size() > 1) {
121 uint32_t high = words[1];
122 result = result | (uint64_t(high) << 32);
123 }
124 return result;
125 }
126
127 friend bool operator==(const Operand& o1, const Operand& o2) {
128 return o1.type == o2.type && o1.words == o2.words;
129 }
130
131 // TODO(antiagainst): create fields for literal number kind, width, etc.
132 };
133
134 inline bool operator!=(const Operand& o1, const Operand& o2) {
135 return !(o1 == o2);
136 }
137
138 // This structure is used to represent a DebugScope instruction from
139 // the OpenCL.100.DebugInfo extended instruction set. Note that we can
140 // ignore the result id of DebugScope instruction because it is not
141 // used for anything. We do not keep it to reduce the size of
142 // structure.
143 // TODO: Let validator check that the result id is not used anywhere.
144 class DebugScope {
145 public:
DebugScope(uint32_t lexical_scope,uint32_t inlined_at)146 DebugScope(uint32_t lexical_scope, uint32_t inlined_at)
147 : lexical_scope_(lexical_scope), inlined_at_(inlined_at) {}
148
149 inline bool operator!=(const DebugScope& d) const {
150 return lexical_scope_ != d.lexical_scope_ || inlined_at_ != d.inlined_at_;
151 }
152
153 // Accessor functions for |lexical_scope_|.
GetLexicalScope()154 uint32_t GetLexicalScope() const { return lexical_scope_; }
SetLexicalScope(uint32_t scope)155 void SetLexicalScope(uint32_t scope) { lexical_scope_ = scope; }
156
157 // Accessor functions for |inlined_at_|.
GetInlinedAt()158 uint32_t GetInlinedAt() const { return inlined_at_; }
SetInlinedAt(uint32_t at)159 void SetInlinedAt(uint32_t at) { inlined_at_ = at; }
160
161 // Pushes the binary segments for this DebugScope instruction into
162 // the back of *|binary|.
163 void ToBinary(uint32_t type_id, uint32_t result_id, uint32_t ext_set,
164 std::vector<uint32_t>* binary) const;
165
166 private:
167 // The result id of the lexical scope in which this debug scope is
168 // contained. The value is kNoDebugScope if there is no scope.
169 uint32_t lexical_scope_;
170
171 // The result id of DebugInlinedAt if instruction in this debug scope
172 // is inlined. The value is kNoInlinedAt if it is not inlined.
173 uint32_t inlined_at_;
174 };
175
176 // A SPIR-V instruction. It contains the opcode and any additional logical
177 // operand, including the result id (if any) and result type id (if any). It
178 // may also contain line-related debug instruction (OpLine, OpNoLine) directly
179 // appearing before this instruction. Note that the result id of an instruction
180 // should never change after the instruction being built. If the result id
181 // needs to change, the user should create a new instruction instead.
182 class Instruction : public utils::IntrusiveNodeBase<Instruction> {
183 public:
184 using OperandList = std::vector<Operand>;
185 using iterator = OperandList::iterator;
186 using const_iterator = OperandList::const_iterator;
187
188 // Creates a default OpNop instruction.
189 // This exists solely for containers that can't do without. Should be removed.
Instruction()190 Instruction()
191 : utils::IntrusiveNodeBase<Instruction>(),
192 context_(nullptr),
193 opcode_(SpvOpNop),
194 has_type_id_(false),
195 has_result_id_(false),
196 unique_id_(0),
197 dbg_scope_(kNoDebugScope, kNoInlinedAt) {}
198
199 // Creates a default OpNop instruction.
200 Instruction(IRContext*);
201 // Creates an instruction with the given opcode |op| and no additional logical
202 // operands.
203 Instruction(IRContext*, SpvOp);
204 // Creates an instruction using the given spv_parsed_instruction_t |inst|. All
205 // the data inside |inst| will be copied and owned in this instance. And keep
206 // record of line-related debug instructions |dbg_line| ahead of this
207 // instruction, if any.
208 Instruction(IRContext* c, const spv_parsed_instruction_t& inst,
209 std::vector<Instruction>&& dbg_line = {});
210
211 Instruction(IRContext* c, const spv_parsed_instruction_t& inst,
212 const DebugScope& dbg_scope);
213
214 // Creates an instruction with the given opcode |op|, type id: |ty_id|,
215 // result id: |res_id| and input operands: |in_operands|.
216 Instruction(IRContext* c, SpvOp op, uint32_t ty_id, uint32_t res_id,
217 const OperandList& in_operands);
218
219 // TODO: I will want to remove these, but will first have to remove the use of
220 // std::vector<Instruction>.
221 Instruction(const Instruction&) = default;
222 Instruction& operator=(const Instruction&) = default;
223
224 Instruction(Instruction&&);
225 Instruction& operator=(Instruction&&);
226
227 ~Instruction() override = default;
228
229 // Returns a newly allocated instruction that has the same operands, result,
230 // and type as |this|. The new instruction is not linked into any list.
231 // It is the responsibility of the caller to make sure that the storage is
232 // removed. It is the caller's responsibility to make sure that there is only
233 // one instruction for each result id.
234 Instruction* Clone(IRContext* c) const;
235
context()236 IRContext* context() const { return context_; }
237
opcode()238 SpvOp opcode() const { return opcode_; }
239 // Sets the opcode of this instruction to a specific opcode. Note this may
240 // invalidate the instruction.
241 // TODO(qining): Remove this function when instruction building and insertion
242 // is well implemented.
SetOpcode(SpvOp op)243 void SetOpcode(SpvOp op) { opcode_ = op; }
type_id()244 uint32_t type_id() const {
245 return has_type_id_ ? GetSingleWordOperand(0) : 0;
246 }
result_id()247 uint32_t result_id() const {
248 return has_result_id_ ? GetSingleWordOperand(has_type_id_ ? 1 : 0) : 0;
249 }
unique_id()250 uint32_t unique_id() const {
251 assert(unique_id_ != 0);
252 return unique_id_;
253 }
254 // Returns the vector of line-related debug instructions attached to this
255 // instruction and the caller can directly modify them.
dbg_line_insts()256 std::vector<Instruction>& dbg_line_insts() { return dbg_line_insts_; }
dbg_line_insts()257 const std::vector<Instruction>& dbg_line_insts() const {
258 return dbg_line_insts_;
259 }
260
dbg_line_inst()261 const Instruction* dbg_line_inst() const {
262 return dbg_line_insts_.empty() ? nullptr : &dbg_line_insts_[0];
263 }
264
265 // Clear line-related debug instructions attached to this instruction.
clear_dbg_line_insts()266 void clear_dbg_line_insts() { dbg_line_insts_.clear(); }
267
268 // Same semantics as in the base class except the list the InstructionList
269 // containing |pos| will now assume ownership of |this|.
270 // inline void MoveBefore(Instruction* pos);
271 // inline void InsertAfter(Instruction* pos);
272
273 // Begin and end iterators for operands.
begin()274 iterator begin() { return operands_.begin(); }
end()275 iterator end() { return operands_.end(); }
begin()276 const_iterator begin() const { return operands_.cbegin(); }
end()277 const_iterator end() const { return operands_.cend(); }
278 // Const begin and end iterators for operands.
cbegin()279 const_iterator cbegin() const { return operands_.cbegin(); }
cend()280 const_iterator cend() const { return operands_.cend(); }
281
282 // Gets the number of logical operands.
NumOperands()283 uint32_t NumOperands() const {
284 return static_cast<uint32_t>(operands_.size());
285 }
286 // Gets the number of SPIR-V words occupied by all logical operands.
NumOperandWords()287 uint32_t NumOperandWords() const {
288 return NumInOperandWords() + TypeResultIdCount();
289 }
290 // Gets the |index|-th logical operand.
291 inline Operand& GetOperand(uint32_t index);
292 inline const Operand& GetOperand(uint32_t index) const;
293 // Adds |operand| to the list of operands of this instruction.
294 // It is the responsibility of the caller to make sure
295 // that the instruction remains valid.
296 inline void AddOperand(Operand&& operand);
297 // Gets the |index|-th logical operand as a single SPIR-V word. This method is
298 // not expected to be used with logical operands consisting of multiple SPIR-V
299 // words.
300 uint32_t GetSingleWordOperand(uint32_t index) const;
301 // Sets the |index|-th in-operand's data to the given |data|.
302 inline void SetInOperand(uint32_t index, Operand::OperandData&& data);
303 // Sets the |index|-th operand's data to the given |data|.
304 // This is for in-operands modification only, but with |index| expressed in
305 // terms of operand index rather than in-operand index.
306 inline void SetOperand(uint32_t index, Operand::OperandData&& data);
307 // Replace all of the in operands with those in |new_operands|.
308 inline void SetInOperands(OperandList&& new_operands);
309 // Sets the result type id.
310 inline void SetResultType(uint32_t ty_id);
HasResultType()311 inline bool HasResultType() const { return has_type_id_; }
312 // Sets the result id
313 inline void SetResultId(uint32_t res_id);
HasResultId()314 inline bool HasResultId() const { return has_result_id_; }
315 // Sets DebugScope.
316 inline void SetDebugScope(const DebugScope& scope);
GetDebugScope()317 inline const DebugScope& GetDebugScope() const { return dbg_scope_; }
318 // Add debug line inst. Renew result id if Debug[No]Line
319 void AddDebugLine(const Instruction* inst);
320 // Updates DebugInlinedAt of DebugScope and OpLine.
321 void UpdateDebugInlinedAt(uint32_t new_inlined_at);
322 // Clear line-related debug instructions attached to this instruction
323 // along with def-use entries.
324 void ClearDbgLineInsts();
325 // Return true if Shader100:Debug[No]Line
326 bool IsDebugLineInst() const;
327 // Return true if Op[No]Line or Shader100:Debug[No]Line
328 bool IsLineInst() const;
329 // Return true if OpLine or Shader100:DebugLine
330 bool IsLine() const;
331 // Return true if OpNoLine or Shader100:DebugNoLine
332 bool IsNoLine() const;
GetDebugInlinedAt()333 inline uint32_t GetDebugInlinedAt() const {
334 return dbg_scope_.GetInlinedAt();
335 }
336 // Updates lexical scope of DebugScope and OpLine.
337 void UpdateLexicalScope(uint32_t scope);
338 // Updates OpLine and DebugScope based on the information of |from|.
339 void UpdateDebugInfoFrom(const Instruction* from);
340 // Remove the |index|-th operand
RemoveOperand(uint32_t index)341 void RemoveOperand(uint32_t index) {
342 operands_.erase(operands_.begin() + index);
343 }
344 // Insert an operand before the |index|-th operand
InsertOperand(uint32_t index,Operand && operand)345 void InsertOperand(uint32_t index, Operand&& operand) {
346 operands_.insert(operands_.begin() + index, operand);
347 }
348
349 // The following methods are similar to the above, but are for in operands.
NumInOperands()350 uint32_t NumInOperands() const {
351 return static_cast<uint32_t>(operands_.size() - TypeResultIdCount());
352 }
353 uint32_t NumInOperandWords() const;
GetInOperand(uint32_t index)354 Operand& GetInOperand(uint32_t index) {
355 return GetOperand(index + TypeResultIdCount());
356 }
GetInOperand(uint32_t index)357 const Operand& GetInOperand(uint32_t index) const {
358 return GetOperand(index + TypeResultIdCount());
359 }
GetSingleWordInOperand(uint32_t index)360 uint32_t GetSingleWordInOperand(uint32_t index) const {
361 return GetSingleWordOperand(index + TypeResultIdCount());
362 }
RemoveInOperand(uint32_t index)363 void RemoveInOperand(uint32_t index) {
364 operands_.erase(operands_.begin() + index + TypeResultIdCount());
365 }
366
367 // Returns true if this instruction is OpNop.
368 inline bool IsNop() const;
369 // Turns this instruction to OpNop. This does not clear out all preceding
370 // line-related debug instructions.
371 inline void ToNop();
372
373 // Runs the given function |f| on this instruction and optionally on the
374 // preceding debug line instructions. The function will always be run
375 // if this is itself a debug line instruction.
376 inline void ForEachInst(const std::function<void(Instruction*)>& f,
377 bool run_on_debug_line_insts = false);
378 inline void ForEachInst(const std::function<void(const Instruction*)>& f,
379 bool run_on_debug_line_insts = false) const;
380
381 // Runs the given function |f| on this instruction and optionally on the
382 // preceding debug line instructions. The function will always be run
383 // if this is itself a debug line instruction. If |f| returns false,
384 // iteration is terminated and this function returns false.
385 inline bool WhileEachInst(const std::function<bool(Instruction*)>& f,
386 bool run_on_debug_line_insts = false);
387 inline bool WhileEachInst(const std::function<bool(const Instruction*)>& f,
388 bool run_on_debug_line_insts = false) const;
389
390 // Runs the given function |f| on all operand ids.
391 //
392 // |f| should not transform an ID into 0, as 0 is an invalid ID.
393 inline void ForEachId(const std::function<void(uint32_t*)>& f);
394 inline void ForEachId(const std::function<void(const uint32_t*)>& f) const;
395
396 // Runs the given function |f| on all "in" operand ids.
397 inline void ForEachInId(const std::function<void(uint32_t*)>& f);
398 inline void ForEachInId(const std::function<void(const uint32_t*)>& f) const;
399
400 // Runs the given function |f| on all "in" operand ids. If |f| returns false,
401 // iteration is terminated and this function returns false.
402 inline bool WhileEachInId(const std::function<bool(uint32_t*)>& f);
403 inline bool WhileEachInId(
404 const std::function<bool(const uint32_t*)>& f) const;
405
406 // Runs the given function |f| on all "in" operands.
407 inline void ForEachInOperand(const std::function<void(uint32_t*)>& f);
408 inline void ForEachInOperand(
409 const std::function<void(const uint32_t*)>& f) const;
410
411 // Runs the given function |f| on all "in" operands. If |f| returns false,
412 // iteration is terminated and this function return false.
413 inline bool WhileEachInOperand(const std::function<bool(uint32_t*)>& f);
414 inline bool WhileEachInOperand(
415 const std::function<bool(const uint32_t*)>& f) const;
416
417 // Returns true if it's an OpBranchConditional instruction
418 // with branch weights.
419 bool HasBranchWeights() const;
420
421 // Returns true if any operands can be labels
422 inline bool HasLabels() const;
423
424 // Pushes the binary segments for this instruction into the back of *|binary|.
425 void ToBinaryWithoutAttachedDebugInsts(std::vector<uint32_t>* binary) const;
426
427 // Replaces the operands to the instruction with |new_operands|. The caller
428 // is responsible for building a complete and valid list of operands for
429 // this instruction.
430 void ReplaceOperands(const OperandList& new_operands);
431
432 // Returns true if the instruction annotates an id with a decoration.
433 inline bool IsDecoration() const;
434
435 // Returns true if the instruction is known to be a load from read-only
436 // memory.
437 bool IsReadOnlyLoad() const;
438
439 // Returns the instruction that gives the base address of an address
440 // calculation. The instruction must be a load, as defined by |IsLoad|,
441 // store, copy, or access chain instruction. In logical addressing mode, will
442 // return an OpVariable or OpFunctionParameter instruction. For relaxed
443 // logical addressing, it would also return a load of a pointer to an opaque
444 // object. For physical addressing mode, could return other types of
445 // instructions.
446 Instruction* GetBaseAddress() const;
447
448 // Returns true if the instruction loads from memory or samples an image, and
449 // stores the result into an id. It considers only core instructions.
450 // Memory-to-memory instructions are not considered loads.
451 inline bool IsLoad() const;
452
453 // Returns true if the instruction generates a pointer that is definitely
454 // read-only. This is determined by analysing the pointer type's storage
455 // class and decorations that target the pointer's id. It does not analyse
456 // other instructions that the pointer may be derived from. Thus if 'true' is
457 // returned, the pointer is definitely read-only, while if 'false' is returned
458 // it is possible that the pointer may actually be read-only if it is derived
459 // from another pointer that is decorated as read-only.
460 bool IsReadOnlyPointer() const;
461
462 // The following functions check for the various descriptor types defined in
463 // the Vulkan specification section 13.1.
464
465 // Returns true if the instruction defines a pointer type that points to a
466 // storage image.
467 bool IsVulkanStorageImage() const;
468
469 // Returns true if the instruction defines a pointer type that points to a
470 // sampled image.
471 bool IsVulkanSampledImage() const;
472
473 // Returns true if the instruction defines a pointer type that points to a
474 // storage texel buffer.
475 bool IsVulkanStorageTexelBuffer() const;
476
477 // Returns true if the instruction defines a pointer type that points to a
478 // storage buffer.
479 bool IsVulkanStorageBuffer() const;
480
481 // Returns true if the instruction defines a variable in StorageBuffer or
482 // Uniform storage class with a pointer type that points to a storage buffer.
483 bool IsVulkanStorageBufferVariable() const;
484
485 // Returns true if the instruction defines a pointer type that points to a
486 // uniform buffer.
487 bool IsVulkanUniformBuffer() const;
488
489 // Returns true if the instruction is an atom operation that uses original
490 // value.
491 inline bool IsAtomicWithLoad() const;
492
493 // Returns true if the instruction is an atom operation.
494 inline bool IsAtomicOp() const;
495
496 // Returns true if this instruction is a branch or switch instruction (either
497 // conditional or not).
IsBranch()498 bool IsBranch() const { return spvOpcodeIsBranch(opcode()); }
499
500 // Returns true if this instruction causes the function to finish execution
501 // and return to its caller
IsReturn()502 bool IsReturn() const { return spvOpcodeIsReturn(opcode()); }
503
504 // Returns true if this instruction exits this function or aborts execution.
IsReturnOrAbort()505 bool IsReturnOrAbort() const { return spvOpcodeIsReturnOrAbort(opcode()); }
506
507 // Returns true if this instruction is a basic block terminator.
IsBlockTerminator()508 bool IsBlockTerminator() const {
509 return spvOpcodeIsBlockTerminator(opcode());
510 }
511
512 // Returns true if |this| is an instruction that define an opaque type. Since
513 // runtime array have similar characteristics they are included as opaque
514 // types.
515 bool IsOpaqueType() const;
516
517 // Returns true if |this| is an instruction which could be folded into a
518 // constant value.
519 bool IsFoldable() const;
520
521 // Returns true if |this| is an instruction which could be folded into a
522 // constant value by |FoldScalar|.
523 bool IsFoldableByFoldScalar() const;
524
525 // Returns true if we are allowed to fold or otherwise manipulate the
526 // instruction that defines |id| in the given context. This includes not
527 // handling NaN values.
528 bool IsFloatingPointFoldingAllowed() const;
529
530 inline bool operator==(const Instruction&) const;
531 inline bool operator!=(const Instruction&) const;
532 inline bool operator<(const Instruction&) const;
533
534 // Takes ownership of the instruction owned by |i| and inserts it immediately
535 // before |this|. Returns the inserted instruction.
536 Instruction* InsertBefore(std::unique_ptr<Instruction>&& i);
537 // Takes ownership of the instructions in |list| and inserts them in order
538 // immediately before |this|. Returns the first inserted instruction.
539 // Assumes the list is non-empty.
540 Instruction* InsertBefore(std::vector<std::unique_ptr<Instruction>>&& list);
541 using utils::IntrusiveNodeBase<Instruction>::InsertBefore;
542
543 // Returns true if |this| is an instruction defining a constant, but not a
544 // Spec constant.
545 inline bool IsConstant() const;
546
547 // Returns true if |this| is an instruction with an opcode safe to move
548 bool IsOpcodeCodeMotionSafe() const;
549
550 // Pretty-prints |inst|.
551 //
552 // Provides the disassembly of a specific instruction. Utilizes |inst|'s
553 // context to provide the correct interpretation of types, constants, etc.
554 //
555 // |options| are the disassembly options. SPV_BINARY_TO_TEXT_OPTION_NO_HEADER
556 // is always added to |options|.
557 std::string PrettyPrint(uint32_t options = 0u) const;
558
559 // Returns true if the result can be a vector and the result of each component
560 // depends on the corresponding component of any vector inputs.
561 bool IsScalarizable() const;
562
563 // Return true if the only effect of this instructions is the result.
564 bool IsOpcodeSafeToDelete() const;
565
566 // Returns true if it is valid to use the result of |inst| as the base
567 // pointer for a load or store. In this case, valid is defined by the relaxed
568 // logical addressing rules when using logical addressing. Normal validation
569 // rules for physical addressing.
570 bool IsValidBasePointer() const;
571
572 // Returns debug opcode of an OpenCL.100.DebugInfo instruction. If
573 // it is not an OpenCL.100.DebugInfo instruction, just returns
574 // OpenCLDebugInfo100InstructionsMax.
575 OpenCLDebugInfo100Instructions GetOpenCL100DebugOpcode() const;
576
577 // Returns debug opcode of an NonSemantic.Shader.DebugInfo.100 instruction. If
578 // it is not an NonSemantic.Shader.DebugInfo.100 instruction, just return
579 // NonSemanticShaderDebugInfo100InstructionsMax.
580 NonSemanticShaderDebugInfo100Instructions GetShader100DebugOpcode() const;
581
582 // Returns debug opcode of an OpenCL.100.DebugInfo or
583 // NonSemantic.Shader.DebugInfo.100 instruction. Since these overlap, we
584 // return the OpenCLDebugInfo code
585 CommonDebugInfoInstructions GetCommonDebugOpcode() const;
586
587 // Returns true if it is an OpenCL.DebugInfo.100 instruction.
IsOpenCL100DebugInstr()588 bool IsOpenCL100DebugInstr() const {
589 return GetOpenCL100DebugOpcode() != OpenCLDebugInfo100InstructionsMax;
590 }
591
592 // Returns true if it is an NonSemantic.Shader.DebugInfo.100 instruction.
IsShader100DebugInstr()593 bool IsShader100DebugInstr() const {
594 return GetShader100DebugOpcode() !=
595 NonSemanticShaderDebugInfo100InstructionsMax;
596 }
IsCommonDebugInstr()597 bool IsCommonDebugInstr() const {
598 return GetCommonDebugOpcode() != CommonDebugInfoInstructionsMax;
599 }
600
601 // Returns true if this instructions a non-semantic instruction.
602 bool IsNonSemanticInstruction() const;
603
604 // Dump this instruction on stderr. Useful when running interactive
605 // debuggers.
606 void Dump() const;
607
608 private:
609 // Returns the total count of result type id and result id.
TypeResultIdCount()610 uint32_t TypeResultIdCount() const {
611 if (has_type_id_ && has_result_id_) return 2;
612 if (has_type_id_ || has_result_id_) return 1;
613 return 0;
614 }
615
616 // Returns true if the instruction generates a read-only pointer, with the
617 // same caveats documented in the comment for IsReadOnlyPointer. The first
618 // version assumes the module is a shader module. The second assumes a
619 // kernel.
620 bool IsReadOnlyPointerShaders() const;
621 bool IsReadOnlyPointerKernel() const;
622
623 // Returns true if the result of |inst| can be used as the base image for an
624 // instruction that samples a image, reads an image, or writes to an image.
625 bool IsValidBaseImage() const;
626
627 IRContext* context_; // IR Context
628 SpvOp opcode_; // Opcode
629 bool has_type_id_; // True if the instruction has a type id
630 bool has_result_id_; // True if the instruction has a result id
631 uint32_t unique_id_; // Unique instruction id
632 // All logical operands, including result type id and result id.
633 OperandList operands_;
634 // Op[No]Line or Debug[No]Line instructions preceding this instruction. Note
635 // that for Instructions representing Op[No]Line or Debug[No]Line themselves,
636 // this field should be empty.
637 std::vector<Instruction> dbg_line_insts_;
638
639 // DebugScope that wraps this instruction.
640 DebugScope dbg_scope_;
641
642 friend InstructionList;
643 };
644
645 // Pretty-prints |inst| to |str| and returns |str|.
646 //
647 // Provides the disassembly of a specific instruction. Utilizes |inst|'s context
648 // to provide the correct interpretation of types, constants, etc.
649 //
650 // Disassembly uses raw ids (not pretty printed names).
651 std::ostream& operator<<(std::ostream& str, const Instruction& inst);
652
653 inline bool Instruction::operator==(const Instruction& other) const {
654 return unique_id() == other.unique_id();
655 }
656
657 inline bool Instruction::operator!=(const Instruction& other) const {
658 return !(*this == other);
659 }
660
661 inline bool Instruction::operator<(const Instruction& other) const {
662 return unique_id() < other.unique_id();
663 }
664
GetOperand(uint32_t index)665 inline Operand& Instruction::GetOperand(uint32_t index) {
666 assert(index < operands_.size() && "operand index out of bound");
667 return operands_[index];
668 }
669
GetOperand(uint32_t index)670 inline const Operand& Instruction::GetOperand(uint32_t index) const {
671 assert(index < operands_.size() && "operand index out of bound");
672 return operands_[index];
673 }
674
AddOperand(Operand && operand)675 inline void Instruction::AddOperand(Operand&& operand) {
676 operands_.push_back(std::move(operand));
677 }
678
SetInOperand(uint32_t index,Operand::OperandData && data)679 inline void Instruction::SetInOperand(uint32_t index,
680 Operand::OperandData&& data) {
681 SetOperand(index + TypeResultIdCount(), std::move(data));
682 }
683
SetOperand(uint32_t index,Operand::OperandData && data)684 inline void Instruction::SetOperand(uint32_t index,
685 Operand::OperandData&& data) {
686 assert(index < operands_.size() && "operand index out of bound");
687 assert(index >= TypeResultIdCount() && "operand is not a in-operand");
688 operands_[index].words = std::move(data);
689 }
690
SetInOperands(OperandList && new_operands)691 inline void Instruction::SetInOperands(OperandList&& new_operands) {
692 // Remove the old in operands.
693 operands_.erase(operands_.begin() + TypeResultIdCount(), operands_.end());
694 // Add the new in operands.
695 operands_.insert(operands_.end(), new_operands.begin(), new_operands.end());
696 }
697
SetResultId(uint32_t res_id)698 inline void Instruction::SetResultId(uint32_t res_id) {
699 // TODO(dsinclair): Allow setting a result id if there wasn't one
700 // previously. Need to make room in the operands_ array to place the result,
701 // and update the has_result_id_ flag.
702 assert(has_result_id_);
703
704 // TODO(dsinclair): Allow removing the result id. This needs to make sure,
705 // if there was a result id previously to remove it from the operands_ array
706 // and reset the has_result_id_ flag.
707 assert(res_id != 0);
708
709 auto ridx = has_type_id_ ? 1 : 0;
710 operands_[ridx].words = {res_id};
711 }
712
SetDebugScope(const DebugScope & scope)713 inline void Instruction::SetDebugScope(const DebugScope& scope) {
714 dbg_scope_ = scope;
715 for (auto& i : dbg_line_insts_) {
716 i.dbg_scope_ = scope;
717 }
718 }
719
SetResultType(uint32_t ty_id)720 inline void Instruction::SetResultType(uint32_t ty_id) {
721 // TODO(dsinclair): Allow setting a type id if there wasn't one
722 // previously. Need to make room in the operands_ array to place the result,
723 // and update the has_type_id_ flag.
724 assert(has_type_id_);
725
726 // TODO(dsinclair): Allow removing the type id. This needs to make sure,
727 // if there was a type id previously to remove it from the operands_ array
728 // and reset the has_type_id_ flag.
729 assert(ty_id != 0);
730
731 operands_.front().words = {ty_id};
732 }
733
IsNop()734 inline bool Instruction::IsNop() const {
735 return opcode_ == SpvOpNop && !has_type_id_ && !has_result_id_ &&
736 operands_.empty();
737 }
738
ToNop()739 inline void Instruction::ToNop() {
740 opcode_ = SpvOpNop;
741 has_type_id_ = false;
742 has_result_id_ = false;
743 operands_.clear();
744 }
745
WhileEachInst(const std::function<bool (Instruction *)> & f,bool run_on_debug_line_insts)746 inline bool Instruction::WhileEachInst(
747 const std::function<bool(Instruction*)>& f, bool run_on_debug_line_insts) {
748 if (run_on_debug_line_insts) {
749 for (auto& dbg_line : dbg_line_insts_) {
750 if (!f(&dbg_line)) return false;
751 }
752 }
753 return f(this);
754 }
755
WhileEachInst(const std::function<bool (const Instruction *)> & f,bool run_on_debug_line_insts)756 inline bool Instruction::WhileEachInst(
757 const std::function<bool(const Instruction*)>& f,
758 bool run_on_debug_line_insts) const {
759 if (run_on_debug_line_insts) {
760 for (auto& dbg_line : dbg_line_insts_) {
761 if (!f(&dbg_line)) return false;
762 }
763 }
764 return f(this);
765 }
766
ForEachInst(const std::function<void (Instruction *)> & f,bool run_on_debug_line_insts)767 inline void Instruction::ForEachInst(const std::function<void(Instruction*)>& f,
768 bool run_on_debug_line_insts) {
769 WhileEachInst(
770 [&f](Instruction* inst) {
771 f(inst);
772 return true;
773 },
774 run_on_debug_line_insts);
775 }
776
ForEachInst(const std::function<void (const Instruction *)> & f,bool run_on_debug_line_insts)777 inline void Instruction::ForEachInst(
778 const std::function<void(const Instruction*)>& f,
779 bool run_on_debug_line_insts) const {
780 WhileEachInst(
781 [&f](const Instruction* inst) {
782 f(inst);
783 return true;
784 },
785 run_on_debug_line_insts);
786 }
787
ForEachId(const std::function<void (uint32_t *)> & f)788 inline void Instruction::ForEachId(const std::function<void(uint32_t*)>& f) {
789 for (auto& operand : operands_)
790 if (spvIsIdType(operand.type)) f(&operand.words[0]);
791 }
792
ForEachId(const std::function<void (const uint32_t *)> & f)793 inline void Instruction::ForEachId(
794 const std::function<void(const uint32_t*)>& f) const {
795 for (const auto& operand : operands_)
796 if (spvIsIdType(operand.type)) f(&operand.words[0]);
797 }
798
WhileEachInId(const std::function<bool (uint32_t *)> & f)799 inline bool Instruction::WhileEachInId(
800 const std::function<bool(uint32_t*)>& f) {
801 for (auto& operand : operands_) {
802 if (spvIsInIdType(operand.type) && !f(&operand.words[0])) {
803 return false;
804 }
805 }
806 return true;
807 }
808
WhileEachInId(const std::function<bool (const uint32_t *)> & f)809 inline bool Instruction::WhileEachInId(
810 const std::function<bool(const uint32_t*)>& f) const {
811 for (const auto& operand : operands_) {
812 if (spvIsInIdType(operand.type) && !f(&operand.words[0])) {
813 return false;
814 }
815 }
816 return true;
817 }
818
ForEachInId(const std::function<void (uint32_t *)> & f)819 inline void Instruction::ForEachInId(const std::function<void(uint32_t*)>& f) {
820 WhileEachInId([&f](uint32_t* id) {
821 f(id);
822 return true;
823 });
824 }
825
ForEachInId(const std::function<void (const uint32_t *)> & f)826 inline void Instruction::ForEachInId(
827 const std::function<void(const uint32_t*)>& f) const {
828 WhileEachInId([&f](const uint32_t* id) {
829 f(id);
830 return true;
831 });
832 }
833
WhileEachInOperand(const std::function<bool (uint32_t *)> & f)834 inline bool Instruction::WhileEachInOperand(
835 const std::function<bool(uint32_t*)>& f) {
836 for (auto& operand : operands_) {
837 switch (operand.type) {
838 case SPV_OPERAND_TYPE_RESULT_ID:
839 case SPV_OPERAND_TYPE_TYPE_ID:
840 break;
841 default:
842 if (!f(&operand.words[0])) return false;
843 break;
844 }
845 }
846 return true;
847 }
848
WhileEachInOperand(const std::function<bool (const uint32_t *)> & f)849 inline bool Instruction::WhileEachInOperand(
850 const std::function<bool(const uint32_t*)>& f) const {
851 for (const auto& operand : operands_) {
852 switch (operand.type) {
853 case SPV_OPERAND_TYPE_RESULT_ID:
854 case SPV_OPERAND_TYPE_TYPE_ID:
855 break;
856 default:
857 if (!f(&operand.words[0])) return false;
858 break;
859 }
860 }
861 return true;
862 }
863
ForEachInOperand(const std::function<void (uint32_t *)> & f)864 inline void Instruction::ForEachInOperand(
865 const std::function<void(uint32_t*)>& f) {
866 WhileEachInOperand([&f](uint32_t* operand) {
867 f(operand);
868 return true;
869 });
870 }
871
ForEachInOperand(const std::function<void (const uint32_t *)> & f)872 inline void Instruction::ForEachInOperand(
873 const std::function<void(const uint32_t*)>& f) const {
874 WhileEachInOperand([&f](const uint32_t* operand) {
875 f(operand);
876 return true;
877 });
878 }
879
HasLabels()880 inline bool Instruction::HasLabels() const {
881 switch (opcode_) {
882 case SpvOpSelectionMerge:
883 case SpvOpBranch:
884 case SpvOpLoopMerge:
885 case SpvOpBranchConditional:
886 case SpvOpSwitch:
887 case SpvOpPhi:
888 return true;
889 break;
890 default:
891 break;
892 }
893 return false;
894 }
895
IsDecoration()896 bool Instruction::IsDecoration() const {
897 return spvOpcodeIsDecoration(opcode());
898 }
899
IsLoad()900 bool Instruction::IsLoad() const { return spvOpcodeIsLoad(opcode()); }
901
IsAtomicWithLoad()902 bool Instruction::IsAtomicWithLoad() const {
903 return spvOpcodeIsAtomicWithLoad(opcode());
904 }
905
IsAtomicOp()906 bool Instruction::IsAtomicOp() const { return spvOpcodeIsAtomicOp(opcode()); }
907
IsConstant()908 bool Instruction::IsConstant() const {
909 return IsCompileTimeConstantInst(opcode());
910 }
911 } // namespace opt
912 } // namespace spvtools
913
914 #endif // SOURCE_OPT_INSTRUCTION_H_
915