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