]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/IR/Instruction.h
Merge ^/head r305397 through r305430.
[FreeBSD/FreeBSD.git] / contrib / llvm / include / llvm / IR / Instruction.h
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 this instruction behaves like a memory fence: it can load
403   /// or store to memory location without being given a memory location.
404   bool isFenceLike() const {
405     switch (getOpcode()) {
406     default:
407       return false;
408     // This list should be kept in sync with the list in mayWriteToMemory for
409     // all opcodes which don't have a memory location.
410     case Instruction::Fence:
411     case Instruction::CatchPad:
412     case Instruction::CatchRet:
413     case Instruction::Call:
414     case Instruction::Invoke:
415       return true;
416     }
417   }
418
419   /// Return true if the instruction may have side effects.
420   ///
421   /// Note that this does not consider malloc and alloca to have side
422   /// effects because the newly allocated memory is completely invisible to
423   /// instructions which don't use the returned value.  For cases where this
424   /// matters, isSafeToSpeculativelyExecute may be more appropriate.
425   bool mayHaveSideEffects() const { return mayWriteToMemory() || mayThrow(); }
426
427   /// Return true if the instruction is a variety of EH-block.
428   bool isEHPad() const {
429     switch (getOpcode()) {
430     case Instruction::CatchSwitch:
431     case Instruction::CatchPad:
432     case Instruction::CleanupPad:
433     case Instruction::LandingPad:
434       return true;
435     default:
436       return false;
437     }
438   }
439
440   /// Create a copy of 'this' instruction that is identical in all ways except
441   /// the following:
442   ///   * The instruction has no parent
443   ///   * The instruction has no name
444   ///
445   Instruction *clone() const;
446
447   /// Return true if the specified instruction is exactly identical to the
448   /// current one. This means that all operands match and any extra information
449   /// (e.g. load is volatile) agree.
450   bool isIdenticalTo(const Instruction *I) const;
451
452   /// This is like isIdenticalTo, except that it ignores the
453   /// SubclassOptionalData flags, which specify conditions under which the
454   /// instruction's result is undefined.
455   bool isIdenticalToWhenDefined(const Instruction *I) const;
456
457   /// When checking for operation equivalence (using isSameOperationAs) it is
458   /// sometimes useful to ignore certain attributes.
459   enum OperationEquivalenceFlags {
460     /// Check for equivalence ignoring load/store alignment.
461     CompareIgnoringAlignment = 1<<0,
462     /// Check for equivalence treating a type and a vector of that type
463     /// as equivalent.
464     CompareUsingScalarTypes = 1<<1
465   };
466
467   /// This function determines if the specified instruction executes the same
468   /// operation as the current one. This means that the opcodes, type, operand
469   /// types and any other factors affecting the operation must be the same. This
470   /// is similar to isIdenticalTo except the operands themselves don't have to
471   /// be identical.
472   /// @returns true if the specified instruction is the same operation as
473   /// the current one.
474   /// @brief Determine if one instruction is the same operation as another.
475   bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
476
477   /// Return true if there are any uses of this instruction in blocks other than
478   /// the specified block. Note that PHI nodes are considered to evaluate their
479   /// operands in the corresponding predecessor block.
480   bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
481
482
483   /// Methods for support type inquiry through isa, cast, and dyn_cast:
484   static inline bool classof(const Value *V) {
485     return V->getValueID() >= Value::InstructionVal;
486   }
487
488   //----------------------------------------------------------------------
489   // Exported enumerations.
490   //
491   enum TermOps {       // These terminate basic blocks
492 #define  FIRST_TERM_INST(N)             TermOpsBegin = N,
493 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
494 #define   LAST_TERM_INST(N)             TermOpsEnd = N+1
495 #include "llvm/IR/Instruction.def"
496   };
497
498   enum BinaryOps {
499 #define  FIRST_BINARY_INST(N)             BinaryOpsBegin = N,
500 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
501 #define   LAST_BINARY_INST(N)             BinaryOpsEnd = N+1
502 #include "llvm/IR/Instruction.def"
503   };
504
505   enum MemoryOps {
506 #define  FIRST_MEMORY_INST(N)             MemoryOpsBegin = N,
507 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
508 #define   LAST_MEMORY_INST(N)             MemoryOpsEnd = N+1
509 #include "llvm/IR/Instruction.def"
510   };
511
512   enum CastOps {
513 #define  FIRST_CAST_INST(N)             CastOpsBegin = N,
514 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
515 #define   LAST_CAST_INST(N)             CastOpsEnd = N+1
516 #include "llvm/IR/Instruction.def"
517   };
518
519   enum FuncletPadOps {
520 #define  FIRST_FUNCLETPAD_INST(N)             FuncletPadOpsBegin = N,
521 #define HANDLE_FUNCLETPAD_INST(N, OPC, CLASS) OPC = N,
522 #define   LAST_FUNCLETPAD_INST(N)             FuncletPadOpsEnd = N+1
523 #include "llvm/IR/Instruction.def"
524   };
525
526   enum OtherOps {
527 #define  FIRST_OTHER_INST(N)             OtherOpsBegin = N,
528 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
529 #define   LAST_OTHER_INST(N)             OtherOpsEnd = N+1
530 #include "llvm/IR/Instruction.def"
531   };
532 private:
533   // Shadow Value::setValueSubclassData with a private forwarding method so that
534   // subclasses cannot accidentally use it.
535   void setValueSubclassData(unsigned short D) {
536     Value::setValueSubclassData(D);
537   }
538   unsigned short getSubclassDataFromValue() const {
539     return Value::getSubclassDataFromValue();
540   }
541
542   void setHasMetadataHashEntry(bool V) {
543     setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
544                          (V ? HasMetadataBit : 0));
545   }
546
547   friend class SymbolTableListTraits<Instruction>;
548   void setParent(BasicBlock *P);
549 protected:
550   // Instruction subclasses can stick up to 15 bits of stuff into the
551   // SubclassData field of instruction with these members.
552
553   // Verify that only the low 15 bits are used.
554   void setInstructionSubclassData(unsigned short D) {
555     assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
556     setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
557   }
558
559   unsigned getSubclassDataFromInstruction() const {
560     return getSubclassDataFromValue() & ~HasMetadataBit;
561   }
562
563   Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
564               Instruction *InsertBefore = nullptr);
565   Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
566               BasicBlock *InsertAtEnd);
567
568 private:
569   /// Create a copy of this instruction.
570   Instruction *cloneImpl() const;
571 };
572
573 // Instruction* is only 4-byte aligned.
574 template<>
575 class PointerLikeTypeTraits<Instruction*> {
576   typedef Instruction* PT;
577 public:
578   static inline void *getAsVoidPointer(PT P) { return P; }
579   static inline PT getFromVoidPointer(void *P) {
580     return static_cast<PT>(P);
581   }
582   enum { NumLowBitsAvailable = 2 };
583 };
584
585 } // End llvm namespace
586
587 #endif