1 //===-- llvm/Instruction.h - Instruction class definition -------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the declaration of the Instruction class, which is the
11 // base class for all of the LLVM instructions.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_IR_INSTRUCTION_H
16 #define LLVM_IR_INSTRUCTION_H
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/ilist_node.h"
22 #include "llvm/IR/DebugLoc.h"
23 #include "llvm/IR/SymbolTableListTraits.h"
24 #include "llvm/IR/User.h"
25 #include "llvm/IR/Value.h"
26 #include "llvm/Support/Casting.h"
39 template <> struct ilist_alloc_traits<Instruction> {
40 static inline void deleteNode(Instruction *V);
43 class Instruction : public User,
44 public ilist_node_with_parent<Instruction, BasicBlock> {
46 DebugLoc DbgLoc; // 'dbg' Metadata cache.
49 /// This is a bit stored in the SubClassData field which indicates whether
50 /// this instruction has metadata attached to it or not.
51 HasMetadataBit = 1 << 15
55 ~Instruction(); // Use deleteValue() to delete a generic Instruction.
58 Instruction(const Instruction &) = delete;
59 Instruction &operator=(const Instruction &) = delete;
61 /// Specialize the methods defined in Value, as we know that an instruction
62 /// can only be used by other instructions.
63 Instruction *user_back() { return cast<Instruction>(*user_begin());}
64 const Instruction *user_back() const { return cast<Instruction>(*user_begin());}
66 inline const BasicBlock *getParent() const { return Parent; }
67 inline BasicBlock *getParent() { return Parent; }
69 /// Return the module owning the function this instruction belongs to
70 /// or nullptr it the function does not have a module.
72 /// Note: this is undefined behavior if the instruction does not have a
73 /// parent, or the parent basic block does not have a parent function.
74 const Module *getModule() const;
76 return const_cast<Module *>(
77 static_cast<const Instruction *>(this)->getModule());
80 /// Return the function this instruction belongs to.
82 /// Note: it is undefined behavior to call this on an instruction not
83 /// currently inserted into a function.
84 const Function *getFunction() const;
85 Function *getFunction() {
86 return const_cast<Function *>(
87 static_cast<const Instruction *>(this)->getFunction());
90 /// This method unlinks 'this' from the containing basic block, but does not
92 void removeFromParent();
94 /// This method unlinks 'this' from the containing basic block and deletes it.
96 /// \returns an iterator pointing to the element after the erased one
97 SymbolTableList<Instruction>::iterator eraseFromParent();
99 /// Insert an unlinked instruction into a basic block immediately before
100 /// the specified instruction.
101 void insertBefore(Instruction *InsertPos);
103 /// Insert an unlinked instruction into a basic block immediately after the
104 /// specified instruction.
105 void insertAfter(Instruction *InsertPos);
107 /// Unlink this instruction from its current basic block and insert it into
108 /// the basic block that MovePos lives in, right before MovePos.
109 void moveBefore(Instruction *MovePos);
111 /// Unlink this instruction and insert into BB before I.
113 /// \pre I is a valid iterator into BB.
114 void moveBefore(BasicBlock &BB, SymbolTableList<Instruction>::iterator I);
116 //===--------------------------------------------------------------------===//
117 // Subclass classification.
118 //===--------------------------------------------------------------------===//
120 /// Returns a member of one of the enums like Instruction::Add.
121 unsigned getOpcode() const { return getValueID() - InstructionVal; }
123 const char *getOpcodeName() const { return getOpcodeName(getOpcode()); }
124 bool isTerminator() const { return isTerminator(getOpcode()); }
125 bool isBinaryOp() const { return isBinaryOp(getOpcode()); }
126 bool isShift() { return isShift(getOpcode()); }
127 bool isCast() const { return isCast(getOpcode()); }
128 bool isFuncletPad() const { return isFuncletPad(getOpcode()); }
130 static const char* getOpcodeName(unsigned OpCode);
132 static inline bool isTerminator(unsigned OpCode) {
133 return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
136 static inline bool isBinaryOp(unsigned Opcode) {
137 return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
140 /// Determine if the Opcode is one of the shift instructions.
141 static inline bool isShift(unsigned Opcode) {
142 return Opcode >= Shl && Opcode <= AShr;
145 /// Return true if this is a logical shift left or a logical shift right.
146 inline bool isLogicalShift() const {
147 return getOpcode() == Shl || getOpcode() == LShr;
150 /// Return true if this is an arithmetic shift right.
151 inline bool isArithmeticShift() const {
152 return getOpcode() == AShr;
155 /// Return true if this is and/or/xor.
156 inline bool isBitwiseLogicOp() const {
157 return getOpcode() == And || getOpcode() == Or || getOpcode() == Xor;
160 /// Determine if the OpCode is one of the CastInst instructions.
161 static inline bool isCast(unsigned OpCode) {
162 return OpCode >= CastOpsBegin && OpCode < CastOpsEnd;
165 /// Determine if the OpCode is one of the FuncletPadInst instructions.
166 static inline bool isFuncletPad(unsigned OpCode) {
167 return OpCode >= FuncletPadOpsBegin && OpCode < FuncletPadOpsEnd;
170 //===--------------------------------------------------------------------===//
171 // Metadata manipulation.
172 //===--------------------------------------------------------------------===//
174 /// Return true if this instruction has any metadata attached to it.
175 bool hasMetadata() const { return DbgLoc || hasMetadataHashEntry(); }
177 /// Return true if this instruction has metadata attached to it other than a
179 bool hasMetadataOtherThanDebugLoc() const {
180 return hasMetadataHashEntry();
183 /// Get the metadata of given kind attached to this Instruction.
184 /// If the metadata is not found then return null.
185 MDNode *getMetadata(unsigned KindID) const {
186 if (!hasMetadata()) return nullptr;
187 return getMetadataImpl(KindID);
190 /// Get the metadata of given kind attached to this Instruction.
191 /// If the metadata is not found then return null.
192 MDNode *getMetadata(StringRef Kind) const {
193 if (!hasMetadata()) return nullptr;
194 return getMetadataImpl(Kind);
197 /// Get all metadata attached to this Instruction. The first element of each
198 /// pair returned is the KindID, the second element is the metadata value.
199 /// This list is returned sorted by the KindID.
201 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
203 getAllMetadataImpl(MDs);
206 /// This does the same thing as getAllMetadata, except that it filters out the
208 void getAllMetadataOtherThanDebugLoc(
209 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
210 if (hasMetadataOtherThanDebugLoc())
211 getAllMetadataOtherThanDebugLocImpl(MDs);
214 /// Fills the AAMDNodes structure with AA metadata from this instruction.
215 /// When Merge is true, the existing AA metadata is merged with that from this
216 /// instruction providing the most-general result.
217 void getAAMetadata(AAMDNodes &N, bool Merge = false) const;
219 /// Set the metadata of the specified kind to the specified node. This updates
220 /// or replaces metadata if already present, or removes it if Node is null.
221 void setMetadata(unsigned KindID, MDNode *Node);
222 void setMetadata(StringRef Kind, MDNode *Node);
224 /// Copy metadata from \p SrcInst to this instruction. \p WL, if not empty,
225 /// specifies the list of meta data that needs to be copied. If \p WL is
226 /// empty, all meta data will be copied.
227 void copyMetadata(const Instruction &SrcInst,
228 ArrayRef<unsigned> WL = ArrayRef<unsigned>());
230 /// If the instruction has "branch_weights" MD_prof metadata and the MDNode
231 /// has three operands (including name string), swap the order of the
233 void swapProfMetadata();
235 /// Drop all unknown metadata except for debug locations.
237 /// Passes are required to drop metadata they don't understand. This is a
238 /// convenience method for passes to do so.
239 void dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs);
240 void dropUnknownNonDebugMetadata() {
241 return dropUnknownNonDebugMetadata(None);
243 void dropUnknownNonDebugMetadata(unsigned ID1) {
244 return dropUnknownNonDebugMetadata(makeArrayRef(ID1));
246 void dropUnknownNonDebugMetadata(unsigned ID1, unsigned ID2) {
247 unsigned IDs[] = {ID1, ID2};
248 return dropUnknownNonDebugMetadata(IDs);
252 /// Sets the metadata on this instruction from the AAMDNodes structure.
253 void setAAMetadata(const AAMDNodes &N);
255 /// Retrieve the raw weight values of a conditional branch or select.
256 /// Returns true on success with profile weights filled in.
257 /// Returns false if no metadata or invalid metadata was found.
258 bool extractProfMetadata(uint64_t &TrueVal, uint64_t &FalseVal) const;
260 /// Retrieve total raw weight values of a branch.
261 /// Returns true on success with profile total weights filled in.
262 /// Returns false if no metadata was found.
263 bool extractProfTotalWeight(uint64_t &TotalVal) const;
265 /// Updates branch_weights metadata by scaling it by \p S / \p T.
266 void updateProfWeight(uint64_t S, uint64_t T);
268 /// Sets the branch_weights metadata to \p W for CallInst.
269 void setProfWeight(uint64_t W);
271 /// Set the debug location information for this instruction.
272 void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); }
274 /// Return the debug location for this node as a DebugLoc.
275 const DebugLoc &getDebugLoc() const { return DbgLoc; }
277 /// Set or clear the nsw flag on this instruction, which must be an operator
278 /// which supports this flag. See LangRef.html for the meaning of this flag.
279 void setHasNoUnsignedWrap(bool b = true);
281 /// Set or clear the nsw flag on this instruction, which must be an operator
282 /// which supports this flag. See LangRef.html for the meaning of this flag.
283 void setHasNoSignedWrap(bool b = true);
285 /// Set or clear the exact flag on this instruction, which must be an operator
286 /// which supports this flag. See LangRef.html for the meaning of this flag.
287 void setIsExact(bool b = true);
289 /// Determine whether the no unsigned wrap flag is set.
290 bool hasNoUnsignedWrap() const;
292 /// Determine whether the no signed wrap flag is set.
293 bool hasNoSignedWrap() const;
295 /// Drops flags that may cause this instruction to evaluate to poison despite
296 /// having non-poison inputs.
297 void dropPoisonGeneratingFlags();
299 /// Determine whether the exact flag is set.
300 bool isExact() const;
302 /// Set or clear the unsafe-algebra flag on this instruction, which must be an
303 /// operator which supports this flag. See LangRef.html for the meaning of
305 void setHasUnsafeAlgebra(bool B);
307 /// Set or clear the no-nans flag on this instruction, which must be an
308 /// operator which supports this flag. See LangRef.html for the meaning of
310 void setHasNoNaNs(bool B);
312 /// Set or clear the no-infs flag on this instruction, which must be an
313 /// operator which supports this flag. See LangRef.html for the meaning of
315 void setHasNoInfs(bool B);
317 /// Set or clear the no-signed-zeros flag on this instruction, which must be
318 /// an operator which supports this flag. See LangRef.html for the meaning of
320 void setHasNoSignedZeros(bool B);
322 /// Set or clear the allow-reciprocal flag on this instruction, which must be
323 /// an operator which supports this flag. See LangRef.html for the meaning of
325 void setHasAllowReciprocal(bool B);
327 /// Convenience function for setting multiple fast-math flags on this
328 /// instruction, which must be an operator which supports these flags. See
329 /// LangRef.html for the meaning of these flags.
330 void setFastMathFlags(FastMathFlags FMF);
332 /// Convenience function for transferring all fast-math flag values to this
333 /// instruction, which must be an operator which supports these flags. See
334 /// LangRef.html for the meaning of these flags.
335 void copyFastMathFlags(FastMathFlags FMF);
337 /// Determine whether the unsafe-algebra flag is set.
338 bool hasUnsafeAlgebra() const;
340 /// Determine whether the no-NaNs flag is set.
341 bool hasNoNaNs() const;
343 /// Determine whether the no-infs flag is set.
344 bool hasNoInfs() const;
346 /// Determine whether the no-signed-zeros flag is set.
347 bool hasNoSignedZeros() const;
349 /// Determine whether the allow-reciprocal flag is set.
350 bool hasAllowReciprocal() const;
352 /// Determine whether the allow-contract flag is set.
353 bool hasAllowContract() const;
355 /// Convenience function for getting all the fast-math flags, which must be an
356 /// operator which supports these flags. See LangRef.html for the meaning of
358 FastMathFlags getFastMathFlags() const;
360 /// Copy I's fast-math flags
361 void copyFastMathFlags(const Instruction *I);
363 /// Convenience method to copy supported wrapping, exact, and fast-math flags
364 /// from V to this instruction.
365 void copyIRFlags(const Value *V);
367 /// Logical 'and' of any supported wrapping, exact, and fast-math flags of
368 /// V and this instruction.
369 void andIRFlags(const Value *V);
372 /// Return true if we have an entry in the on-the-side metadata hash.
373 bool hasMetadataHashEntry() const {
374 return (getSubclassDataFromValue() & HasMetadataBit) != 0;
377 // These are all implemented in Metadata.cpp.
378 MDNode *getMetadataImpl(unsigned KindID) const;
379 MDNode *getMetadataImpl(StringRef Kind) const;
381 getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
382 void getAllMetadataOtherThanDebugLocImpl(
383 SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
384 /// Clear all hashtable-based metadata from this instruction.
385 void clearMetadataHashEntries();
388 //===--------------------------------------------------------------------===//
389 // Predicates and helper methods.
390 //===--------------------------------------------------------------------===//
392 /// Return true if the instruction is associative:
394 /// Associative operators satisfy: x op (y op z) === (x op y) op z
396 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
398 bool isAssociative() const LLVM_READONLY;
399 static bool isAssociative(unsigned Opcode) {
400 return Opcode == And || Opcode == Or || Opcode == Xor ||
401 Opcode == Add || Opcode == Mul;
404 /// Return true if the instruction is commutative:
406 /// Commutative operators satisfy: (x op y) === (y op x)
408 /// In LLVM, these are the commutative operators, plus SetEQ and SetNE, when
409 /// applied to any type.
411 bool isCommutative() const { return isCommutative(getOpcode()); }
412 static bool isCommutative(unsigned Opcode) {
416 case And: case Or: case Xor:
423 /// Return true if the instruction is idempotent:
425 /// Idempotent operators satisfy: x op x === x
427 /// In LLVM, the And and Or operators are idempotent.
429 bool isIdempotent() const { return isIdempotent(getOpcode()); }
430 static bool isIdempotent(unsigned Opcode) {
431 return Opcode == And || Opcode == Or;
434 /// Return true if the instruction is nilpotent:
436 /// Nilpotent operators satisfy: x op x === Id,
438 /// where Id is the identity for the operator, i.e. a constant such that
439 /// x op Id === x and Id op x === x for all x.
441 /// In LLVM, the Xor operator is nilpotent.
443 bool isNilpotent() const { return isNilpotent(getOpcode()); }
444 static bool isNilpotent(unsigned Opcode) {
445 return Opcode == Xor;
448 /// Return true if this instruction may modify memory.
449 bool mayWriteToMemory() const;
451 /// Return true if this instruction may read memory.
452 bool mayReadFromMemory() const;
454 /// Return true if this instruction may read or write memory.
455 bool mayReadOrWriteMemory() const {
456 return mayReadFromMemory() || mayWriteToMemory();
459 /// Return true if this instruction has an AtomicOrdering of unordered or
461 bool isAtomic() const;
463 /// Return true if this atomic instruction loads from memory.
464 bool hasAtomicLoad() const;
466 /// Return true if this atomic instruction stores to memory.
467 bool hasAtomicStore() const;
469 /// Return true if this instruction may throw an exception.
470 bool mayThrow() const;
472 /// Return true if this instruction behaves like a memory fence: it can load
473 /// or store to memory location without being given a memory location.
474 bool isFenceLike() const {
475 switch (getOpcode()) {
478 // This list should be kept in sync with the list in mayWriteToMemory for
479 // all opcodes which don't have a memory location.
480 case Instruction::Fence:
481 case Instruction::CatchPad:
482 case Instruction::CatchRet:
483 case Instruction::Call:
484 case Instruction::Invoke:
489 /// Return true if the instruction may have side effects.
491 /// Note that this does not consider malloc and alloca to have side
492 /// effects because the newly allocated memory is completely invisible to
493 /// instructions which don't use the returned value. For cases where this
494 /// matters, isSafeToSpeculativelyExecute may be more appropriate.
495 bool mayHaveSideEffects() const { return mayWriteToMemory() || mayThrow(); }
497 /// Return true if the instruction is a variety of EH-block.
498 bool isEHPad() const {
499 switch (getOpcode()) {
500 case Instruction::CatchSwitch:
501 case Instruction::CatchPad:
502 case Instruction::CleanupPad:
503 case Instruction::LandingPad:
510 /// Create a copy of 'this' instruction that is identical in all ways except
512 /// * The instruction has no parent
513 /// * The instruction has no name
515 Instruction *clone() const;
517 /// Return true if the specified instruction is exactly identical to the
518 /// current one. This means that all operands match and any extra information
519 /// (e.g. load is volatile) agree.
520 bool isIdenticalTo(const Instruction *I) const;
522 /// This is like isIdenticalTo, except that it ignores the
523 /// SubclassOptionalData flags, which may specify conditions under which the
524 /// instruction's result is undefined.
525 bool isIdenticalToWhenDefined(const Instruction *I) const;
527 /// When checking for operation equivalence (using isSameOperationAs) it is
528 /// sometimes useful to ignore certain attributes.
529 enum OperationEquivalenceFlags {
530 /// Check for equivalence ignoring load/store alignment.
531 CompareIgnoringAlignment = 1<<0,
532 /// Check for equivalence treating a type and a vector of that type
534 CompareUsingScalarTypes = 1<<1
537 /// This function determines if the specified instruction executes the same
538 /// operation as the current one. This means that the opcodes, type, operand
539 /// types and any other factors affecting the operation must be the same. This
540 /// is similar to isIdenticalTo except the operands themselves don't have to
542 /// @returns true if the specified instruction is the same operation as
544 /// @brief Determine if one instruction is the same operation as another.
545 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
547 /// Return true if there are any uses of this instruction in blocks other than
548 /// the specified block. Note that PHI nodes are considered to evaluate their
549 /// operands in the corresponding predecessor block.
550 bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
553 /// Methods for support type inquiry through isa, cast, and dyn_cast:
554 static inline bool classof(const Value *V) {
555 return V->getValueID() >= Value::InstructionVal;
558 //----------------------------------------------------------------------
559 // Exported enumerations.
561 enum TermOps { // These terminate basic blocks
562 #define FIRST_TERM_INST(N) TermOpsBegin = N,
563 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
564 #define LAST_TERM_INST(N) TermOpsEnd = N+1
565 #include "llvm/IR/Instruction.def"
569 #define FIRST_BINARY_INST(N) BinaryOpsBegin = N,
570 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
571 #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1
572 #include "llvm/IR/Instruction.def"
576 #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N,
577 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
578 #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1
579 #include "llvm/IR/Instruction.def"
583 #define FIRST_CAST_INST(N) CastOpsBegin = N,
584 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
585 #define LAST_CAST_INST(N) CastOpsEnd = N+1
586 #include "llvm/IR/Instruction.def"
590 #define FIRST_FUNCLETPAD_INST(N) FuncletPadOpsBegin = N,
591 #define HANDLE_FUNCLETPAD_INST(N, OPC, CLASS) OPC = N,
592 #define LAST_FUNCLETPAD_INST(N) FuncletPadOpsEnd = N+1
593 #include "llvm/IR/Instruction.def"
597 #define FIRST_OTHER_INST(N) OtherOpsBegin = N,
598 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
599 #define LAST_OTHER_INST(N) OtherOpsEnd = N+1
600 #include "llvm/IR/Instruction.def"
604 friend class SymbolTableListTraits<Instruction>;
606 // Shadow Value::setValueSubclassData with a private forwarding method so that
607 // subclasses cannot accidentally use it.
608 void setValueSubclassData(unsigned short D) {
609 Value::setValueSubclassData(D);
612 unsigned short getSubclassDataFromValue() const {
613 return Value::getSubclassDataFromValue();
616 void setHasMetadataHashEntry(bool V) {
617 setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
618 (V ? HasMetadataBit : 0));
621 void setParent(BasicBlock *P);
624 // Instruction subclasses can stick up to 15 bits of stuff into the
625 // SubclassData field of instruction with these members.
627 // Verify that only the low 15 bits are used.
628 void setInstructionSubclassData(unsigned short D) {
629 assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
630 setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
633 unsigned getSubclassDataFromInstruction() const {
634 return getSubclassDataFromValue() & ~HasMetadataBit;
637 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
638 Instruction *InsertBefore = nullptr);
639 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
640 BasicBlock *InsertAtEnd);
643 /// Create a copy of this instruction.
644 Instruction *cloneImpl() const;
647 inline void ilist_alloc_traits<Instruction>::deleteNode(Instruction *V) {
651 } // end namespace llvm
653 #endif // LLVM_IR_INSTRUCTION_H