OSDN Git Service

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