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/ADT/None.h"
21 #include "llvm/ADT/StringRef.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 class Instruction : public User,
40 public ilist_node_with_parent<Instruction, BasicBlock> {
42 DebugLoc DbgLoc; // 'dbg' Metadata cache.
45 /// This is a bit stored in the SubClassData field which indicates whether
46 /// this instruction has metadata attached to it or not.
47 HasMetadataBit = 1 << 15
51 Instruction(const Instruction &) = delete;
52 Instruction &operator=(const Instruction &) = delete;
54 // Out of line virtual method, so the vtable, etc has a home.
55 ~Instruction() override;
57 /// Specialize the methods defined in Value, as we know that an instruction
58 /// can only be used by other instructions.
59 Instruction *user_back() { return cast<Instruction>(*user_begin());}
60 const Instruction *user_back() const { return cast<Instruction>(*user_begin());}
62 inline const BasicBlock *getParent() const { return Parent; }
63 inline BasicBlock *getParent() { return Parent; }
65 /// Return the module owning the function this instruction belongs to
66 /// or nullptr it the function does not have a module.
68 /// Note: this is undefined behavior if the instruction does not have a
69 /// parent, or the parent basic block does not have a parent function.
70 const Module *getModule() const;
72 return const_cast<Module *>(
73 static_cast<const Instruction *>(this)->getModule());
76 /// Return the function this instruction belongs to.
78 /// Note: it is undefined behavior to call this on an instruction not
79 /// currently inserted into a function.
80 const Function *getFunction() const;
81 Function *getFunction() {
82 return const_cast<Function *>(
83 static_cast<const Instruction *>(this)->getFunction());
86 /// This method unlinks 'this' from the containing basic block, but does not
88 void removeFromParent();
90 /// This method unlinks 'this' from the containing basic block and deletes it.
92 /// \returns an iterator pointing to the element after the erased one
93 SymbolTableList<Instruction>::iterator eraseFromParent();
95 /// Insert an unlinked instruction into a basic block immediately before
96 /// the specified instruction.
97 void insertBefore(Instruction *InsertPos);
99 /// Insert an unlinked instruction into a basic block immediately after the
100 /// specified instruction.
101 void insertAfter(Instruction *InsertPos);
103 /// Unlink this instruction from its current basic block and insert it into
104 /// the basic block that MovePos lives in, right before MovePos.
105 void moveBefore(Instruction *MovePos);
107 /// Unlink this instruction and insert into BB before I.
109 /// \pre I is a valid iterator into BB.
110 void moveBefore(BasicBlock &BB, SymbolTableList<Instruction>::iterator I);
112 //===--------------------------------------------------------------------===//
113 // Subclass classification.
114 //===--------------------------------------------------------------------===//
116 /// Returns a member of one of the enums like Instruction::Add.
117 unsigned getOpcode() const { return getValueID() - InstructionVal; }
119 const char *getOpcodeName() const { return getOpcodeName(getOpcode()); }
120 bool isTerminator() const { return isTerminator(getOpcode()); }
121 bool isBinaryOp() const { return isBinaryOp(getOpcode()); }
122 bool isShift() { return isShift(getOpcode()); }
123 bool isCast() const { return isCast(getOpcode()); }
124 bool isFuncletPad() const { return isFuncletPad(getOpcode()); }
126 static const char* getOpcodeName(unsigned OpCode);
128 static inline bool isTerminator(unsigned OpCode) {
129 return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
132 static inline bool isBinaryOp(unsigned Opcode) {
133 return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
136 /// Determine if the Opcode is one of the shift instructions.
137 static inline bool isShift(unsigned Opcode) {
138 return Opcode >= Shl && Opcode <= AShr;
141 /// Return true if this is a logical shift left or a logical shift right.
142 inline bool isLogicalShift() const {
143 return getOpcode() == Shl || getOpcode() == LShr;
146 /// Return true if this is an arithmetic shift right.
147 inline bool isArithmeticShift() const {
148 return getOpcode() == AShr;
151 /// Return true if this is and/or/xor.
152 inline bool isBitwiseLogicOp() const {
153 return getOpcode() == And || getOpcode() == Or || getOpcode() == Xor;
156 /// Determine if the OpCode is one of the CastInst instructions.
157 static inline bool isCast(unsigned OpCode) {
158 return OpCode >= CastOpsBegin && OpCode < CastOpsEnd;
161 /// Determine if the OpCode is one of the FuncletPadInst instructions.
162 static inline bool isFuncletPad(unsigned OpCode) {
163 return OpCode >= FuncletPadOpsBegin && OpCode < FuncletPadOpsEnd;
166 //===--------------------------------------------------------------------===//
167 // Metadata manipulation.
168 //===--------------------------------------------------------------------===//
170 /// Return true if this instruction has any metadata attached to it.
171 bool hasMetadata() const { return DbgLoc || hasMetadataHashEntry(); }
173 /// Return true if this instruction has metadata attached to it other than a
175 bool hasMetadataOtherThanDebugLoc() const {
176 return hasMetadataHashEntry();
179 /// Get the metadata of given kind attached to this Instruction.
180 /// If the metadata is not found then return null.
181 MDNode *getMetadata(unsigned KindID) const {
182 if (!hasMetadata()) return nullptr;
183 return getMetadataImpl(KindID);
186 /// Get the metadata of given kind attached to this Instruction.
187 /// If the metadata is not found then return null.
188 MDNode *getMetadata(StringRef Kind) const {
189 if (!hasMetadata()) return nullptr;
190 return getMetadataImpl(Kind);
193 /// Get all metadata attached to this Instruction. The first element of each
194 /// pair returned is the KindID, the second element is the metadata value.
195 /// This list is returned sorted by the KindID.
197 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
199 getAllMetadataImpl(MDs);
202 /// This does the same thing as getAllMetadata, except that it filters out the
204 void getAllMetadataOtherThanDebugLoc(
205 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
206 if (hasMetadataOtherThanDebugLoc())
207 getAllMetadataOtherThanDebugLocImpl(MDs);
210 /// Fills the AAMDNodes structure with AA metadata from this instruction.
211 /// When Merge is true, the existing AA metadata is merged with that from this
212 /// instruction providing the most-general result.
213 void getAAMetadata(AAMDNodes &N, bool Merge = false) const;
215 /// Set the metadata of the specified kind to the specified node. This updates
216 /// or replaces metadata if already present, or removes it if Node is null.
217 void setMetadata(unsigned KindID, MDNode *Node);
218 void setMetadata(StringRef Kind, MDNode *Node);
220 /// Copy metadata from \p SrcInst to this instruction. \p WL, if not empty,
221 /// specifies the list of meta data that needs to be copied. If \p WL is
222 /// empty, all meta data will be copied.
223 void copyMetadata(const Instruction &SrcInst,
224 ArrayRef<unsigned> WL = ArrayRef<unsigned>());
226 /// If the instruction has "branch_weights" MD_prof metadata and the MDNode
227 /// has three operands (including name string), swap the order of the
229 void swapProfMetadata();
231 /// Drop all unknown metadata except for debug locations.
233 /// Passes are required to drop metadata they don't understand. This is a
234 /// convenience method for passes to do so.
235 void dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs);
236 void dropUnknownNonDebugMetadata() {
237 return dropUnknownNonDebugMetadata(None);
239 void dropUnknownNonDebugMetadata(unsigned ID1) {
240 return dropUnknownNonDebugMetadata(makeArrayRef(ID1));
242 void dropUnknownNonDebugMetadata(unsigned ID1, unsigned ID2) {
243 unsigned IDs[] = {ID1, ID2};
244 return dropUnknownNonDebugMetadata(IDs);
248 /// Sets the metadata on this instruction from the AAMDNodes structure.
249 void setAAMetadata(const AAMDNodes &N);
251 /// Retrieve the raw weight values of a conditional branch or select.
252 /// Returns true on success with profile weights filled in.
253 /// Returns false if no metadata or invalid metadata was found.
254 bool extractProfMetadata(uint64_t &TrueVal, uint64_t &FalseVal) const;
256 /// Retrieve total raw weight values of a branch.
257 /// Returns true on success with profile total weights filled in.
258 /// Returns false if no metadata was found.
259 bool extractProfTotalWeight(uint64_t &TotalVal) const;
261 /// Updates branch_weights metadata by scaling it by \p S / \p T.
262 void updateProfWeight(uint64_t S, uint64_t T);
264 /// Sets the branch_weights metadata to \p W for CallInst.
265 void setProfWeight(uint64_t W);
267 /// Set the debug location information for this instruction.
268 void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); }
270 /// Return the debug location for this node as a DebugLoc.
271 const DebugLoc &getDebugLoc() const { return DbgLoc; }
273 /// Set or clear the nsw flag on this instruction, which must be an operator
274 /// which supports this flag. See LangRef.html for the meaning of this flag.
275 void setHasNoUnsignedWrap(bool b = true);
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 setHasNoSignedWrap(bool b = true);
281 /// Set or clear the exact 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 setIsExact(bool b = true);
285 /// Determine whether the no unsigned wrap flag is set.
286 bool hasNoUnsignedWrap() const;
288 /// Determine whether the no signed wrap flag is set.
289 bool hasNoSignedWrap() const;
291 /// Drops flags that may cause this instruction to evaluate to poison despite
292 /// having non-poison inputs.
293 void dropPoisonGeneratingFlags();
295 /// Determine whether the exact flag is set.
296 bool isExact() const;
298 /// Set or clear the unsafe-algebra flag on this instruction, which must be an
299 /// operator which supports this flag. See LangRef.html for the meaning of
301 void setHasUnsafeAlgebra(bool B);
303 /// Set or clear the no-nans flag on this instruction, which must be an
304 /// operator which supports this flag. See LangRef.html for the meaning of
306 void setHasNoNaNs(bool B);
308 /// Set or clear the no-infs flag on this instruction, which must be an
309 /// operator which supports this flag. See LangRef.html for the meaning of
311 void setHasNoInfs(bool B);
313 /// Set or clear the no-signed-zeros flag on this instruction, which must be
314 /// an operator which supports this flag. See LangRef.html for the meaning of
316 void setHasNoSignedZeros(bool B);
318 /// Set or clear the allow-reciprocal flag on this instruction, which must be
319 /// an operator which supports this flag. See LangRef.html for the meaning of
321 void setHasAllowReciprocal(bool B);
323 /// Convenience function for setting multiple fast-math flags on this
324 /// instruction, which must be an operator which supports these flags. See
325 /// LangRef.html for the meaning of these flags.
326 void setFastMathFlags(FastMathFlags FMF);
328 /// Convenience function for transferring all fast-math flag values to this
329 /// instruction, which must be an operator which supports these flags. See
330 /// LangRef.html for the meaning of these flags.
331 void copyFastMathFlags(FastMathFlags FMF);
333 /// Determine whether the unsafe-algebra flag is set.
334 bool hasUnsafeAlgebra() const;
336 /// Determine whether the no-NaNs flag is set.
337 bool hasNoNaNs() const;
339 /// Determine whether the no-infs flag is set.
340 bool hasNoInfs() const;
342 /// Determine whether the no-signed-zeros flag is set.
343 bool hasNoSignedZeros() const;
345 /// Determine whether the allow-reciprocal flag is set.
346 bool hasAllowReciprocal() const;
348 /// Determine whether the allow-contract flag is set.
349 bool hasAllowContract() const;
351 /// Convenience function for getting all the fast-math flags, which must be an
352 /// operator which supports these flags. See LangRef.html for the meaning of
354 FastMathFlags getFastMathFlags() const;
356 /// Copy I's fast-math flags
357 void copyFastMathFlags(const Instruction *I);
359 /// Convenience method to copy supported wrapping, exact, and fast-math flags
360 /// from V to this instruction.
361 void copyIRFlags(const Value *V);
363 /// Logical 'and' of any supported wrapping, exact, and fast-math flags of
364 /// V and this instruction.
365 void andIRFlags(const Value *V);
368 /// Return true if we have an entry in the on-the-side metadata hash.
369 bool hasMetadataHashEntry() const {
370 return (getSubclassDataFromValue() & HasMetadataBit) != 0;
373 // These are all implemented in Metadata.cpp.
374 MDNode *getMetadataImpl(unsigned KindID) const;
375 MDNode *getMetadataImpl(StringRef Kind) const;
377 getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
378 void getAllMetadataOtherThanDebugLocImpl(
379 SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
380 /// Clear all hashtable-based metadata from this instruction.
381 void clearMetadataHashEntries();
384 //===--------------------------------------------------------------------===//
385 // Predicates and helper methods.
386 //===--------------------------------------------------------------------===//
388 /// Return true if the instruction is associative:
390 /// Associative operators satisfy: x op (y op z) === (x op y) op z
392 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
394 bool isAssociative() const LLVM_READONLY;
395 static bool isAssociative(unsigned Opcode) {
396 return Opcode == And || Opcode == Or || Opcode == Xor ||
397 Opcode == Add || Opcode == Mul;
400 /// Return true if the instruction is commutative:
402 /// Commutative operators satisfy: (x op y) === (y op x)
404 /// In LLVM, these are the commutative operators, plus SetEQ and SetNE, when
405 /// applied to any type.
407 bool isCommutative() const { return isCommutative(getOpcode()); }
408 static bool isCommutative(unsigned Opcode) {
412 case And: case Or: case Xor:
419 /// Return true if the instruction is idempotent:
421 /// Idempotent operators satisfy: x op x === x
423 /// In LLVM, the And and Or operators are idempotent.
425 bool isIdempotent() const { return isIdempotent(getOpcode()); }
426 static bool isIdempotent(unsigned Opcode) {
427 return Opcode == And || Opcode == Or;
430 /// Return true if the instruction is nilpotent:
432 /// Nilpotent operators satisfy: x op x === Id,
434 /// where Id is the identity for the operator, i.e. a constant such that
435 /// x op Id === x and Id op x === x for all x.
437 /// In LLVM, the Xor operator is nilpotent.
439 bool isNilpotent() const { return isNilpotent(getOpcode()); }
440 static bool isNilpotent(unsigned Opcode) {
441 return Opcode == Xor;
444 /// Return true if this instruction may modify memory.
445 bool mayWriteToMemory() const;
447 /// Return true if this instruction may read memory.
448 bool mayReadFromMemory() const;
450 /// Return true if this instruction may read or write memory.
451 bool mayReadOrWriteMemory() const {
452 return mayReadFromMemory() || mayWriteToMemory();
455 /// Return true if this instruction has an AtomicOrdering of unordered or
457 bool isAtomic() const;
459 /// Return true if this instruction may throw an exception.
460 bool mayThrow() const;
462 /// Return true if this instruction behaves like a memory fence: it can load
463 /// or store to memory location without being given a memory location.
464 bool isFenceLike() const {
465 switch (getOpcode()) {
468 // This list should be kept in sync with the list in mayWriteToMemory for
469 // all opcodes which don't have a memory location.
470 case Instruction::Fence:
471 case Instruction::CatchPad:
472 case Instruction::CatchRet:
473 case Instruction::Call:
474 case Instruction::Invoke:
479 /// Return true if the instruction may have side effects.
481 /// Note that this does not consider malloc and alloca to have side
482 /// effects because the newly allocated memory is completely invisible to
483 /// instructions which don't use the returned value. For cases where this
484 /// matters, isSafeToSpeculativelyExecute may be more appropriate.
485 bool mayHaveSideEffects() const { return mayWriteToMemory() || mayThrow(); }
487 /// Return true if the instruction is a variety of EH-block.
488 bool isEHPad() const {
489 switch (getOpcode()) {
490 case Instruction::CatchSwitch:
491 case Instruction::CatchPad:
492 case Instruction::CleanupPad:
493 case Instruction::LandingPad:
500 /// Create a copy of 'this' instruction that is identical in all ways except
502 /// * The instruction has no parent
503 /// * The instruction has no name
505 Instruction *clone() const;
507 /// Return true if the specified instruction is exactly identical to the
508 /// current one. This means that all operands match and any extra information
509 /// (e.g. load is volatile) agree.
510 bool isIdenticalTo(const Instruction *I) const;
512 /// This is like isIdenticalTo, except that it ignores the
513 /// SubclassOptionalData flags, which may specify conditions under which the
514 /// instruction's result is undefined.
515 bool isIdenticalToWhenDefined(const Instruction *I) const;
517 /// When checking for operation equivalence (using isSameOperationAs) it is
518 /// sometimes useful to ignore certain attributes.
519 enum OperationEquivalenceFlags {
520 /// Check for equivalence ignoring load/store alignment.
521 CompareIgnoringAlignment = 1<<0,
522 /// Check for equivalence treating a type and a vector of that type
524 CompareUsingScalarTypes = 1<<1
527 /// This function determines if the specified instruction executes the same
528 /// operation as the current one. This means that the opcodes, type, operand
529 /// types and any other factors affecting the operation must be the same. This
530 /// is similar to isIdenticalTo except the operands themselves don't have to
532 /// @returns true if the specified instruction is the same operation as
534 /// @brief Determine if one instruction is the same operation as another.
535 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
537 /// Return true if there are any uses of this instruction in blocks other than
538 /// the specified block. Note that PHI nodes are considered to evaluate their
539 /// operands in the corresponding predecessor block.
540 bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
543 /// Methods for support type inquiry through isa, cast, and dyn_cast:
544 static inline bool classof(const Value *V) {
545 return V->getValueID() >= Value::InstructionVal;
548 //----------------------------------------------------------------------
549 // Exported enumerations.
551 enum TermOps { // These terminate basic blocks
552 #define FIRST_TERM_INST(N) TermOpsBegin = N,
553 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
554 #define LAST_TERM_INST(N) TermOpsEnd = N+1
555 #include "llvm/IR/Instruction.def"
559 #define FIRST_BINARY_INST(N) BinaryOpsBegin = N,
560 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
561 #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1
562 #include "llvm/IR/Instruction.def"
566 #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N,
567 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
568 #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1
569 #include "llvm/IR/Instruction.def"
573 #define FIRST_CAST_INST(N) CastOpsBegin = N,
574 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
575 #define LAST_CAST_INST(N) CastOpsEnd = N+1
576 #include "llvm/IR/Instruction.def"
580 #define FIRST_FUNCLETPAD_INST(N) FuncletPadOpsBegin = N,
581 #define HANDLE_FUNCLETPAD_INST(N, OPC, CLASS) OPC = N,
582 #define LAST_FUNCLETPAD_INST(N) FuncletPadOpsEnd = N+1
583 #include "llvm/IR/Instruction.def"
587 #define FIRST_OTHER_INST(N) OtherOpsBegin = N,
588 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
589 #define LAST_OTHER_INST(N) OtherOpsEnd = N+1
590 #include "llvm/IR/Instruction.def"
594 friend class SymbolTableListTraits<Instruction>;
596 // Shadow Value::setValueSubclassData with a private forwarding method so that
597 // subclasses cannot accidentally use it.
598 void setValueSubclassData(unsigned short D) {
599 Value::setValueSubclassData(D);
602 unsigned short getSubclassDataFromValue() const {
603 return Value::getSubclassDataFromValue();
606 void setHasMetadataHashEntry(bool V) {
607 setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
608 (V ? HasMetadataBit : 0));
611 void setParent(BasicBlock *P);
614 // Instruction subclasses can stick up to 15 bits of stuff into the
615 // SubclassData field of instruction with these members.
617 // Verify that only the low 15 bits are used.
618 void setInstructionSubclassData(unsigned short D) {
619 assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
620 setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
623 unsigned getSubclassDataFromInstruction() const {
624 return getSubclassDataFromValue() & ~HasMetadataBit;
627 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
628 Instruction *InsertBefore = nullptr);
629 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
630 BasicBlock *InsertAtEnd);
633 /// Create a copy of this instruction.
634 Instruction *cloneImpl() const;
637 } // end namespace llvm
639 #endif // LLVM_IR_INSTRUCTION_H