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