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.
159 void getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs)const{
161 getAllMetadataImpl(MDs);
164 /// getAllMetadataOtherThanDebugLoc - This does the same thing as
165 /// getAllMetadata, except that it filters out the debug location.
166 void getAllMetadataOtherThanDebugLoc(SmallVectorImpl<std::pair<unsigned,
167 MDNode*> > &MDs) const {
168 if (hasMetadataOtherThanDebugLoc())
169 getAllMetadataOtherThanDebugLocImpl(MDs);
172 /// getAAMetadata - Fills the AAMDNodes structure with AA metadata from
173 /// this instruction. When Merge is true, the existing AA metadata is
174 /// merged with that from this instruction providing the most-general result.
175 void getAAMetadata(AAMDNodes &N, bool Merge = false) const;
177 /// setMetadata - Set the metadata of the specified kind to the specified
178 /// node. This updates/replaces metadata if already present, or removes it if
180 void setMetadata(unsigned KindID, MDNode *Node);
181 void setMetadata(StringRef Kind, MDNode *Node);
183 /// \brief Drop unknown metadata.
184 /// Passes are required to drop metadata they don't understand. This is a
185 /// convenience method for passes to do so.
186 void dropUnknownMetadata(ArrayRef<unsigned> KnownIDs);
187 void dropUnknownMetadata() {
188 return dropUnknownMetadata(ArrayRef<unsigned>());
190 void dropUnknownMetadata(unsigned ID1) {
191 return dropUnknownMetadata(makeArrayRef(ID1));
193 void dropUnknownMetadata(unsigned ID1, unsigned ID2) {
194 unsigned IDs[] = {ID1, ID2};
195 return dropUnknownMetadata(IDs);
198 /// setAAMetadata - Sets the metadata on this instruction from the
199 /// AAMDNodes structure.
200 void setAAMetadata(const AAMDNodes &N);
202 /// setDebugLoc - Set the debug location information for this instruction.
203 void setDebugLoc(const DebugLoc &Loc) { DbgLoc = Loc; }
205 /// getDebugLoc - Return the debug location for this node as a DebugLoc.
206 const DebugLoc &getDebugLoc() const { return DbgLoc; }
208 /// Set or clear the unsafe-algebra flag on this instruction, which must be an
209 /// operator which supports this flag. See LangRef.html for the meaning of
211 void setHasUnsafeAlgebra(bool B);
213 /// Set or clear the no-nans flag on this instruction, which must be an
214 /// operator which supports this flag. See LangRef.html for the meaning of
216 void setHasNoNaNs(bool B);
218 /// Set or clear the no-infs flag on this instruction, which must be an
219 /// operator which supports this flag. See LangRef.html for the meaning of
221 void setHasNoInfs(bool B);
223 /// Set or clear the no-signed-zeros flag on this instruction, which must be
224 /// an operator which supports this flag. See LangRef.html for the meaning of
226 void setHasNoSignedZeros(bool B);
228 /// Set or clear the allow-reciprocal flag on this instruction, which must be
229 /// an operator which supports this flag. See LangRef.html for the meaning of
231 void setHasAllowReciprocal(bool B);
233 /// Convenience function for setting all the fast-math flags on this
234 /// instruction, which must be an operator which supports these flags. See
235 /// LangRef.html for the meaning of these flats.
236 void setFastMathFlags(FastMathFlags FMF);
238 /// Determine whether the unsafe-algebra flag is set.
239 bool hasUnsafeAlgebra() const;
241 /// Determine whether the no-NaNs flag is set.
242 bool hasNoNaNs() const;
244 /// Determine whether the no-infs flag is set.
245 bool hasNoInfs() const;
247 /// Determine whether the no-signed-zeros flag is set.
248 bool hasNoSignedZeros() const;
250 /// Determine whether the allow-reciprocal flag is set.
251 bool hasAllowReciprocal() const;
253 /// Convenience function for getting all the fast-math flags, which must be an
254 /// operator which supports these flags. See LangRef.html for the meaning of
256 FastMathFlags getFastMathFlags() const;
258 /// Copy I's fast-math flags
259 void copyFastMathFlags(const Instruction *I);
262 /// hasMetadataHashEntry - Return true if we have an entry in the on-the-side
264 bool hasMetadataHashEntry() const {
265 return (getSubclassDataFromValue() & HasMetadataBit) != 0;
268 // These are all implemented in Metadata.cpp.
269 MDNode *getMetadataImpl(unsigned KindID) const;
270 MDNode *getMetadataImpl(StringRef Kind) const;
271 void getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,MDNode*> > &)const;
272 void getAllMetadataOtherThanDebugLocImpl(SmallVectorImpl<std::pair<unsigned,
274 void clearMetadataHashEntries();
276 //===--------------------------------------------------------------------===//
277 // Predicates and helper methods.
278 //===--------------------------------------------------------------------===//
281 /// isAssociative - Return true if the instruction is associative:
283 /// Associative operators satisfy: x op (y op z) === (x op y) op z
285 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
287 bool isAssociative() const;
288 static bool isAssociative(unsigned op);
290 /// isCommutative - Return true if the instruction is commutative:
292 /// Commutative operators satisfy: (x op y) === (y op x)
294 /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
295 /// applied to any type.
297 bool isCommutative() const { return isCommutative(getOpcode()); }
298 static bool isCommutative(unsigned op);
300 /// isIdempotent - Return true if the instruction is idempotent:
302 /// Idempotent operators satisfy: x op x === x
304 /// In LLVM, the And and Or operators are idempotent.
306 bool isIdempotent() const { return isIdempotent(getOpcode()); }
307 static bool isIdempotent(unsigned op);
309 /// isNilpotent - Return true if the instruction is nilpotent:
311 /// Nilpotent operators satisfy: x op x === Id,
313 /// where Id is the identity for the operator, i.e. a constant such that
314 /// x op Id === x and Id op x === x for all x.
316 /// In LLVM, the Xor operator is nilpotent.
318 bool isNilpotent() const { return isNilpotent(getOpcode()); }
319 static bool isNilpotent(unsigned op);
321 /// mayWriteToMemory - Return true if this instruction may modify memory.
323 bool mayWriteToMemory() const;
325 /// mayReadFromMemory - Return true if this instruction may read memory.
327 bool mayReadFromMemory() const;
329 /// mayReadOrWriteMemory - Return true if this instruction may read or
332 bool mayReadOrWriteMemory() const {
333 return mayReadFromMemory() || mayWriteToMemory();
336 /// mayThrow - Return true if this instruction may throw an exception.
338 bool mayThrow() const;
340 /// mayReturn - Return true if this is a function that may return.
341 /// this is true for all normal instructions. The only exception
342 /// is functions that are marked with the 'noreturn' attribute.
344 bool mayReturn() const;
346 /// mayHaveSideEffects - Return true if the instruction may have side effects.
348 /// Note that this does not consider malloc and alloca to have side
349 /// effects because the newly allocated memory is completely invisible to
350 /// instructions which don't used the returned value. For cases where this
351 /// matters, isSafeToSpeculativelyExecute may be more appropriate.
352 bool mayHaveSideEffects() const {
353 return mayWriteToMemory() || mayThrow() || !mayReturn();
356 /// clone() - Create a copy of 'this' instruction that is identical in all
357 /// ways except the following:
358 /// * The instruction has no parent
359 /// * The instruction has no name
361 Instruction *clone() const;
363 /// isIdenticalTo - Return true if the specified instruction is exactly
364 /// identical to the current one. This means that all operands match and any
365 /// extra information (e.g. load is volatile) agree.
366 bool isIdenticalTo(const Instruction *I) const;
368 /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
369 /// ignores the SubclassOptionalData flags, which specify conditions
370 /// under which the instruction's result is undefined.
371 bool isIdenticalToWhenDefined(const Instruction *I) const;
373 /// When checking for operation equivalence (using isSameOperationAs) it is
374 /// sometimes useful to ignore certain attributes.
375 enum OperationEquivalenceFlags {
376 /// Check for equivalence ignoring load/store alignment.
377 CompareIgnoringAlignment = 1<<0,
378 /// Check for equivalence treating a type and a vector of that type
380 CompareUsingScalarTypes = 1<<1
383 /// This function determines if the specified instruction executes the same
384 /// operation as the current one. This means that the opcodes, type, operand
385 /// types and any other factors affecting the operation must be the same. This
386 /// is similar to isIdenticalTo except the operands themselves don't have to
388 /// @returns true if the specified instruction is the same operation as
390 /// @brief Determine if one instruction is the same operation as another.
391 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
393 /// isUsedOutsideOfBlock - Return true if there are any uses of this
394 /// instruction in blocks other than the specified block. Note that PHI nodes
395 /// are considered to evaluate their operands in the corresponding predecessor
397 bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
400 /// Methods for support type inquiry through isa, cast, and dyn_cast:
401 static inline bool classof(const Value *V) {
402 return V->getValueID() >= Value::InstructionVal;
405 //----------------------------------------------------------------------
406 // Exported enumerations.
408 enum TermOps { // These terminate basic blocks
409 #define FIRST_TERM_INST(N) TermOpsBegin = N,
410 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
411 #define LAST_TERM_INST(N) TermOpsEnd = N+1
412 #include "llvm/IR/Instruction.def"
416 #define FIRST_BINARY_INST(N) BinaryOpsBegin = N,
417 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
418 #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1
419 #include "llvm/IR/Instruction.def"
423 #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N,
424 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
425 #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1
426 #include "llvm/IR/Instruction.def"
430 #define FIRST_CAST_INST(N) CastOpsBegin = N,
431 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
432 #define LAST_CAST_INST(N) CastOpsEnd = N+1
433 #include "llvm/IR/Instruction.def"
437 #define FIRST_OTHER_INST(N) OtherOpsBegin = N,
438 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
439 #define LAST_OTHER_INST(N) OtherOpsEnd = N+1
440 #include "llvm/IR/Instruction.def"
443 // Shadow Value::setValueSubclassData with a private forwarding method so that
444 // subclasses cannot accidentally use it.
445 void setValueSubclassData(unsigned short D) {
446 Value::setValueSubclassData(D);
448 unsigned short getSubclassDataFromValue() const {
449 return Value::getSubclassDataFromValue();
452 void setHasMetadataHashEntry(bool V) {
453 setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
454 (V ? HasMetadataBit : 0));
457 friend class SymbolTableListTraits<Instruction, BasicBlock>;
458 void setParent(BasicBlock *P);
460 // Instruction subclasses can stick up to 15 bits of stuff into the
461 // SubclassData field of instruction with these members.
463 // Verify that only the low 15 bits are used.
464 void setInstructionSubclassData(unsigned short D) {
465 assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
466 setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
469 unsigned getSubclassDataFromInstruction() const {
470 return getSubclassDataFromValue() & ~HasMetadataBit;
473 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
474 Instruction *InsertBefore = nullptr);
475 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
476 BasicBlock *InsertAtEnd);
477 virtual Instruction *clone_impl() const = 0;
481 // Instruction* is only 4-byte aligned.
483 class PointerLikeTypeTraits<Instruction*> {
484 typedef Instruction* PT;
486 static inline void *getAsVoidPointer(PT P) { return P; }
487 static inline PT getFromVoidPointer(void *P) {
488 return static_cast<PT>(P);
490 enum { NumLowBitsAvailable = 2 };
493 } // End llvm namespace