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/ilist_node.h"
20 #include "llvm/IR/DebugLoc.h"
21 #include "llvm/IR/User.h"
30 template<typename ValueSubClass, typename ItemParentClass>
31 class SymbolTableListTraits;
33 class Instruction : public User, public ilist_node<Instruction> {
34 void operator=(const Instruction &) = delete;
35 Instruction(const Instruction &) = delete;
38 DebugLoc DbgLoc; // 'dbg' Metadata cache.
41 /// HasMetadataBit - This is a bit stored in the SubClassData field which
42 /// indicates whether this instruction has metadata attached to it or not.
43 HasMetadataBit = 1 << 15
46 // Out of line virtual method, so the vtable, etc has a home.
49 /// user_back - Specialize the methods defined in Value, as we know that an
50 /// instruction can only be used by other instructions.
51 Instruction *user_back() { return cast<Instruction>(*user_begin());}
52 const Instruction *user_back() const { return cast<Instruction>(*user_begin());}
54 inline const BasicBlock *getParent() const { return Parent; }
55 inline BasicBlock *getParent() { return Parent; }
57 /// \brief Return the module owning the function this instruction belongs to
58 /// or nullptr it the function does not have a module.
60 /// Note: this is undefined behavior if the instruction does not have a
61 /// parent, or the parent basic block does not have a parent function.
62 const Module *getModule() const;
64 /// removeFromParent - This method unlinks 'this' from the containing basic
65 /// block, but does not delete it.
67 void removeFromParent();
69 /// eraseFromParent - This method unlinks 'this' from the containing basic
70 /// block and deletes it.
72 void eraseFromParent();
74 /// insertBefore - Insert an unlinked instructions into a basic block
75 /// immediately before the specified instruction.
76 void insertBefore(Instruction *InsertPos);
78 /// insertAfter - Insert an unlinked instructions into a basic block
79 /// immediately after the specified instruction.
80 void insertAfter(Instruction *InsertPos);
82 /// moveBefore - Unlink this instruction from its current basic block and
83 /// insert it into the basic block that MovePos lives in, right before
85 void moveBefore(Instruction *MovePos);
87 //===--------------------------------------------------------------------===//
88 // Subclass classification.
89 //===--------------------------------------------------------------------===//
91 /// getOpcode() returns a member of one of the enums like Instruction::Add.
92 unsigned getOpcode() const { return getValueID() - InstructionVal; }
94 const char *getOpcodeName() const { return getOpcodeName(getOpcode()); }
95 bool isTerminator() const { return isTerminator(getOpcode()); }
96 bool isBinaryOp() const { return isBinaryOp(getOpcode()); }
97 bool isShift() { return isShift(getOpcode()); }
98 bool isCast() const { return isCast(getOpcode()); }
100 static const char* getOpcodeName(unsigned OpCode);
102 static inline bool isTerminator(unsigned OpCode) {
103 return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
106 static inline bool isBinaryOp(unsigned Opcode) {
107 return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
110 /// @brief Determine if the Opcode is one of the shift instructions.
111 static inline bool isShift(unsigned Opcode) {
112 return Opcode >= Shl && Opcode <= AShr;
115 /// isLogicalShift - Return true if this is a logical shift left or a logical
117 inline bool isLogicalShift() const {
118 return getOpcode() == Shl || getOpcode() == LShr;
121 /// isArithmeticShift - Return true if this is an arithmetic shift right.
122 inline bool isArithmeticShift() const {
123 return getOpcode() == AShr;
126 /// @brief Determine if the OpCode is one of the CastInst instructions.
127 static inline bool isCast(unsigned OpCode) {
128 return OpCode >= CastOpsBegin && OpCode < CastOpsEnd;
131 //===--------------------------------------------------------------------===//
132 // Metadata manipulation.
133 //===--------------------------------------------------------------------===//
135 /// hasMetadata() - Return true if this instruction has any metadata attached
137 bool hasMetadata() const {
138 return !DbgLoc.isUnknown() || hasMetadataHashEntry();
141 /// hasMetadataOtherThanDebugLoc - Return true if this instruction has
142 /// metadata attached to it other than a debug location.
143 bool hasMetadataOtherThanDebugLoc() const {
144 return hasMetadataHashEntry();
147 /// getMetadata - Get the metadata of given kind attached to this Instruction.
148 /// If the metadata is not found then return null.
149 MDNode *getMetadata(unsigned KindID) const {
150 if (!hasMetadata()) return nullptr;
151 return getMetadataImpl(KindID);
154 /// getMetadata - Get the metadata of given kind attached to this Instruction.
155 /// If the metadata is not found then return null.
156 MDNode *getMetadata(StringRef Kind) const {
157 if (!hasMetadata()) return nullptr;
158 return getMetadataImpl(Kind);
161 /// getAllMetadata - Get all metadata attached to this Instruction. The first
162 /// element of each pair returned is the KindID, the second element is the
163 /// metadata value. This list is returned sorted by the KindID.
165 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
167 getAllMetadataImpl(MDs);
170 /// getAllMetadataOtherThanDebugLoc - This does the same thing as
171 /// getAllMetadata, except that it filters out the debug location.
172 void getAllMetadataOtherThanDebugLoc(
173 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
174 if (hasMetadataOtherThanDebugLoc())
175 getAllMetadataOtherThanDebugLocImpl(MDs);
178 /// getAAMetadata - Fills the AAMDNodes structure with AA metadata from
179 /// this instruction. When Merge is true, the existing AA metadata is
180 /// merged with that from this instruction providing the most-general result.
181 void getAAMetadata(AAMDNodes &N, bool Merge = false) const;
183 /// setMetadata - Set the metadata of the specified kind to the specified
184 /// node. This updates/replaces metadata if already present, or removes it if
186 void setMetadata(unsigned KindID, MDNode *Node);
187 void setMetadata(StringRef Kind, MDNode *Node);
189 /// \brief Drop unknown metadata.
190 /// Passes are required to drop metadata they don't understand. This is a
191 /// convenience method for passes to do so.
192 void dropUnknownMetadata(ArrayRef<unsigned> KnownIDs);
193 void dropUnknownMetadata() {
194 return dropUnknownMetadata(None);
196 void dropUnknownMetadata(unsigned ID1) {
197 return dropUnknownMetadata(makeArrayRef(ID1));
199 void dropUnknownMetadata(unsigned ID1, unsigned ID2) {
200 unsigned IDs[] = {ID1, ID2};
201 return dropUnknownMetadata(IDs);
204 /// setAAMetadata - Sets the metadata on this instruction from the
205 /// AAMDNodes structure.
206 void setAAMetadata(const AAMDNodes &N);
208 /// setDebugLoc - Set the debug location information for this instruction.
209 void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); }
211 /// getDebugLoc - Return the debug location for this node as a DebugLoc.
212 const DebugLoc &getDebugLoc() const { return DbgLoc; }
214 /// Set or clear the unsafe-algebra flag on this instruction, which must be an
215 /// operator which supports this flag. See LangRef.html for the meaning of
217 void setHasUnsafeAlgebra(bool B);
219 /// Set or clear the no-nans flag on this instruction, which must be an
220 /// operator which supports this flag. See LangRef.html for the meaning of
222 void setHasNoNaNs(bool B);
224 /// Set or clear the no-infs flag on this instruction, which must be an
225 /// operator which supports this flag. See LangRef.html for the meaning of
227 void setHasNoInfs(bool B);
229 /// Set or clear the no-signed-zeros flag on this instruction, which must be
230 /// an operator which supports this flag. See LangRef.html for the meaning of
232 void setHasNoSignedZeros(bool B);
234 /// Set or clear the allow-reciprocal flag on this instruction, which must be
235 /// an operator which supports this flag. See LangRef.html for the meaning of
237 void setHasAllowReciprocal(bool B);
239 /// Convenience function for setting multiple fast-math flags on this
240 /// instruction, which must be an operator which supports these flags. See
241 /// LangRef.html for the meaning of these flags.
242 void setFastMathFlags(FastMathFlags FMF);
244 /// Convenience function for transferring all fast-math flag values to this
245 /// instruction, which must be an operator which supports these flags. See
246 /// LangRef.html for the meaning of these flags.
247 void copyFastMathFlags(FastMathFlags FMF);
249 /// Determine whether the unsafe-algebra flag is set.
250 bool hasUnsafeAlgebra() const;
252 /// Determine whether the no-NaNs flag is set.
253 bool hasNoNaNs() const;
255 /// Determine whether the no-infs flag is set.
256 bool hasNoInfs() const;
258 /// Determine whether the no-signed-zeros flag is set.
259 bool hasNoSignedZeros() const;
261 /// Determine whether the allow-reciprocal flag is set.
262 bool hasAllowReciprocal() const;
264 /// Convenience function for getting all the fast-math flags, which must be an
265 /// operator which supports these flags. See LangRef.html for the meaning of
267 FastMathFlags getFastMathFlags() const;
269 /// Copy I's fast-math flags
270 void copyFastMathFlags(const Instruction *I);
273 /// hasMetadataHashEntry - Return true if we have an entry in the on-the-side
275 bool hasMetadataHashEntry() const {
276 return (getSubclassDataFromValue() & HasMetadataBit) != 0;
279 // These are all implemented in Metadata.cpp.
280 MDNode *getMetadataImpl(unsigned KindID) const;
281 MDNode *getMetadataImpl(StringRef Kind) const;
283 getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
284 void getAllMetadataOtherThanDebugLocImpl(
285 SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
286 void clearMetadataHashEntries();
288 //===--------------------------------------------------------------------===//
289 // Predicates and helper methods.
290 //===--------------------------------------------------------------------===//
293 /// isAssociative - Return true if the instruction is associative:
295 /// Associative operators satisfy: x op (y op z) === (x op y) op z
297 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
299 bool isAssociative() const;
300 static bool isAssociative(unsigned op);
302 /// isCommutative - Return true if the instruction is commutative:
304 /// Commutative operators satisfy: (x op y) === (y op x)
306 /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
307 /// applied to any type.
309 bool isCommutative() const { return isCommutative(getOpcode()); }
310 static bool isCommutative(unsigned op);
312 /// isIdempotent - Return true if the instruction is idempotent:
314 /// Idempotent operators satisfy: x op x === x
316 /// In LLVM, the And and Or operators are idempotent.
318 bool isIdempotent() const { return isIdempotent(getOpcode()); }
319 static bool isIdempotent(unsigned op);
321 /// isNilpotent - Return true if the instruction is nilpotent:
323 /// Nilpotent operators satisfy: x op x === Id,
325 /// where Id is the identity for the operator, i.e. a constant such that
326 /// x op Id === x and Id op x === x for all x.
328 /// In LLVM, the Xor operator is nilpotent.
330 bool isNilpotent() const { return isNilpotent(getOpcode()); }
331 static bool isNilpotent(unsigned op);
333 /// mayWriteToMemory - Return true if this instruction may modify memory.
335 bool mayWriteToMemory() const;
337 /// mayReadFromMemory - Return true if this instruction may read memory.
339 bool mayReadFromMemory() const;
341 /// mayReadOrWriteMemory - Return true if this instruction may read or
344 bool mayReadOrWriteMemory() const {
345 return mayReadFromMemory() || mayWriteToMemory();
348 /// isAtomic - Return true if this instruction has an
349 /// AtomicOrdering of unordered or higher.
351 bool isAtomic() const;
353 /// mayThrow - Return true if this instruction may throw an exception.
355 bool mayThrow() const;
357 /// mayReturn - Return true if this is a function that may return.
358 /// this is true for all normal instructions. The only exception
359 /// is functions that are marked with the 'noreturn' attribute.
361 bool mayReturn() const;
363 /// mayHaveSideEffects - Return true if the instruction may have side effects.
365 /// Note that this does not consider malloc and alloca to have side
366 /// effects because the newly allocated memory is completely invisible to
367 /// instructions which don't used the returned value. For cases where this
368 /// matters, isSafeToSpeculativelyExecute may be more appropriate.
369 bool mayHaveSideEffects() const {
370 return mayWriteToMemory() || mayThrow() || !mayReturn();
373 /// clone() - Create a copy of 'this' instruction that is identical in all
374 /// ways except the following:
375 /// * The instruction has no parent
376 /// * The instruction has no name
378 Instruction *clone() const;
380 /// isIdenticalTo - Return true if the specified instruction is exactly
381 /// identical to the current one. This means that all operands match and any
382 /// extra information (e.g. load is volatile) agree.
383 bool isIdenticalTo(const Instruction *I) const;
385 /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
386 /// ignores the SubclassOptionalData flags, which specify conditions
387 /// under which the instruction's result is undefined.
388 bool isIdenticalToWhenDefined(const Instruction *I) const;
390 /// When checking for operation equivalence (using isSameOperationAs) it is
391 /// sometimes useful to ignore certain attributes.
392 enum OperationEquivalenceFlags {
393 /// Check for equivalence ignoring load/store alignment.
394 CompareIgnoringAlignment = 1<<0,
395 /// Check for equivalence treating a type and a vector of that type
397 CompareUsingScalarTypes = 1<<1
400 /// This function determines if the specified instruction executes the same
401 /// operation as the current one. This means that the opcodes, type, operand
402 /// types and any other factors affecting the operation must be the same. This
403 /// is similar to isIdenticalTo except the operands themselves don't have to
405 /// @returns true if the specified instruction is the same operation as
407 /// @brief Determine if one instruction is the same operation as another.
408 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
410 /// isUsedOutsideOfBlock - Return true if there are any uses of this
411 /// instruction in blocks other than the specified block. Note that PHI nodes
412 /// are considered to evaluate their operands in the corresponding predecessor
414 bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
417 /// Methods for support type inquiry through isa, cast, and dyn_cast:
418 static inline bool classof(const Value *V) {
419 return V->getValueID() >= Value::InstructionVal;
422 //----------------------------------------------------------------------
423 // Exported enumerations.
425 enum TermOps { // These terminate basic blocks
426 #define FIRST_TERM_INST(N) TermOpsBegin = N,
427 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
428 #define LAST_TERM_INST(N) TermOpsEnd = N+1
429 #include "llvm/IR/Instruction.def"
433 #define FIRST_BINARY_INST(N) BinaryOpsBegin = N,
434 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
435 #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1
436 #include "llvm/IR/Instruction.def"
440 #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N,
441 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
442 #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1
443 #include "llvm/IR/Instruction.def"
447 #define FIRST_CAST_INST(N) CastOpsBegin = N,
448 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
449 #define LAST_CAST_INST(N) CastOpsEnd = N+1
450 #include "llvm/IR/Instruction.def"
454 #define FIRST_OTHER_INST(N) OtherOpsBegin = N,
455 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
456 #define LAST_OTHER_INST(N) OtherOpsEnd = N+1
457 #include "llvm/IR/Instruction.def"
460 // Shadow Value::setValueSubclassData with a private forwarding method so that
461 // subclasses cannot accidentally use it.
462 void setValueSubclassData(unsigned short D) {
463 Value::setValueSubclassData(D);
465 unsigned short getSubclassDataFromValue() const {
466 return Value::getSubclassDataFromValue();
469 void setHasMetadataHashEntry(bool V) {
470 setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
471 (V ? HasMetadataBit : 0));
474 friend class SymbolTableListTraits<Instruction, BasicBlock>;
475 void setParent(BasicBlock *P);
477 // Instruction subclasses can stick up to 15 bits of stuff into the
478 // SubclassData field of instruction with these members.
480 // Verify that only the low 15 bits are used.
481 void setInstructionSubclassData(unsigned short D) {
482 assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
483 setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
486 unsigned getSubclassDataFromInstruction() const {
487 return getSubclassDataFromValue() & ~HasMetadataBit;
490 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
491 Instruction *InsertBefore = nullptr);
492 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
493 BasicBlock *InsertAtEnd);
494 virtual Instruction *clone_impl() const = 0;
498 // Instruction* is only 4-byte aligned.
500 class PointerLikeTypeTraits<Instruction*> {
501 typedef Instruction* PT;
503 static inline void *getAsVoidPointer(PT P) { return P; }
504 static inline PT getFromVoidPointer(void *P) {
505 return static_cast<PT>(P);
507 enum { NumLowBitsAvailable = 2 };
510 } // End llvm namespace