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/ilist_node.h"
19 #include "llvm/IR/User.h"
20 #include "llvm/Support/DebugLoc.h"
28 template<typename ValueSubClass, typename ItemParentClass>
29 class SymbolTableListTraits;
31 class Instruction : public User, public ilist_node<Instruction> {
32 void operator=(const Instruction &) LLVM_DELETED_FUNCTION;
33 Instruction(const Instruction &) LLVM_DELETED_FUNCTION;
36 DebugLoc DbgLoc; // 'dbg' Metadata cache.
39 /// HasMetadataBit - This is a bit stored in the SubClassData field which
40 /// indicates whether this instruction has metadata attached to it or not.
41 HasMetadataBit = 1 << 15
44 // Out of line virtual method, so the vtable, etc has a home.
47 /// use_back - Specialize the methods defined in Value, as we know that an
48 /// instruction can only be used by other instructions.
49 Instruction *use_back() { return cast<Instruction>(*use_begin());}
50 const Instruction *use_back() const { return cast<Instruction>(*use_begin());}
52 inline const BasicBlock *getParent() const { return Parent; }
53 inline BasicBlock *getParent() { return Parent; }
55 /// removeFromParent - This method unlinks 'this' from the containing basic
56 /// block, but does not delete it.
58 void removeFromParent();
60 /// eraseFromParent - This method unlinks 'this' from the containing basic
61 /// block and deletes it.
63 void eraseFromParent();
65 /// insertBefore - Insert an unlinked instructions into a basic block
66 /// immediately before the specified instruction.
67 void insertBefore(Instruction *InsertPos);
69 /// insertAfter - Insert an unlinked instructions into a basic block
70 /// immediately after the specified instruction.
71 void insertAfter(Instruction *InsertPos);
73 /// moveBefore - Unlink this instruction from its current basic block and
74 /// insert it into the basic block that MovePos lives in, right before
76 void moveBefore(Instruction *MovePos);
78 //===--------------------------------------------------------------------===//
79 // Subclass classification.
80 //===--------------------------------------------------------------------===//
82 /// getOpcode() returns a member of one of the enums like Instruction::Add.
83 unsigned getOpcode() const { return getValueID() - InstructionVal; }
85 const char *getOpcodeName() const { return getOpcodeName(getOpcode()); }
86 bool isTerminator() const { return isTerminator(getOpcode()); }
87 bool isBinaryOp() const { return isBinaryOp(getOpcode()); }
88 bool isShift() { return isShift(getOpcode()); }
89 bool isCast() const { return isCast(getOpcode()); }
91 static const char* getOpcodeName(unsigned OpCode);
93 static inline bool isTerminator(unsigned OpCode) {
94 return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
97 static inline bool isBinaryOp(unsigned Opcode) {
98 return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
101 /// @brief Determine if the Opcode is one of the shift instructions.
102 static inline bool isShift(unsigned Opcode) {
103 return Opcode >= Shl && Opcode <= AShr;
106 /// isLogicalShift - Return true if this is a logical shift left or a logical
108 inline bool isLogicalShift() const {
109 return getOpcode() == Shl || getOpcode() == LShr;
112 /// isArithmeticShift - Return true if this is an arithmetic shift right.
113 inline bool isArithmeticShift() const {
114 return getOpcode() == AShr;
117 /// @brief Determine if the OpCode is one of the CastInst instructions.
118 static inline bool isCast(unsigned OpCode) {
119 return OpCode >= CastOpsBegin && OpCode < CastOpsEnd;
122 //===--------------------------------------------------------------------===//
123 // Metadata manipulation.
124 //===--------------------------------------------------------------------===//
126 /// hasMetadata() - Return true if this instruction has any metadata attached
128 bool hasMetadata() const {
129 return !DbgLoc.isUnknown() || hasMetadataHashEntry();
132 /// hasMetadataOtherThanDebugLoc - Return true if this instruction has
133 /// metadata attached to it other than a debug location.
134 bool hasMetadataOtherThanDebugLoc() const {
135 return hasMetadataHashEntry();
138 /// getMetadata - Get the metadata of given kind attached to this Instruction.
139 /// If the metadata is not found then return null.
140 MDNode *getMetadata(unsigned KindID) const {
141 if (!hasMetadata()) return 0;
142 return getMetadataImpl(KindID);
145 /// getMetadata - Get the metadata of given kind attached to this Instruction.
146 /// If the metadata is not found then return null.
147 MDNode *getMetadata(StringRef Kind) const {
148 if (!hasMetadata()) return 0;
149 return getMetadataImpl(Kind);
152 /// getAllMetadata - Get all metadata attached to this Instruction. The first
153 /// element of each pair returned is the KindID, the second element is the
154 /// metadata value. This list is returned sorted by the KindID.
155 void getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs)const{
157 getAllMetadataImpl(MDs);
160 /// getAllMetadataOtherThanDebugLoc - This does the same thing as
161 /// getAllMetadata, except that it filters out the debug location.
162 void getAllMetadataOtherThanDebugLoc(SmallVectorImpl<std::pair<unsigned,
163 MDNode*> > &MDs) const {
164 if (hasMetadataOtherThanDebugLoc())
165 getAllMetadataOtherThanDebugLocImpl(MDs);
168 /// setMetadata - Set the metadata of the specified kind to the specified
169 /// node. This updates/replaces metadata if already present, or removes it if
171 void setMetadata(unsigned KindID, MDNode *Node);
172 void setMetadata(StringRef Kind, MDNode *Node);
174 /// setDebugLoc - Set the debug location information for this instruction.
175 void setDebugLoc(const DebugLoc &Loc) { DbgLoc = Loc; }
177 /// getDebugLoc - Return the debug location for this node as a DebugLoc.
178 const DebugLoc &getDebugLoc() const { return DbgLoc; }
180 /// Set or clear the unsafe-algebra flag on this instruction, which must be an
181 /// operator which supports this flag. See LangRef.html for the meaning of
183 void setHasUnsafeAlgebra(bool B);
185 /// Set or clear the no-nans flag on this instruction, which must be an
186 /// operator which supports this flag. See LangRef.html for the meaning of
188 void setHasNoNaNs(bool B);
190 /// Set or clear the no-infs flag on this instruction, which must be an
191 /// operator which supports this flag. See LangRef.html for the meaning of
193 void setHasNoInfs(bool B);
195 /// Set or clear the no-signed-zeros flag on this instruction, which must be
196 /// an operator which supports this flag. See LangRef.html for the meaning of
198 void setHasNoSignedZeros(bool B);
200 /// Set or clear the allow-reciprocal flag on this instruction, which must be
201 /// an operator which supports this flag. See LangRef.html for the meaning of
203 void setHasAllowReciprocal(bool B);
205 /// Convenience function for setting all the fast-math flags on this
206 /// instruction, which must be an operator which supports these flags. See
207 /// LangRef.html for the meaning of these flats.
208 void setFastMathFlags(FastMathFlags FMF);
210 /// Determine whether the unsafe-algebra flag is set.
211 bool hasUnsafeAlgebra() const;
213 /// Determine whether the no-NaNs flag is set.
214 bool hasNoNaNs() const;
216 /// Determine whether the no-infs flag is set.
217 bool hasNoInfs() const;
219 /// Determine whether the no-signed-zeros flag is set.
220 bool hasNoSignedZeros() const;
222 /// Determine whether the allow-reciprocal flag is set.
223 bool hasAllowReciprocal() const;
225 /// Convenience function for getting all the fast-math flags, which must be an
226 /// operator which supports these flags. See LangRef.html for the meaning of
228 FastMathFlags getFastMathFlags() const;
230 /// Copy I's fast-math flags
231 void copyFastMathFlags(const Instruction *I);
234 /// hasMetadataHashEntry - Return true if we have an entry in the on-the-side
236 bool hasMetadataHashEntry() const {
237 return (getSubclassDataFromValue() & HasMetadataBit) != 0;
240 // These are all implemented in Metadata.cpp.
241 MDNode *getMetadataImpl(unsigned KindID) const;
242 MDNode *getMetadataImpl(StringRef Kind) const;
243 void getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,MDNode*> > &)const;
244 void getAllMetadataOtherThanDebugLocImpl(SmallVectorImpl<std::pair<unsigned,
246 void clearMetadataHashEntries();
248 //===--------------------------------------------------------------------===//
249 // Predicates and helper methods.
250 //===--------------------------------------------------------------------===//
253 /// isAssociative - Return true if the instruction is associative:
255 /// Associative operators satisfy: x op (y op z) === (x op y) op z
257 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
259 bool isAssociative() const;
260 static bool isAssociative(unsigned op);
262 /// isCommutative - Return true if the instruction is commutative:
264 /// Commutative operators satisfy: (x op y) === (y op x)
266 /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
267 /// applied to any type.
269 bool isCommutative() const { return isCommutative(getOpcode()); }
270 static bool isCommutative(unsigned op);
272 /// isIdempotent - Return true if the instruction is idempotent:
274 /// Idempotent operators satisfy: x op x === x
276 /// In LLVM, the And and Or operators are idempotent.
278 bool isIdempotent() const { return isIdempotent(getOpcode()); }
279 static bool isIdempotent(unsigned op);
281 /// isNilpotent - Return true if the instruction is nilpotent:
283 /// Nilpotent operators satisfy: x op x === Id,
285 /// where Id is the identity for the operator, i.e. a constant such that
286 /// x op Id === x and Id op x === x for all x.
288 /// In LLVM, the Xor operator is nilpotent.
290 bool isNilpotent() const { return isNilpotent(getOpcode()); }
291 static bool isNilpotent(unsigned op);
293 /// mayWriteToMemory - Return true if this instruction may modify memory.
295 bool mayWriteToMemory() const;
297 /// mayReadFromMemory - Return true if this instruction may read memory.
299 bool mayReadFromMemory() const;
301 /// mayReadOrWriteMemory - Return true if this instruction may read or
304 bool mayReadOrWriteMemory() const {
305 return mayReadFromMemory() || mayWriteToMemory();
308 /// mayThrow - Return true if this instruction may throw an exception.
310 bool mayThrow() const;
312 /// mayReturn - Return true if this is a function that may return.
313 /// this is true for all normal instructions. The only exception
314 /// is functions that are marked with the 'noreturn' attribute.
316 bool mayReturn() const;
318 /// mayHaveSideEffects - Return true if the instruction may have side effects.
320 /// Note that this does not consider malloc and alloca to have side
321 /// effects because the newly allocated memory is completely invisible to
322 /// instructions which don't used the returned value. For cases where this
323 /// matters, isSafeToSpeculativelyExecute may be more appropriate.
324 bool mayHaveSideEffects() const {
325 return mayWriteToMemory() || mayThrow() || !mayReturn();
328 /// clone() - Create a copy of 'this' instruction that is identical in all
329 /// ways except the following:
330 /// * The instruction has no parent
331 /// * The instruction has no name
333 Instruction *clone() const;
335 /// isIdenticalTo - Return true if the specified instruction is exactly
336 /// identical to the current one. This means that all operands match and any
337 /// extra information (e.g. load is volatile) agree.
338 bool isIdenticalTo(const Instruction *I) const;
340 /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
341 /// ignores the SubclassOptionalData flags, which specify conditions
342 /// under which the instruction's result is undefined.
343 bool isIdenticalToWhenDefined(const Instruction *I) const;
345 /// When checking for operation equivalence (using isSameOperationAs) it is
346 /// sometimes useful to ignore certain attributes.
347 enum OperationEquivalenceFlags {
348 /// Check for equivalence ignoring load/store alignment.
349 CompareIgnoringAlignment = 1<<0,
350 /// Check for equivalence treating a type and a vector of that type
352 CompareUsingScalarTypes = 1<<1
355 /// This function determines if the specified instruction executes the same
356 /// operation as the current one. This means that the opcodes, type, operand
357 /// types and any other factors affecting the operation must be the same. This
358 /// is similar to isIdenticalTo except the operands themselves don't have to
360 /// @returns true if the specified instruction is the same operation as
362 /// @brief Determine if one instruction is the same operation as another.
363 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
365 /// isUsedOutsideOfBlock - Return true if there are any uses of this
366 /// instruction in blocks other than the specified block. Note that PHI nodes
367 /// are considered to evaluate their operands in the corresponding predecessor
369 bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
372 /// Methods for support type inquiry through isa, cast, and dyn_cast:
373 static inline bool classof(const Value *V) {
374 return V->getValueID() >= Value::InstructionVal;
377 //----------------------------------------------------------------------
378 // Exported enumerations.
380 enum TermOps { // These terminate basic blocks
381 #define FIRST_TERM_INST(N) TermOpsBegin = N,
382 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
383 #define LAST_TERM_INST(N) TermOpsEnd = N+1
384 #include "llvm/IR/Instruction.def"
388 #define FIRST_BINARY_INST(N) BinaryOpsBegin = N,
389 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
390 #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1
391 #include "llvm/IR/Instruction.def"
395 #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N,
396 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
397 #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1
398 #include "llvm/IR/Instruction.def"
402 #define FIRST_CAST_INST(N) CastOpsBegin = N,
403 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
404 #define LAST_CAST_INST(N) CastOpsEnd = N+1
405 #include "llvm/IR/Instruction.def"
409 #define FIRST_OTHER_INST(N) OtherOpsBegin = N,
410 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
411 #define LAST_OTHER_INST(N) OtherOpsEnd = N+1
412 #include "llvm/IR/Instruction.def"
415 // Shadow Value::setValueSubclassData with a private forwarding method so that
416 // subclasses cannot accidentally use it.
417 void setValueSubclassData(unsigned short D) {
418 Value::setValueSubclassData(D);
420 unsigned short getSubclassDataFromValue() const {
421 return Value::getSubclassDataFromValue();
424 void setHasMetadataHashEntry(bool V) {
425 setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
426 (V ? HasMetadataBit : 0));
429 friend class SymbolTableListTraits<Instruction, BasicBlock>;
430 void setParent(BasicBlock *P);
432 // Instruction subclasses can stick up to 15 bits of stuff into the
433 // SubclassData field of instruction with these members.
435 // Verify that only the low 15 bits are used.
436 void setInstructionSubclassData(unsigned short D) {
437 assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
438 setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
441 unsigned getSubclassDataFromInstruction() const {
442 return getSubclassDataFromValue() & ~HasMetadataBit;
445 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
446 Instruction *InsertBefore = 0);
447 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
448 BasicBlock *InsertAtEnd);
449 virtual Instruction *clone_impl() const = 0;
453 // Instruction* is only 4-byte aligned.
455 class PointerLikeTypeTraits<Instruction*> {
456 typedef Instruction* PT;
458 static inline void *getAsVoidPointer(PT P) { return P; }
459 static inline PT getFromVoidPointer(void *P) {
460 return static_cast<PT>(P);
462 enum { NumLowBitsAvailable = 2 };
465 } // End llvm namespace