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