• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 constexpr uint32_t kNoDebugScope = 0;
40 constexpr 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_(spv::Op::OpNop),
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*, spv::Op);
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, spv::Op 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   spv::Op 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(spv::Op op)243   void SetOpcode(spv::Op 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   // Adds a copy of |operand| to the list of operands of this instruction.
298   inline void AddOperand(const Operand& operand);
299   // Gets the |index|-th logical operand as a single SPIR-V word. This method is
300   // not expected to be used with logical operands consisting of multiple SPIR-V
301   // words.
302   uint32_t GetSingleWordOperand(uint32_t index) const;
303   // Sets the |index|-th in-operand's data to the given |data|.
304   inline void SetInOperand(uint32_t index, Operand::OperandData&& data);
305   // Sets the |index|-th operand's data to the given |data|.
306   // This is for in-operands modification only, but with |index| expressed in
307   // terms of operand index rather than in-operand index.
308   inline void SetOperand(uint32_t index, Operand::OperandData&& data);
309   // Replace all of the in operands with those in |new_operands|.
310   inline void SetInOperands(OperandList&& new_operands);
311   // Sets the result type id.
312   inline void SetResultType(uint32_t ty_id);
HasResultType()313   inline bool HasResultType() const { return has_type_id_; }
314   // Sets the result id
315   inline void SetResultId(uint32_t res_id);
HasResultId()316   inline bool HasResultId() const { return has_result_id_; }
317   // Sets DebugScope.
318   inline void SetDebugScope(const DebugScope& scope);
GetDebugScope()319   inline const DebugScope& GetDebugScope() const { return dbg_scope_; }
320   // Add debug line inst. Renew result id if Debug[No]Line
321   void AddDebugLine(const Instruction* inst);
322   // Updates DebugInlinedAt of DebugScope and OpLine.
323   void UpdateDebugInlinedAt(uint32_t new_inlined_at);
324   // Clear line-related debug instructions attached to this instruction
325   // along with def-use entries.
326   void ClearDbgLineInsts();
327   // Return true if Shader100:Debug[No]Line
328   bool IsDebugLineInst() const;
329   // Return true if Op[No]Line or Shader100:Debug[No]Line
330   bool IsLineInst() const;
331   // Return true if OpLine or Shader100:DebugLine
332   bool IsLine() const;
333   // Return true if OpNoLine or Shader100:DebugNoLine
334   bool IsNoLine() const;
GetDebugInlinedAt()335   inline uint32_t GetDebugInlinedAt() const {
336     return dbg_scope_.GetInlinedAt();
337   }
338   // Updates lexical scope of DebugScope and OpLine.
339   void UpdateLexicalScope(uint32_t scope);
340   // Updates OpLine and DebugScope based on the information of |from|.
341   void UpdateDebugInfoFrom(const Instruction* from);
342   // Remove the |index|-th operand
RemoveOperand(uint32_t index)343   void RemoveOperand(uint32_t index) {
344     operands_.erase(operands_.begin() + index);
345   }
346   // Insert an operand before the |index|-th operand
InsertOperand(uint32_t index,Operand && operand)347   void InsertOperand(uint32_t index, Operand&& operand) {
348     operands_.insert(operands_.begin() + index, operand);
349   }
350 
351   // The following methods are similar to the above, but are for in operands.
NumInOperands()352   uint32_t NumInOperands() const {
353     return static_cast<uint32_t>(operands_.size() - TypeResultIdCount());
354   }
355   uint32_t NumInOperandWords() const;
GetInOperand(uint32_t index)356   Operand& GetInOperand(uint32_t index) {
357     return GetOperand(index + TypeResultIdCount());
358   }
GetInOperand(uint32_t index)359   const Operand& GetInOperand(uint32_t index) const {
360     return GetOperand(index + TypeResultIdCount());
361   }
GetSingleWordInOperand(uint32_t index)362   uint32_t GetSingleWordInOperand(uint32_t index) const {
363     return GetSingleWordOperand(index + TypeResultIdCount());
364   }
RemoveInOperand(uint32_t index)365   void RemoveInOperand(uint32_t index) {
366     operands_.erase(operands_.begin() + index + TypeResultIdCount());
367   }
368 
369   // Returns true if this instruction is OpNop.
370   inline bool IsNop() const;
371   // Turns this instruction to OpNop. This does not clear out all preceding
372   // line-related debug instructions.
373   inline void ToNop();
374 
375   // Runs the given function |f| on this instruction and optionally on the
376   // preceding debug line instructions.  The function will always be run
377   // if this is itself a debug line instruction.
378   inline void ForEachInst(const std::function<void(Instruction*)>& f,
379                           bool run_on_debug_line_insts = false);
380   inline void ForEachInst(const std::function<void(const Instruction*)>& f,
381                           bool run_on_debug_line_insts = false) const;
382 
383   // Runs the given function |f| on this instruction and optionally on the
384   // preceding debug line instructions.  The function will always be run
385   // if this is itself a debug line instruction. If |f| returns false,
386   // iteration is terminated and this function returns false.
387   inline bool WhileEachInst(const std::function<bool(Instruction*)>& f,
388                             bool run_on_debug_line_insts = false);
389   inline bool WhileEachInst(const std::function<bool(const Instruction*)>& f,
390                             bool run_on_debug_line_insts = false) const;
391 
392   // Runs the given function |f| on all operand ids.
393   //
394   // |f| should not transform an ID into 0, as 0 is an invalid ID.
395   inline void ForEachId(const std::function<void(uint32_t*)>& f);
396   inline void ForEachId(const std::function<void(const uint32_t*)>& f) const;
397 
398   // Runs the given function |f| on all "in" operand ids.
399   inline void ForEachInId(const std::function<void(uint32_t*)>& f);
400   inline void ForEachInId(const std::function<void(const uint32_t*)>& f) const;
401 
402   // Runs the given function |f| on all "in" operand ids. If |f| returns false,
403   // iteration is terminated and this function returns false.
404   inline bool WhileEachInId(const std::function<bool(uint32_t*)>& f);
405   inline bool WhileEachInId(
406       const std::function<bool(const uint32_t*)>& f) const;
407 
408   // Runs the given function |f| on all "in" operands.
409   inline void ForEachInOperand(const std::function<void(uint32_t*)>& f);
410   inline void ForEachInOperand(
411       const std::function<void(const uint32_t*)>& f) const;
412 
413   // Runs the given function |f| on all "in" operands. If |f| returns false,
414   // iteration is terminated and this function return false.
415   inline bool WhileEachInOperand(const std::function<bool(uint32_t*)>& f);
416   inline bool WhileEachInOperand(
417       const std::function<bool(const uint32_t*)>& f) const;
418 
419   // Returns true if it's an OpBranchConditional instruction
420   // with branch weights.
421   bool HasBranchWeights() const;
422 
423   // Returns true if any operands can be labels
424   inline bool HasLabels() const;
425 
426   // Pushes the binary segments for this instruction into the back of *|binary|.
427   void ToBinaryWithoutAttachedDebugInsts(std::vector<uint32_t>* binary) const;
428 
429   // Replaces the operands to the instruction with |new_operands|. The caller
430   // is responsible for building a complete and valid list of operands for
431   // this instruction.
432   void ReplaceOperands(const OperandList& new_operands);
433 
434   // Returns true if the instruction annotates an id with a decoration.
435   inline bool IsDecoration() const;
436 
437   // Returns true if the instruction is known to be a load from read-only
438   // memory.
439   bool IsReadOnlyLoad() const;
440 
441   // Returns the instruction that gives the base address of an address
442   // calculation.  The instruction must be a load, as defined by |IsLoad|,
443   // store, copy, or access chain instruction.  In logical addressing mode, will
444   // return an OpVariable or OpFunctionParameter instruction. For relaxed
445   // logical addressing, it would also return a load of a pointer to an opaque
446   // object.  For physical addressing mode, could return other types of
447   // instructions.
448   Instruction* GetBaseAddress() const;
449 
450   // Returns true if the instruction loads from memory or samples an image, and
451   // stores the result into an id. It considers only core instructions.
452   // Memory-to-memory instructions are not considered loads.
453   inline bool IsLoad() const;
454 
455   // Returns true if the instruction generates a pointer that is definitely
456   // read-only.  This is determined by analysing the pointer type's storage
457   // class and decorations that target the pointer's id.  It does not analyse
458   // other instructions that the pointer may be derived from.  Thus if 'true' is
459   // returned, the pointer is definitely read-only, while if 'false' is returned
460   // it is possible that the pointer may actually be read-only if it is derived
461   // from another pointer that is decorated as read-only.
462   bool IsReadOnlyPointer() const;
463 
464   // The following functions check for the various descriptor types defined in
465   // the Vulkan specification section 13.1.
466 
467   // Returns true if the instruction defines a pointer type that points to a
468   // storage image.
469   bool IsVulkanStorageImage() const;
470 
471   // Returns true if the instruction defines a pointer type that points to a
472   // sampled image.
473   bool IsVulkanSampledImage() const;
474 
475   // Returns true if the instruction defines a pointer type that points to a
476   // storage texel buffer.
477   bool IsVulkanStorageTexelBuffer() const;
478 
479   // Returns true if the instruction defines a pointer type that points to a
480   // storage buffer.
481   bool IsVulkanStorageBuffer() const;
482 
483   // Returns true if the instruction defines a variable in StorageBuffer or
484   // Uniform storage class with a pointer type that points to a storage buffer.
485   bool IsVulkanStorageBufferVariable() const;
486 
487   // Returns true if the instruction defines a pointer type that points to a
488   // uniform buffer.
489   bool IsVulkanUniformBuffer() const;
490 
491   // Returns true if the instruction is an atom operation that uses original
492   // value.
493   inline bool IsAtomicWithLoad() const;
494 
495   // Returns true if the instruction is an atom operation.
496   inline bool IsAtomicOp() const;
497 
498   // Returns true if this instruction is a branch or switch instruction (either
499   // conditional or not).
IsBranch()500   bool IsBranch() const { return spvOpcodeIsBranch(opcode()); }
501 
502   // Returns true if this instruction causes the function to finish execution
503   // and return to its caller
IsReturn()504   bool IsReturn() const { return spvOpcodeIsReturn(opcode()); }
505 
506   // Returns true if this instruction exits this function or aborts execution.
IsReturnOrAbort()507   bool IsReturnOrAbort() const { return spvOpcodeIsReturnOrAbort(opcode()); }
508 
509   // Returns true if this instruction is a basic block terminator.
IsBlockTerminator()510   bool IsBlockTerminator() const {
511     return spvOpcodeIsBlockTerminator(opcode());
512   }
513 
514   // Returns true if |this| is an instruction that define an opaque type.  Since
515   // runtime array have similar characteristics they are included as opaque
516   // types.
517   bool IsOpaqueType() const;
518 
519   // Returns true if |this| is an instruction which could be folded into a
520   // constant value.
521   bool IsFoldable() const;
522 
523   // Returns true if |this| is an instruction which could be folded into a
524   // constant value by |FoldScalar|.
525   bool IsFoldableByFoldScalar() const;
526 
527   // Returns true if |this| is an instruction which could be folded into a
528   // constant value by |FoldVector|.
529   bool IsFoldableByFoldVector() const;
530 
531   // Returns true if we are allowed to fold or otherwise manipulate the
532   // instruction that defines |id| in the given context. This includes not
533   // handling NaN values.
534   bool IsFloatingPointFoldingAllowed() const;
535 
536   inline bool operator==(const Instruction&) const;
537   inline bool operator!=(const Instruction&) const;
538   inline bool operator<(const Instruction&) const;
539 
540   // Takes ownership of the instruction owned by |i| and inserts it immediately
541   // before |this|. Returns the inserted instruction.
542   Instruction* InsertBefore(std::unique_ptr<Instruction>&& i);
543   // Takes ownership of the instructions in |list| and inserts them in order
544   // immediately before |this|.  Returns the first inserted instruction.
545   // Assumes the list is non-empty.
546   Instruction* InsertBefore(std::vector<std::unique_ptr<Instruction>>&& list);
547   using utils::IntrusiveNodeBase<Instruction>::InsertBefore;
548 
549   // Returns true if |this| is an instruction defining a constant, but not a
550   // Spec constant.
551   inline bool IsConstant() const;
552 
553   // Returns true if |this| is an instruction with an opcode safe to move
554   bool IsOpcodeCodeMotionSafe() const;
555 
556   // Pretty-prints |inst|.
557   //
558   // Provides the disassembly of a specific instruction. Utilizes |inst|'s
559   // context to provide the correct interpretation of types, constants, etc.
560   //
561   // |options| are the disassembly options. SPV_BINARY_TO_TEXT_OPTION_NO_HEADER
562   // is always added to |options|.
563   std::string PrettyPrint(uint32_t options = 0u) const;
564 
565   // Returns true if the result can be a vector and the result of each component
566   // depends on the corresponding component of any vector inputs.
567   bool IsScalarizable() const;
568 
569   // Return true if the only effect of this instructions is the result.
570   bool IsOpcodeSafeToDelete() const;
571 
572   // Returns true if it is valid to use the result of |inst| as the base
573   // pointer for a load or store.  In this case, valid is defined by the relaxed
574   // logical addressing rules when using logical addressing.  Normal validation
575   // rules for physical addressing.
576   bool IsValidBasePointer() const;
577 
578   // Returns debug opcode of an OpenCL.100.DebugInfo instruction. If
579   // it is not an OpenCL.100.DebugInfo instruction, just returns
580   // OpenCLDebugInfo100InstructionsMax.
581   OpenCLDebugInfo100Instructions GetOpenCL100DebugOpcode() const;
582 
583   // Returns debug opcode of an NonSemantic.Shader.DebugInfo.100 instruction. If
584   // it is not an NonSemantic.Shader.DebugInfo.100 instruction, just return
585   // NonSemanticShaderDebugInfo100InstructionsMax.
586   NonSemanticShaderDebugInfo100Instructions GetShader100DebugOpcode() const;
587 
588   // Returns debug opcode of an OpenCL.100.DebugInfo or
589   // NonSemantic.Shader.DebugInfo.100 instruction. Since these overlap, we
590   // return the OpenCLDebugInfo code
591   CommonDebugInfoInstructions GetCommonDebugOpcode() const;
592 
593   // Returns true if it is an OpenCL.DebugInfo.100 instruction.
IsOpenCL100DebugInstr()594   bool IsOpenCL100DebugInstr() const {
595     return GetOpenCL100DebugOpcode() != OpenCLDebugInfo100InstructionsMax;
596   }
597 
598   // Returns true if it is an NonSemantic.Shader.DebugInfo.100 instruction.
IsShader100DebugInstr()599   bool IsShader100DebugInstr() const {
600     return GetShader100DebugOpcode() !=
601            NonSemanticShaderDebugInfo100InstructionsMax;
602   }
IsCommonDebugInstr()603   bool IsCommonDebugInstr() const {
604     return GetCommonDebugOpcode() != CommonDebugInfoInstructionsMax;
605   }
606 
607   // Returns true if this instructions a non-semantic instruction.
608   bool IsNonSemanticInstruction() const;
609 
610   // Dump this instruction on stderr.  Useful when running interactive
611   // debuggers.
612   void Dump() const;
613 
614  private:
615   // Returns the total count of result type id and result id.
TypeResultIdCount()616   uint32_t TypeResultIdCount() const {
617     if (has_type_id_ && has_result_id_) return 2;
618     if (has_type_id_ || has_result_id_) return 1;
619     return 0;
620   }
621 
622   // Returns true if the instruction generates a read-only pointer, with the
623   // same caveats documented in the comment for IsReadOnlyPointer.  The first
624   // version assumes the module is a shader module.  The second assumes a
625   // kernel.
626   bool IsReadOnlyPointerShaders() const;
627   bool IsReadOnlyPointerKernel() const;
628 
629   // Returns true if the result of |inst| can be used as the base image for an
630   // instruction that samples a image, reads an image, or writes to an image.
631   bool IsValidBaseImage() const;
632 
633   IRContext* context_;  // IR Context
634   spv::Op opcode_;      // Opcode
635   bool has_type_id_;    // True if the instruction has a type id
636   bool has_result_id_;  // True if the instruction has a result id
637   uint32_t unique_id_;  // Unique instruction id
638   // All logical operands, including result type id and result id.
639   OperandList operands_;
640   // Op[No]Line or Debug[No]Line instructions preceding this instruction. Note
641   // that for Instructions representing Op[No]Line or Debug[No]Line themselves,
642   // this field should be empty.
643   std::vector<Instruction> dbg_line_insts_;
644 
645   // DebugScope that wraps this instruction.
646   DebugScope dbg_scope_;
647 
648   friend InstructionList;
649 };
650 
651 // Pretty-prints |inst| to |str| and returns |str|.
652 //
653 // Provides the disassembly of a specific instruction. Utilizes |inst|'s context
654 // to provide the correct interpretation of types, constants, etc.
655 //
656 // Disassembly uses raw ids (not pretty printed names).
657 std::ostream& operator<<(std::ostream& str, const Instruction& inst);
658 
659 inline bool Instruction::operator==(const Instruction& other) const {
660   return unique_id() == other.unique_id();
661 }
662 
663 inline bool Instruction::operator!=(const Instruction& other) const {
664   return !(*this == other);
665 }
666 
667 inline bool Instruction::operator<(const Instruction& other) const {
668   return unique_id() < other.unique_id();
669 }
670 
GetOperand(uint32_t index)671 inline Operand& Instruction::GetOperand(uint32_t index) {
672   assert(index < operands_.size() && "operand index out of bound");
673   return operands_[index];
674 }
675 
GetOperand(uint32_t index)676 inline const Operand& Instruction::GetOperand(uint32_t index) const {
677   assert(index < operands_.size() && "operand index out of bound");
678   return operands_[index];
679 }
680 
AddOperand(Operand && operand)681 inline void Instruction::AddOperand(Operand&& operand) {
682   operands_.push_back(std::move(operand));
683 }
684 
AddOperand(const Operand & operand)685 inline void Instruction::AddOperand(const Operand& operand) {
686   operands_.push_back(operand);
687 }
688 
SetInOperand(uint32_t index,Operand::OperandData && data)689 inline void Instruction::SetInOperand(uint32_t index,
690                                       Operand::OperandData&& data) {
691   SetOperand(index + TypeResultIdCount(), std::move(data));
692 }
693 
SetOperand(uint32_t index,Operand::OperandData && data)694 inline void Instruction::SetOperand(uint32_t index,
695                                     Operand::OperandData&& data) {
696   assert(index < operands_.size() && "operand index out of bound");
697   assert(index >= TypeResultIdCount() && "operand is not a in-operand");
698   operands_[index].words = std::move(data);
699 }
700 
SetInOperands(OperandList && new_operands)701 inline void Instruction::SetInOperands(OperandList&& new_operands) {
702   // Remove the old in operands.
703   operands_.erase(operands_.begin() + TypeResultIdCount(), operands_.end());
704   // Add the new in operands.
705   operands_.insert(operands_.end(), new_operands.begin(), new_operands.end());
706 }
707 
SetResultId(uint32_t res_id)708 inline void Instruction::SetResultId(uint32_t res_id) {
709   // TODO(dsinclair): Allow setting a result id if there wasn't one
710   // previously. Need to make room in the operands_ array to place the result,
711   // and update the has_result_id_ flag.
712   assert(has_result_id_);
713 
714   // TODO(dsinclair): Allow removing the result id. This needs to make sure,
715   // if there was a result id previously to remove it from the operands_ array
716   // and reset the has_result_id_ flag.
717   assert(res_id != 0);
718 
719   auto ridx = has_type_id_ ? 1 : 0;
720   operands_[ridx].words = {res_id};
721 }
722 
SetDebugScope(const DebugScope & scope)723 inline void Instruction::SetDebugScope(const DebugScope& scope) {
724   dbg_scope_ = scope;
725   for (auto& i : dbg_line_insts_) {
726     i.dbg_scope_ = scope;
727   }
728 }
729 
SetResultType(uint32_t ty_id)730 inline void Instruction::SetResultType(uint32_t ty_id) {
731   // TODO(dsinclair): Allow setting a type id if there wasn't one
732   // previously. Need to make room in the operands_ array to place the result,
733   // and update the has_type_id_ flag.
734   assert(has_type_id_);
735 
736   // TODO(dsinclair): Allow removing the type id. This needs to make sure,
737   // if there was a type id previously to remove it from the operands_ array
738   // and reset the has_type_id_ flag.
739   assert(ty_id != 0);
740 
741   operands_.front().words = {ty_id};
742 }
743 
IsNop()744 inline bool Instruction::IsNop() const {
745   return opcode_ == spv::Op::OpNop && !has_type_id_ && !has_result_id_ &&
746          operands_.empty();
747 }
748 
ToNop()749 inline void Instruction::ToNop() {
750   opcode_ = spv::Op::OpNop;
751   has_type_id_ = false;
752   has_result_id_ = false;
753   operands_.clear();
754 }
755 
WhileEachInst(const std::function<bool (Instruction *)> & f,bool run_on_debug_line_insts)756 inline bool Instruction::WhileEachInst(
757     const std::function<bool(Instruction*)>& f, bool run_on_debug_line_insts) {
758   if (run_on_debug_line_insts) {
759     for (auto& dbg_line : dbg_line_insts_) {
760       if (!f(&dbg_line)) return false;
761     }
762   }
763   return f(this);
764 }
765 
WhileEachInst(const std::function<bool (const Instruction *)> & f,bool run_on_debug_line_insts)766 inline bool Instruction::WhileEachInst(
767     const std::function<bool(const Instruction*)>& f,
768     bool run_on_debug_line_insts) const {
769   if (run_on_debug_line_insts) {
770     for (auto& dbg_line : dbg_line_insts_) {
771       if (!f(&dbg_line)) return false;
772     }
773   }
774   return f(this);
775 }
776 
ForEachInst(const std::function<void (Instruction *)> & f,bool run_on_debug_line_insts)777 inline void Instruction::ForEachInst(const std::function<void(Instruction*)>& f,
778                                      bool run_on_debug_line_insts) {
779   WhileEachInst(
780       [&f](Instruction* inst) {
781         f(inst);
782         return true;
783       },
784       run_on_debug_line_insts);
785 }
786 
ForEachInst(const std::function<void (const Instruction *)> & f,bool run_on_debug_line_insts)787 inline void Instruction::ForEachInst(
788     const std::function<void(const Instruction*)>& f,
789     bool run_on_debug_line_insts) const {
790   WhileEachInst(
791       [&f](const Instruction* inst) {
792         f(inst);
793         return true;
794       },
795       run_on_debug_line_insts);
796 }
797 
ForEachId(const std::function<void (uint32_t *)> & f)798 inline void Instruction::ForEachId(const std::function<void(uint32_t*)>& f) {
799   for (auto& operand : operands_)
800     if (spvIsIdType(operand.type)) f(&operand.words[0]);
801 }
802 
ForEachId(const std::function<void (const uint32_t *)> & f)803 inline void Instruction::ForEachId(
804     const std::function<void(const uint32_t*)>& f) const {
805   for (const auto& operand : operands_)
806     if (spvIsIdType(operand.type)) f(&operand.words[0]);
807 }
808 
WhileEachInId(const std::function<bool (uint32_t *)> & f)809 inline bool Instruction::WhileEachInId(
810     const std::function<bool(uint32_t*)>& f) {
811   for (auto& operand : operands_) {
812     if (spvIsInIdType(operand.type) && !f(&operand.words[0])) {
813       return false;
814     }
815   }
816   return true;
817 }
818 
WhileEachInId(const std::function<bool (const uint32_t *)> & f)819 inline bool Instruction::WhileEachInId(
820     const std::function<bool(const uint32_t*)>& f) const {
821   for (const auto& operand : operands_) {
822     if (spvIsInIdType(operand.type) && !f(&operand.words[0])) {
823       return false;
824     }
825   }
826   return true;
827 }
828 
ForEachInId(const std::function<void (uint32_t *)> & f)829 inline void Instruction::ForEachInId(const std::function<void(uint32_t*)>& f) {
830   WhileEachInId([&f](uint32_t* id) {
831     f(id);
832     return true;
833   });
834 }
835 
ForEachInId(const std::function<void (const uint32_t *)> & f)836 inline void Instruction::ForEachInId(
837     const std::function<void(const uint32_t*)>& f) const {
838   WhileEachInId([&f](const uint32_t* id) {
839     f(id);
840     return true;
841   });
842 }
843 
WhileEachInOperand(const std::function<bool (uint32_t *)> & f)844 inline bool Instruction::WhileEachInOperand(
845     const std::function<bool(uint32_t*)>& f) {
846   for (auto& operand : operands_) {
847     switch (operand.type) {
848       case SPV_OPERAND_TYPE_RESULT_ID:
849       case SPV_OPERAND_TYPE_TYPE_ID:
850         break;
851       default:
852         if (!f(&operand.words[0])) return false;
853         break;
854     }
855   }
856   return true;
857 }
858 
WhileEachInOperand(const std::function<bool (const uint32_t *)> & f)859 inline bool Instruction::WhileEachInOperand(
860     const std::function<bool(const uint32_t*)>& f) const {
861   for (const auto& operand : operands_) {
862     switch (operand.type) {
863       case SPV_OPERAND_TYPE_RESULT_ID:
864       case SPV_OPERAND_TYPE_TYPE_ID:
865         break;
866       default:
867         if (!f(&operand.words[0])) return false;
868         break;
869     }
870   }
871   return true;
872 }
873 
ForEachInOperand(const std::function<void (uint32_t *)> & f)874 inline void Instruction::ForEachInOperand(
875     const std::function<void(uint32_t*)>& f) {
876   WhileEachInOperand([&f](uint32_t* operand) {
877     f(operand);
878     return true;
879   });
880 }
881 
ForEachInOperand(const std::function<void (const uint32_t *)> & f)882 inline void Instruction::ForEachInOperand(
883     const std::function<void(const uint32_t*)>& f) const {
884   WhileEachInOperand([&f](const uint32_t* operand) {
885     f(operand);
886     return true;
887   });
888 }
889 
HasLabels()890 inline bool Instruction::HasLabels() const {
891   switch (opcode_) {
892     case spv::Op::OpSelectionMerge:
893     case spv::Op::OpBranch:
894     case spv::Op::OpLoopMerge:
895     case spv::Op::OpBranchConditional:
896     case spv::Op::OpSwitch:
897     case spv::Op::OpPhi:
898       return true;
899       break;
900     default:
901       break;
902   }
903   return false;
904 }
905 
IsDecoration()906 bool Instruction::IsDecoration() const {
907   return spvOpcodeIsDecoration(opcode());
908 }
909 
IsLoad()910 bool Instruction::IsLoad() const { return spvOpcodeIsLoad(opcode()); }
911 
IsAtomicWithLoad()912 bool Instruction::IsAtomicWithLoad() const {
913   return spvOpcodeIsAtomicWithLoad(opcode());
914 }
915 
IsAtomicOp()916 bool Instruction::IsAtomicOp() const { return spvOpcodeIsAtomicOp(opcode()); }
917 
IsConstant()918 bool Instruction::IsConstant() const {
919   return IsConstantInst(opcode()) && !IsSpecConstantInst(opcode());
920 }
921 }  // namespace opt
922 }  // namespace spvtools
923 
924 #endif  // SOURCE_OPT_INSTRUCTION_H_
925