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