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 /// \brief Drop unknown metadata.
208 /// Passes are required to drop metadata they don't understand. This is a
209 /// convenience method for passes to do so.
210 void dropUnknownMetadata(ArrayRef<unsigned> KnownIDs);
211 void dropUnknownMetadata() {
212 return dropUnknownMetadata(None);
214 void dropUnknownMetadata(unsigned ID1) {
215 return dropUnknownMetadata(makeArrayRef(ID1));
217 void dropUnknownMetadata(unsigned ID1, unsigned ID2) {
218 unsigned IDs[] = {ID1, ID2};
219 return dropUnknownMetadata(IDs);
222 /// setAAMetadata - Sets the metadata on this instruction from the
223 /// AAMDNodes structure.
224 void setAAMetadata(const AAMDNodes &N);
226 /// setDebugLoc - Set the debug location information for this instruction.
227 void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); }
229 /// getDebugLoc - Return the debug location for this node as a DebugLoc.
230 const DebugLoc &getDebugLoc() const { return DbgLoc; }
232 /// Set or clear the unsafe-algebra flag on this instruction, which must be an
233 /// operator which supports this flag. See LangRef.html for the meaning of
235 void setHasUnsafeAlgebra(bool B);
237 /// Set or clear the no-nans flag on this instruction, which must be an
238 /// operator which supports this flag. See LangRef.html for the meaning of
240 void setHasNoNaNs(bool B);
242 /// Set or clear the no-infs flag on this instruction, which must be an
243 /// operator which supports this flag. See LangRef.html for the meaning of
245 void setHasNoInfs(bool B);
247 /// Set or clear the no-signed-zeros flag on this instruction, which must be
248 /// an operator which supports this flag. See LangRef.html for the meaning of
250 void setHasNoSignedZeros(bool B);
252 /// Set or clear the allow-reciprocal flag on this instruction, which must be
253 /// an operator which supports this flag. See LangRef.html for the meaning of
255 void setHasAllowReciprocal(bool B);
257 /// Convenience function for setting multiple fast-math flags on this
258 /// instruction, which must be an operator which supports these flags. See
259 /// LangRef.html for the meaning of these flags.
260 void setFastMathFlags(FastMathFlags FMF);
262 /// Convenience function for transferring all fast-math flag values to this
263 /// instruction, which must be an operator which supports these flags. See
264 /// LangRef.html for the meaning of these flags.
265 void copyFastMathFlags(FastMathFlags FMF);
267 /// Determine whether the unsafe-algebra flag is set.
268 bool hasUnsafeAlgebra() const;
270 /// Determine whether the no-NaNs flag is set.
271 bool hasNoNaNs() const;
273 /// Determine whether the no-infs flag is set.
274 bool hasNoInfs() const;
276 /// Determine whether the no-signed-zeros flag is set.
277 bool hasNoSignedZeros() const;
279 /// Determine whether the allow-reciprocal flag is set.
280 bool hasAllowReciprocal() const;
282 /// Convenience function for getting all the fast-math flags, which must be an
283 /// operator which supports these flags. See LangRef.html for the meaning of
285 FastMathFlags getFastMathFlags() const;
287 /// Copy I's fast-math flags
288 void copyFastMathFlags(const Instruction *I);
291 /// hasMetadataHashEntry - Return true if we have an entry in the on-the-side
293 bool hasMetadataHashEntry() const {
294 return (getSubclassDataFromValue() & HasMetadataBit) != 0;
297 // These are all implemented in Metadata.cpp.
298 MDNode *getMetadataImpl(unsigned KindID) const;
299 MDNode *getMetadataImpl(StringRef Kind) const;
301 getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
302 void getAllMetadataOtherThanDebugLocImpl(
303 SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
304 void clearMetadataHashEntries();
306 //===--------------------------------------------------------------------===//
307 // Predicates and helper methods.
308 //===--------------------------------------------------------------------===//
311 /// isAssociative - Return true if the instruction is associative:
313 /// Associative operators satisfy: x op (y op z) === (x op y) op z
315 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
317 bool isAssociative() const;
318 static bool isAssociative(unsigned op);
320 /// isCommutative - Return true if the instruction is commutative:
322 /// Commutative operators satisfy: (x op y) === (y op x)
324 /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
325 /// applied to any type.
327 bool isCommutative() const { return isCommutative(getOpcode()); }
328 static bool isCommutative(unsigned op);
330 /// isIdempotent - Return true if the instruction is idempotent:
332 /// Idempotent operators satisfy: x op x === x
334 /// In LLVM, the And and Or operators are idempotent.
336 bool isIdempotent() const { return isIdempotent(getOpcode()); }
337 static bool isIdempotent(unsigned op);
339 /// isNilpotent - Return true if the instruction is nilpotent:
341 /// Nilpotent operators satisfy: x op x === Id,
343 /// where Id is the identity for the operator, i.e. a constant such that
344 /// x op Id === x and Id op x === x for all x.
346 /// In LLVM, the Xor operator is nilpotent.
348 bool isNilpotent() const { return isNilpotent(getOpcode()); }
349 static bool isNilpotent(unsigned op);
351 /// mayWriteToMemory - Return true if this instruction may modify memory.
353 bool mayWriteToMemory() const;
355 /// mayReadFromMemory - Return true if this instruction may read memory.
357 bool mayReadFromMemory() const;
359 /// mayReadOrWriteMemory - Return true if this instruction may read or
362 bool mayReadOrWriteMemory() const {
363 return mayReadFromMemory() || mayWriteToMemory();
366 /// isAtomic - Return true if this instruction has an
367 /// AtomicOrdering of unordered or higher.
369 bool isAtomic() const;
371 /// mayThrow - Return true if this instruction may throw an exception.
373 bool mayThrow() const;
375 /// mayReturn - Return true if this is a function that may return.
376 /// this is true for all normal instructions. The only exception
377 /// is functions that are marked with the 'noreturn' attribute.
379 bool mayReturn() const;
381 /// mayHaveSideEffects - Return true if the instruction may have side effects.
383 /// Note that this does not consider malloc and alloca to have side
384 /// effects because the newly allocated memory is completely invisible to
385 /// instructions which don't used the returned value. For cases where this
386 /// matters, isSafeToSpeculativelyExecute may be more appropriate.
387 bool mayHaveSideEffects() const {
388 return mayWriteToMemory() || mayThrow() || !mayReturn();
391 /// clone() - Create a copy of 'this' instruction that is identical in all
392 /// ways except the following:
393 /// * The instruction has no parent
394 /// * The instruction has no name
396 Instruction *clone() const;
398 /// isIdenticalTo - Return true if the specified instruction is exactly
399 /// identical to the current one. This means that all operands match and any
400 /// extra information (e.g. load is volatile) agree.
401 bool isIdenticalTo(const Instruction *I) const;
403 /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
404 /// ignores the SubclassOptionalData flags, which specify conditions
405 /// under which the instruction's result is undefined.
406 bool isIdenticalToWhenDefined(const Instruction *I) const;
408 /// When checking for operation equivalence (using isSameOperationAs) it is
409 /// sometimes useful to ignore certain attributes.
410 enum OperationEquivalenceFlags {
411 /// Check for equivalence ignoring load/store alignment.
412 CompareIgnoringAlignment = 1<<0,
413 /// Check for equivalence treating a type and a vector of that type
415 CompareUsingScalarTypes = 1<<1
418 /// This function determines if the specified instruction executes the same
419 /// operation as the current one. This means that the opcodes, type, operand
420 /// types and any other factors affecting the operation must be the same. This
421 /// is similar to isIdenticalTo except the operands themselves don't have to
423 /// @returns true if the specified instruction is the same operation as
425 /// @brief Determine if one instruction is the same operation as another.
426 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
428 /// isUsedOutsideOfBlock - Return true if there are any uses of this
429 /// instruction in blocks other than the specified block. Note that PHI nodes
430 /// are considered to evaluate their operands in the corresponding predecessor
432 bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
435 /// Methods for support type inquiry through isa, cast, and dyn_cast:
436 static inline bool classof(const Value *V) {
437 return V->getValueID() >= Value::InstructionVal;
440 //----------------------------------------------------------------------
441 // Exported enumerations.
443 enum TermOps { // These terminate basic blocks
444 #define FIRST_TERM_INST(N) TermOpsBegin = N,
445 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
446 #define LAST_TERM_INST(N) TermOpsEnd = N+1
447 #include "llvm/IR/Instruction.def"
451 #define FIRST_BINARY_INST(N) BinaryOpsBegin = N,
452 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
453 #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1
454 #include "llvm/IR/Instruction.def"
458 #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N,
459 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
460 #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1
461 #include "llvm/IR/Instruction.def"
465 #define FIRST_CAST_INST(N) CastOpsBegin = N,
466 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
467 #define LAST_CAST_INST(N) CastOpsEnd = N+1
468 #include "llvm/IR/Instruction.def"
472 #define FIRST_OTHER_INST(N) OtherOpsBegin = N,
473 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
474 #define LAST_OTHER_INST(N) OtherOpsEnd = N+1
475 #include "llvm/IR/Instruction.def"
478 // Shadow Value::setValueSubclassData with a private forwarding method so that
479 // subclasses cannot accidentally use it.
480 void setValueSubclassData(unsigned short D) {
481 Value::setValueSubclassData(D);
483 unsigned short getSubclassDataFromValue() const {
484 return Value::getSubclassDataFromValue();
487 void setHasMetadataHashEntry(bool V) {
488 setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
489 (V ? HasMetadataBit : 0));
492 friend class SymbolTableListTraits<Instruction, BasicBlock>;
493 void setParent(BasicBlock *P);
495 // Instruction subclasses can stick up to 15 bits of stuff into the
496 // SubclassData field of instruction with these members.
498 // Verify that only the low 15 bits are used.
499 void setInstructionSubclassData(unsigned short D) {
500 assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
501 setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
504 unsigned getSubclassDataFromInstruction() const {
505 return getSubclassDataFromValue() & ~HasMetadataBit;
508 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
509 Instruction *InsertBefore = nullptr);
510 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
511 BasicBlock *InsertAtEnd);
512 virtual Instruction *clone_impl() const = 0;
516 inline Instruction *ilist_traits<Instruction>::createSentinel() const {
517 // Since i(p)lists always publicly derive from their corresponding traits,
518 // placing a data member in this class will augment the i(p)list. But since
519 // the NodeTy is expected to be publicly derive from ilist_node<NodeTy>,
520 // there is a legal viable downcast from it to NodeTy. We use this trick to
521 // superimpose an i(p)list with a "ghostly" NodeTy, which becomes the
522 // sentinel. Dereferencing the sentinel is forbidden (save the
523 // ilist_node<NodeTy>), so no one will ever notice the superposition.
524 return static_cast<Instruction *>(&Sentinel);
527 // Instruction* is only 4-byte aligned.
529 class PointerLikeTypeTraits<Instruction*> {
530 typedef Instruction* PT;
532 static inline void *getAsVoidPointer(PT P) { return P; }
533 static inline PT getFromVoidPointer(void *P) {
534 return static_cast<PT>(P);
536 enum { NumLowBitsAvailable = 2 };
539 } // End llvm namespace