LLVM API Documentation

Instruction.h
Go to the documentation of this file.
00001 //===-- llvm/Instruction.h - Instruction class definition -------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains the declaration of the Instruction class, which is the
00011 // base class for all of the LLVM instructions.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #ifndef LLVM_IR_INSTRUCTION_H
00016 #define LLVM_IR_INSTRUCTION_H
00017 
00018 #include "llvm/ADT/ArrayRef.h"
00019 #include "llvm/ADT/ilist_node.h"
00020 #include "llvm/IR/DebugLoc.h"
00021 #include "llvm/IR/User.h"
00022 
00023 namespace llvm {
00024 
00025 class FastMathFlags;
00026 class LLVMContext;
00027 class MDNode;
00028 struct AAMDNodes;
00029 
00030 template<typename ValueSubClass, typename ItemParentClass>
00031   class SymbolTableListTraits;
00032 
00033 class Instruction : public User, public ilist_node<Instruction> {
00034   void operator=(const Instruction &) LLVM_DELETED_FUNCTION;
00035   Instruction(const Instruction &) LLVM_DELETED_FUNCTION;
00036 
00037   BasicBlock *Parent;
00038   DebugLoc DbgLoc;                         // 'dbg' Metadata cache.
00039 
00040   enum {
00041     /// HasMetadataBit - This is a bit stored in the SubClassData field which
00042     /// indicates whether this instruction has metadata attached to it or not.
00043     HasMetadataBit = 1 << 15
00044   };
00045 public:
00046   // Out of line virtual method, so the vtable, etc has a home.
00047   ~Instruction();
00048 
00049   /// user_back - Specialize the methods defined in Value, as we know that an
00050   /// instruction can only be used by other instructions.
00051   Instruction       *user_back()       { return cast<Instruction>(*user_begin());}
00052   const Instruction *user_back() const { return cast<Instruction>(*user_begin());}
00053 
00054   inline const BasicBlock *getParent() const { return Parent; }
00055   inline       BasicBlock *getParent()       { return Parent; }
00056 
00057   const DataLayout *getDataLayout() const;
00058 
00059   /// removeFromParent - This method unlinks 'this' from the containing basic
00060   /// block, but does not delete it.
00061   ///
00062   void removeFromParent();
00063 
00064   /// eraseFromParent - This method unlinks 'this' from the containing basic
00065   /// block and deletes it.
00066   ///
00067   void eraseFromParent();
00068 
00069   /// insertBefore - Insert an unlinked instructions into a basic block
00070   /// immediately before the specified instruction.
00071   void insertBefore(Instruction *InsertPos);
00072 
00073   /// insertAfter - Insert an unlinked instructions into a basic block
00074   /// immediately after the specified instruction.
00075   void insertAfter(Instruction *InsertPos);
00076 
00077   /// moveBefore - Unlink this instruction from its current basic block and
00078   /// insert it into the basic block that MovePos lives in, right before
00079   /// MovePos.
00080   void moveBefore(Instruction *MovePos);
00081 
00082   //===--------------------------------------------------------------------===//
00083   // Subclass classification.
00084   //===--------------------------------------------------------------------===//
00085 
00086   /// getOpcode() returns a member of one of the enums like Instruction::Add.
00087   unsigned getOpcode() const { return getValueID() - InstructionVal; }
00088 
00089   const char *getOpcodeName() const { return getOpcodeName(getOpcode()); }
00090   bool isTerminator() const { return isTerminator(getOpcode()); }
00091   bool isBinaryOp() const { return isBinaryOp(getOpcode()); }
00092   bool isShift() { return isShift(getOpcode()); }
00093   bool isCast() const { return isCast(getOpcode()); }
00094 
00095   static const char* getOpcodeName(unsigned OpCode);
00096 
00097   static inline bool isTerminator(unsigned OpCode) {
00098     return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
00099   }
00100 
00101   static inline bool isBinaryOp(unsigned Opcode) {
00102     return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
00103   }
00104 
00105   /// @brief Determine if the Opcode is one of the shift instructions.
00106   static inline bool isShift(unsigned Opcode) {
00107     return Opcode >= Shl && Opcode <= AShr;
00108   }
00109 
00110   /// isLogicalShift - Return true if this is a logical shift left or a logical
00111   /// shift right.
00112   inline bool isLogicalShift() const {
00113     return getOpcode() == Shl || getOpcode() == LShr;
00114   }
00115 
00116   /// isArithmeticShift - Return true if this is an arithmetic shift right.
00117   inline bool isArithmeticShift() const {
00118     return getOpcode() == AShr;
00119   }
00120 
00121   /// @brief Determine if the OpCode is one of the CastInst instructions.
00122   static inline bool isCast(unsigned OpCode) {
00123     return OpCode >= CastOpsBegin && OpCode < CastOpsEnd;
00124   }
00125 
00126   //===--------------------------------------------------------------------===//
00127   // Metadata manipulation.
00128   //===--------------------------------------------------------------------===//
00129 
00130   /// hasMetadata() - Return true if this instruction has any metadata attached
00131   /// to it.
00132   bool hasMetadata() const {
00133     return !DbgLoc.isUnknown() || hasMetadataHashEntry();
00134   }
00135 
00136   /// hasMetadataOtherThanDebugLoc - Return true if this instruction has
00137   /// metadata attached to it other than a debug location.
00138   bool hasMetadataOtherThanDebugLoc() const {
00139     return hasMetadataHashEntry();
00140   }
00141 
00142   /// getMetadata - Get the metadata of given kind attached to this Instruction.
00143   /// If the metadata is not found then return null.
00144   MDNode *getMetadata(unsigned KindID) const {
00145     if (!hasMetadata()) return nullptr;
00146     return getMetadataImpl(KindID);
00147   }
00148 
00149   /// getMetadata - Get the metadata of given kind attached to this Instruction.
00150   /// If the metadata is not found then return null.
00151   MDNode *getMetadata(StringRef Kind) const {
00152     if (!hasMetadata()) return nullptr;
00153     return getMetadataImpl(Kind);
00154   }
00155 
00156   /// getAllMetadata - Get all metadata attached to this Instruction.  The first
00157   /// element of each pair returned is the KindID, the second element is the
00158   /// metadata value.  This list is returned sorted by the KindID.
00159   void
00160   getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
00161     if (hasMetadata())
00162       getAllMetadataImpl(MDs);
00163   }
00164 
00165   /// getAllMetadataOtherThanDebugLoc - This does the same thing as
00166   /// getAllMetadata, except that it filters out the debug location.
00167   void getAllMetadataOtherThanDebugLoc(
00168       SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
00169     if (hasMetadataOtherThanDebugLoc())
00170       getAllMetadataOtherThanDebugLocImpl(MDs);
00171   }
00172 
00173   /// getAAMetadata - Fills the AAMDNodes structure with AA metadata from
00174   /// this instruction. When Merge is true, the existing AA metadata is
00175   /// merged with that from this instruction providing the most-general result.
00176   void getAAMetadata(AAMDNodes &N, bool Merge = false) const;
00177 
00178   /// setMetadata - Set the metadata of the specified kind to the specified
00179   /// node.  This updates/replaces metadata if already present, or removes it if
00180   /// Node is null.
00181   void setMetadata(unsigned KindID, MDNode *Node);
00182   void setMetadata(StringRef Kind, MDNode *Node);
00183 
00184   /// \brief Drop unknown metadata.
00185   /// Passes are required to drop metadata they don't understand. This is a
00186   /// convenience method for passes to do so.
00187   void dropUnknownMetadata(ArrayRef<unsigned> KnownIDs);
00188   void dropUnknownMetadata() {
00189     return dropUnknownMetadata(None);
00190   }
00191   void dropUnknownMetadata(unsigned ID1) {
00192     return dropUnknownMetadata(makeArrayRef(ID1));
00193   }
00194   void dropUnknownMetadata(unsigned ID1, unsigned ID2) {
00195     unsigned IDs[] = {ID1, ID2};
00196     return dropUnknownMetadata(IDs);
00197   }
00198 
00199   /// setAAMetadata - Sets the metadata on this instruction from the
00200   /// AAMDNodes structure.
00201   void setAAMetadata(const AAMDNodes &N);
00202 
00203   /// setDebugLoc - Set the debug location information for this instruction.
00204   void setDebugLoc(const DebugLoc &Loc) { DbgLoc = Loc; }
00205 
00206   /// getDebugLoc - Return the debug location for this node as a DebugLoc.
00207   const DebugLoc &getDebugLoc() const { return DbgLoc; }
00208 
00209   /// Set or clear the unsafe-algebra flag on this instruction, which must be an
00210   /// operator which supports this flag. See LangRef.html for the meaning of
00211   /// this flag.
00212   void setHasUnsafeAlgebra(bool B);
00213 
00214   /// Set or clear the no-nans flag on this instruction, which must be an
00215   /// operator which supports this flag. See LangRef.html for the meaning of
00216   /// this flag.
00217   void setHasNoNaNs(bool B);
00218 
00219   /// Set or clear the no-infs flag on this instruction, which must be an
00220   /// operator which supports this flag. See LangRef.html for the meaning of
00221   /// this flag.
00222   void setHasNoInfs(bool B);
00223 
00224   /// Set or clear the no-signed-zeros flag on this instruction, which must be
00225   /// an operator which supports this flag. See LangRef.html for the meaning of
00226   /// this flag.
00227   void setHasNoSignedZeros(bool B);
00228 
00229   /// Set or clear the allow-reciprocal flag on this instruction, which must be
00230   /// an operator which supports this flag. See LangRef.html for the meaning of
00231   /// this flag.
00232   void setHasAllowReciprocal(bool B);
00233 
00234   /// Convenience function for setting multiple fast-math flags on this
00235   /// instruction, which must be an operator which supports these flags. See
00236   /// LangRef.html for the meaning of these flags.
00237   void setFastMathFlags(FastMathFlags FMF);
00238 
00239   /// Convenience function for transferring all fast-math flag values to this
00240   /// instruction, which must be an operator which supports these flags. See
00241   /// LangRef.html for the meaning of these flags.
00242   void copyFastMathFlags(FastMathFlags FMF);
00243 
00244   /// Determine whether the unsafe-algebra flag is set.
00245   bool hasUnsafeAlgebra() const;
00246 
00247   /// Determine whether the no-NaNs flag is set.
00248   bool hasNoNaNs() const;
00249 
00250   /// Determine whether the no-infs flag is set.
00251   bool hasNoInfs() const;
00252 
00253   /// Determine whether the no-signed-zeros flag is set.
00254   bool hasNoSignedZeros() const;
00255 
00256   /// Determine whether the allow-reciprocal flag is set.
00257   bool hasAllowReciprocal() const;
00258 
00259   /// Convenience function for getting all the fast-math flags, which must be an
00260   /// operator which supports these flags. See LangRef.html for the meaning of
00261   /// these flags.
00262   FastMathFlags getFastMathFlags() const;
00263 
00264   /// Copy I's fast-math flags
00265   void copyFastMathFlags(const Instruction *I);
00266 
00267 private:
00268   /// hasMetadataHashEntry - Return true if we have an entry in the on-the-side
00269   /// metadata hash.
00270   bool hasMetadataHashEntry() const {
00271     return (getSubclassDataFromValue() & HasMetadataBit) != 0;
00272   }
00273 
00274   // These are all implemented in Metadata.cpp.
00275   MDNode *getMetadataImpl(unsigned KindID) const;
00276   MDNode *getMetadataImpl(StringRef Kind) const;
00277   void
00278   getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
00279   void getAllMetadataOtherThanDebugLocImpl(
00280       SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
00281   void clearMetadataHashEntries();
00282 public:
00283   //===--------------------------------------------------------------------===//
00284   // Predicates and helper methods.
00285   //===--------------------------------------------------------------------===//
00286 
00287 
00288   /// isAssociative - Return true if the instruction is associative:
00289   ///
00290   ///   Associative operators satisfy:  x op (y op z) === (x op y) op z
00291   ///
00292   /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
00293   ///
00294   bool isAssociative() const;
00295   static bool isAssociative(unsigned op);
00296 
00297   /// isCommutative - Return true if the instruction is commutative:
00298   ///
00299   ///   Commutative operators satisfy: (x op y) === (y op x)
00300   ///
00301   /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
00302   /// applied to any type.
00303   ///
00304   bool isCommutative() const { return isCommutative(getOpcode()); }
00305   static bool isCommutative(unsigned op);
00306 
00307   /// isIdempotent - Return true if the instruction is idempotent:
00308   ///
00309   ///   Idempotent operators satisfy:  x op x === x
00310   ///
00311   /// In LLVM, the And and Or operators are idempotent.
00312   ///
00313   bool isIdempotent() const { return isIdempotent(getOpcode()); }
00314   static bool isIdempotent(unsigned op);
00315 
00316   /// isNilpotent - Return true if the instruction is nilpotent:
00317   ///
00318   ///   Nilpotent operators satisfy:  x op x === Id,
00319   ///
00320   ///   where Id is the identity for the operator, i.e. a constant such that
00321   ///     x op Id === x and Id op x === x for all x.
00322   ///
00323   /// In LLVM, the Xor operator is nilpotent.
00324   ///
00325   bool isNilpotent() const { return isNilpotent(getOpcode()); }
00326   static bool isNilpotent(unsigned op);
00327 
00328   /// mayWriteToMemory - Return true if this instruction may modify memory.
00329   ///
00330   bool mayWriteToMemory() const;
00331 
00332   /// mayReadFromMemory - Return true if this instruction may read memory.
00333   ///
00334   bool mayReadFromMemory() const;
00335 
00336   /// mayReadOrWriteMemory - Return true if this instruction may read or
00337   /// write memory.
00338   ///
00339   bool mayReadOrWriteMemory() const {
00340     return mayReadFromMemory() || mayWriteToMemory();
00341   }
00342 
00343   /// isAtomic - Return true if this instruction has an
00344   /// AtomicOrdering of unordered or higher.
00345   ///
00346   bool isAtomic() const;
00347 
00348   /// mayThrow - Return true if this instruction may throw an exception.
00349   ///
00350   bool mayThrow() const;
00351 
00352   /// mayReturn - Return true if this is a function that may return.
00353   /// this is true for all normal instructions. The only exception
00354   /// is functions that are marked with the 'noreturn' attribute.
00355   ///
00356   bool mayReturn() const;
00357 
00358   /// mayHaveSideEffects - Return true if the instruction may have side effects.
00359   ///
00360   /// Note that this does not consider malloc and alloca to have side
00361   /// effects because the newly allocated memory is completely invisible to
00362   /// instructions which don't used the returned value.  For cases where this
00363   /// matters, isSafeToSpeculativelyExecute may be more appropriate.
00364   bool mayHaveSideEffects() const {
00365     return mayWriteToMemory() || mayThrow() || !mayReturn();
00366   }
00367 
00368   /// clone() - Create a copy of 'this' instruction that is identical in all
00369   /// ways except the following:
00370   ///   * The instruction has no parent
00371   ///   * The instruction has no name
00372   ///
00373   Instruction *clone() const;
00374 
00375   /// isIdenticalTo - Return true if the specified instruction is exactly
00376   /// identical to the current one.  This means that all operands match and any
00377   /// extra information (e.g. load is volatile) agree.
00378   bool isIdenticalTo(const Instruction *I) const;
00379 
00380   /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
00381   /// ignores the SubclassOptionalData flags, which specify conditions
00382   /// under which the instruction's result is undefined.
00383   bool isIdenticalToWhenDefined(const Instruction *I) const;
00384 
00385   /// When checking for operation equivalence (using isSameOperationAs) it is
00386   /// sometimes useful to ignore certain attributes.
00387   enum OperationEquivalenceFlags {
00388     /// Check for equivalence ignoring load/store alignment.
00389     CompareIgnoringAlignment = 1<<0,
00390     /// Check for equivalence treating a type and a vector of that type
00391     /// as equivalent.
00392     CompareUsingScalarTypes = 1<<1
00393   };
00394 
00395   /// This function determines if the specified instruction executes the same
00396   /// operation as the current one. This means that the opcodes, type, operand
00397   /// types and any other factors affecting the operation must be the same. This
00398   /// is similar to isIdenticalTo except the operands themselves don't have to
00399   /// be identical.
00400   /// @returns true if the specified instruction is the same operation as
00401   /// the current one.
00402   /// @brief Determine if one instruction is the same operation as another.
00403   bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
00404 
00405   /// isUsedOutsideOfBlock - Return true if there are any uses of this
00406   /// instruction in blocks other than the specified block.  Note that PHI nodes
00407   /// are considered to evaluate their operands in the corresponding predecessor
00408   /// block.
00409   bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
00410 
00411 
00412   /// Methods for support type inquiry through isa, cast, and dyn_cast:
00413   static inline bool classof(const Value *V) {
00414     return V->getValueID() >= Value::InstructionVal;
00415   }
00416 
00417   //----------------------------------------------------------------------
00418   // Exported enumerations.
00419   //
00420   enum TermOps {       // These terminate basic blocks
00421 #define  FIRST_TERM_INST(N)             TermOpsBegin = N,
00422 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
00423 #define   LAST_TERM_INST(N)             TermOpsEnd = N+1
00424 #include "llvm/IR/Instruction.def"
00425   };
00426 
00427   enum BinaryOps {
00428 #define  FIRST_BINARY_INST(N)             BinaryOpsBegin = N,
00429 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
00430 #define   LAST_BINARY_INST(N)             BinaryOpsEnd = N+1
00431 #include "llvm/IR/Instruction.def"
00432   };
00433 
00434   enum MemoryOps {
00435 #define  FIRST_MEMORY_INST(N)             MemoryOpsBegin = N,
00436 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
00437 #define   LAST_MEMORY_INST(N)             MemoryOpsEnd = N+1
00438 #include "llvm/IR/Instruction.def"
00439   };
00440 
00441   enum CastOps {
00442 #define  FIRST_CAST_INST(N)             CastOpsBegin = N,
00443 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
00444 #define   LAST_CAST_INST(N)             CastOpsEnd = N+1
00445 #include "llvm/IR/Instruction.def"
00446   };
00447 
00448   enum OtherOps {
00449 #define  FIRST_OTHER_INST(N)             OtherOpsBegin = N,
00450 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
00451 #define   LAST_OTHER_INST(N)             OtherOpsEnd = N+1
00452 #include "llvm/IR/Instruction.def"
00453   };
00454 private:
00455   // Shadow Value::setValueSubclassData with a private forwarding method so that
00456   // subclasses cannot accidentally use it.
00457   void setValueSubclassData(unsigned short D) {
00458     Value::setValueSubclassData(D);
00459   }
00460   unsigned short getSubclassDataFromValue() const {
00461     return Value::getSubclassDataFromValue();
00462   }
00463 
00464   void setHasMetadataHashEntry(bool V) {
00465     setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
00466                          (V ? HasMetadataBit : 0));
00467   }
00468 
00469   friend class SymbolTableListTraits<Instruction, BasicBlock>;
00470   void setParent(BasicBlock *P);
00471 protected:
00472   // Instruction subclasses can stick up to 15 bits of stuff into the
00473   // SubclassData field of instruction with these members.
00474 
00475   // Verify that only the low 15 bits are used.
00476   void setInstructionSubclassData(unsigned short D) {
00477     assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
00478     setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
00479   }
00480 
00481   unsigned getSubclassDataFromInstruction() const {
00482     return getSubclassDataFromValue() & ~HasMetadataBit;
00483   }
00484 
00485   Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
00486               Instruction *InsertBefore = nullptr);
00487   Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
00488               BasicBlock *InsertAtEnd);
00489   virtual Instruction *clone_impl() const = 0;
00490 
00491 };
00492 
00493 // Instruction* is only 4-byte aligned.
00494 template<>
00495 class PointerLikeTypeTraits<Instruction*> {
00496   typedef Instruction* PT;
00497 public:
00498   static inline void *getAsVoidPointer(PT P) { return P; }
00499   static inline PT getFromVoidPointer(void *P) {
00500     return static_cast<PT>(P);
00501   }
00502   enum { NumLowBitsAvailable = 2 };
00503 };
00504 
00505 } // End llvm namespace
00506 
00507 #endif