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 &) LLVM_DELETED_FUNCTION;
35 Instruction(const Instruction &) LLVM_DELETED_FUNCTION;
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 const DataLayout *getDataLayout() const;
59 /// removeFromParent - This method unlinks 'this' from the containing basic
60 /// block, but does not delete it.
62 void removeFromParent();
64 /// eraseFromParent - This method unlinks 'this' from the containing basic
65 /// block and deletes it.
67 void eraseFromParent();
69 /// insertBefore - Insert an unlinked instructions into a basic block
70 /// immediately before the specified instruction.
71 void insertBefore(Instruction *InsertPos);
73 /// insertAfter - Insert an unlinked instructions into a basic block
74 /// immediately after the specified instruction.
75 void insertAfter(Instruction *InsertPos);
77 /// moveBefore - Unlink this instruction from its current basic block and
78 /// insert it into the basic block that MovePos lives in, right before
80 void moveBefore(Instruction *MovePos);
82 //===--------------------------------------------------------------------===//
83 // Subclass classification.
84 //===--------------------------------------------------------------------===//
86 /// getOpcode() returns a member of one of the enums like Instruction::Add.
87 unsigned getOpcode() const { return getValueID() - InstructionVal; }
89 const char *getOpcodeName() const { return getOpcodeName(getOpcode()); }
90 bool isTerminator() const { return isTerminator(getOpcode()); }
91 bool isBinaryOp() const { return isBinaryOp(getOpcode()); }
92 bool isShift() { return isShift(getOpcode()); }
93 bool isCast() const { return isCast(getOpcode()); }
95 static const char* getOpcodeName(unsigned OpCode);
97 static inline bool isTerminator(unsigned OpCode) {
98 return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
101 static inline bool isBinaryOp(unsigned Opcode) {
102 return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
105 /// @brief Determine if the Opcode is one of the shift instructions.
106 static inline bool isShift(unsigned Opcode) {
107 return Opcode >= Shl && Opcode <= AShr;
110 /// isLogicalShift - Return true if this is a logical shift left or a logical
112 inline bool isLogicalShift() const {
113 return getOpcode() == Shl || getOpcode() == LShr;
116 /// isArithmeticShift - Return true if this is an arithmetic shift right.
117 inline bool isArithmeticShift() const {
118 return getOpcode() == AShr;
121 /// @brief Determine if the OpCode is one of the CastInst instructions.
122 static inline bool isCast(unsigned OpCode) {
123 return OpCode >= CastOpsBegin && OpCode < CastOpsEnd;
126 //===--------------------------------------------------------------------===//
127 // Metadata manipulation.
128 //===--------------------------------------------------------------------===//
130 /// hasMetadata() - Return true if this instruction has any metadata attached
132 bool hasMetadata() const {
133 return !DbgLoc.isUnknown() || hasMetadataHashEntry();
136 /// hasMetadataOtherThanDebugLoc - Return true if this instruction has
137 /// metadata attached to it other than a debug location.
138 bool hasMetadataOtherThanDebugLoc() const {
139 return hasMetadataHashEntry();
142 /// getMetadata - Get the metadata of given kind attached to this Instruction.
143 /// If the metadata is not found then return null.
144 MDNode *getMetadata(unsigned KindID) const {
145 if (!hasMetadata()) return nullptr;
146 return getMetadataImpl(KindID);
149 /// getMetadata - Get the metadata of given kind attached to this Instruction.
150 /// If the metadata is not found then return null.
151 MDNode *getMetadata(StringRef Kind) const {
152 if (!hasMetadata()) return nullptr;
153 return getMetadataImpl(Kind);
156 /// getAllMetadata - Get all metadata attached to this Instruction. The first
157 /// element of each pair returned is the KindID, the second element is the
158 /// metadata value. This list is returned sorted by the KindID.
160 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
162 getAllMetadataImpl(MDs);
165 /// getAllMetadataOtherThanDebugLoc - This does the same thing as
166 /// getAllMetadata, except that it filters out the debug location.
167 void getAllMetadataOtherThanDebugLoc(
168 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
169 if (hasMetadataOtherThanDebugLoc())
170 getAllMetadataOtherThanDebugLocImpl(MDs);
173 /// getAAMetadata - Fills the AAMDNodes structure with AA metadata from
174 /// this instruction. When Merge is true, the existing AA metadata is
175 /// merged with that from this instruction providing the most-general result.
176 void getAAMetadata(AAMDNodes &N, bool Merge = false) const;
178 /// setMetadata - Set the metadata of the specified kind to the specified
179 /// node. This updates/replaces metadata if already present, or removes it if
181 void setMetadata(unsigned KindID, MDNode *Node);
182 void setMetadata(StringRef Kind, MDNode *Node);
184 /// \brief Drop unknown metadata.
185 /// Passes are required to drop metadata they don't understand. This is a
186 /// convenience method for passes to do so.
187 void dropUnknownMetadata(ArrayRef<unsigned> KnownIDs);
188 void dropUnknownMetadata() {
189 return dropUnknownMetadata(None);
191 void dropUnknownMetadata(unsigned ID1) {
192 return dropUnknownMetadata(makeArrayRef(ID1));
194 void dropUnknownMetadata(unsigned ID1, unsigned ID2) {
195 unsigned IDs[] = {ID1, ID2};
196 return dropUnknownMetadata(IDs);
199 /// setAAMetadata - Sets the metadata on this instruction from the
200 /// AAMDNodes structure.
201 void setAAMetadata(const AAMDNodes &N);
203 /// setDebugLoc - Set the debug location information for this instruction.
204 void setDebugLoc(const DebugLoc &Loc) { DbgLoc = Loc; }
206 /// getDebugLoc - Return the debug location for this node as a DebugLoc.
207 const DebugLoc &getDebugLoc() const { return DbgLoc; }
209 /// Set or clear the unsafe-algebra flag on this instruction, which must be an
210 /// operator which supports this flag. See LangRef.html for the meaning of
212 void setHasUnsafeAlgebra(bool B);
214 /// Set or clear the no-nans flag on this instruction, which must be an
215 /// operator which supports this flag. See LangRef.html for the meaning of
217 void setHasNoNaNs(bool B);
219 /// Set or clear the no-infs flag on this instruction, which must be an
220 /// operator which supports this flag. See LangRef.html for the meaning of
222 void setHasNoInfs(bool B);
224 /// Set or clear the no-signed-zeros flag on this instruction, which must be
225 /// an operator which supports this flag. See LangRef.html for the meaning of
227 void setHasNoSignedZeros(bool B);
229 /// Set or clear the allow-reciprocal flag on this instruction, which must be
230 /// an operator which supports this flag. See LangRef.html for the meaning of
232 void setHasAllowReciprocal(bool B);
234 /// Convenience function for setting multiple fast-math flags on this
235 /// instruction, which must be an operator which supports these flags. See
236 /// LangRef.html for the meaning of these flags.
237 void setFastMathFlags(FastMathFlags FMF);
239 /// Convenience function for transferring all fast-math flag values to this
240 /// instruction, which must be an operator which supports these flags. See
241 /// LangRef.html for the meaning of these flags.
242 void copyFastMathFlags(FastMathFlags FMF);
244 /// Determine whether the unsafe-algebra flag is set.
245 bool hasUnsafeAlgebra() const;
247 /// Determine whether the no-NaNs flag is set.
248 bool hasNoNaNs() const;
250 /// Determine whether the no-infs flag is set.
251 bool hasNoInfs() const;
253 /// Determine whether the no-signed-zeros flag is set.
254 bool hasNoSignedZeros() const;
256 /// Determine whether the allow-reciprocal flag is set.
257 bool hasAllowReciprocal() const;
259 /// Convenience function for getting all the fast-math flags, which must be an
260 /// operator which supports these flags. See LangRef.html for the meaning of
262 FastMathFlags getFastMathFlags() const;
264 /// Copy I's fast-math flags
265 void copyFastMathFlags(const Instruction *I);
268 /// hasMetadataHashEntry - Return true if we have an entry in the on-the-side
270 bool hasMetadataHashEntry() const {
271 return (getSubclassDataFromValue() & HasMetadataBit) != 0;
274 // These are all implemented in Metadata.cpp.
275 MDNode *getMetadataImpl(unsigned KindID) const;
276 MDNode *getMetadataImpl(StringRef Kind) const;
278 getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
279 void getAllMetadataOtherThanDebugLocImpl(
280 SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
281 void clearMetadataHashEntries();
283 //===--------------------------------------------------------------------===//
284 // Predicates and helper methods.
285 //===--------------------------------------------------------------------===//
288 /// isAssociative - Return true if the instruction is associative:
290 /// Associative operators satisfy: x op (y op z) === (x op y) op z
292 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
294 bool isAssociative() const;
295 static bool isAssociative(unsigned op);
297 /// isCommutative - Return true if the instruction is commutative:
299 /// Commutative operators satisfy: (x op y) === (y op x)
301 /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
302 /// applied to any type.
304 bool isCommutative() const { return isCommutative(getOpcode()); }
305 static bool isCommutative(unsigned op);
307 /// isIdempotent - Return true if the instruction is idempotent:
309 /// Idempotent operators satisfy: x op x === x
311 /// In LLVM, the And and Or operators are idempotent.
313 bool isIdempotent() const { return isIdempotent(getOpcode()); }
314 static bool isIdempotent(unsigned op);
316 /// isNilpotent - Return true if the instruction is nilpotent:
318 /// Nilpotent operators satisfy: x op x === Id,
320 /// where Id is the identity for the operator, i.e. a constant such that
321 /// x op Id === x and Id op x === x for all x.
323 /// In LLVM, the Xor operator is nilpotent.
325 bool isNilpotent() const { return isNilpotent(getOpcode()); }
326 static bool isNilpotent(unsigned op);
328 /// mayWriteToMemory - Return true if this instruction may modify memory.
330 bool mayWriteToMemory() const;
332 /// mayReadFromMemory - Return true if this instruction may read memory.
334 bool mayReadFromMemory() const;
336 /// mayReadOrWriteMemory - Return true if this instruction may read or
339 bool mayReadOrWriteMemory() const {
340 return mayReadFromMemory() || mayWriteToMemory();
343 /// isAtomic - Return true if this instruction has an
344 /// AtomicOrdering of unordered or higher.
346 bool isAtomic() const;
348 /// mayThrow - Return true if this instruction may throw an exception.
350 bool mayThrow() const;
352 /// mayReturn - Return true if this is a function that may return.
353 /// this is true for all normal instructions. The only exception
354 /// is functions that are marked with the 'noreturn' attribute.
356 bool mayReturn() const;
358 /// mayHaveSideEffects - Return true if the instruction may have side effects.
360 /// Note that this does not consider malloc and alloca to have side
361 /// effects because the newly allocated memory is completely invisible to
362 /// instructions which don't used the returned value. For cases where this
363 /// matters, isSafeToSpeculativelyExecute may be more appropriate.
364 bool mayHaveSideEffects() const {
365 return mayWriteToMemory() || mayThrow() || !mayReturn();
368 /// clone() - Create a copy of 'this' instruction that is identical in all
369 /// ways except the following:
370 /// * The instruction has no parent
371 /// * The instruction has no name
373 Instruction *clone() const;
375 /// isIdenticalTo - Return true if the specified instruction is exactly
376 /// identical to the current one. This means that all operands match and any
377 /// extra information (e.g. load is volatile) agree.
378 bool isIdenticalTo(const Instruction *I) const;
380 /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
381 /// ignores the SubclassOptionalData flags, which specify conditions
382 /// under which the instruction's result is undefined.
383 bool isIdenticalToWhenDefined(const Instruction *I) const;
385 /// When checking for operation equivalence (using isSameOperationAs) it is
386 /// sometimes useful to ignore certain attributes.
387 enum OperationEquivalenceFlags {
388 /// Check for equivalence ignoring load/store alignment.
389 CompareIgnoringAlignment = 1<<0,
390 /// Check for equivalence treating a type and a vector of that type
392 CompareUsingScalarTypes = 1<<1
395 /// This function determines if the specified instruction executes the same
396 /// operation as the current one. This means that the opcodes, type, operand
397 /// types and any other factors affecting the operation must be the same. This
398 /// is similar to isIdenticalTo except the operands themselves don't have to
400 /// @returns true if the specified instruction is the same operation as
402 /// @brief Determine if one instruction is the same operation as another.
403 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
405 /// isUsedOutsideOfBlock - Return true if there are any uses of this
406 /// instruction in blocks other than the specified block. Note that PHI nodes
407 /// are considered to evaluate their operands in the corresponding predecessor
409 bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
412 /// Methods for support type inquiry through isa, cast, and dyn_cast:
413 static inline bool classof(const Value *V) {
414 return V->getValueID() >= Value::InstructionVal;
417 //----------------------------------------------------------------------
418 // Exported enumerations.
420 enum TermOps { // These terminate basic blocks
421 #define FIRST_TERM_INST(N) TermOpsBegin = N,
422 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
423 #define LAST_TERM_INST(N) TermOpsEnd = N+1
424 #include "llvm/IR/Instruction.def"
428 #define FIRST_BINARY_INST(N) BinaryOpsBegin = N,
429 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
430 #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1
431 #include "llvm/IR/Instruction.def"
435 #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N,
436 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
437 #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1
438 #include "llvm/IR/Instruction.def"
442 #define FIRST_CAST_INST(N) CastOpsBegin = N,
443 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
444 #define LAST_CAST_INST(N) CastOpsEnd = N+1
445 #include "llvm/IR/Instruction.def"
449 #define FIRST_OTHER_INST(N) OtherOpsBegin = N,
450 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
451 #define LAST_OTHER_INST(N) OtherOpsEnd = N+1
452 #include "llvm/IR/Instruction.def"
455 // Shadow Value::setValueSubclassData with a private forwarding method so that
456 // subclasses cannot accidentally use it.
457 void setValueSubclassData(unsigned short D) {
458 Value::setValueSubclassData(D);
460 unsigned short getSubclassDataFromValue() const {
461 return Value::getSubclassDataFromValue();
464 void setHasMetadataHashEntry(bool V) {
465 setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
466 (V ? HasMetadataBit : 0));
469 friend class SymbolTableListTraits<Instruction, BasicBlock>;
470 void setParent(BasicBlock *P);
472 // Instruction subclasses can stick up to 15 bits of stuff into the
473 // SubclassData field of instruction with these members.
475 // Verify that only the low 15 bits are used.
476 void setInstructionSubclassData(unsigned short D) {
477 assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
478 setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
481 unsigned getSubclassDataFromInstruction() const {
482 return getSubclassDataFromValue() & ~HasMetadataBit;
485 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
486 Instruction *InsertBefore = nullptr);
487 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
488 BasicBlock *InsertAtEnd);
489 virtual Instruction *clone_impl() const = 0;
493 // Instruction* is only 4-byte aligned.
495 class PointerLikeTypeTraits<Instruction*> {
496 typedef Instruction* PT;
498 static inline void *getAsVoidPointer(PT P) { return P; }
499 static inline PT getFromVoidPointer(void *P) {
500 return static_cast<PT>(P);
502 enum { NumLowBitsAvailable = 2 };
505 } // End llvm namespace