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