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