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