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/SymbolTableListTraits.h"
22 #include "llvm/IR/User.h"
33 struct ilist_traits<Instruction>
34 : public SymbolTableListTraits<Instruction, BasicBlock> {
36 /// \brief Return a node that marks the end of a list.
38 /// The sentinel is relative to this instance, so we use a non-static
40 Instruction *createSentinel() const;
41 static void destroySentinel(Instruction *) {}
43 Instruction *provideInitialHead() const { return createSentinel(); }
44 Instruction *ensureHead(Instruction *) const { return createSentinel(); }
45 static void noteHead(Instruction *, Instruction *) {}
48 mutable ilist_half_node<Instruction> Sentinel;
51 class Instruction : public User, public ilist_node<Instruction> {
52 void operator=(const Instruction &) = delete;
53 Instruction(const Instruction &) = delete;
56 DebugLoc DbgLoc; // 'dbg' Metadata cache.
59 /// HasMetadataBit - This is a bit stored in the SubClassData field which
60 /// indicates whether this instruction has metadata attached to it or not.
61 HasMetadataBit = 1 << 15
64 // Out of line virtual method, so the vtable, etc has a home.
65 ~Instruction() override;
67 /// user_back - Specialize the methods defined in Value, as we know that an
68 /// instruction can only be used by other instructions.
69 Instruction *user_back() { return cast<Instruction>(*user_begin());}
70 const Instruction *user_back() const { return cast<Instruction>(*user_begin());}
72 inline const BasicBlock *getParent() const { return Parent; }
73 inline BasicBlock *getParent() { return Parent; }
75 /// \brief Return the module owning the function this instruction belongs to
76 /// or nullptr it the function does not have a module.
78 /// Note: this is undefined behavior if the instruction does not have a
79 /// parent, or the parent basic block does not have a parent function.
80 const Module *getModule() const;
83 /// removeFromParent - This method unlinks 'this' from the containing basic
84 /// block, but does not delete it.
86 void removeFromParent();
88 /// eraseFromParent - This method unlinks 'this' from the containing basic
89 /// block and deletes it.
91 /// \returns an iterator pointing to the element after the erased one
92 iplist<Instruction>::iterator eraseFromParent();
94 /// Insert an unlinked instruction into a basic block immediately before
95 /// the specified instruction.
96 void insertBefore(Instruction *InsertPos);
98 /// Insert an unlinked instruction into a basic block immediately after the
99 /// specified instruction.
100 void insertAfter(Instruction *InsertPos);
102 /// moveBefore - Unlink this instruction from its current basic block and
103 /// insert it into the basic block that MovePos lives in, right before
105 void moveBefore(Instruction *MovePos);
107 //===--------------------------------------------------------------------===//
108 // Subclass classification.
109 //===--------------------------------------------------------------------===//
111 /// getOpcode() returns a member of one of the enums like Instruction::Add.
112 unsigned getOpcode() const { return getValueID() - InstructionVal; }
114 const char *getOpcodeName() const { return getOpcodeName(getOpcode()); }
115 bool isTerminator() const { return isTerminator(getOpcode()); }
116 bool isBinaryOp() const { return isBinaryOp(getOpcode()); }
117 bool isShift() { return isShift(getOpcode()); }
118 bool isCast() const { return isCast(getOpcode()); }
120 static const char* getOpcodeName(unsigned OpCode);
122 static inline bool isTerminator(unsigned OpCode) {
123 return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
126 static inline bool isBinaryOp(unsigned Opcode) {
127 return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
130 /// @brief Determine if the Opcode is one of the shift instructions.
131 static inline bool isShift(unsigned Opcode) {
132 return Opcode >= Shl && Opcode <= AShr;
135 /// isLogicalShift - Return true if this is a logical shift left or a logical
137 inline bool isLogicalShift() const {
138 return getOpcode() == Shl || getOpcode() == LShr;
141 /// isArithmeticShift - Return true if this is an arithmetic shift right.
142 inline bool isArithmeticShift() const {
143 return getOpcode() == AShr;
146 /// @brief Determine if the OpCode is one of the CastInst instructions.
147 static inline bool isCast(unsigned OpCode) {
148 return OpCode >= CastOpsBegin && OpCode < CastOpsEnd;
151 //===--------------------------------------------------------------------===//
152 // Metadata manipulation.
153 //===--------------------------------------------------------------------===//
155 /// hasMetadata() - Return true if this instruction has any metadata attached
157 bool hasMetadata() const { return DbgLoc || hasMetadataHashEntry(); }
159 /// hasMetadataOtherThanDebugLoc - Return true if this instruction has
160 /// metadata attached to it other than a debug location.
161 bool hasMetadataOtherThanDebugLoc() const {
162 return hasMetadataHashEntry();
165 /// getMetadata - Get the metadata of given kind attached to this Instruction.
166 /// If the metadata is not found then return null.
167 MDNode *getMetadata(unsigned KindID) const {
168 if (!hasMetadata()) return nullptr;
169 return getMetadataImpl(KindID);
172 /// getMetadata - Get the metadata of given kind attached to this Instruction.
173 /// If the metadata is not found then return null.
174 MDNode *getMetadata(StringRef Kind) const {
175 if (!hasMetadata()) return nullptr;
176 return getMetadataImpl(Kind);
179 /// getAllMetadata - Get all metadata attached to this Instruction. The first
180 /// element of each pair returned is the KindID, the second element is the
181 /// metadata value. This list is returned sorted by the KindID.
183 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
185 getAllMetadataImpl(MDs);
188 /// getAllMetadataOtherThanDebugLoc - This does the same thing as
189 /// getAllMetadata, except that it filters out the debug location.
190 void getAllMetadataOtherThanDebugLoc(
191 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
192 if (hasMetadataOtherThanDebugLoc())
193 getAllMetadataOtherThanDebugLocImpl(MDs);
196 /// getAAMetadata - Fills the AAMDNodes structure with AA metadata from
197 /// this instruction. When Merge is true, the existing AA metadata is
198 /// merged with that from this instruction providing the most-general result.
199 void getAAMetadata(AAMDNodes &N, bool Merge = false) const;
201 /// setMetadata - Set the metadata of the specified kind to the specified
202 /// node. This updates/replaces metadata if already present, or removes it if
204 void setMetadata(unsigned KindID, MDNode *Node);
205 void setMetadata(StringRef Kind, MDNode *Node);
207 /// Drop all unknown metadata except for debug locations.
209 /// Passes are required to drop metadata they don't understand. This is a
210 /// convenience method for passes to do so.
211 void dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs);
212 void dropUnknownNonDebugMetadata() {
213 return dropUnknownNonDebugMetadata(None);
215 void dropUnknownNonDebugMetadata(unsigned ID1) {
216 return dropUnknownNonDebugMetadata(makeArrayRef(ID1));
218 void dropUnknownNonDebugMetadata(unsigned ID1, unsigned ID2) {
219 unsigned IDs[] = {ID1, ID2};
220 return dropUnknownNonDebugMetadata(IDs);
224 /// setAAMetadata - Sets the metadata on this instruction from the
225 /// AAMDNodes structure.
226 void setAAMetadata(const AAMDNodes &N);
228 /// setDebugLoc - Set the debug location information for this instruction.
229 void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); }
231 /// getDebugLoc - Return the debug location for this node as a DebugLoc.
232 const DebugLoc &getDebugLoc() const { return DbgLoc; }
234 /// Set or clear the unsafe-algebra flag on this instruction, which must be an
235 /// operator which supports this flag. See LangRef.html for the meaning of
237 void setHasUnsafeAlgebra(bool B);
239 /// Set or clear the no-nans flag on this instruction, which must be an
240 /// operator which supports this flag. See LangRef.html for the meaning of
242 void setHasNoNaNs(bool B);
244 /// Set or clear the no-infs flag on this instruction, which must be an
245 /// operator which supports this flag. See LangRef.html for the meaning of
247 void setHasNoInfs(bool B);
249 /// Set or clear the no-signed-zeros flag on this instruction, which must be
250 /// an operator which supports this flag. See LangRef.html for the meaning of
252 void setHasNoSignedZeros(bool B);
254 /// Set or clear the allow-reciprocal flag on this instruction, which must be
255 /// an operator which supports this flag. See LangRef.html for the meaning of
257 void setHasAllowReciprocal(bool B);
259 /// Convenience function for setting multiple fast-math flags on this
260 /// instruction, which must be an operator which supports these flags. See
261 /// LangRef.html for the meaning of these flags.
262 void setFastMathFlags(FastMathFlags FMF);
264 /// Convenience function for transferring all fast-math flag values to this
265 /// instruction, which must be an operator which supports these flags. See
266 /// LangRef.html for the meaning of these flags.
267 void copyFastMathFlags(FastMathFlags FMF);
269 /// Determine whether the unsafe-algebra flag is set.
270 bool hasUnsafeAlgebra() const;
272 /// Determine whether the no-NaNs flag is set.
273 bool hasNoNaNs() const;
275 /// Determine whether the no-infs flag is set.
276 bool hasNoInfs() const;
278 /// Determine whether the no-signed-zeros flag is set.
279 bool hasNoSignedZeros() const;
281 /// Determine whether the allow-reciprocal flag is set.
282 bool hasAllowReciprocal() const;
284 /// Convenience function for getting all the fast-math flags, which must be an
285 /// operator which supports these flags. See LangRef.html for the meaning of
287 FastMathFlags getFastMathFlags() const;
289 /// Copy I's fast-math flags
290 void copyFastMathFlags(const Instruction *I);
293 /// hasMetadataHashEntry - Return true if we have an entry in the on-the-side
295 bool hasMetadataHashEntry() const {
296 return (getSubclassDataFromValue() & HasMetadataBit) != 0;
299 // These are all implemented in Metadata.cpp.
300 MDNode *getMetadataImpl(unsigned KindID) const;
301 MDNode *getMetadataImpl(StringRef Kind) const;
303 getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
304 void getAllMetadataOtherThanDebugLocImpl(
305 SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
306 void clearMetadataHashEntries();
308 //===--------------------------------------------------------------------===//
309 // Predicates and helper methods.
310 //===--------------------------------------------------------------------===//
313 /// isAssociative - Return true if the instruction is associative:
315 /// Associative operators satisfy: x op (y op z) === (x op y) op z
317 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
319 bool isAssociative() const;
320 static bool isAssociative(unsigned op);
322 /// isCommutative - Return true if the instruction is commutative:
324 /// Commutative operators satisfy: (x op y) === (y op x)
326 /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
327 /// applied to any type.
329 bool isCommutative() const { return isCommutative(getOpcode()); }
330 static bool isCommutative(unsigned op);
332 /// isIdempotent - Return true if the instruction is idempotent:
334 /// Idempotent operators satisfy: x op x === x
336 /// In LLVM, the And and Or operators are idempotent.
338 bool isIdempotent() const { return isIdempotent(getOpcode()); }
339 static bool isIdempotent(unsigned op);
341 /// isNilpotent - Return true if the instruction is nilpotent:
343 /// Nilpotent operators satisfy: x op x === Id,
345 /// where Id is the identity for the operator, i.e. a constant such that
346 /// x op Id === x and Id op x === x for all x.
348 /// In LLVM, the Xor operator is nilpotent.
350 bool isNilpotent() const { return isNilpotent(getOpcode()); }
351 static bool isNilpotent(unsigned op);
353 /// mayWriteToMemory - Return true if this instruction may modify memory.
355 bool mayWriteToMemory() const;
357 /// mayReadFromMemory - Return true if this instruction may read memory.
359 bool mayReadFromMemory() const;
361 /// mayReadOrWriteMemory - Return true if this instruction may read or
364 bool mayReadOrWriteMemory() const {
365 return mayReadFromMemory() || mayWriteToMemory();
368 /// isAtomic - Return true if this instruction has an
369 /// AtomicOrdering of unordered or higher.
371 bool isAtomic() const;
373 /// mayThrow - Return true if this instruction may throw an exception.
375 bool mayThrow() const;
377 /// mayReturn - Return true if this is a function that may return.
378 /// this is true for all normal instructions. The only exception
379 /// is functions that are marked with the 'noreturn' attribute.
381 bool mayReturn() const;
383 /// mayHaveSideEffects - Return true if the instruction may have side effects.
385 /// Note that this does not consider malloc and alloca to have side
386 /// effects because the newly allocated memory is completely invisible to
387 /// instructions which don't use the returned value. For cases where this
388 /// matters, isSafeToSpeculativelyExecute may be more appropriate.
389 bool mayHaveSideEffects() const {
390 return mayWriteToMemory() || mayThrow() || !mayReturn();
393 /// \brief Return true if the instruction is a variety of EH-block.
394 bool isEHPad() const {
395 switch (getOpcode()) {
396 case Instruction::CatchPad:
397 case Instruction::CatchEndPad:
398 case Instruction::CleanupPad:
399 case Instruction::CleanupEndPad:
400 case Instruction::LandingPad:
401 case Instruction::TerminatePad:
408 /// clone() - Create a copy of 'this' instruction that is identical in all
409 /// ways except the following:
410 /// * The instruction has no parent
411 /// * The instruction has no name
413 Instruction *clone() const;
415 /// isIdenticalTo - Return true if the specified instruction is exactly
416 /// identical to the current one. This means that all operands match and any
417 /// extra information (e.g. load is volatile) agree.
418 bool isIdenticalTo(const Instruction *I) const;
420 /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
421 /// ignores the SubclassOptionalData flags, which specify conditions
422 /// under which the instruction's result is undefined.
423 bool isIdenticalToWhenDefined(const Instruction *I) const;
425 /// When checking for operation equivalence (using isSameOperationAs) it is
426 /// sometimes useful to ignore certain attributes.
427 enum OperationEquivalenceFlags {
428 /// Check for equivalence ignoring load/store alignment.
429 CompareIgnoringAlignment = 1<<0,
430 /// Check for equivalence treating a type and a vector of that type
432 CompareUsingScalarTypes = 1<<1
435 /// This function determines if the specified instruction executes the same
436 /// operation as the current one. This means that the opcodes, type, operand
437 /// types and any other factors affecting the operation must be the same. This
438 /// is similar to isIdenticalTo except the operands themselves don't have to
440 /// @returns true if the specified instruction is the same operation as
442 /// @brief Determine if one instruction is the same operation as another.
443 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
445 /// isUsedOutsideOfBlock - Return true if there are any uses of this
446 /// instruction in blocks other than the specified block. Note that PHI nodes
447 /// are considered to evaluate their operands in the corresponding predecessor
449 bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
452 /// Methods for support type inquiry through isa, cast, and dyn_cast:
453 static inline bool classof(const Value *V) {
454 return V->getValueID() >= Value::InstructionVal;
457 //----------------------------------------------------------------------
458 // Exported enumerations.
460 enum TermOps { // These terminate basic blocks
461 #define FIRST_TERM_INST(N) TermOpsBegin = N,
462 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
463 #define LAST_TERM_INST(N) TermOpsEnd = N+1
464 #include "llvm/IR/Instruction.def"
468 #define FIRST_BINARY_INST(N) BinaryOpsBegin = N,
469 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
470 #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1
471 #include "llvm/IR/Instruction.def"
475 #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N,
476 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
477 #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1
478 #include "llvm/IR/Instruction.def"
482 #define FIRST_CAST_INST(N) CastOpsBegin = N,
483 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
484 #define LAST_CAST_INST(N) CastOpsEnd = N+1
485 #include "llvm/IR/Instruction.def"
489 #define FIRST_OTHER_INST(N) OtherOpsBegin = N,
490 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
491 #define LAST_OTHER_INST(N) OtherOpsEnd = N+1
492 #include "llvm/IR/Instruction.def"
495 // Shadow Value::setValueSubclassData with a private forwarding method so that
496 // subclasses cannot accidentally use it.
497 void setValueSubclassData(unsigned short D) {
498 Value::setValueSubclassData(D);
500 unsigned short getSubclassDataFromValue() const {
501 return Value::getSubclassDataFromValue();
504 void setHasMetadataHashEntry(bool V) {
505 setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
506 (V ? HasMetadataBit : 0));
509 friend class SymbolTableListTraits<Instruction, BasicBlock>;
510 void setParent(BasicBlock *P);
512 // Instruction subclasses can stick up to 15 bits of stuff into the
513 // SubclassData field of instruction with these members.
515 // Verify that only the low 15 bits are used.
516 void setInstructionSubclassData(unsigned short D) {
517 assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
518 setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
521 unsigned getSubclassDataFromInstruction() const {
522 return getSubclassDataFromValue() & ~HasMetadataBit;
525 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
526 Instruction *InsertBefore = nullptr);
527 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
528 BasicBlock *InsertAtEnd);
531 /// Create a copy of this instruction.
532 Instruction *cloneImpl() const;
535 inline Instruction *ilist_traits<Instruction>::createSentinel() const {
536 // Since i(p)lists always publicly derive from their corresponding traits,
537 // placing a data member in this class will augment the i(p)list. But since
538 // the NodeTy is expected to be publicly derive from ilist_node<NodeTy>,
539 // there is a legal viable downcast from it to NodeTy. We use this trick to
540 // superimpose an i(p)list with a "ghostly" NodeTy, which becomes the
541 // sentinel. Dereferencing the sentinel is forbidden (save the
542 // ilist_node<NodeTy>), so no one will ever notice the superposition.
543 return static_cast<Instruction *>(&Sentinel);
546 // Instruction* is only 4-byte aligned.
548 class PointerLikeTypeTraits<Instruction*> {
549 typedef Instruction* PT;
551 static inline void *getAsVoidPointer(PT P) { return P; }
552 static inline PT getFromVoidPointer(void *P) {
553 return static_cast<PT>(P);
555 enum { NumLowBitsAvailable = 2 };
558 } // End llvm namespace