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