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