• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- llvm/Instruction.h - Instruction class definition -------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the declaration of the Instruction class, which is the
11 // base class for all of the LLVM instructions.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_IR_INSTRUCTION_H
16 #define LLVM_IR_INSTRUCTION_H
17 
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/ilist_node.h"
20 #include "llvm/IR/DebugLoc.h"
21 #include "llvm/IR/SymbolTableListTraits.h"
22 #include "llvm/IR/User.h"
23 
24 namespace llvm {
25 
26 class FastMathFlags;
27 class LLVMContext;
28 class MDNode;
29 class BasicBlock;
30 struct AAMDNodes;
31 
32 template <>
33 struct SymbolTableListSentinelTraits<Instruction>
34     : public ilist_half_embedded_sentinel_traits<Instruction> {};
35 
36 class Instruction : public User,
37                     public ilist_node_with_parent<Instruction, BasicBlock> {
38   void operator=(const Instruction &) = delete;
39   Instruction(const Instruction &) = delete;
40 
41   BasicBlock *Parent;
42   DebugLoc DbgLoc;                         // 'dbg' Metadata cache.
43 
44   enum {
45     /// HasMetadataBit - This is a bit stored in the SubClassData field which
46     /// indicates whether this instruction has metadata attached to it or not.
47     HasMetadataBit = 1 << 15
48   };
49 public:
50   // Out of line virtual method, so the vtable, etc has a home.
51   ~Instruction() override;
52 
53   /// user_back - Specialize the methods defined in Value, as we know that an
54   /// instruction can only be used by other instructions.
55   Instruction       *user_back()       { return cast<Instruction>(*user_begin());}
56   const Instruction *user_back() const { return cast<Instruction>(*user_begin());}
57 
58   inline const BasicBlock *getParent() const { return Parent; }
59   inline       BasicBlock *getParent()       { return Parent; }
60 
61   /// \brief Return the module owning the function this instruction belongs to
62   /// or nullptr it the function does not have a module.
63   ///
64   /// Note: this is undefined behavior if the instruction does not have a
65   /// parent, or the parent basic block does not have a parent function.
66   const Module *getModule() const;
67   Module *getModule();
68 
69   /// \brief Return the function this instruction belongs to.
70   ///
71   /// Note: it is undefined behavior to call this on an instruction not
72   /// currently inserted into a function.
73   const Function *getFunction() const;
74   Function *getFunction();
75 
76   /// removeFromParent - This method unlinks 'this' from the containing basic
77   /// block, but does not delete it.
78   ///
79   void removeFromParent();
80 
81   /// eraseFromParent - This method unlinks 'this' from the containing basic
82   /// block and deletes it.
83   ///
84   /// \returns an iterator pointing to the element after the erased one
85   SymbolTableList<Instruction>::iterator eraseFromParent();
86 
87   /// Insert an unlinked instruction into a basic block immediately before
88   /// the specified instruction.
89   void insertBefore(Instruction *InsertPos);
90 
91   /// Insert an unlinked instruction into a basic block immediately after the
92   /// specified instruction.
93   void insertAfter(Instruction *InsertPos);
94 
95   /// moveBefore - Unlink this instruction from its current basic block and
96   /// insert it into the basic block that MovePos lives in, right before
97   /// MovePos.
98   void moveBefore(Instruction *MovePos);
99 
100   //===--------------------------------------------------------------------===//
101   // Subclass classification.
102   //===--------------------------------------------------------------------===//
103 
104   /// getOpcode() returns a member of one of the enums like Instruction::Add.
105   unsigned getOpcode() const { return getValueID() - InstructionVal; }
106 
107   const char *getOpcodeName() const { return getOpcodeName(getOpcode()); }
108   bool isTerminator() const { return isTerminator(getOpcode()); }
109   bool isBinaryOp() const { return isBinaryOp(getOpcode()); }
110   bool isShift() { return isShift(getOpcode()); }
111   bool isCast() const { return isCast(getOpcode()); }
112   bool isFuncletPad() const { return isFuncletPad(getOpcode()); }
113 
114   static const char* getOpcodeName(unsigned OpCode);
115 
116   static inline bool isTerminator(unsigned OpCode) {
117     return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
118   }
119 
120   static inline bool isBinaryOp(unsigned Opcode) {
121     return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
122   }
123 
124   /// @brief Determine if the Opcode is one of the shift instructions.
125   static inline bool isShift(unsigned Opcode) {
126     return Opcode >= Shl && Opcode <= AShr;
127   }
128 
129   /// isLogicalShift - Return true if this is a logical shift left or a logical
130   /// shift right.
131   inline bool isLogicalShift() const {
132     return getOpcode() == Shl || getOpcode() == LShr;
133   }
134 
135   /// isArithmeticShift - Return true if this is an arithmetic shift right.
136   inline bool isArithmeticShift() const {
137     return getOpcode() == AShr;
138   }
139 
140   /// @brief Determine if the OpCode is one of the CastInst instructions.
141   static inline bool isCast(unsigned OpCode) {
142     return OpCode >= CastOpsBegin && OpCode < CastOpsEnd;
143   }
144 
145   /// @brief Determine if the OpCode is one of the FuncletPadInst instructions.
146   static inline bool isFuncletPad(unsigned OpCode) {
147     return OpCode >= FuncletPadOpsBegin && OpCode < FuncletPadOpsEnd;
148   }
149 
150   //===--------------------------------------------------------------------===//
151   // Metadata manipulation.
152   //===--------------------------------------------------------------------===//
153 
154   /// hasMetadata() - Return true if this instruction has any metadata attached
155   /// to it.
156   bool hasMetadata() const { return DbgLoc || hasMetadataHashEntry(); }
157 
158   /// hasMetadataOtherThanDebugLoc - Return true if this instruction has
159   /// metadata attached to it other than a debug location.
160   bool hasMetadataOtherThanDebugLoc() const {
161     return hasMetadataHashEntry();
162   }
163 
164   /// getMetadata - Get the metadata of given kind attached to this Instruction.
165   /// If the metadata is not found then return null.
166   MDNode *getMetadata(unsigned KindID) const {
167     if (!hasMetadata()) return nullptr;
168     return getMetadataImpl(KindID);
169   }
170 
171   /// getMetadata - Get the metadata of given kind attached to this Instruction.
172   /// If the metadata is not found then return null.
173   MDNode *getMetadata(StringRef Kind) const {
174     if (!hasMetadata()) return nullptr;
175     return getMetadataImpl(Kind);
176   }
177 
178   /// getAllMetadata - Get all metadata attached to this Instruction.  The first
179   /// element of each pair returned is the KindID, the second element is the
180   /// metadata value.  This list is returned sorted by the KindID.
181   void
182   getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
183     if (hasMetadata())
184       getAllMetadataImpl(MDs);
185   }
186 
187   /// getAllMetadataOtherThanDebugLoc - This does the same thing as
188   /// getAllMetadata, except that it filters out the debug location.
189   void getAllMetadataOtherThanDebugLoc(
190       SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
191     if (hasMetadataOtherThanDebugLoc())
192       getAllMetadataOtherThanDebugLocImpl(MDs);
193   }
194 
195   /// getAAMetadata - Fills the AAMDNodes structure with AA metadata from
196   /// this instruction. When Merge is true, the existing AA metadata is
197   /// merged with that from this instruction providing the most-general result.
198   void getAAMetadata(AAMDNodes &N, bool Merge = false) const;
199 
200   /// setMetadata - Set the metadata of the specified kind to the specified
201   /// node.  This updates/replaces metadata if already present, or removes it if
202   /// Node is null.
203   void setMetadata(unsigned KindID, MDNode *Node);
204   void setMetadata(StringRef Kind, MDNode *Node);
205 
206   /// Drop all unknown metadata except for debug locations.
207   /// @{
208   /// Passes are required to drop metadata they don't understand. This is a
209   /// convenience method for passes to do so.
210   void dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs);
211   void dropUnknownNonDebugMetadata() {
212     return dropUnknownNonDebugMetadata(None);
213   }
214   void dropUnknownNonDebugMetadata(unsigned ID1) {
215     return dropUnknownNonDebugMetadata(makeArrayRef(ID1));
216   }
217   void dropUnknownNonDebugMetadata(unsigned ID1, unsigned ID2) {
218     unsigned IDs[] = {ID1, ID2};
219     return dropUnknownNonDebugMetadata(IDs);
220   }
221   /// @}
222 
223   /// setAAMetadata - Sets the metadata on this instruction from the
224   /// AAMDNodes structure.
225   void setAAMetadata(const AAMDNodes &N);
226 
227   /// setDebugLoc - Set the debug location information for this instruction.
228   void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); }
229 
230   /// getDebugLoc - Return the debug location for this node as a DebugLoc.
231   const DebugLoc &getDebugLoc() const { return DbgLoc; }
232 
233   /// Set or clear the unsafe-algebra flag on this instruction, which must be an
234   /// operator which supports this flag. See LangRef.html for the meaning of
235   /// this flag.
236   void setHasUnsafeAlgebra(bool B);
237 
238   /// Set or clear the no-nans flag on this instruction, which must be an
239   /// operator which supports this flag. See LangRef.html for the meaning of
240   /// this flag.
241   void setHasNoNaNs(bool B);
242 
243   /// Set or clear the no-infs flag on this instruction, which must be an
244   /// operator which supports this flag. See LangRef.html for the meaning of
245   /// this flag.
246   void setHasNoInfs(bool B);
247 
248   /// Set or clear the no-signed-zeros flag on this instruction, which must be
249   /// an operator which supports this flag. See LangRef.html for the meaning of
250   /// this flag.
251   void setHasNoSignedZeros(bool B);
252 
253   /// Set or clear the allow-reciprocal flag on this instruction, which must be
254   /// an operator which supports this flag. See LangRef.html for the meaning of
255   /// this flag.
256   void setHasAllowReciprocal(bool B);
257 
258   /// Convenience function for setting multiple fast-math flags on this
259   /// instruction, which must be an operator which supports these flags. See
260   /// LangRef.html for the meaning of these flags.
261   void setFastMathFlags(FastMathFlags FMF);
262 
263   /// Convenience function for transferring all fast-math flag values to this
264   /// instruction, which must be an operator which supports these flags. See
265   /// LangRef.html for the meaning of these flags.
266   void copyFastMathFlags(FastMathFlags FMF);
267 
268   /// Determine whether the unsafe-algebra flag is set.
269   bool hasUnsafeAlgebra() const;
270 
271   /// Determine whether the no-NaNs flag is set.
272   bool hasNoNaNs() const;
273 
274   /// Determine whether the no-infs flag is set.
275   bool hasNoInfs() const;
276 
277   /// Determine whether the no-signed-zeros flag is set.
278   bool hasNoSignedZeros() const;
279 
280   /// Determine whether the allow-reciprocal flag is set.
281   bool hasAllowReciprocal() const;
282 
283   /// Convenience function for getting all the fast-math flags, which must be an
284   /// operator which supports these flags. See LangRef.html for the meaning of
285   /// these flags.
286   FastMathFlags getFastMathFlags() const;
287 
288   /// Copy I's fast-math flags
289   void copyFastMathFlags(const Instruction *I);
290 
291 private:
292   /// hasMetadataHashEntry - Return true if we have an entry in the on-the-side
293   /// metadata hash.
294   bool hasMetadataHashEntry() const {
295     return (getSubclassDataFromValue() & HasMetadataBit) != 0;
296   }
297 
298   // These are all implemented in Metadata.cpp.
299   MDNode *getMetadataImpl(unsigned KindID) const;
300   MDNode *getMetadataImpl(StringRef Kind) const;
301   void
302   getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
303   void getAllMetadataOtherThanDebugLocImpl(
304       SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
305   void clearMetadataHashEntries();
306 public:
307   //===--------------------------------------------------------------------===//
308   // Predicates and helper methods.
309   //===--------------------------------------------------------------------===//
310 
311 
312   /// isAssociative - Return true if the instruction is associative:
313   ///
314   ///   Associative operators satisfy:  x op (y op z) === (x op y) op z
315   ///
316   /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
317   ///
318   bool isAssociative() const;
319   static bool isAssociative(unsigned op);
320 
321   /// isCommutative - Return true if the instruction is commutative:
322   ///
323   ///   Commutative operators satisfy: (x op y) === (y op x)
324   ///
325   /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
326   /// applied to any type.
327   ///
328   bool isCommutative() const { return isCommutative(getOpcode()); }
329   static bool isCommutative(unsigned op);
330 
331   /// isIdempotent - Return true if the instruction is idempotent:
332   ///
333   ///   Idempotent operators satisfy:  x op x === x
334   ///
335   /// In LLVM, the And and Or operators are idempotent.
336   ///
337   bool isIdempotent() const { return isIdempotent(getOpcode()); }
338   static bool isIdempotent(unsigned op);
339 
340   /// isNilpotent - Return true if the instruction is nilpotent:
341   ///
342   ///   Nilpotent operators satisfy:  x op x === Id,
343   ///
344   ///   where Id is the identity for the operator, i.e. a constant such that
345   ///     x op Id === x and Id op x === x for all x.
346   ///
347   /// In LLVM, the Xor operator is nilpotent.
348   ///
349   bool isNilpotent() const { return isNilpotent(getOpcode()); }
350   static bool isNilpotent(unsigned op);
351 
352   /// mayWriteToMemory - Return true if this instruction may modify memory.
353   ///
354   bool mayWriteToMemory() const;
355 
356   /// mayReadFromMemory - Return true if this instruction may read memory.
357   ///
358   bool mayReadFromMemory() const;
359 
360   /// mayReadOrWriteMemory - Return true if this instruction may read or
361   /// write memory.
362   ///
363   bool mayReadOrWriteMemory() const {
364     return mayReadFromMemory() || mayWriteToMemory();
365   }
366 
367   /// isAtomic - Return true if this instruction has an
368   /// AtomicOrdering of unordered or higher.
369   ///
370   bool isAtomic() const;
371 
372   /// mayThrow - Return true if this instruction may throw an exception.
373   ///
374   bool mayThrow() const;
375 
376   /// mayReturn - Return true if this is a function that may return.
377   /// this is true for all normal instructions. The only exception
378   /// is functions that are marked with the 'noreturn' attribute.
379   ///
380   bool mayReturn() const;
381 
382   /// mayHaveSideEffects - Return true if the instruction may have side effects.
383   ///
384   /// Note that this does not consider malloc and alloca to have side
385   /// effects because the newly allocated memory is completely invisible to
386   /// instructions which don't use the returned value.  For cases where this
387   /// matters, isSafeToSpeculativelyExecute may be more appropriate.
388   bool mayHaveSideEffects() const {
389     return mayWriteToMemory() || mayThrow() || !mayReturn();
390   }
391 
392   /// \brief Return true if the instruction is a variety of EH-block.
393   bool isEHPad() const {
394     switch (getOpcode()) {
395     case Instruction::CatchSwitch:
396     case Instruction::CatchPad:
397     case Instruction::CleanupPad:
398     case Instruction::LandingPad:
399       return true;
400     default:
401       return false;
402     }
403   }
404 
405   /// clone() - Create a copy of 'this' instruction that is identical in all
406   /// ways except the following:
407   ///   * The instruction has no parent
408   ///   * The instruction has no name
409   ///
410   Instruction *clone() const;
411 
412   /// isIdenticalTo - Return true if the specified instruction is exactly
413   /// identical to the current one.  This means that all operands match and any
414   /// extra information (e.g. load is volatile) agree.
415   bool isIdenticalTo(const Instruction *I) const;
416 
417   /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
418   /// ignores the SubclassOptionalData flags, which specify conditions
419   /// under which the instruction's result is undefined.
420   bool isIdenticalToWhenDefined(const Instruction *I) const;
421 
422   /// When checking for operation equivalence (using isSameOperationAs) it is
423   /// sometimes useful to ignore certain attributes.
424   enum OperationEquivalenceFlags {
425     /// Check for equivalence ignoring load/store alignment.
426     CompareIgnoringAlignment = 1<<0,
427     /// Check for equivalence treating a type and a vector of that type
428     /// as equivalent.
429     CompareUsingScalarTypes = 1<<1
430   };
431 
432   /// This function determines if the specified instruction executes the same
433   /// operation as the current one. This means that the opcodes, type, operand
434   /// types and any other factors affecting the operation must be the same. This
435   /// is similar to isIdenticalTo except the operands themselves don't have to
436   /// be identical.
437   /// @returns true if the specified instruction is the same operation as
438   /// the current one.
439   /// @brief Determine if one instruction is the same operation as another.
440   bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
441 
442   /// isUsedOutsideOfBlock - Return true if there are any uses of this
443   /// instruction in blocks other than the specified block.  Note that PHI nodes
444   /// are considered to evaluate their operands in the corresponding predecessor
445   /// block.
446   bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
447 
448 
449   /// Methods for support type inquiry through isa, cast, and dyn_cast:
450   static inline bool classof(const Value *V) {
451     return V->getValueID() >= Value::InstructionVal;
452   }
453 
454   //----------------------------------------------------------------------
455   // Exported enumerations.
456   //
457   enum TermOps {       // These terminate basic blocks
458 #define  FIRST_TERM_INST(N)             TermOpsBegin = N,
459 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
460 #define   LAST_TERM_INST(N)             TermOpsEnd = N+1
461 #include "llvm/IR/Instruction.def"
462   };
463 
464   enum BinaryOps {
465 #define  FIRST_BINARY_INST(N)             BinaryOpsBegin = N,
466 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
467 #define   LAST_BINARY_INST(N)             BinaryOpsEnd = N+1
468 #include "llvm/IR/Instruction.def"
469   };
470 
471   enum MemoryOps {
472 #define  FIRST_MEMORY_INST(N)             MemoryOpsBegin = N,
473 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
474 #define   LAST_MEMORY_INST(N)             MemoryOpsEnd = N+1
475 #include "llvm/IR/Instruction.def"
476   };
477 
478   enum CastOps {
479 #define  FIRST_CAST_INST(N)             CastOpsBegin = N,
480 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
481 #define   LAST_CAST_INST(N)             CastOpsEnd = N+1
482 #include "llvm/IR/Instruction.def"
483   };
484 
485   enum FuncletPadOps {
486 #define  FIRST_FUNCLETPAD_INST(N)             FuncletPadOpsBegin = N,
487 #define HANDLE_FUNCLETPAD_INST(N, OPC, CLASS) OPC = N,
488 #define   LAST_FUNCLETPAD_INST(N)             FuncletPadOpsEnd = N+1
489 #include "llvm/IR/Instruction.def"
490   };
491 
492   enum OtherOps {
493 #define  FIRST_OTHER_INST(N)             OtherOpsBegin = N,
494 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
495 #define   LAST_OTHER_INST(N)             OtherOpsEnd = N+1
496 #include "llvm/IR/Instruction.def"
497   };
498 private:
499   // Shadow Value::setValueSubclassData with a private forwarding method so that
500   // subclasses cannot accidentally use it.
501   void setValueSubclassData(unsigned short D) {
502     Value::setValueSubclassData(D);
503   }
504   unsigned short getSubclassDataFromValue() const {
505     return Value::getSubclassDataFromValue();
506   }
507 
508   void setHasMetadataHashEntry(bool V) {
509     setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
510                          (V ? HasMetadataBit : 0));
511   }
512 
513   friend class SymbolTableListTraits<Instruction>;
514   void setParent(BasicBlock *P);
515 protected:
516   // Instruction subclasses can stick up to 15 bits of stuff into the
517   // SubclassData field of instruction with these members.
518 
519   // Verify that only the low 15 bits are used.
520   void setInstructionSubclassData(unsigned short D) {
521     assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
522     setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
523   }
524 
525   unsigned getSubclassDataFromInstruction() const {
526     return getSubclassDataFromValue() & ~HasMetadataBit;
527   }
528 
529   Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
530               Instruction *InsertBefore = nullptr);
531   Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
532               BasicBlock *InsertAtEnd);
533 
534 private:
535   /// Create a copy of this instruction.
536   Instruction *cloneImpl() const;
537 };
538 
539 // Instruction* is only 4-byte aligned.
540 template<>
541 class PointerLikeTypeTraits<Instruction*> {
542   typedef Instruction* PT;
543 public:
544   static inline void *getAsVoidPointer(PT P) { return P; }
545   static inline PT getFromVoidPointer(void *P) {
546     return static_cast<PT>(P);
547   }
548   enum { NumLowBitsAvailable = 2 };
549 };
550 
551 } // End llvm namespace
552 
553 #endif
554